appclerk-core

Platform-agnostic compliance infrastructure SDK for AppClerk

📦 npm: appclerk-core•📄 License: MIT•View on npm →

Installation

npm install appclerk-core
# or
yarn add appclerk-core
# or
pnpm add appclerk-core

Quick Start

import { init } from "appclerk-core";

// Initialize SDK
const appclerk = init({
  apiKey: process.env.APPCLERK_API_KEY,
  projectId: process.env.APPCLERK_PROJECT_ID,
});

// Get document markdown
const privacyPolicy = await appclerk.getDocumentMarkdown("privacy-policy");
console.log(privacyPolicy.content);

// Get compliance status
const compliance = await appclerk.getComplianceStatus();
console.log(`Compliance Score: ${compliance.score}%`);

Configuration

The init() function accepts the following configuration options:

interface AppClerkConfig {
  /** Your AppClerk API key (required) */
  apiKey: string;
  
  /** Your AppClerk project ID (required) */
  projectId: string;
  
  /** Custom API URL (optional, defaults to https://appclerk.dev/api/v1) */
  apiUrl?: string;
  
  /** Enable debug logging (optional, default: false) */
  debug?: boolean;
  
  /** Cache TTL in milliseconds (optional, default: 300000 = 5 minutes) */
  cacheTtl?: number;
  
  /** Maximum retry attempts (optional, default: 3) */
  maxRetries?: number;
}

API Reference

getDocumentMarkdown()

Fetch markdown content for a document. Returns the full document content along with metadata.

const document = await appclerk.getDocumentMarkdown("privacy-policy");

// Returns:
interface DocumentContent {
  content: string;           // Markdown content
  lastUpdated: string;       // ISO 8601 timestamp
  version: number;           // Document version number
  title: string;            // Document title
  hostedUrl: string;        // Public hosted URL
}

getDocumentMetadata()

Fetch document metadata without the full content. Useful when you only need information about the document.

const metadata = await appclerk.getDocumentMetadata("privacy-policy");

// Returns:
interface DocumentMetadata {
  title: string;            // Document title
  lastUpdated: string;      // ISO 8601 timestamp
  version: number;          // Document version number
  hostedUrl: string;        // Public hosted URL
  status: string;           // Document status (e.g., "published")
}

getComplianceStatus()

Get overall compliance status for your project, including score, status, and any issues.

const compliance = await appclerk.getComplianceStatus();

// Returns:
interface ComplianceStatus {
  score: number;                    // Overall compliance score (0-100)
  status: string;                   // "compliant" | "needs_review" | "non_compliant"
  verificationStatus: string;        // Verification status
  issues: Array<{                    // Array of compliance issues
    documentType: string;
    issue: string;
    severity: string;
  }>;
  documents: Array<{                 // Per-document compliance status
    documentId: string;
    documentType: string;
    score: number;
    status: string;
  }>;
  lastChecked: string;               // ISO 8601 timestamp
}

getPrivacyPolicyUrl()

Get the hosted URL for your privacy policy. Returns a public URL that can be shared or embedded.

const url = await appclerk.getPrivacyPolicyUrl();
// Returns: "https://appclerk.dev/p/your-slug/privacy-policy"

getTermsUrl()

Get the hosted URL for your terms of service.

const url = await appclerk.getTermsUrl();
// Returns: "https://appclerk.dev/p/your-slug/terms-conditions"

clearCache()

Clear all cached data. Useful when you need to force a fresh fetch of data.

appclerk.clearCache();

Error Handling

The SDK throws custom error classes that you can catch and handle appropriately:

import {
  AuthenticationError,
  AuthorizationError,
  NotFoundError,
  RateLimitError,
  ValidationError,
  NetworkError,
  ServerError,
} from "appclerk-core";

try {
  const doc = await appclerk.getDocumentMarkdown("privacy-policy");
} catch (error) {
  if (error instanceof NotFoundError) {
    console.error("Document not found");
  } else if (error instanceof RateLimitError) {
    console.error(`Rate limit exceeded. Retry after: ${error.retryAfter} seconds`);
  } else if (error instanceof AuthenticationError) {
    console.error("Invalid API key");
  } else if (error instanceof NetworkError) {
    console.error("Network request failed");
  } else {
    console.error("Unexpected error:", error);
  }
}

Caching

The SDK includes built-in in-memory caching to improve performance and reduce API calls:

  • Document content: 5 minutes (configurable via cacheTtl)
  • Document metadata: 5 minutes
  • Compliance status: 1 minute

Cache is automatically cleaned up and can be cleared with clearCache().

Retry Logic

The SDK automatically retries failed requests with exponential backoff:

  • Network errors: Up to 3 retries (configurable via maxRetries)
  • Rate limit errors: Retries after the Retry-After header delay
  • Exponential backoff: Delays increase with each retry attempt

Examples

Node.js / Express

import { init } from "appclerk-core";
import express from "express";

const app = express();
const appclerk = init({
  apiKey: process.env.APPCLERK_API_KEY,
  projectId: process.env.APPCLERK_PROJECT_ID,
});

app.get("/privacy-policy", async (req, res) => {
  try {
    const doc = await appclerk.getDocumentMarkdown("privacy-policy");
    res.json(doc);
  } catch (error) {
    res.status(500).json({ error: "Failed to fetch document" });
  }
});

Next.js API Route

import { init } from "appclerk-core";
import type { NextApiRequest, NextApiResponse } from "next";

const appclerk = init({
  apiKey: process.env.APPCLERK_API_KEY,
  projectId: process.env.APPCLERK_PROJECT_ID,
});

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== "GET") {
    return res.status(405).json({ error: "Method not allowed" });
  }

  try {
    const compliance = await appclerk.getComplianceStatus();
    res.json(compliance);
  } catch (error) {
    res.status(500).json({ error: "Failed to fetch compliance status" });
  }
}

Getting Started

To use the SDK, you need an API key and project ID from your AppClerk dashboard.

  1. Sign up for AppClerk or log in to your account
  2. Create a project in your dashboard
  3. Generate an API key from API Keys settings
  4. Install the package and start using it!