{"version":3,"sources":["../../src/server/index.ts","../../src/http/errors.ts","../../src/regions/endpoints.ts","../../src/regions/resolver.ts","../../src/http/client.ts","../../src/auth/oauth-client.ts","../../src/server/middleware/auth.ts","../../src/server/middleware/session.ts","../../src/server/proxy/proxy-base.ts","../../src/server/proxy/rate-limiter.ts","../../src/server/proxy/scope-guard.ts","../../src/server/proxy/cma-proxy.ts","../../src/server/proxy/launch-proxy.ts","../../src/server/proxy/brandkit-proxy.ts","../../src/server/proxy/developer-hub-proxy.ts","../../src/server/webhooks/verify.ts","../../src/server/webhooks/handler.ts"],"sourcesContent":["// @timbenniks/contentstack-platform-sdk/server\n// Public barrel export — re-exports from all sub-modules\nexport * from \"./middleware/index.js\"\nexport * from \"./proxy/index.js\"\nexport * from \"./webhooks/index.js\"\n","/**\n * Base error class for all Contentstack SDK errors.\n * Every error includes an actionable message and relevant context.\n */\nexport class ContentstackError extends Error {\n  override readonly name: string = \"ContentstackError\"\n  readonly status?: number\n  readonly errorCode?: number\n  readonly errors?: Record<string, string[]>\n  readonly requestPath?: string\n\n  constructor(\n    message: string,\n    options?: {\n      status?: number\n      errorCode?: number\n      errors?: Record<string, string[]>\n      requestPath?: string\n      cause?: Error\n    },\n  ) {\n    super(message, options?.cause ? { cause: options.cause } : undefined)\n    this.status = options?.status\n    this.errorCode = options?.errorCode\n    this.errors = options?.errors\n    this.requestPath = options?.requestPath\n  }\n}\n\nexport class ContentstackAuthError extends ContentstackError {\n  override readonly name = \"ContentstackAuthError\"\n  override readonly status = 401\n}\n\nexport class ContentstackForbiddenError extends ContentstackError {\n  override readonly name = \"ContentstackForbiddenError\"\n  override readonly status = 403\n}\n\nexport class ContentstackNotFoundError extends ContentstackError {\n  override readonly name = \"ContentstackNotFoundError\"\n  override readonly status = 404\n}\n\nexport class ContentstackValidationError extends ContentstackError {\n  override readonly name = \"ContentstackValidationError\"\n  override readonly status: number\n\n  constructor(\n    message: string,\n    options?: {\n      status?: number\n      errorCode?: number\n      errors?: Record<string, string[]>\n      requestPath?: string\n      cause?: Error\n    },\n  ) {\n    super(message, options)\n    this.status = options?.status ?? 400\n  }\n}\n\nexport class ContentstackInvalidApiKeyError extends ContentstackError {\n  override readonly name = \"ContentstackInvalidApiKeyError\"\n  override readonly status = 412\n}\n\nexport class ContentstackRateLimitError extends ContentstackError {\n  override readonly name = \"ContentstackRateLimitError\"\n  override readonly status = 429\n  readonly retryAfter?: number\n\n  constructor(\n    message: string,\n    options?: {\n      errorCode?: number\n      errors?: Record<string, string[]>\n      requestPath?: string\n      cause?: Error\n      retryAfter?: number\n    },\n  ) {\n    super(message, { ...options, status: 429 })\n    this.retryAfter = options?.retryAfter\n  }\n}\n\nexport class ContentstackServerError extends ContentstackError {\n  override readonly name = \"ContentstackServerError\"\n}\n\nexport class ContentstackConfigError extends ContentstackError {\n  override readonly name = \"ContentstackConfigError\"\n}\n","import {\n  type ContentstackEndpoints as UpstreamEndpoints,\n  getContentstackEndpoints,\n  getRegionForString,\n} from \"@timbenniks/contentstack-endpoints\"\nimport type { ContentstackEndpoints, ContentstackRegion } from \"./resolver.js\"\n\n/** Brand Kit endpoints not available in upstream package — maintained locally */\nconst BRAND_KIT_URLS: Record<ContentstackRegion, { brandKit: string; brandKitAI: string }> = {\n  us: {\n    brandKit: \"https://brand-kits-api.contentstack.com\",\n    brandKitAI: \"https://ai.contentstack.com/brand-kits\",\n  },\n  eu: {\n    brandKit: \"https://eu-brand-kits-api.contentstack.com\",\n    brandKitAI: \"https://eu-ai.contentstack.com/brand-kits\",\n  },\n  au: {\n    brandKit: \"https://au-brand-kits-api.contentstack.com\",\n    brandKitAI: \"https://au-ai.contentstack.com/brand-kits\",\n  },\n  \"azure-na\": {\n    brandKit: \"https://azure-na-brand-kits-api.contentstack.com\",\n    brandKitAI: \"https://azure-na-ai.contentstack.com/brand-kits\",\n  },\n  \"azure-eu\": {\n    brandKit: \"https://azure-eu-brand-kits-api.contentstack.com\",\n    brandKitAI: \"https://azure-eu-ai.contentstack.com/brand-kits\",\n  },\n  \"gcp-na\": {\n    brandKit: \"https://gcp-na-brand-kits-api.contentstack.com\",\n    brandKitAI: \"https://gcp-na-ai.contentstack.com/brand-kits\",\n  },\n  \"gcp-eu\": {\n    brandKit: \"https://gcp-eu-brand-kits-api.contentstack.com\",\n    brandKitAI: \"https://gcp-eu-ai.contentstack.com/brand-kits\",\n  },\n}\n\nfunction mapEndpoints(\n  upstream: UpstreamEndpoints,\n  region: ContentstackRegion,\n  hostsOnly: boolean,\n): ContentstackEndpoints {\n  const bk = BRAND_KIT_URLS[region]\n  const stripProtocol = (url: string) => url.replace(/^https?:\\/\\//, \"\")\n\n  return Object.freeze({\n    cma: upstream.contentManagement ?? \"\",\n    cda: upstream.contentDelivery ?? \"\",\n    graphql: upstream.graphqlDelivery ?? \"\",\n    images: upstream.images ?? \"\",\n    app: upstream.application ?? \"\",\n    preview: upstream.preview ?? \"\",\n    graphqlPreview: upstream.graphqlPreview ?? \"\",\n    launch: upstream.launch ?? \"\",\n    personalizeEdge: upstream.personalizeEdge ?? \"\",\n    brandKit: hostsOnly ? stripProtocol(bk.brandKit) : bk.brandKit,\n    brandKitAI: hostsOnly ? stripProtocol(bk.brandKitAI) : bk.brandKitAI,\n    developerHub: hostsOnly\n      ? stripProtocol(upstream.developerHub ?? \"\")\n      : (upstream.developerHub ?? \"\"),\n  })\n}\n\nconst ALL_REGIONS: ContentstackRegion[] = [\n  \"us\",\n  \"eu\",\n  \"au\",\n  \"azure-na\",\n  \"azure-eu\",\n  \"gcp-na\",\n  \"gcp-eu\",\n]\n\nfunction buildEndpointMap(): Record<ContentstackRegion, ContentstackEndpoints> {\n  const map = {} as Record<ContentstackRegion, ContentstackEndpoints>\n  for (const region of ALL_REGIONS) {\n    map[region] = mapEndpoints(getContentstackEndpoints(region), region, false)\n  }\n  return Object.freeze(map)\n}\n\nfunction buildHostMap(): Record<ContentstackRegion, ContentstackEndpoints> {\n  const map = {} as Record<ContentstackRegion, ContentstackEndpoints>\n  for (const region of ALL_REGIONS) {\n    map[region] = mapEndpoints(getContentstackEndpoints(region, true), region, true)\n  }\n  return Object.freeze(map)\n}\n\nexport const ENDPOINT_MAP = buildEndpointMap()\nexport const HOST_MAP = buildHostMap()\n\n/** Check if a string is a valid region via the upstream package */\nexport function isValidRegion(input: string): boolean {\n  return getRegionForString(input) !== undefined\n}\n\n/** Map of extra aliases our SDK supports beyond what the upstream package handles */\nexport const EXTRA_ALIASES: Record<string, ContentstackRegion> = {\n  \"north-america\": \"us\",\n  europe: \"eu\",\n  australia: \"au\",\n}\n","import { ContentstackConfigError } from \"../http/errors.js\"\nimport { ENDPOINT_MAP, EXTRA_ALIASES, HOST_MAP, isValidRegion } from \"./endpoints.js\"\n\n/** All 7 Contentstack regions */\nexport type ContentstackRegion = \"us\" | \"eu\" | \"au\" | \"azure-na\" | \"azure-eu\" | \"gcp-na\" | \"gcp-eu\"\n\n/** Resolved endpoint URLs for a region */\nexport interface ContentstackEndpoints {\n  /** CMA base URL, e.g. \"https://api.contentstack.io\" */\n  cma: string\n  /** CDA REST base URL, e.g. \"https://cdn.contentstack.io\" */\n  cda: string\n  /** GraphQL CDA endpoint */\n  graphql: string\n  /** Asset/image delivery base URL */\n  images: string\n  /** Application URL (for OAuth), e.g. \"https://app.contentstack.com\" */\n  app: string\n  /** Preview API base URL */\n  preview: string\n  /** GraphQL preview endpoint */\n  graphqlPreview: string\n  /** Launch API base URL */\n  launch: string\n  /** Personalize edge endpoint */\n  personalizeEdge: string\n  /** Brand Kit Management API base URL */\n  brandKit: string\n  /** Brand Kit GenAI and Knowledge Vault base URL */\n  brandKitAI: string\n  /** Developer Hub (Marketplace) API base URL */\n  developerHub: string\n}\n\nconst VALID_REGIONS = new Set<string>(Object.keys(ENDPOINT_MAP))\n\n/**\n * Resolve all API endpoints for a Contentstack region.\n *\n * @example\n * ```ts\n * const endpoints = resolveEndpoints(\"eu\");\n * // endpoints.cma === \"https://eu-api.contentstack.com\"\n * // endpoints.app === \"https://eu-app.contentstack.com\"\n * ```\n */\nexport function resolveEndpoints(region: ContentstackRegion): ContentstackEndpoints {\n  return ENDPOINT_MAP[region]\n}\n\n/**\n * Resolve endpoints with https:// stripped (for SDK host parameters).\n *\n * @example\n * ```ts\n * const hosts = resolveHosts(\"eu\");\n * // hosts.cda === \"eu-cdn.contentstack.com\"\n * ```\n */\nexport function resolveHosts(region: ContentstackRegion): ContentstackEndpoints {\n  return HOST_MAP[region]\n}\n\n/**\n * Normalize region aliases: \"na\" → \"us\", \"NA\" → \"us\", etc.\n * Case-insensitive. Throws ContentstackConfigError for unknown regions.\n */\nexport function normalizeRegion(input: string): ContentstackRegion {\n  const lower = input.toLowerCase().trim()\n\n  if (VALID_REGIONS.has(lower)) {\n    return lower as ContentstackRegion\n  }\n\n  // Check extra aliases our SDK supports (north-america, europe, australia)\n  const extraAlias = EXTRA_ALIASES[lower]\n  if (extraAlias) {\n    return extraAlias\n  }\n\n  // Check aliases handled by the upstream package (na, us, aws-na, etc.)\n  if (isValidRegion(lower)) {\n    // The upstream package recognized it — map back to our canonical region\n    // \"na\" and \"us\" both map to the NA region which we call \"us\"\n    if (lower === \"na\" || lower === \"aws-na\" || lower === \"aws_na\") return \"us\"\n    if (lower === \"aws-eu\" || lower === \"aws_eu\") return \"eu\"\n    if (lower === \"aws-au\" || lower === \"aws_au\") return \"au\"\n    if (lower === \"azure_na\") return \"azure-na\"\n    if (lower === \"azure_eu\") return \"azure-eu\"\n    if (lower === \"gcp_na\") return \"gcp-na\"\n    if (lower === \"gcp_eu\") return \"gcp-eu\"\n  }\n\n  const validRegions = [...VALID_REGIONS].join(\", \")\n  const validAliases = [...Object.keys(EXTRA_ALIASES), \"na\", \"aws-na\", \"aws-eu\", \"aws-au\"].join(\n    \", \",\n  )\n  throw new ContentstackConfigError(\n    `Unknown region \"${input}\". Valid regions: ${validRegions}. Aliases: ${validAliases}.`,\n  )\n}\n\nexport { ContentstackConfigError }\n","import {\n  ContentstackAuthError,\n  ContentstackConfigError,\n  ContentstackError,\n  ContentstackForbiddenError,\n  ContentstackInvalidApiKeyError,\n  ContentstackNotFoundError,\n  ContentstackRateLimitError,\n  ContentstackServerError,\n  ContentstackValidationError,\n} from \"./errors.js\"\nimport type { HttpClientConfig, HttpResponse } from \"./types.js\"\n\nconst DEFAULT_TIMEOUT = 30_000\nconst DEFAULT_RETRY_LIMIT = 5\nconst DEFAULT_RETRY_DELAY = 300\nconst MAX_JITTER = 100\n\nexport class ContentstackHttpClient {\n  private readonly config: Required<\n    Pick<HttpClientConfig, \"baseUrl\" | \"timeout\" | \"retryOnError\" | \"retryLimit\" | \"retryDelay\">\n  > & {\n    headers: Record<string, string>\n    fetch: typeof globalThis.fetch\n    resolveHeaders?: HttpClientConfig[\"resolveHeaders\"]\n  }\n\n  constructor(config: HttpClientConfig) {\n    this.config = {\n      baseUrl: config.baseUrl,\n      headers: config.headers ?? {},\n      timeout: config.timeout ?? DEFAULT_TIMEOUT,\n      retryOnError: config.retryOnError ?? true,\n      retryLimit: config.retryLimit ?? DEFAULT_RETRY_LIMIT,\n      retryDelay: config.retryDelay ?? DEFAULT_RETRY_DELAY,\n      fetch: config.fetch ?? globalThis.fetch.bind(globalThis),\n      resolveHeaders: config.resolveHeaders,\n    }\n  }\n\n  async get<T>(path: string, params?: Record<string, string>): Promise<HttpResponse<T>> {\n    let url = `${this.config.baseUrl}${path}`\n    if (params) {\n      const searchParams = new URLSearchParams(params)\n      url += `?${searchParams.toString()}`\n    }\n    return this.request<T>(url, { method: \"GET\" }, path)\n  }\n\n  async post<T>(path: string, body?: unknown): Promise<HttpResponse<T>> {\n    const url = `${this.config.baseUrl}${path}`\n    return this.request<T>(\n      url,\n      {\n        method: \"POST\",\n        headers: { \"Content-Type\": \"application/json\" },\n        body: body !== undefined ? JSON.stringify(body) : undefined,\n      },\n      path,\n    )\n  }\n\n  async put<T>(path: string, body?: unknown): Promise<HttpResponse<T>> {\n    const url = `${this.config.baseUrl}${path}`\n    return this.request<T>(\n      url,\n      {\n        method: \"PUT\",\n        headers: { \"Content-Type\": \"application/json\" },\n        body: body !== undefined ? JSON.stringify(body) : undefined,\n      },\n      path,\n    )\n  }\n\n  async patch<T>(path: string, body?: unknown): Promise<HttpResponse<T>> {\n    const url = `${this.config.baseUrl}${path}`\n    return this.request<T>(\n      url,\n      {\n        method: \"PATCH\",\n        headers: { \"Content-Type\": \"application/json\" },\n        body: body !== undefined ? JSON.stringify(body) : undefined,\n      },\n      path,\n    )\n  }\n\n  async delete<T>(path: string): Promise<HttpResponse<T>> {\n    const url = `${this.config.baseUrl}${path}`\n    return this.request<T>(url, { method: \"DELETE\" }, path)\n  }\n\n  async postForm<T>(path: string, params: URLSearchParams): Promise<HttpResponse<T>> {\n    const url = `${this.config.baseUrl}${path}`\n    return this.request<T>(\n      url,\n      {\n        method: \"POST\",\n        headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n        body: params.toString(),\n      },\n      path,\n    )\n  }\n\n  async upload<T>(path: string, form: FormData): Promise<HttpResponse<T>> {\n    const url = `${this.config.baseUrl}${path}`\n    return this.request<T>(url, { method: \"POST\", body: form }, path)\n  }\n\n  /** Return a new client with additional headers merged */\n  withHeaders(headers: Record<string, string>): ContentstackHttpClient {\n    return new ContentstackHttpClient({\n      ...this.config,\n      headers: { ...this.config.headers, ...headers },\n    })\n  }\n\n  /** Return a new client with a different base URL */\n  withBaseUrl(baseUrl: string): ContentstackHttpClient {\n    return new ContentstackHttpClient({\n      ...this.config,\n      baseUrl,\n    })\n  }\n\n  private async request<T>(url: string, init: RequestInit, path: string): Promise<HttpResponse<T>> {\n    const headers = new Headers(this.config.headers)\n    const resolvedHeaders = await this.config.resolveHeaders?.()\n\n    if (resolvedHeaders) {\n      for (const [key, value] of Object.entries(resolvedHeaders)) {\n        headers.set(key, value)\n      }\n    }\n\n    if (init.headers) {\n      const initHeaders =\n        init.headers instanceof Headers\n          ? init.headers\n          : new Headers(init.headers as Record<string, string>)\n      initHeaders.forEach((value, key) => headers.set(key, value))\n    }\n\n    let lastError: Error | undefined\n    const maxAttempts = this.config.retryOnError ? this.config.retryLimit + 1 : 1\n\n    for (let attempt = 0; attempt < maxAttempts; attempt++) {\n      const controller = new AbortController()\n      const timeoutId = setTimeout(() => controller.abort(), this.config.timeout)\n\n      try {\n        const response = await this.config.fetch(url, {\n          ...init,\n          headers,\n          signal: controller.signal,\n        })\n\n        if (response.ok) {\n          const data = (await response.json().catch(() => ({}))) as T\n          return { data, status: response.status, headers: response.headers }\n        }\n\n        // Check if retryable\n        const isRetryable = response.status === 429 || response.status >= 500\n        if (isRetryable && this.config.retryOnError && attempt < maxAttempts - 1) {\n          const delay = this.calculateDelay(response, attempt)\n          await sleep(delay)\n          lastError = await this.createError(response, path)\n          continue\n        }\n\n        throw await this.createError(response, path)\n      } catch (error) {\n        if (error instanceof ContentstackError) {\n          throw error\n        }\n\n        if (error instanceof ContentstackConfigError) {\n          throw error\n        }\n\n        if (error instanceof DOMException && error.name === \"AbortError\") {\n          throw new ContentstackError(`Request timed out after ${this.config.timeout}ms`, {\n            requestPath: path,\n            cause: error,\n          })\n        }\n\n        throw new ContentstackError(\"Network request failed\", {\n          requestPath: path,\n          cause: error instanceof Error ? error : new Error(String(error)),\n        })\n      } finally {\n        clearTimeout(timeoutId)\n      }\n    }\n\n    // Should not reach here, but just in case\n    throw lastError ?? new ContentstackError(\"Request failed after retries\", { requestPath: path })\n  }\n\n  private calculateDelay(response: Response, attempt: number): number {\n    const retryAfter = response.headers.get(\"Retry-After\")\n    if (retryAfter) {\n      const seconds = Number.parseFloat(retryAfter)\n      if (!Number.isNaN(seconds)) {\n        return seconds * 1000\n      }\n    }\n\n    const jitter = Math.random() * MAX_JITTER\n    return this.config.retryDelay * 2 ** attempt + jitter\n  }\n\n  private async createError(response: Response, path: string): Promise<ContentstackError> {\n    let body: Record<string, unknown> = {}\n    try {\n      body = (await response.json()) as Record<string, unknown>\n    } catch {\n      // Response body may not be JSON\n    }\n\n    const message =\n      (body.error_message as string | undefined) ??\n      (body.error_description as string | undefined) ??\n      (body.message as string | undefined) ??\n      `HTTP ${response.status} error`\n    const errorCode = body.error_code as number | undefined\n    const errors = body.errors as Record<string, string[]> | undefined\n    const retryAfter = response.headers.get(\"Retry-After\")\n\n    const opts = { status: response.status, errorCode, errors, requestPath: path }\n\n    switch (response.status) {\n      case 400:\n        return new ContentstackValidationError(message, { ...opts, status: 400 })\n      case 401:\n        return new ContentstackAuthError(message, opts)\n      case 403:\n        return new ContentstackForbiddenError(message, opts)\n      case 404:\n        return new ContentstackNotFoundError(message, opts)\n      case 412:\n        return new ContentstackInvalidApiKeyError(message, opts)\n      case 422:\n        return new ContentstackValidationError(message, { ...opts, status: 422 })\n      case 429:\n        return new ContentstackRateLimitError(message, {\n          ...opts,\n          retryAfter: retryAfter ? Number.parseFloat(retryAfter) : undefined,\n        })\n      default:\n        if (response.status >= 500) {\n          return new ContentstackServerError(message, opts)\n        }\n        return new ContentstackError(message, opts)\n    }\n  }\n}\n\nfunction sleep(ms: number): Promise<void> {\n  return new Promise((resolve) => setTimeout(resolve, ms))\n}\n","import { ContentstackHttpClient } from \"../http/client.js\"\nimport {\n  ContentstackAuthError,\n  ContentstackConfigError,\n  ContentstackError,\n} from \"../http/errors.js\"\nimport type { ContentstackRegion } from \"../regions/index.js\"\nimport { resolveEndpoints } from \"../regions/index.js\"\nimport { generateCodeChallenge, generateCodeVerifier } from \"./pkce.js\"\nimport type { AuthHttpOptions, ContentstackUser, OAuthConfig, OAuthTokens } from \"./types.js\"\n\ninterface AuthorizationUrlOptions {\n  state?: string\n  usePKCE?: boolean\n}\n\ninterface AuthorizationUrlResult {\n  url: string\n  state: string\n  codeVerifier?: string\n}\n\ninterface ExchangeCodeOptions {\n  codeVerifier?: string\n  httpOptions?: AuthHttpOptions\n}\n\nfunction validateConfig(config: OAuthConfig): void {\n  if (!config.appId) {\n    throw new ContentstackConfigError(\n      \"appId is required for OAuth. This is your Contentstack app's UID, not the client ID.\",\n    )\n  }\n  if (config.appId === config.clientId) {\n    throw new ContentstackConfigError(\n      \"appId and clientId must be different. appId is your Contentstack app UID; clientId is the OAuth client identifier.\",\n    )\n  }\n}\n\n/**\n * Build a Contentstack OAuth authorization URL.\n *\n * @example\n * ```ts\n * const { url, state, codeVerifier } = await buildAuthorizationUrl({\n *   region: \"us\",\n *   appId: \"app-uid\",\n *   clientId: \"client-id\",\n *   clientSecret: \"secret\",\n *   scopes: [\"user:read\"],\n *   redirectUri: \"http://localhost:3000/api/auth/callback/contentstack\",\n * }, { usePKCE: true })\n * ```\n */\nexport async function buildAuthorizationUrl(\n  config: OAuthConfig,\n  options?: AuthorizationUrlOptions,\n): Promise<AuthorizationUrlResult> {\n  validateConfig(config)\n\n  const endpoints = resolveEndpoints(config.region)\n  const authorizationUrl = `${endpoints.app}/apps/${config.appId}/authorize`\n\n  const state = options?.state ?? generateCodeVerifier()\n\n  const params = new URLSearchParams({\n    response_type: \"code\",\n    client_id: config.clientId,\n    redirect_uri: config.redirectUri,\n    scope: config.scopes.join(\" \"),\n    state,\n  })\n\n  let codeVerifier: string | undefined\n  if (options?.usePKCE) {\n    codeVerifier = generateCodeVerifier()\n    const codeChallenge = await generateCodeChallenge(codeVerifier)\n    params.set(\"code_challenge\", codeChallenge)\n    params.set(\"code_challenge_method\", \"S256\")\n  }\n\n  return {\n    url: `${authorizationUrl}?${params.toString()}`,\n    state,\n    codeVerifier,\n  }\n}\n\nfunction mapTokenResponse(data: Record<string, unknown>): OAuthTokens {\n  return {\n    accessToken: data.access_token as string,\n    refreshToken: (data.refresh_token as string | undefined) ?? \"\",\n    expiresIn: data.expires_in as number,\n    tokenType: data.token_type as string,\n  }\n}\n\nasync function makeTokenRequest(\n  appBaseUrl: string,\n  body: URLSearchParams,\n  errorMessage: string,\n  httpOptions?: AuthHttpOptions,\n): Promise<OAuthTokens> {\n  const client = new ContentstackHttpClient({ ...httpOptions, baseUrl: appBaseUrl })\n  try {\n    const { data } = await client.postForm<Record<string, unknown>>(\"/apps-api/token\", body)\n    return mapTokenResponse(data)\n  } catch (err) {\n    if (err instanceof ContentstackError) {\n      throw new ContentstackAuthError(err.message || errorMessage, {\n        status: err.status,\n        requestPath: \"/apps-api/token\",\n        cause: err,\n      })\n    }\n    throw new ContentstackAuthError(errorMessage, {\n      requestPath: \"/apps-api/token\",\n      cause: err instanceof Error ? err : undefined,\n    })\n  }\n}\n\n/**\n * Exchange an authorization code for OAuth tokens.\n */\nexport async function exchangeCode(\n  config: OAuthConfig,\n  code: string,\n  options?: ExchangeCodeOptions,\n): Promise<OAuthTokens> {\n  const endpoints = resolveEndpoints(config.region)\n\n  const body = new URLSearchParams({\n    grant_type: \"authorization_code\",\n    code,\n    redirect_uri: config.redirectUri,\n    client_id: config.clientId,\n    client_secret: config.clientSecret,\n  })\n\n  if (options?.codeVerifier) {\n    body.set(\"code_verifier\", options.codeVerifier)\n  }\n\n  return makeTokenRequest(\n    endpoints.app,\n    body,\n    \"Failed to exchange authorization code\",\n    options?.httpOptions,\n  )\n}\n\n/**\n * Refresh an expired access token using a refresh token.\n */\nexport async function refreshToken(\n  config: OAuthConfig,\n  token: string,\n  options?: { httpOptions?: AuthHttpOptions },\n): Promise<OAuthTokens> {\n  const endpoints = resolveEndpoints(config.region)\n\n  const body = new URLSearchParams({\n    grant_type: \"refresh_token\",\n    refresh_token: token,\n    client_id: config.clientId,\n    client_secret: config.clientSecret,\n  })\n\n  return makeTokenRequest(endpoints.app, body, \"Failed to refresh token\", options?.httpOptions)\n}\n\nexport interface AppTokenCredentials {\n  clientId: string\n  clientSecret: string\n}\n\n/**\n * Obtain an app token (client credentials grant) for machine-to-machine integrations.\n * Requires the app's `app_token_config` to be enabled with the needed scopes.\n */\nexport async function exchangeAppToken(\n  region: ContentstackRegion,\n  credentials: AppTokenCredentials,\n  options?: { httpOptions?: AuthHttpOptions },\n): Promise<OAuthTokens> {\n  const endpoints = resolveEndpoints(region)\n\n  const body = new URLSearchParams({\n    grant_type: \"client_credentials\",\n    client_id: credentials.clientId,\n    client_secret: credentials.clientSecret,\n  })\n\n  return makeTokenRequest(endpoints.app, body, \"Failed to obtain app token\", options?.httpOptions)\n}\n\nfunction mapUser(user: Record<string, unknown>): ContentstackUser {\n  return {\n    uid: user.uid as string,\n    email: user.email as string,\n    firstName: (user.first_name as string) ?? undefined,\n    lastName: (user.last_name as string) ?? undefined,\n    username: (user.username as string) ?? undefined,\n    profileImage: (user.profile_image as string) ?? undefined,\n  }\n}\n\n/**\n * Fetch the authenticated user's profile from Contentstack.\n * Unwraps the nested `user` key and maps snake_case → camelCase.\n */\nexport async function getUser(\n  region: ContentstackRegion,\n  accessToken: string,\n  options?: { httpOptions?: AuthHttpOptions },\n): Promise<ContentstackUser> {\n  const endpoints = resolveEndpoints(region)\n  const client = new ContentstackHttpClient({\n    ...options?.httpOptions,\n    baseUrl: `${endpoints.cma}/v3`,\n    headers: { Authorization: `Bearer ${accessToken}` },\n  })\n\n  try {\n    const { data } = await client.get<{ user: Record<string, unknown> }>(\"/user\")\n    return mapUser(data.user)\n  } catch (err) {\n    if (err instanceof ContentstackError) {\n      throw new ContentstackAuthError(err.message || \"Failed to fetch user profile\", {\n        status: err.status,\n        requestPath: \"/v3/user\",\n        cause: err,\n      })\n    }\n    throw new ContentstackAuthError(\"Failed to fetch user profile\", {\n      requestPath: \"/v3/user\",\n      cause: err instanceof Error ? err : undefined,\n    })\n  }\n}\n\n/**\n * Create an Auth.js v5 provider config object for Contentstack.\n *\n * No Auth.js dependency is required in this package — the returned object\n * conforms to the Auth.js OAuthConfig shape and can be passed directly to\n * `next-auth` or `@auth/core`.\n *\n * @example\n * ```ts\n * // app/api/auth/[...nextauth]/route.ts\n * import NextAuth from \"next-auth\"\n * import { createAuthProvider } from \"@timbenniks/contentstack-platform-sdk/auth\"\n *\n * export const { handlers, signIn, signOut, auth } = NextAuth({\n *   providers: [createAuthProvider({ region: \"us\", appId: \"...\", ... })],\n * })\n * ```\n */\nexport function createAuthProvider(config: OAuthConfig): Record<string, unknown> {\n  validateConfig(config)\n\n  const endpoints = resolveEndpoints(config.region)\n  const userClient = new ContentstackHttpClient({ baseUrl: `${endpoints.cma}/v3` })\n\n  return {\n    id: \"contentstack\",\n    name: \"Contentstack\",\n    type: \"oauth\",\n    checks: [\"state\"],\n    authorization: {\n      url: `${endpoints.app}/apps/${config.appId}/authorize`,\n      params: {\n        response_type: \"code\",\n        scope: config.scopes.join(\" \"),\n      },\n    },\n    token: `${endpoints.app}/apps-api/token`,\n    userinfo: {\n      url: `${endpoints.cma}/v3/user`,\n      async request({ tokens }: { tokens: { access_token: string } }) {\n        const authedClient = userClient.withHeaders({\n          Authorization: `Bearer ${tokens.access_token}`,\n        })\n        const { data } = await authedClient.get<Record<string, unknown>>(\"/user\")\n        return data\n      },\n    },\n    profile(profile: { user: Record<string, unknown> }) {\n      const user = profile.user\n      return {\n        id: user.uid as string,\n        name:\n          [user.first_name, user.last_name].filter(Boolean).join(\" \") || (user.username as string),\n        email: user.email as string,\n        image: (user.profile_image as string) ?? null,\n      }\n    },\n    clientId: config.clientId,\n    clientSecret: config.clientSecret,\n  }\n}\n\n/**\n * Create Auth.js v5 callbacks for token persistence and automatic refresh.\n *\n * The `jwt` callback persists OAuth tokens on initial sign-in and attempts\n * to refresh expired tokens (with a 60-second safety window).\n *\n * The `session` callback exposes the access token and any refresh errors\n * on the session object.\n *\n * @example\n * ```ts\n * import NextAuth from \"next-auth\"\n * import { createAuthProvider, contentstackAuthCallbacks } from \"@timbenniks/contentstack-platform-sdk/auth\"\n *\n * export const { handlers, auth } = NextAuth({\n *   providers: [createAuthProvider({ ... })],\n *   callbacks: contentstackAuthCallbacks({ region: \"us\", ... }),\n * })\n * ```\n */\nexport function contentstackAuthCallbacks(config: OAuthConfig) {\n  return {\n    async jwt({\n      token,\n      account,\n    }: { token: Record<string, unknown>; account?: Record<string, unknown> | null }) {\n      // Initial sign-in: persist tokens from the OAuth account\n      if (account) {\n        token.accessToken = account.access_token\n        token.refreshToken = account.refresh_token\n        token.accessTokenExpiresAt = Date.now() + ((account.expires_in as number) ?? 3600) * 1000\n        return token\n      }\n\n      // Subsequent calls: check if token needs refresh (60s safety window)\n      const expiresAt = token.accessTokenExpiresAt as number | undefined\n      if (expiresAt && Date.now() < expiresAt - 60_000) {\n        return token\n      }\n\n      // Token is expired or about to expire — attempt refresh\n      const currentRefreshToken = token.refreshToken as string | undefined\n      if (!currentRefreshToken) {\n        token.error = \"RefreshAccessTokenError\"\n        return token\n      }\n\n      try {\n        const tokens = await refreshToken(config, currentRefreshToken)\n        token.accessToken = tokens.accessToken\n        token.refreshToken = tokens.refreshToken\n        token.accessTokenExpiresAt = Date.now() + tokens.expiresIn * 1000\n        token.error = undefined\n      } catch {\n        token.error = \"RefreshAccessTokenError\"\n      }\n\n      return token\n    },\n    async session({\n      session,\n      token,\n    }: { session: Record<string, unknown>; token: Record<string, unknown> }) {\n      session.accessToken = token.accessToken\n      if (token.error) {\n        session.error = token.error\n      }\n      return session\n    },\n  }\n}\n","import { contentstackAuthCallbacks, createAuthProvider, getUser } from \"../../index.js\"\nimport type { OAuthMiddlewareConfig } from \"./types.js\"\n\n/**\n * Create a complete Auth.js v5 (NextAuth) configuration for Contentstack OAuth.\n *\n * This wraps NextAuth with all Contentstack-specific config baked in, reducing\n * ~150 lines of Auth.js configuration down to ~10 lines.\n *\n * Requires `next-auth@>=5.0.0-beta.0` as an installed peer dependency.\n *\n * @example\n * ```ts\n * import { createContentstackAuth } from \"@timbenniks/contentstack-platform-sdk/server/middleware\"\n *\n * const { handlers, auth, signIn, signOut } = await createContentstackAuth({\n *   region: \"us\",\n *   appId: \"your-app-uid\",\n *   clientId: \"your-client-id\",\n *   clientSecret: \"your-client-secret\",\n *   scopes: [\"user:read\"],\n *   secret: process.env.AUTH_SECRET!,\n * })\n *\n * // app/api/auth/[...nextauth]/route.ts\n * export const { GET, POST } = handlers\n * ```\n */\nexport async function createContentstackAuth(config: OAuthMiddlewareConfig) {\n  // Dynamic import — next-auth is an optional peer dependency.\n  // This prevents module resolution errors when importing the middleware\n  // module in environments where next-auth is not installed.\n  const { default: NextAuth } = await import(\"next-auth\")\n\n  const oauthConfig = {\n    region: config.region,\n    appId: config.appId,\n    clientId: config.clientId,\n    clientSecret: config.clientSecret,\n    scopes: config.scopes,\n    redirectUri: config.redirectUri ?? \"auto\",\n  }\n\n  const provider = createAuthProvider(oauthConfig)\n  const baseCallbacks = contentstackAuthCallbacks(oauthConfig)\n\n  const callbacks = {\n    async jwt(params: {\n      token: Record<string, unknown>\n      account?: Record<string, unknown> | null\n    }) {\n      const token = await baseCallbacks.jwt(params)\n\n      // Call onSignIn on initial sign-in (account is only present once)\n      if (params.account && config.onSignIn) {\n        try {\n          const user = await getUser(config.region, token.accessToken as string)\n          const tokens = {\n            accessToken: token.accessToken as string,\n            refreshToken: token.refreshToken as string,\n            expiresIn: Math.floor(((token.accessTokenExpiresAt as number) - Date.now()) / 1000),\n            tokenType: \"Bearer\",\n          }\n          await config.onSignIn(user, tokens)\n        } catch {\n          // onSignIn errors should not block authentication\n        }\n      }\n\n      return token\n    },\n    session: baseCallbacks.session,\n  }\n\n  // The core package returns generic `Record<string, unknown>` for framework\n  // independence. Cast to `never` at the NextAuth boundary — the shape is\n  // guaranteed correct by createAuthProvider/contentstackAuthCallbacks.\n  return NextAuth({\n    providers: [provider as never],\n    callbacks: callbacks as never,\n    secret: config.secret,\n    logger: config.logger,\n    trustHost: config.trustHost ?? true,\n    session: { strategy: \"jwt\" as const },\n    pages: {\n      signIn: config.signInPage ?? \"/login\",\n      error: config.errorPage ?? \"/login\",\n    },\n  })\n}\n","import { ContentstackAuthError } from \"../../index.js\"\nimport type { AuthFn, ContentstackSession } from \"./types.js\"\n\n/**\n * Get the current Contentstack session.\n *\n * @param authFn - Framework-agnostic auth function (e.g., the `auth()` function from NextAuth)\n * @returns The session with `accessToken`, or `null` if unauthenticated.\n */\nexport async function getSession(authFn: AuthFn): Promise<ContentstackSession | null> {\n  const session = await authFn()\n  if (!session?.accessToken) return null\n  return { accessToken: session.accessToken, user: session.user }\n}\n\n/**\n * Require an authenticated Contentstack session.\n * Throws `ContentstackAuthError` if no session or no access token is present.\n *\n * @param authFn - Framework-agnostic auth function\n * @param redirectTo - Optional redirect path included in the error for the caller to use\n * @returns The session with a guaranteed `accessToken`.\n */\nexport async function requireSession(\n  authFn: AuthFn,\n  redirectTo?: string,\n): Promise<ContentstackSession> {\n  const session = await getSession(authFn)\n  if (!session) {\n    throw new ContentstackAuthError(\n      redirectTo\n        ? `Authentication required. Redirect to: ${redirectTo}`\n        : \"Authentication required\",\n      { status: 401 },\n    )\n  }\n  return session\n}\n\n/**\n * Get the OAuth access token from the current session.\n *\n * @param authFn - Framework-agnostic auth function\n * @returns The access token string, or `null` if unauthenticated.\n */\nexport async function getAccessToken(authFn: AuthFn): Promise<string | null> {\n  const session = await authFn()\n  return session?.accessToken ?? null\n}\n","import type { ProxyAuthConfig, ProxyAuthHeaders } from \"./types.js\"\n\n/**\n * Shared proxy infrastructure for Contentstack API proxies.\n *\n * Both the CMA proxy and Launch proxy build on these helpers to avoid\n * duplicating auth checks, URL parsing, body extraction, and fetch logic.\n */\n\nexport type BaseProxyConfig = ProxyAuthConfig & {\n  basePath: string\n  timeout: number\n}\n\nexport interface ProxyRequestContext {\n  authHeaders: ProxyAuthHeaders\n  authKey: string\n  apiPath: string\n  search: string\n  method: string\n  body: ArrayBuffer | undefined\n  request: Request\n}\n\n/** Return a JSON error response with the given message and HTTP status. */\nexport function jsonErrorResponse(error: string, status: number): Response {\n  return new Response(JSON.stringify({ error }), {\n    status,\n    headers: { \"Content-Type\": \"application/json\" },\n  })\n}\n\nfunction normalizeAuthHeaders(headers: ProxyAuthHeaders): ProxyAuthHeaders {\n  return Object.fromEntries(\n    Object.entries(headers)\n      .map(([key, value]) => [key.toLowerCase(), value.trim()] as const)\n      .filter(([, value]) => value.length > 0),\n  )\n}\n\nfunction resolveAuthKey(headers: ProxyAuthHeaders): string | null {\n  const authorization = headers.authorization\n  if (authorization) {\n    return authorization\n  }\n\n  const authtoken = headers.authtoken\n  if (authtoken) {\n    return authtoken\n  }\n\n  const serialized = Object.entries(headers)\n    .sort(([left], [right]) => left.localeCompare(right))\n    .map(([key, value]) => `${key}:${value}`)\n    .join(\"|\")\n\n  return serialized.length > 0 ? serialized : null\n}\n\nasync function resolveRequestAuth(\n  config: BaseProxyConfig,\n  request: Request,\n): Promise<{ authHeaders: ProxyAuthHeaders; authKey: string } | null> {\n  if (config.getAuthHeaders) {\n    const authHeaders = normalizeAuthHeaders((await config.getAuthHeaders(request)) ?? {})\n    const authKey = resolveAuthKey(authHeaders)\n\n    if (!authKey) {\n      return null\n    }\n\n    return { authHeaders, authKey }\n  }\n\n  if (config.getAccessToken) {\n    const token = await config.getAccessToken(request)\n    if (!token) {\n      return null\n    }\n\n    return {\n      authHeaders: { authorization: `Bearer ${token}` },\n      authKey: token,\n    }\n  }\n\n  return null\n}\n\n/**\n * Create the shared proxy pipeline: auth check → URL parse → body extract.\n *\n * The `handleRequest` callback receives a validated context and is responsible\n * for building headers, constructing the target URL, and forwarding the request.\n */\nexport function createBaseProxy(\n  config: BaseProxyConfig,\n  handleRequest: (ctx: ProxyRequestContext) => Promise<Response>,\n): (request: Request) => Promise<Response> {\n  return async (request: Request): Promise<Response> => {\n    const auth = await resolveRequestAuth(config, request)\n    if (!auth) {\n      return jsonErrorResponse(\"Unauthorized\", 401)\n    }\n\n    const url = new URL(request.url)\n    const apiPath = url.pathname.replace(config.basePath, \"\")\n\n    const body =\n      [\"GET\", \"HEAD\"].includes(request.method) || request.body === null\n        ? undefined\n        : await request.arrayBuffer()\n\n    return handleRequest({\n      authHeaders: auth.authHeaders,\n      authKey: auth.authKey,\n      apiPath,\n      search: url.search,\n      method: request.method,\n      body,\n      request,\n    })\n  }\n}\n\n/**\n * Forward a request to an upstream API and stream the response back.\n *\n * Returns a 502 \"Bad Gateway\" response on any fetch failure (network error, timeout).\n */\nexport async function forwardRequest(\n  url: string,\n  method: string,\n  headers: Record<string, string>,\n  body: ArrayBuffer | undefined,\n  timeout: number,\n): Promise<Response> {\n  try {\n    const upstream = await fetch(url, {\n      method,\n      headers,\n      body,\n      signal: AbortSignal.timeout(timeout),\n    })\n\n    return new Response(upstream.body, {\n      status: upstream.status,\n      headers: {\n        \"content-type\": upstream.headers.get(\"content-type\") ?? \"application/json\",\n      },\n    })\n  } catch {\n    return jsonErrorResponse(\"Bad Gateway\", 502)\n  }\n}\n","interface RateWindow {\n  count: number\n  windowStart: number\n}\n\n/**\n * Create a simple in-memory sliding window rate limiter.\n *\n * Each unique key (typically an access token) gets its own counter\n * that resets after the window expires.\n *\n * @param maxRequests - Maximum requests allowed per window\n * @param windowMs - Window duration in milliseconds (default: 60000)\n */\nexport function createRateLimiter(maxRequests: number, windowMs = 60_000) {\n  const windows = new Map<string, RateWindow>()\n\n  return {\n    /**\n     * Check if the request is within rate limits.\n     * @returns `true` if the request is allowed, `false` if rate limited.\n     */\n    check(key: string): boolean {\n      const now = Date.now()\n      const window = windows.get(key)\n\n      // Clean stale entries on each check\n      for (const [k, w] of windows) {\n        if (now - w.windowStart > windowMs) {\n          windows.delete(k)\n        }\n      }\n\n      if (!window || now - window.windowStart > windowMs) {\n        windows.set(key, { count: 1, windowStart: now })\n        return true\n      }\n\n      window.count++\n      return window.count <= maxRequests\n    },\n  }\n}\n","import type { CMAScope } from \"./types.js\"\n\nconst READ_METHODS = new Set([\"GET\", \"HEAD\"])\n\n/**\n * Resolve the required CMA scope for a given HTTP method and path.\n *\n * Path matching checks for known segments. The order matters:\n * `/entries` is checked before `/content_types` because entry URLs\n * like `/content_types/blog/entries` contain both.\n *\n * @returns The required scope, or `null` if the path is unrecognized.\n */\nexport function resolveScope(method: string, path: string): CMAScope | null {\n  const isRead = READ_METHODS.has(method.toUpperCase())\n  const suffix = isRead ? \":read\" : \":write\"\n  const segments = path.split(\"/\")\n\n  if (segments.includes(\"entries\")) return `entries${suffix}` as CMAScope\n  if (segments.includes(\"content_types\")) return `content-types${suffix}` as CMAScope\n  if (segments.includes(\"assets\")) return `assets${suffix}` as CMAScope\n  if (segments.includes(\"environments\")) return \"environments:read\"\n  if (segments.includes(\"locales\")) return \"locales:read\"\n  if (segments.includes(\"releases\")) return `releases${suffix}` as CMAScope\n  if (segments.includes(\"taxonomies\")) return `taxonomies${suffix}` as CMAScope\n  if (segments.includes(\"workflows\")) return `workflows${suffix}` as CMAScope\n  if (segments.includes(\"webhooks\")) return `webhooks${suffix}` as CMAScope\n\n  return null\n}\n\n/**\n * Check whether a required scope is present in the allowed scopes list.\n *\n * @returns An error message if the scope is not allowed, or `null` if permitted.\n */\nexport function checkScope(required: CMAScope, allowed: CMAScope[]): string | null {\n  if (allowed.includes(required)) return null\n  return `Scope \"${required}\" is not allowed. Allowed scopes: ${allowed.join(\", \")}`\n}\n","import { resolveEndpoints } from \"../../index.js\"\nimport { createBaseProxy, forwardRequest, jsonErrorResponse } from \"./proxy-base.js\"\nimport { createRateLimiter } from \"./rate-limiter.js\"\nimport { checkScope, resolveScope } from \"./scope-guard.js\"\nimport type { CMAProxyConfig } from \"./types.js\"\n\n/**\n * Create a CMA proxy handler that forwards requests to Contentstack.\n *\n * The returned function accepts a standard `Request` and returns a `Response`,\n * making it compatible with Next.js route handlers, Deno/Bun servers, and\n * any framework that uses the Web API Request/Response model.\n *\n * @example\n * ```ts\n * // app/api/cma/[...path]/route.ts\n * const proxy = createCMAProxy({\n *   region: \"us\",\n *   apiKey: \"your-api-key\",\n *   getAccessToken: async (req) => {\n *     const session = await auth()\n *     return session?.accessToken ?? null\n *   },\n * })\n *\n * export const GET = proxy\n * export const POST = proxy\n * export const PUT = proxy\n * export const DELETE = proxy\n * ```\n */\nexport function createCMAProxy(config: CMAProxyConfig): (request: Request) => Promise<Response> {\n  const endpoints = resolveEndpoints(config.region)\n  const cmaBase = `${endpoints.cma}/v3`\n  const timeout = config.timeout ?? 30_000\n  const rateLimiter = config.rateLimit ? createRateLimiter(config.rateLimit) : null\n\n  return createBaseProxy(\n    {\n      ...(config.getAuthHeaders\n        ? { getAuthHeaders: config.getAuthHeaders }\n        : { getAccessToken: config.getAccessToken }),\n      basePath: config.basePath ?? \"/api/cma\",\n      timeout,\n    },\n    async (ctx) => {\n      if (rateLimiter && !rateLimiter.check(ctx.authKey)) {\n        return jsonErrorResponse(\"Too Many Requests\", 429)\n      }\n\n      if (config.allowedScopes) {\n        const scope = resolveScope(ctx.method, ctx.apiPath)\n        if (!scope) {\n          if ((config.unmappedScopeBehavior ?? \"deny\") === \"deny\") {\n            return jsonErrorResponse(\n              `No scope mapping found for \"${ctx.method} ${ctx.apiPath}\". Add a mapping or set unmappedScopeBehavior: \"allow\".`,\n              403,\n            )\n          }\n        } else {\n          const rejection = checkScope(scope, config.allowedScopes)\n          if (rejection) {\n            return jsonErrorResponse(rejection, 403)\n          }\n        }\n      }\n\n      const headers: Record<string, string> = {\n        api_key: config.apiKey,\n        ...ctx.authHeaders,\n      }\n      const contentType = ctx.request.headers.get(\"content-type\")\n      if (contentType) {\n        headers[\"content-type\"] = contentType\n      }\n\n      return forwardRequest(\n        cmaBase + ctx.apiPath + ctx.search,\n        ctx.method,\n        headers,\n        ctx.body,\n        timeout,\n      )\n    },\n  )\n}\n","import { resolveEndpoints } from \"../../index.js\"\nimport type { ContentstackRegion } from \"../../index.js\"\nimport { createBaseProxy, forwardRequest, jsonErrorResponse } from \"./proxy-base.js\"\nimport type { ProxyAuthConfig } from \"./types.js\"\n\nexport type LaunchProxyConfig = ProxyAuthConfig & {\n  /** Contentstack region */\n  region: ContentstackRegion\n  /** Organization UID — required for all Launch API calls */\n  organizationUid: string\n  /** URL prefix to strip when extracting the Launch API path (default: \"/api/launch\") */\n  basePath?: string\n  /** Restrict operations: \"read\" allows GET only, \"manage\" allows all methods */\n  allowedOperations?: (\"read\" | \"manage\")[]\n  /** Request timeout in milliseconds (default: 30000) */\n  timeout?: number\n}\n\n/**\n * Create a Launch API proxy handler that forwards requests to Contentstack Launch.\n *\n * The returned function accepts a standard `Request` and returns a `Response`,\n * making it compatible with Next.js route handlers, Deno/Bun servers, and\n * any framework that uses the Web API Request/Response model.\n *\n * @example\n * ```ts\n * // app/api/launch/[...path]/route.ts\n * const proxy = createLaunchProxy({\n *   region: \"us\",\n *   organizationUid: \"org-uid\",\n *   getAccessToken: async () => {\n *     const session = await auth()\n *     return session?.accessToken ?? null\n *   },\n * })\n *\n * export const GET = proxy\n * export const POST = proxy\n * export const PUT = proxy\n * export const DELETE = proxy\n * ```\n */\nexport function createLaunchProxy(\n  config: LaunchProxyConfig,\n): (request: Request) => Promise<Response> {\n  const endpoints = resolveEndpoints(config.region)\n  const launchBase = endpoints.launch\n  const timeout = config.timeout ?? 30_000\n\n  return createBaseProxy(\n    {\n      ...(config.getAuthHeaders\n        ? { getAuthHeaders: config.getAuthHeaders }\n        : { getAccessToken: config.getAccessToken }),\n      basePath: config.basePath ?? \"/api/launch\",\n      timeout,\n    },\n    async (ctx) => {\n      if (config.allowedOperations?.length) {\n        const hasManage = config.allowedOperations.includes(\"manage\")\n        if (!hasManage && ![\"GET\", \"HEAD\"].includes(ctx.method)) {\n          return jsonErrorResponse(\"Forbidden: read-only mode\", 403)\n        }\n      }\n\n      const headers: Record<string, string> = {\n        ...ctx.authHeaders,\n        organization_uid: config.organizationUid,\n        \"content-type\": \"application/json\",\n      }\n\n      return forwardRequest(\n        launchBase + ctx.apiPath + ctx.search,\n        ctx.method,\n        headers,\n        ctx.body,\n        timeout,\n      )\n    },\n  )\n}\n","import { resolveEndpoints } from \"../../index.js\"\nimport type { ContentstackRegion } from \"../../index.js\"\nimport { createBaseProxy, forwardRequest, jsonErrorResponse } from \"./proxy-base.js\"\nimport type { ProxyAuthConfig } from \"./types.js\"\n\nexport type BrandKitProxyConfig = ProxyAuthConfig & {\n  /** Contentstack region */\n  region: ContentstackRegion\n  /** Organization UID — required for all Brand Kit API calls */\n  organizationUid: string\n  /** Brand Kit UID — required for all Brand Kit API calls */\n  brandKitUid: string\n  /** URL prefix to strip when extracting the API path (default: \"/api/brandkit\") */\n  basePath?: string\n  /** Restrict operations: \"read\" allows GET only, \"manage\" allows all methods */\n  allowedOperations?: (\"read\" | \"manage\")[]\n  /** Request timeout in milliseconds (default: 30000) */\n  timeout?: number\n}\n\n/**\n * Create a Brand Kit proxy handler that forwards requests to Contentstack\n * Brand Kit Management, Knowledge Vault, and Generative AI APIs.\n *\n * Routes are determined by path:\n * - Paths containing `/knowledge-vault` or `/generative-ai` → brandKitAI base URL\n * - All other paths (brand kits, voice profiles) → brandKit base URL\n *\n * @example\n * ```ts\n * // app/api/brandkit/[...path]/route.ts\n * const proxy = createBrandKitProxy({\n *   region: \"us\",\n *   organizationUid: \"org-uid\",\n *   brandKitUid: \"bk-uid\",\n *   getAccessToken: async () => {\n *     const session = await auth()\n *     return session?.accessToken ?? null\n *   },\n * })\n *\n * export const GET = proxy\n * export const POST = proxy\n * export const PUT = proxy\n * export const DELETE = proxy\n * ```\n */\nexport function createBrandKitProxy(\n  config: BrandKitProxyConfig,\n): (request: Request) => Promise<Response> {\n  const endpoints = resolveEndpoints(config.region)\n  const brandKitBase = endpoints.brandKit\n  const brandKitAIBase = endpoints.brandKitAI\n  const timeout = config.timeout ?? 30_000\n\n  return createBaseProxy(\n    {\n      ...(config.getAuthHeaders\n        ? { getAuthHeaders: config.getAuthHeaders }\n        : { getAccessToken: config.getAccessToken }),\n      basePath: config.basePath ?? \"/api/brandkit\",\n      timeout,\n    },\n    async (ctx) => {\n      if (config.allowedOperations?.length) {\n        const hasManage = config.allowedOperations.includes(\"manage\")\n        if (!hasManage && ![\"GET\", \"HEAD\"].includes(ctx.method)) {\n          return jsonErrorResponse(\"Forbidden: read-only mode\", 403)\n        }\n      }\n\n      const headers: Record<string, string> = {\n        ...ctx.authHeaders,\n        organization_uid: config.organizationUid,\n        brand_kit_uid: config.brandKitUid,\n        \"content-type\": \"application/json\",\n      }\n\n      const isAIPath =\n        ctx.apiPath.includes(\"/knowledge-vault\") || ctx.apiPath.includes(\"/generative-ai\")\n      const baseUrl = isAIPath ? brandKitAIBase : brandKitBase\n\n      return forwardRequest(\n        baseUrl + ctx.apiPath + ctx.search,\n        ctx.method,\n        headers,\n        ctx.body,\n        timeout,\n      )\n    },\n  )\n}\n","import { resolveEndpoints } from \"../../index.js\"\nimport type { ContentstackRegion } from \"../../index.js\"\nimport { createBaseProxy, forwardRequest, jsonErrorResponse } from \"./proxy-base.js\"\nimport type { ProxyAuthConfig } from \"./types.js\"\n\nexport type DeveloperHubProxyConfig = ProxyAuthConfig & {\n  /** Contentstack region */\n  region: ContentstackRegion\n  /** Organization UID — required for all Developer Hub API calls */\n  organizationUid: string\n  /** URL prefix to strip when extracting the Developer Hub API path (default: \"/api/developerhub\") */\n  basePath?: string\n  /** Restrict operations: \"read\" allows GET only, \"manage\" allows all methods */\n  allowedOperations?: (\"read\" | \"manage\")[]\n  /** Request timeout in milliseconds (default: 30000) */\n  timeout?: number\n}\n\n/**\n * Create a Developer Hub API proxy handler that forwards requests to Contentstack Developer Hub.\n *\n * The returned function accepts a standard `Request` and returns a `Response`,\n * making it compatible with Next.js route handlers, Deno/Bun servers, and\n * any framework that uses the Web API Request/Response model.\n *\n * @example\n * ```ts\n * // app/api/developerhub/[...path]/route.ts\n * const proxy = createDeveloperHubProxy({\n *   region: \"us\",\n *   organizationUid: \"org-uid\",\n *   getAccessToken: async () => {\n *     const session = await auth()\n *     return session?.accessToken ?? null\n *   },\n * })\n *\n * export const GET = proxy\n * export const POST = proxy\n * export const PUT = proxy\n * export const DELETE = proxy\n * ```\n */\nexport function createDeveloperHubProxy(\n  config: DeveloperHubProxyConfig,\n): (request: Request) => Promise<Response> {\n  const endpoints = resolveEndpoints(config.region)\n  const devHubBase = endpoints.developerHub\n  const timeout = config.timeout ?? 30_000\n\n  return createBaseProxy(\n    {\n      ...(config.getAuthHeaders\n        ? { getAuthHeaders: config.getAuthHeaders }\n        : { getAccessToken: config.getAccessToken }),\n      basePath: config.basePath ?? \"/api/developerhub\",\n      timeout,\n    },\n    async (ctx) => {\n      if (config.allowedOperations?.length) {\n        const hasManage = config.allowedOperations.includes(\"manage\")\n        if (!hasManage && ![\"GET\", \"HEAD\"].includes(ctx.method)) {\n          return jsonErrorResponse(\"Forbidden: read-only mode\", 403)\n        }\n      }\n\n      const headers: Record<string, string> = {\n        ...ctx.authHeaders,\n        organization_uid: config.organizationUid,\n        \"content-type\": \"application/json\",\n      }\n\n      return forwardRequest(\n        devHubBase + ctx.apiPath + ctx.search,\n        ctx.method,\n        headers,\n        ctx.body,\n        timeout,\n      )\n    },\n  )\n}\n","/**\n * Webhook signature verification using HMAC-SHA256.\n * Uses the Web Crypto API for cross-runtime compatibility (Node 18+, Deno, Bun, edge).\n */\n\nfunction hexEncode(buffer: ArrayBuffer): string {\n  const bytes = new Uint8Array(buffer)\n  let hex = \"\"\n  for (const byte of bytes) {\n    hex += byte.toString(16).padStart(2, \"0\")\n  }\n  return hex\n}\n\nfunction hexDecode(hex: string): Uint8Array {\n  const bytes = new Uint8Array(hex.length / 2)\n  for (let i = 0; i < hex.length; i += 2) {\n    bytes[i / 2] = Number.parseInt(hex.substring(i, i + 2), 16)\n  }\n  return bytes\n}\n\n/**\n * Constant-time comparison of two byte arrays.\n * Prevents timing attacks by always comparing all bytes regardless of mismatch.\n */\nfunction timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {\n  if (a.length !== b.length) return false\n  let result = 0\n  for (let i = 0; i < a.length; i++) {\n    result |= (a[i] ?? 0) ^ (b[i] ?? 0)\n  }\n  return result === 0\n}\n\n/**\n * Verify a Contentstack webhook signature using HMAC-SHA256.\n *\n * @param body - The raw request body string\n * @param signature - The hex-encoded signature from the `X-Contentstack-Request-Signature` header\n * @param secret - The webhook secret configured in Contentstack\n * @returns `true` if the signature is valid\n */\nexport async function verifyWebhookSignature(\n  body: string,\n  signature: string,\n  secret: string,\n): Promise<boolean> {\n  const encoder = new TextEncoder()\n  const key = await globalThis.crypto.subtle.importKey(\n    \"raw\",\n    encoder.encode(secret),\n    { name: \"HMAC\", hash: \"SHA-256\" },\n    false,\n    [\"sign\"],\n  )\n\n  const expectedBuffer = await globalThis.crypto.subtle.sign(\"HMAC\", key, encoder.encode(body))\n  const expectedBytes = new Uint8Array(expectedBuffer)\n  const signatureBytes = hexDecode(signature)\n\n  return timingSafeEqual(expectedBytes, signatureBytes)\n}\n","import { ContentstackAuthError } from \"../../index.js\"\nimport type { WebhookEvent, WebhookHandlerConfig } from \"./types.js\"\nimport { verifyWebhookSignature } from \"./verify.js\"\n\nconst SIGNATURE_HEADER = \"x-contentstack-request-signature\"\n\nfunction parseWebhookBody(body: string): WebhookEvent {\n  const raw = JSON.parse(body) as Record<string, unknown>\n  const module = raw.module as string\n  const event = raw.event as string\n  const type = `${module}.${event}`\n\n  return {\n    ...raw,\n    type,\n    module,\n    event,\n  } as WebhookEvent\n}\n\n/**\n * Create a webhook handler with signature verification and typed event parsing.\n *\n * @example\n * ```ts\n * const handler = createWebhookHandler({ secret: process.env.WEBHOOK_SECRET })\n *\n * // In a route handler:\n * const event = await handler.verify(request)\n * if (event.type === \"entry.publish\") {\n *   console.log(event.data.entry.uid)\n * }\n * ```\n */\nexport function createWebhookHandler(config: WebhookHandlerConfig) {\n  return {\n    /**\n     * Read the request body, verify the signature, and return a typed event.\n     * Throws `ContentstackAuthError` if the signature is missing or invalid.\n     */\n    async verify(request: Request): Promise<WebhookEvent> {\n      const body = await request.text()\n      const signature = request.headers.get(SIGNATURE_HEADER)\n\n      if (!signature) {\n        throw new ContentstackAuthError(\"Missing webhook signature header\", {\n          status: 401,\n          requestPath: new URL(request.url).pathname,\n        })\n      }\n\n      const valid = await verifyWebhookSignature(body, signature, config.secret)\n      if (!valid) {\n        throw new ContentstackAuthError(\"Invalid webhook signature\", {\n          status: 401,\n          requestPath: new URL(request.url).pathname,\n        })\n      }\n\n      return parseWebhookBody(body)\n    },\n\n    /**\n     * Read the request body and return a typed event without verifying the signature.\n     */\n    async parse(request: Request): Promise<WebhookEvent> {\n      const body = await request.text()\n      return parseWebhookBody(body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