{"version":3,"sources":["../../../src/server/middleware/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"],"sourcesContent":["export type { OAuthMiddlewareConfig, AuthFn, AuthLogger, ContentstackSession } from \"./types.js\"\nexport { createContentstackAuth } from \"./auth.js\"\nexport { getSession, requireSession, getAccessToken } from \"./session.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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIO,IAAM,oBAAN,cAAgC,MAAM;AAAA,EACzB,OAAe;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,SACA,SAOA;AACA,UAAM,SAAS,SAAS,QAAQ,EAAE,OAAO,QAAQ,MAAM,IAAI,MAAS;AACpE,SAAK,SAAS,SAAS;AACvB,SAAK,YAAY,SAAS;AAC1B,SAAK,SAAS,SAAS;AACvB,SAAK,cAAc,SAAS;AAAA,EAC9B;AACF;AAEO,IAAM,wBAAN,cAAoC,kBAAkB;AAAA,EACzC,OAAO;AAAA,EACP,SAAS;AAC7B;AAEO,IAAM,6BAAN,cAAyC,kBAAkB;AAAA,EAC9C,OAAO;AAAA,EACP,SAAS;AAC7B;AAEO,IAAM,4BAAN,cAAwC,kBAAkB;AAAA,EAC7C,OAAO;AAAA,EACP,SAAS;AAC7B;AAEO,IAAM,8BAAN,cAA0C,kBAAkB;AAAA,EAC/C,OAAO;AAAA,EACP;AAAA,EAElB,YACE,SACA,SAOA;AACA,UAAM,SAAS,OAAO;AACtB,SAAK,SAAS,SAAS,UAAU;AAAA,EACnC;AACF;AAEO,IAAM,iCAAN,cAA6C,kBAAkB;AAAA,EAClD,OAAO;AAAA,EACP,SAAS;AAC7B;AAEO,IAAM,6BAAN,cAAyC,kBAAk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