@qafka/react-native-cms 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +510 -0
- package/README.md +244 -2
- package/android/build.gradle +41 -0
- package/android/src/main/AndroidManifest.xml +2 -0
- package/android/src/main/java/com/qafkacms/QafkaCmsPackage.kt +21 -0
- package/android/src/main/java/com/qafkacms/attestation/QafkaCmsAttestationModule.kt +92 -0
- package/android/src/main/java/com/qafkacms/push/QafkaCmsPushModule.kt +163 -0
- package/android/src/main/java/com/qafkacms/storage/QafkaCmsStorageModule.kt +80 -0
- package/app.plugin.js +1 -0
- package/dist/index.d.ts +2373 -0
- package/dist/index.js +4468 -0
- package/dist/index.js.map +1 -0
- package/expo-plugin/apnsForwarding.js +48 -0
- package/expo-plugin/withQafkaCms.js +23 -0
- package/expo-plugin/withQafkaCmsAttestation.js +27 -0
- package/expo-plugin/withQafkaCmsPush.js +53 -0
- package/ios/QafkaCmsAttestation.m +25 -0
- package/ios/QafkaCmsAttestation.swift +128 -0
- package/ios/QafkaCmsPush.m +22 -0
- package/ios/QafkaCmsPush.swift +143 -0
- package/ios/QafkaCmsReactImports.h +2 -0
- package/ios/QafkaCmsStorage.m +26 -0
- package/ios/QafkaCmsStorage.swift +118 -0
- package/package.json +42 -4
- package/qafkacms.config.d.ts +9 -0
- package/qafkacms.config.js +13 -0
- package/react-native-qafkacms.podspec +20 -0
- package/react-native.config.js +17 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../../core/src/constants.ts","../../core/src/app-version.ts","../../core/src/transport/problem-details.ts","../../core/src/transport/proof.ts","../../core/src/transport/HttpClient.ts","../../core/src/auth/jwt-decode.ts","../../core/src/auth/AuthClient.ts","../../core/src/auth/token-store.ts","../../core/src/content/filter-serialize.ts","../../core/src/content/ContentClient.ts","../../core/src/content/unlock-token-store.ts","../../core/src/sync/VersionPoller.ts","../../core/src/sync/SseSupervisor.ts","../../core/src/config-sync/ConfigSyncClient.ts","../../core/src/i18n/LanguageManager.ts","../../core/src/content-sync/versions.ts","../../core/src/core/client.ts","../../core/src/cache/duration.ts","../../core/src/cache/query-key.ts","../../core/src/cache/conditional.ts","../../core/src/cache/version-gate.ts","../../core/src/cache/QueryCache.ts","../../core/src/cache/cache-storage.ts","../../core/src/cache/secure-migration.ts","../../core/src/content-sync/ContentChangeHub.ts","../../core/src/content-bundle/filter.ts","../../core/src/content-bundle/ContentBundleClient.ts","../../core/src/color/resolveColor.ts","../../core/src/services/storageCore.ts","../../core/src/types/filter.ts","../src/native/QafkaCmsAttestation.ts","../src/native/QafkaCmsStorage.ts","../src/services/storage.ts","../src/services/AttestationManager.ts","../src/config-sync/sse.ts","../src/config/runtime-config-loader.ts","../src/config/resolve-runtime-config-source.ts","../src/config/resolve-project-config.ts","../src/native/QafkaCmsPush.ts","../src/push/DeviceRegistrationManager.ts","../src/QafkaCmsSdk.ts","../../react/src/QafkaCmsProvider.ts","../../react/src/context.ts","../../react/src/bootstrap.ts","../../react/src/auth-cache-reset.ts","../../react/src/unlock-cache-reset.ts","../../react/src/locale-cache-reset.ts","../../react/src/require-language.ts","../../react/src/useQuery.ts","../../react/src/useMutation.ts","../../react/src/useContent.ts","../../react/src/useBundle.ts","../../react/src/useLookup.ts","../../react/src/useAuth.ts","../../react/src/useLocale.ts","../../react/src/useTranslation.ts","../src/rn-react.ts","../src/react/usePush.ts","../src/react/useResolvedColor.ts"],"sourcesContent":["/// <reference path=\"./shims/globals.d.ts\" />\n\nimport { SDK_VERSION } from '@qafka/cms-core';\n\n// --- Core client --------------------------------------------------------\nexport { QafkaCmsClient, createClient } from './QafkaCmsSdk';\nexport type { QafkaCmsConfig, QafkaCmsClientDeps } from './types/sdk';\n\n// --- Sub-clients (types for advanced/host use) --------------------------\nexport { AuthClient } from '@qafka/cms-core';\nexport type { AuthClientOptions } from '@qafka/cms-core';\nexport { ContentClient } from '@qafka/cms-core';\nexport type { LookupResult } from '@qafka/cms-core';\nexport { UnlockTokenStore } from '@qafka/cms-core';\nexport { AttestationManager } from './services/AttestationManager';\nexport { DeviceRegistrationManager } from './push/DeviceRegistrationManager';\nexport type {\n DeviceRegistrationState,\n DeviceRegisterBody,\n} from './push/DeviceRegistrationManager';\nexport type {\n NativePushApi,\n AndroidPushConfig,\n PushPermissionStatus,\n DeviceInfo,\n} from './native/QafkaCmsPush';\nexport { ConfigSyncClient } from '@qafka/cms-core';\nexport { ProblemError } from '@qafka/cms-core';\n\n// --- Public types -------------------------------------------------------\nexport type { AuthMethod, EndUserAuthMethod, RegisterInput, EndUser, LoginInput, AuthTokens, RefreshResult, AuthState, AuthMethods, ExternalSignInResult } from '@qafka/cms-core';\nexport type { AnonymousAuthMode, AnonymousSignInResult, UpgradeInput, UpgradeResult, UpgradeOutcome } from '@qafka/cms-core';\nexport type { ContentRecord, GetParams, JoinResult, ListParams, ListResult, RelationManyValue, RelationManyWrite } from '@qafka/cms-core';\nexport type { ContentClientOptions } from '@qafka/cms-core';\nexport type { FilterNode, FieldOps, FilterOp, QuantifierOps } from '@qafka/cms-core';\nexport { CURRENT_USER, NOW, now } from '@qafka/cms-core';\nexport type { AccessTokenClaims } from '@qafka/cms-core';\nexport type { ConfigSnapshot, ConnectSse, SseHandlers, SseConnection, AppStateProvider } from '@qafka/cms-core';\nexport type { ContentChangesApi, ContentChangesStatus, ContentLiveMode, ContentWatchTarget, ContentWatchOptions, ContentInvalidationTarget } from '@qafka/cms-core';\nexport type { ProblemDetails } from '@qafka/cms-core';\nexport type { ContentBundleApi, ContentBundleConfig, ContentBundleOption } from '@qafka/cms-core';\nexport type { ContentBundleSyncResult } from '@qafka/cms-core';\nexport type { ContentBundleStatus, ContentBundleView, ContentBundleItemView } from '@qafka/cms-core';\nexport type { BundleFile, BundleCollection, BundleCollectionAppVersion, BundleComponentInfo } from '@qafka/cms-core';\nexport type { BundleFieldMeta } from '@qafka/cms-core';\n\n// --- React layer (Provider + hooks) -------------------------------------\n// Shared hooks narrowed to QafkaCmsClient (QFK2-E73) live in ./rn-react.\nexport { QafkaCmsProvider, useQafkaCms, useQafkaCmsClient, useQuery, useMutation } from './rn-react';\nexport type { QafkaCmsProviderProps, QafkaCmsContextValue, PrefetchResource } from './rn-react';\nexport { useQafkaCmsCache } from '@qafka/cms-react';\nexport type { QafkaCmsStatus } from '@qafka/cms-react';\nexport type { UseQueryOptions, UseQueryResult } from '@qafka/cms-react';\nexport type { UseContentOptions, ContentLiveOption } from '@qafka/cms-react';\nexport { useContent, useContentItem } from '@qafka/cms-react';\nexport { useBundle, useBundleItem } from '@qafka/cms-react';\nexport type { UseBundleResult, UseBundleItemResult } from '@qafka/cms-react';\nexport { useLookup } from '@qafka/cms-react';\nexport type { UseLookupVars } from '@qafka/cms-react';\nexport type { UseMutationOptions, UseMutationResult } from '@qafka/cms-react';\nexport { useAuth } from '@qafka/cms-react';\nexport { usePush } from './react/usePush';\nexport type { UsePushResult } from './react/usePush';\nexport { useLocale } from '@qafka/cms-react';\nexport type { UseLocaleResult } from '@qafka/cms-react';\nexport { useTranslation } from '@qafka/cms-react';\nexport type { UseTranslationResult } from '@qafka/cms-react';\n\n// --- Color helpers (E90) -------------------------------------------------\nexport { resolveColor } from '@qafka/cms-core';\nexport { useResolvedColor } from './react/useResolvedColor';\nexport type { ColorValue, GradientValue, GradientStop, SchemedColor, HexColor } from '@qafka/cms-core';\n\n// --- i18n / active language (E55) ---------------------------------------\nexport { LanguageManager } from '@qafka/cms-core';\nexport type { LanguageManagerDeps } from '@qafka/cms-core';\nexport type { LocalesData, I18nData, TranslateParams } from '@qafka/cms-core';\n\n// --- Query cache (framework-agnostic; advanced/host use) ----------------\nexport { QueryCache } from '@qafka/cms-core';\nexport type { QueryCacheOptions } from '@qafka/cms-core';\nexport { serializeKey } from '@qafka/cms-core';\nexport type { QueryKey } from '@qafka/cms-core';\nexport type { QueryState, QueryStatus, QueryOptions } from '@qafka/cms-core';\nexport { createMemoryCacheStorage } from '@qafka/cms-core';\nexport type { CacheStorage } from '@qafka/cms-core';\nexport { parseDuration } from '@qafka/cms-core';\nexport type { Duration } from '@qafka/cms-core';\n\nexport { SDK_VERSION };\n\n/** Returns the running SDK version. */\nexport function getVersion(): string {\n return SDK_VERSION;\n}\n","/** SDK version — surfaced in the `x-sdk-version` request header. */\nexport const SDK_VERSION = '0.0.0';\n\n/** Base path segment for the end-user API surface (no global prefix on the API). */\nexport const END_USER_BASE_PATH = '/v1/end-user';\n\n/** Secure-storage key namespace. Mirrors Qafka's `@qafka/*` convention. */\nexport const STORAGE_PREFIX = '@qafka/cms/';\n\n/** iOS App Attest key id — persisted across cold starts. */\nexport const STORAGE_KEY_ATTESTATION_KEY_ID = `${STORAGE_PREFIX}attestation_key_id`;\n\n/**\n * Client-generated stable device id (E57) — the anchor a device row is keyed on.\n * Persisted in secure storage so it survives cold starts (iOS Keychain may even\n * survive reinstall; Android EncryptedSharedPreferences is cleared on uninstall).\n */\nexport const STORAGE_KEY_DEVICE_ID = `${STORAGE_PREFIX}device_id`;\n\n/** End-user refresh token (opaque `qfk_euref_…`). */\nexport const STORAGE_KEY_REFRESH_TOKEN = `${STORAGE_PREFIX}refresh_token`;\n\n/** Marks a session started by an external identity token (E44); no refresh token exists for it. */\nexport const STORAGE_KEY_EXTERNAL_SESSION = `${STORAGE_PREFIX}external_session`;\n\n/**\n * QFK2-T322 — marks the stored refresh-token session as anonymous. The access\n * token (and its `anon` claim) lives in memory only, so after a cold start this\n * is how a refresh 401 is recognised as a lost anonymous identity.\n */\nexport const STORAGE_KEY_ANONYMOUS_SESSION = `${STORAGE_PREFIX}anonymous_session`;\n\n/** Cached config-sync snapshot, keyed per domain. */\nexport const STORAGE_KEY_CONFIG_PREFIX = `${STORAGE_PREFIX}config:`;\n\n/** Persisted active UI locale (E55). Survives cold starts via secure storage. */\nexport const STORAGE_KEY_LOCALE = `${STORAGE_PREFIX}locale`;\n\n/**\n * Persisted query-cache entry, keyed per serialized query key. Written to the\n * injected (non-secure) `CacheStorage`, NOT the secure storage that holds\n * tokens — bulk content does not belong in the Keychain.\n */\nexport const STORAGE_KEY_QUERY_PREFIX = `${STORAGE_PREFIX}query:`;\n/** Index of every persisted query key, so `QueryCache.clear()` also drops keys not touched this session. */\nexport const STORAGE_KEY_QUERY_INDEX = `${STORAGE_PREFIX}query-index`;\n\n/** Android attestation keystore alias. */\nexport const ANDROID_ATTEST_ALIAS = 'qafkacms_attest';\n\n/** Persisted code-lookup unlock tokens (QFK2-E78): JSON `[{collection,id,token}]`, newest 20. */\nexport const STORAGE_KEY_UNLOCK_TOKENS = `${STORAGE_PREFIX}unlock_tokens`;\n","/**\n * App versions (QFK2-E59 V1): 1–4 numeric segments, `1.4` = `1.4.0` = `1.4.0.0`.\n * The API's `content/app-version.ts` applies the same format; the SDK only\n * sends a value that parses (anything else would read as \"unknown\" anyway).\n */\nexport type AppVersionTuple = [number, number, number, number];\n\nconst APP_VERSION_RE = /^\\d{1,9}(\\.\\d{1,9}){0,3}$/;\n\n/** The four segments of a valid app version (missing ones 0), or `null`. */\nexport function parseAppVersion(s: unknown): AppVersionTuple | null {\n if (typeof s !== 'string' || !APP_VERSION_RE.test(s)) return null;\n const parts = s.split('.').map(Number);\n return [parts[0]!, parts[1] ?? 0, parts[2] ?? 0, parts[3] ?? 0];\n}\n\n/** Segment-wise comparison: negative, 0 or positive. Throws on an invalid version. */\nexport function compareAppVersion(a: string | AppVersionTuple, b: string | AppVersionTuple): number {\n const x = typeof a === 'string' ? parseAppVersion(a) : a;\n const y = typeof b === 'string' ? parseAppVersion(b) : b;\n if (!x || !y) throw new Error(`QafkaCMS: invalid app version \"${String(x ? b : a)}\"`);\n for (let i = 0; i < 4; i++) if (x[i] !== y[i]) return x[i]! - y[i]!;\n return 0;\n}\n\n/** The value itself when it is a valid app version, else `null` (what the SDK sends / tags). */\nexport function validAppVersion(s: unknown): string | null {\n return parseAppVersion(s) ? (s as string) : null;\n}\n","/**\n * RFC 7807 Problem Details. The QafkaCMS API returns errors in this shape\n * (`ProblemDetailsFilter`), so the SDK surfaces a typed error rather than a\n * bare `Error`, letting callers branch on `status` / `type`.\n */\nexport interface ProblemDetails {\n type?: string;\n title?: string;\n status?: number;\n detail?: string;\n instance?: string;\n [key: string]: unknown;\n}\n\nexport class ProblemError extends Error {\n readonly status: number;\n readonly type?: string;\n readonly title?: string;\n readonly detail?: string;\n readonly instance?: string;\n /** Machine-readable error code from the problem body (e.g. `EMAIL_NOT_VERIFIED`). */\n readonly code?: string;\n readonly raw: ProblemDetails;\n\n constructor(status: number, problem: ProblemDetails) {\n super(problem.detail || problem.title || `HTTP ${status}`);\n this.name = 'ProblemError';\n this.status = status;\n this.type = problem.type;\n this.title = problem.title;\n this.detail = problem.detail;\n this.instance = problem.instance;\n this.code = problem.code as string | undefined;\n this.raw = problem;\n }\n}\n\n/** Parse a non-OK response body into a ProblemError (best effort). */\nexport async function toProblemError(response: Response): Promise<ProblemError> {\n let problem: ProblemDetails = {};\n try {\n problem = (await response.json()) as ProblemDetails;\n } catch {\n problem = { title: response.statusText || 'Request failed' };\n }\n return new ProblemError(response.status, problem ?? {});\n}\n","import type { ProofContext, ProofProvider } from '../platform/types';\n\n/**\n * Proof providers (QFK2-E73 §4.1): the project-identity + client-proof headers\n * of every end-user request, and how a lapsed proof is renewed. The transport\n * (`HttpClient`) owns the Bearer token, locale, unlock tokens and the retry\n * choreography; the provider owns everything that says *which project* and\n * *why this client may talk to it*.\n */\n\n/** Project identity shared by every provider. */\nexport interface ProjectIdentity {\n /** Project id (UUID) — sent as `X-Project-Id` on every request. */\n projectId?: string;\n /** Publishable key (`qpk_…`) — sent as `X-Project-Key` only when the context asks (no Bearer). */\n publishableKey?: string;\n /** Optional project label — `X-Project-Slug`. */\n projectSlug?: string;\n}\n\n/** `X-Project-Id`, `X-Project-Key` (when `withProjectKey`), `X-Project-Slug`. */\nfunction identityHeaders(identity: ProjectIdentity, ctx: ProofContext): Record<string, string> {\n const headers: Record<string, string> = {};\n if (identity.projectId) headers['X-Project-Id'] = identity.projectId;\n if (ctx.withProjectKey && identity.publishableKey) headers['X-Project-Key'] = identity.publishableKey;\n const slug = ctx.projectSlug ?? identity.projectSlug;\n if (slug) headers['X-Project-Slug'] = slug;\n return headers;\n}\n\n/** The attestation session source; `AttestationManager` satisfies it. */\nexport interface AttestationProofDeps {\n /** Current attestation session token (the getter may renew an expired one). */\n getSessionToken?: () => Promise<string | null>;\n /** Renew the attestation session; resolves the new token, or null (no retry). */\n refresh?: () => Promise<string | null>;\n /** Dev-bypass API key → `x-api-key` when non-null (never in release). */\n getDevApiKey?: () => string | null;\n /** First attestation; wrapped single-flight by {@link AttestationProof.initialize}. */\n initialize?: () => Promise<void>;\n}\n\n/**\n * React Native device proof: `X-Project-Id`, `X-Project-Key` (only without a\n * Bearer), `X-Project-Slug`, and `X-Session-Token` (attestation session) or\n * `x-api-key` (dev-bypass). `refresh` = `AttestationManager.refresh()`; its new\n * token is overlaid on the retry as `X-Session-Token`.\n *\n * Platform-neutral code: it only calls the injected functions, so the\n * transport also uses it to adapt its legacy `getSessionToken` /\n * `onRefreshRequired` / `getDevApiKey` deps.\n */\nexport class AttestationProof implements ProofProvider {\n readonly refresh?: () => Promise<Record<string, string> | null>;\n private ready: Promise<void> | null = null;\n\n constructor(\n private readonly identity: ProjectIdentity,\n private readonly deps: AttestationProofDeps,\n ) {\n const renew = deps.refresh;\n if (renew) {\n this.refresh = async () => {\n const token = await renew();\n return token ? { 'X-Session-Token': token } : null;\n };\n }\n }\n\n async headers(ctx: ProofContext): Promise<Record<string, string>> {\n const headers = identityHeaders(this.identity, ctx);\n if (this.deps.getSessionToken) {\n const session = await this.deps.getSessionToken();\n if (session) headers['X-Session-Token'] = session;\n }\n const devKey = this.deps.getDevApiKey?.();\n if (devKey) headers['x-api-key'] = devKey;\n return headers;\n }\n\n /**\n * Run the first attestation exactly once; concurrent callers await the same\n * promise. A failed attempt is forgotten so the next call retries.\n */\n initialize(): Promise<void> {\n if (!this.ready) {\n const attempt = this.deps.initialize ? this.deps.initialize() : Promise.resolve();\n this.ready = attempt;\n attempt.catch(() => {\n if (this.ready === attempt) this.ready = null;\n });\n }\n return this.ready;\n }\n\n /** True once {@link initialize} has started (and not failed). */\n hasStarted(): boolean {\n return this.ready !== null;\n }\n}\n\n/**\n * End-user auth POSTs that a captcha token protects (QFK2-E73 §5, T7c): the\n * account-creating / mail-sending calls a bot would hammer.\n */\nexport const CAPTCHA_AUTH_PATHS: readonly string[] = [\n '/auth/register',\n '/auth/magic-link/request',\n '/auth/password-reset/request',\n '/auth/anonymous',\n];\n\nexport interface PublishableKeyProofOptions extends ProjectIdentity {\n publishableKey: string;\n /**\n * Captcha (e.g. Cloudflare Turnstile) token source. Called only for the\n * {@link CAPTCHA_AUTH_PATHS} POSTs; a non-empty result is sent as\n * `X-Captcha-Token`. Tokens are single-use, so it is called per request.\n */\n captcha?: () => Promise<string | null | undefined> | string | null | undefined;\n}\n\n/**\n * Web / server publishable-key proof: `X-Project-Key` only on requests without\n * a Bearer (E63 decision 14), `X-Project-Id` / `X-Project-Slug` when\n * configured, and `X-Captcha-Token` on the captcha-protected auth POSTs when a\n * captcha provider is given. No attestation, no refresh.\n */\nexport class PublishableKeyProof implements ProofProvider {\n constructor(private readonly options: PublishableKeyProofOptions) {}\n\n async headers(ctx: ProofContext): Promise<Record<string, string>> {\n const headers = identityHeaders(this.options, ctx);\n if (\n this.options.captcha &&\n ctx.method === 'POST' &&\n ctx.path !== undefined &&\n CAPTCHA_AUTH_PATHS.includes(ctx.path)\n ) {\n const token = await this.options.captcha();\n if (token) headers['X-Captcha-Token'] = token;\n }\n return headers;\n }\n}\n","import { END_USER_BASE_PATH, SDK_VERSION } from '../constants';\nimport type { FetchLike, ProofProvider } from '../platform/types';\nimport { toProblemError } from './problem-details';\nimport { AttestationProof } from './proof';\nimport { validAppVersion } from '../app-version';\n\n/**\n * HTTP transport for the end-user API. Composes the three QafkaCMS trust axes\n * onto every request and handles attestation session-token refresh.\n *\n * Trust axes (K1 in the spec):\n * - `Authorization: Bearer <accessToken>` — end-user identity (E7 JWT)\n * - `X-Session-Token: <sessionToken>` — device trust (E22 attestation)\n * - `X-Project-Key: <qpk_…>` — publishable key (sent when no Bearer token)\n * - `X-Project-Id: <uuid>` — project id (mobile; sent on every request)\n * - `x-api-key: <test key>` — dev-bypass only\n * - `X-Project-Slug: <slug>` — optional project label\n *\n * The project/proof headers (everything but the Bearer) come from a\n * {@link ProofProvider} (QFK2-E73): `AttestationProof` on React Native,\n * `PublishableKeyProof` on the web. Without an explicit `proof`, the legacy\n * `getSessionToken` / `onRefreshRequired` / `getDevApiKey` deps are adapted\n * into an `AttestationProof`.\n *\n * Refresh choreography is copied from Qafka's BackendService: a 429 with\n * `X-Token-Refresh-Required` (or a 401 `ATTESTATION_SESSION_EXPIRED`) triggers\n * a reactive `proof.refresh()` + single retry, while a low\n * `X-Token-Budget-Remaining` triggers a proactive fire-and-forget refresh.\n */\nexport type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';\n\nexport interface HttpClientConfig {\n apiUrl: string;\n projectSlug?: string;\n /** Project publishable key (`qpk_…`) — sent as `X-Project-Key` on requests without a Bearer token. */\n publishableKey?: string;\n /** Project id (UUID) — sent as `X-Project-Id` on every request. */\n projectId?: string;\n sdkVersion?: string;\n /**\n * Sent as `x-platform` (`ios` / `android` / `web` / `node`). The transport\n * never asks the runtime: every client passes it (core: `PlatformAdapter.os`);\n * when absent the header is omitted.\n */\n platformOS?: string;\n /**\n * The app's version (QFK2-E59 V9), sent as `X-App-Version` on every request\n * when it is a valid app version (`parseAppVersion`); otherwise omitted.\n */\n appVersion?: string | null;\n}\n\nexport interface HttpClientDeps {\n fetch: FetchLike;\n /**\n * Project + proof headers and proof refresh. When set, the legacy\n * `getSessionToken` / `onRefreshRequired` / `getDevApiKey` deps (and the\n * config's `projectId` / `publishableKey` / `projectSlug`) are not used for\n * headers — the provider owns them.\n */\n proof?: ProofProvider;\n /** End-user access token (the getter may refresh it internally). */\n getAccessToken?: () => Promise<string | null>;\n /** Attestation session token. */\n getSessionToken?: () => Promise<string | null>;\n /** Force an attestation refresh; returns the new session token (or null). */\n onRefreshRequired?: () => Promise<string | null>;\n /** Active UI locale → sent as `Accept-Language` on every request (E55). */\n getLocale?: () => string | null;\n /** Dev-bypass API key → sent as `x-api-key` when non-null (never in release). */\n getDevApiKey?: () => string | null;\n /** Code-lookup unlock tokens → sent as `X-Unlock-Token` (comma-separated) when non-empty. */\n getUnlockTokens?: () => string[];\n}\n\nexport interface RequestOptions {\n body?: unknown;\n query?: Record<string, string | number | boolean | undefined | null>;\n /** Override the configured project slug for this request. */\n projectSlug?: string;\n /** Skip the Authorization header even if an access token exists. */\n anonymous?: boolean;\n /** Send `X-Unlock-Token` (content + lookup requests only; set by ContentClient). */\n withUnlockTokens?: boolean;\n}\n\n/** Options of {@link HttpClient.requestConditional} (QFK2-E59 D3). */\nexport interface ConditionalRequestOptions extends RequestOptions {\n /** ETag of the copy the caller holds → `If-None-Match`; sent only when a non-empty string. */\n ifNoneMatch?: string | null;\n}\n\n/**\n * Result of {@link HttpClient.requestConditional}: `notModified` when the server\n * answered 304 to our `If-None-Match`, otherwise the body and its `ETag`\n * (`null` when absent or not exposed to the browser by CORS).\n */\nexport type ConditionalResponse<T> =\n | { notModified: true }\n | { notModified: false; data: T; etag: string | null };\n\nconst BUDGET_REFRESH_THRESHOLD = 1000;\n\nexport class HttpClient {\n private readonly config: HttpClientConfig;\n private readonly d: HttpClientDeps;\n private readonly proof: ProofProvider;\n /** The configured app version when valid (sent as `X-App-Version`), else `null`. */\n readonly appVersion: string | null;\n\n constructor(config: HttpClientConfig, deps: HttpClientDeps) {\n this.config = config;\n this.d = deps;\n this.appVersion = validAppVersion(config.appVersion);\n this.proof =\n deps.proof ??\n new AttestationProof(\n { projectId: config.projectId, publishableKey: config.publishableKey, projectSlug: config.projectSlug },\n { getSessionToken: deps.getSessionToken, refresh: deps.onRefreshRequired, getDevApiKey: deps.getDevApiKey },\n );\n }\n\n async request<T = unknown>(method: HttpMethod, path: string, options: RequestOptions = {}): Promise<T> {\n const res = await this.send(method, path, options);\n if (!res.ok) throw await toProblemError(res);\n if (res.status === 204) return undefined as T;\n return (await res.json()) as T;\n }\n\n /**\n * {@link request} with HTTP conditional-GET support (QFK2-E59 D3). Sends\n * `If-None-Match` only when `options.ifNoneMatch` is a non-empty string; a\n * 304 counts as \"not modified\" only then. A 304 to a request without it is\n * an error, exactly as in {@link request}. Same headers, refresh and retry.\n */\n async requestConditional<T = unknown>(\n method: HttpMethod,\n path: string,\n options: ConditionalRequestOptions = {},\n ): Promise<ConditionalResponse<T>> {\n const { ifNoneMatch, ...rest } = options;\n const tag = typeof ifNoneMatch === 'string' && ifNoneMatch.length > 0 ? ifNoneMatch : null;\n const res = await this.send(method, path, rest, tag ? { 'If-None-Match': tag } : undefined);\n if (tag && res.status === 304) return { notModified: true };\n if (!res.ok) throw await toProblemError(res);\n const etag = res.headers?.get?.('ETag') || null;\n if (res.status === 204) return { notModified: false, data: undefined as T, etag };\n return { notModified: false, data: (await res.json()) as T, etag };\n }\n\n /** Build the URL + headers, send through the refresh path; status handling is the caller's. */\n private async send(\n method: HttpMethod,\n path: string,\n options: RequestOptions,\n extraHeaders?: Record<string, string>,\n ): Promise<Response> {\n const url = this.buildUrl(path, options.query);\n const headers = await this.securityHeaders(options, { method, path });\n if (extraHeaders) Object.assign(headers, extraHeaders);\n const init: { method: string; headers: Record<string, string>; body?: string } = { method, headers };\n if (options.body !== undefined) init.body = JSON.stringify(options.body);\n return this.fetchWithRefresh(url, init);\n }\n\n /**\n * Exposed for clients that need the resolved security headers (e.g. SSE).\n * `target` (method + end-user path) lets the proof provider scope\n * request-specific headers (e.g. a captcha token on auth POSTs).\n */\n async securityHeaders(\n options: RequestOptions = {},\n target?: { method: string; path: string },\n ): Promise<Record<string, string>> {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.config.platformOS) headers['x-platform'] = this.config.platformOS;\n headers['x-sdk-version'] = this.config.sdkVersion ?? SDK_VERSION;\n if (this.appVersion) headers['X-App-Version'] = this.appVersion;\n\n if (!options.anonymous && this.d.getAccessToken) {\n const token = await this.d.getAccessToken();\n if (token) headers['Authorization'] = `Bearer ${token}`;\n }\n\n // Anonymous / token-less requests identify the project via the publishable key.\n const authenticated = Boolean(headers['Authorization']);\n Object.assign(\n headers,\n await this.proof.headers({\n authenticated,\n withProjectKey: !authenticated,\n projectSlug: options.projectSlug,\n method: target?.method,\n path: target?.path,\n }),\n );\n\n // Content negotiation: the active locale rides along as Accept-Language so\n // the backend can localize even when no explicit `?locale=` is sent. Content\n // requests ALSO carry an explicit `?locale=` (ContentClient); query wins.\n const locale = this.d.getLocale?.();\n if (locale) headers['Accept-Language'] = locale;\n\n const unlock = options.withUnlockTokens ? this.d.getUnlockTokens?.() : undefined;\n if (unlock && unlock.length) headers['X-Unlock-Token'] = unlock.join(',');\n\n return headers;\n }\n\n /**\n * Project + proof headers: `X-Project-Id`, `X-Project-Key` (when\n * `withProjectKey`), `X-Project-Slug`, and `X-Session-Token` (release) or\n * `x-api-key` (dev-bypass). {@link securityHeaders} sends the key only on\n * requests without a Bearer; `getRequestHeaders()` (no Authorization, the\n * caller decides) always does.\n */\n async projectProofHeaders(options: {\n withProjectKey: boolean;\n projectSlug?: string;\n }): Promise<Record<string, string>> {\n return this.proof.headers({\n authenticated: false,\n withProjectKey: options.withProjectKey,\n projectSlug: options.projectSlug,\n });\n }\n\n /** The proof provider (for `initialize()` / own-client header helpers). */\n getProof(): ProofProvider {\n return this.proof;\n }\n\n private async fetchWithRefresh(\n url: string,\n init: { method: string; headers: Record<string, string>; body?: string },\n retries = 1,\n ): Promise<Response> {\n const res = await this.d.fetch(url, init);\n\n const refreshRequired = res.headers.get('X-Token-Refresh-Required') === 'true';\n const remainingStr = res.headers.get('X-Token-Budget-Remaining');\n const remaining = remainingStr != null ? parseInt(remainingStr, 10) : NaN;\n\n const refresh = this.proof.refresh ? () => this.proof.refresh!() : null;\n\n // Reactive refresh — backend explicitly demands a new token.\n if (res.status === 429 && refreshRequired && retries > 0 && refresh) {\n const overlay = await refresh();\n if (overlay) {\n const headers = { ...init.headers, ...overlay };\n return this.fetchWithRefresh(url, { ...init, headers }, retries - 1);\n }\n }\n\n // Reactive refresh — the attestation session lapsed (validly signed, expired).\n if (\n res.status === 401 &&\n retries > 0 &&\n refresh &&\n (await problemCode(res)) === 'ATTESTATION_SESSION_EXPIRED'\n ) {\n const overlay = await refresh();\n if (overlay) {\n const headers = { ...init.headers, ...overlay };\n return this.fetchWithRefresh(url, { ...init, headers }, retries - 1);\n }\n }\n\n // Proactive refresh — budget running low; don't block the response.\n if (refresh && (refreshRequired || (!isNaN(remaining) && remaining < BUDGET_REFRESH_THRESHOLD))) {\n void refresh();\n }\n\n return res;\n }\n\n private buildUrl(path: string, query?: RequestOptions['query']): string {\n const base = `${this.config.apiUrl.replace(/\\/$/, '')}${END_USER_BASE_PATH}${path}`;\n if (!query) return base;\n const parts: string[] = [];\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);\n }\n return parts.length ? `${base}?${parts.join('&')}` : base;\n }\n}\n\n/** RFC 7807 `code` of an error response, read from a clone so the body stays readable. */\nasync function problemCode(res: Response): Promise<string | undefined> {\n try {\n if (typeof res.clone !== 'function') return undefined;\n const body = (await res.clone().json()) as { code?: unknown } | null;\n return typeof body?.code === 'string' ? body.code : undefined;\n } catch {\n return undefined;\n }\n}\n","/**\n * End-user access-token claims minted by the QafkaCMS backend (`jwt.ts`).\n * Decoded client-side so the SDK can resolve the project without an extra round\n * trip. The signature is NOT verified here — that is the backend's job; the SDK\n * only reads claims it already trusts the transport to have authenticated.\n */\nexport interface AccessTokenClaims {\n sub: string;\n projectId?: string;\n schema?: string;\n /**\n * E54 — consumer-tier role ids the end-user holds (premium/special). Lets the\n * app branch UI on tier (e.g. unlock premium screens); access itself is always\n * enforced server-side. Absent on tokens minted before tiers existed.\n */\n roles?: string[];\n /**\n * QFK2-T322 — `true` only on tokens of an anonymous end-user. Absent on\n * registered (and older) tokens.\n */\n anon?: boolean;\n iat?: number;\n exp?: number;\n}\n\nfunction base64UrlDecode(input: string): string {\n const b64 = input.replace(/-/g, '+').replace(/_/g, '/');\n const pad = b64.length % 4 === 0 ? 0 : 4 - (b64.length % 4);\n const padded = b64 + '='.repeat(pad);\n const binary = atob(padded); // throws on invalid base64\n // Reconstruct UTF-8 from the binary string (handles multibyte chars).\n try {\n return decodeURIComponent(\n binary\n .split('')\n .map((c) => '%' + c.charCodeAt(0).toString(16).padStart(2, '0'))\n .join(''),\n );\n } catch {\n return binary;\n }\n}\n\n/** Decode a JWT's payload into typed claims, or null when it cannot be parsed. */\nexport function decodeAccessToken(token: string | null | undefined): AccessTokenClaims | null {\n if (!token) return null;\n const parts = token.split('.');\n if (parts.length < 2 || !parts[1]) return null;\n try {\n const claims = JSON.parse(base64UrlDecode(parts[1])) as AccessTokenClaims;\n if (!claims || typeof claims !== 'object') return null;\n return claims;\n } catch {\n return null;\n }\n}\n","import { STORAGE_KEY_ANONYMOUS_SESSION, STORAGE_KEY_EXTERNAL_SESSION } from '../constants';\nimport type { QafkaCmsStorage } from '../services/storageCore';\nimport { ProblemError } from '../transport/problem-details';\nimport type { HttpClient } from '../transport/HttpClient';\nimport type { TokenStore } from './token-store';\nimport { decodeAccessToken, type AccessTokenClaims } from './jwt-decode';\nimport type {\n AnonymousAuthMode,\n AnonymousSignInResult,\n AuthMethods,\n AuthState,\n AuthTokens,\n EndUser,\n ExternalSignInResult, LoginInput,\n RefreshResult,\n RegisterInput,\n UpgradeInput,\n UpgradeOutcome,\n UpgradeResult,\n} from '../types/auth';\n\nconst AUTH = '/auth';\n\n/** Options for external-identity sign-in (E44). */\nexport interface AuthClientOptions {\n /**\n * Returns a fresh token from the host app's own identity provider, or `null`\n * when that session is over. Called when the CMS access token expires and\n * after an app restart.\n */\n externalTokenProvider?: () => Promise<string | null>;\n /** Where the external-session marker is persisted (secure storage). */\n storage?: Pick<QafkaCmsStorage, 'getItem' | 'setItem' | 'removeItem'>;\n /**\n * Default external provider key (`authConfig.externalProviders[].key`) used by\n * `signInWithExternalToken` / `linkExternal` / re-exchange when no per-call\n * `provider` is given.\n */\n externalProvider?: string;\n /**\n * QFK2-T322 — `'auto'` re-creates an anonymous end-user lazily after\n * `logout()` / `deleteAccount()`: the next call that needs an access token\n * (any SDK request, `getValidAccessToken()`) runs `signInAnonymously()`.\n * The boot-time creation is done by `QafkaCmsClient.initialize()`. Default\n * `'manual'`: the SDK never creates one on its own.\n */\n anonymousAuth?: AnonymousAuthMode;\n}\n\n/** Marker value for an external session that has no explicit provider key. */\nconst EXTERNAL_MARKER_DEFAULT = '1';\n\ninterface ExchangeResult {\n accessToken: string;\n /** Present only for providers configured with `sessionMode: 'cms'`. */\n refreshToken?: string;\n expiresIn: number;\n endUser: EndUser;\n created: boolean;\n}\n\n/** `POST /auth/anonymous` response (QFK2-T322). */\ninterface AnonymousResult extends AuthTokens {\n endUser: EndUser;\n}\n\n/**\n * `POST /auth/upgrade` response (QFK2-T322). The email method in a project that\n * requires e-mail verification answers `{ verificationRequired: true, endUser }`\n * without tokens (the server has revoked the anonymous sessions).\n */\ntype UpgradeResponse = Omit<UpgradeResult, 'accessToken' | 'expiresIn' | 'signedIn'> & {\n accessToken?: string;\n expiresIn?: number;\n};\n\nconst UPGRADE_OUTCOMES: readonly UpgradeOutcome[] = ['upgraded', 'switched'];\n\n/** A refresh 401 that means the session itself is gone (not a missing/expired device proof). */\nfunction isSessionRejected(e: unknown): boolean {\n if (!(e instanceof ProblemError) || e.status !== 401) return false;\n const code = e.raw.code;\n return !(typeof code === 'string' && code.startsWith('ATTESTATION_'));\n}\n\n/**\n * End-user authentication against `/v1/end-user/auth/*`. All calls are\n * `anonymous` (no `Authorization` header) — identity is established by the\n * payload, not by an existing session. The resulting tokens flow into the\n * shared `TokenStore`, which the transport reads via `getValidAccessToken`.\n */\nexport class AuthClient {\n /** Shared in-flight refresh, so concurrent requests trigger a single `/refresh`. */\n private refreshing: Promise<string | null> | null = null;\n private authStateCache: AuthState | null = null;\n private authStateVersion = -1;\n /** Shared in-flight anonymous sign-in (QFK2-T322). */\n private anonymousSigningIn: Promise<AnonymousSignInResult> | null = null;\n /** `anonymousAuth: 'auto'`: create an anonymous user on the next token need (set by logout/deleteAccount). */\n private autoAnonymousArmed = false;\n private lastUpgradeOutcome: UpgradeOutcome | null = null;\n /** Mirror of the persisted anonymous-session marker; null = not read/written yet. */\n private anonymousMarker: boolean | null = null;\n\n constructor(\n private readonly http: HttpClient,\n private readonly store: TokenStore,\n private readonly now: () => number = Date.now,\n private readonly options: AuthClientOptions = {},\n ) {}\n\n async register(input: RegisterInput): Promise<EndUser> {\n return this.http.request<EndUser>('POST', `${AUTH}/register`, { body: input, anonymous: true });\n }\n\n async login(input: LoginInput): Promise<AuthTokens> {\n const tokens = await this.http.request<AuthTokens>('POST', `${AUTH}/login`, { body: input, anonymous: true });\n await this.storeCmsTokens(tokens);\n return tokens;\n }\n\n /**\n * Sign in with a token from the customer's own identity provider (E44).\n * For a `sessionMode: 'external'` provider the CMS issues an access token\n * only; it is renewed through `externalTokenProvider`. For `'cms'` providers\n * the response carries a refresh token and the session behaves exactly like\n * a normal login (E72). `opts.provider` selects the provider by key.\n *\n * `opts.nonce` is the RAW nonce. Generate a random raw nonce, pass\n * `sha256(raw)` (hex) to BOTH Apple's and Google's request and the **raw**\n * value here (a token whose nonce claim equals the raw value is rejected).\n * The provider must have `nonce`\n * set to `optional` or `required`; `required` is meant for `cms` session mode\n * (silent re-exchange through `externalTokenProvider` carries no nonce).\n */\n async signInWithExternalToken(token: string, opts?: { provider?: string; nonce?: string }): Promise<ExternalSignInResult> {\n const provider = opts?.provider ?? this.options.externalProvider;\n const result = await this.exchange(token, provider, opts?.nonce);\n await this.applyExchange(result, provider);\n return { endUser: result.endUser, created: result.created };\n }\n\n /** The signed-in member as the server sees it (Bearer session); `linkedProviders` is filled here. */\n async me(): Promise<EndUser> {\n return this.http.request<EndUser>('GET', `${AUTH}/me`);\n }\n\n /** Attach an external identity to the signed-in member. `opts.nonce`: raw nonce; give the provider sha256(raw), see `signInWithExternalToken`. */\n async linkExternal(token: string, opts?: { provider?: string; nonce?: string }): Promise<{ endUser: EndUser }> {\n // QFK2-T322 — the server answers 409 UPGRADE_REQUIRED for an anonymous\n // caller; fail the same way without the round trip.\n if (this.isAnonymous()) {\n throw new ProblemError(409, {\n status: 409,\n title: 'Upgrade required',\n code: 'UPGRADE_REQUIRED',\n detail: \"An anonymous end-user cannot link an identity; use auth.upgrade({ method: 'external', token }).\",\n });\n }\n const provider = opts?.provider ?? this.options.externalProvider;\n return this.http.request<{ endUser: EndUser }>('POST', `${AUTH}/external/link`, {\n body: { token, ...(provider ? { provider } : {}), ...(opts?.nonce ? { nonce: opts.nonce } : {}) },\n });\n }\n\n /** Detach external identities from the signed-in member (all, or only `opts.provider`). */\n async unlinkExternal(opts?: { provider?: string }): Promise<{ endUser: EndUser }> {\n const query = opts?.provider ? `?provider=${encodeURIComponent(opts.provider)}` : '';\n return this.http.request<{ endUser: EndUser }>('DELETE', `${AUTH}/external/link${query}`);\n }\n\n /**\n * QFK2-T322 — sign in as a new anonymous end-user (`POST /auth/anonymous`,\n * attestation proof required). Idempotent: when a session already exists\n * (anonymous, registered or external) it returns the current identity\n * without a request. Concurrent calls share one request.\n */\n async signInAnonymously(): Promise<AnonymousSignInResult> {\n if (this.anonymousSigningIn) return this.anonymousSigningIn;\n this.anonymousSigningIn = this.runSignInAnonymously().finally(() => {\n this.anonymousSigningIn = null;\n });\n return this.anonymousSigningIn;\n }\n\n private async runSignInAnonymously(): Promise<AnonymousSignInResult> {\n if (this.isAuthenticated() || (await this.hasExternalSession())) {\n const claims = this.getClaims();\n return { userId: claims?.sub ?? null, isAnonymous: claims?.anon === true, created: false, endUser: null };\n }\n const result = await this.http.request<AnonymousResult>('POST', `${AUTH}/anonymous`, { anonymous: true });\n await this.storeCmsTokens({\n accessToken: result.accessToken,\n refreshToken: result.refreshToken,\n expiresIn: result.expiresIn,\n });\n const claims = this.getClaims();\n return {\n userId: claims?.sub ?? result.endUser?.id ?? null,\n isAnonymous: claims?.anon === true,\n created: true,\n endUser: result.endUser,\n };\n }\n\n /** QFK2-T322 — true when the current access token carries `anon: true`. */\n isAnonymous(): boolean {\n return this.getClaims()?.anon === true;\n }\n\n /**\n * QFK2-T322 — turn the signed-in anonymous end-user into an account, keeping\n * its id (`POST /auth/upgrade`, Bearer = the anonymous access token).\n * `email` and `external` replace the session with the returned tokens\n * (`signedIn: true`); an email upgrade that needs verification comes back\n * without tokens (`signedIn: false`) and leaves the client signed out;\n * `magic_link` only sends the e-mail (finish with `handleMagicLinkCallback`,\n * then read `getLastUpgradeOutcome()`). Conflicts are `ProblemError`s\n * (`raw.code`: `ACCOUNT_EXISTS_SIGN_IN_REQUIRED`, `ACCOUNT_EXISTS_LINK_REQUIRED`,\n * `IDENTITY_IN_USE`, `NOT_ANONYMOUS`); the anonymous session is kept then.\n */\n async upgrade(input: Extract<UpgradeInput, { method: 'magic_link' }>): Promise<{ ok: boolean }>;\n async upgrade(input: Extract<UpgradeInput, { method: 'email' | 'external' }>): Promise<UpgradeResult>;\n async upgrade(input: UpgradeInput): Promise<UpgradeResult | { ok: boolean }>;\n async upgrade(input: UpgradeInput): Promise<UpgradeResult | { ok: boolean }> {\n if (input.method === 'magic_link') {\n return this.http.request<{ ok: boolean }>('POST', `${AUTH}/upgrade`, {\n body: { method: 'magic_link', email: input.email },\n });\n }\n let body: Record<string, string>;\n let provider: string | undefined;\n if (input.method === 'email') {\n body = { method: 'email', email: input.email, password: input.password };\n } else {\n provider = input.provider ?? this.options.externalProvider;\n body = { method: 'external', token: input.token, ...(provider ? { provider } : {}), ...(input.nonce ? { nonce: input.nonce } : {}) };\n }\n const result = await this.http.request<UpgradeResponse>('POST', `${AUTH}/upgrade`, { body });\n if (!result.accessToken) {\n // Verification pending: upgraded in place, but the server revoked the\n // anonymous sessions and issued none. Drop the dead local session; in\n // 'auto' mode do NOT create a new anonymous user meanwhile (the user is\n // about to verify and log in) — logout()/deleteAccount() re-arm it.\n await this.endLocalSession(false);\n return {\n accessToken: '',\n expiresIn: 0,\n endUser: result.endUser,\n verificationRequired: result.verificationRequired === true,\n signedIn: false,\n };\n }\n const session = { ...result, accessToken: result.accessToken, expiresIn: result.expiresIn ?? 900 };\n await this.applySession(session, provider);\n return { ...session, signedIn: true };\n }\n\n /** QFK2-T322 — outcome of the last magic-link callback that carried `upgrade=`; null otherwise. */\n getLastUpgradeOutcome(): UpgradeOutcome | null {\n return this.lastUpgradeOutcome;\n }\n\n /**\n * QFK2-T322 — delete the signed-in end-user's account (`DELETE /auth/me`,\n * anonymous or registered) and clear the local session. On an error the\n * session is kept and the `ProblemError` is thrown.\n */\n async deleteAccount(): Promise<void> {\n await this.http.request<void>('DELETE', `${AUTH}/me`);\n await this.clearExternalMarker();\n await this.endLocalSession(true);\n }\n\n /** Which sign-in options the project offers (`GET /auth/methods`, anonymous; cache-friendly). */\n async methods(): Promise<AuthMethods> {\n return this.http.request<AuthMethods>('GET', `${AUTH}/methods`, { anonymous: true });\n }\n\n /** Request a password-reset e-mail. Always resolves `{ ok: true }` for existing/unknown addresses alike. */\n async requestPasswordReset(email: string): Promise<{ ok: boolean }> {\n return this.http.request<{ ok: boolean }>('POST', `${AUTH}/password-reset/request`, {\n body: { email },\n anonymous: true,\n });\n }\n\n /** Set a new password with the token from the reset e-mail. Does not sign in. */\n async confirmPasswordReset(token: string, newPassword: string): Promise<{ ok: boolean }> {\n return this.http.request<{ ok: boolean }>('POST', `${AUTH}/password-reset/confirm`, {\n body: { token, newPassword },\n anonymous: true,\n });\n }\n\n private async exchange(token: string, provider?: string, nonce?: string): Promise<ExchangeResult> {\n return this.http.request('POST', `${AUTH}/external/exchange`, {\n body: { token, ...(provider ? { provider } : {}), ...(nonce ? { nonce } : {}) },\n anonymous: true,\n });\n }\n\n /** Persist an exchange result: cms mode (refresh token) = normal login, else external session. */\n private async applyExchange(result: ExchangeResult, provider?: string): Promise<void> {\n await this.applySession(result, provider);\n }\n\n private async applySession(\n result: { accessToken: string; refreshToken?: string; expiresIn: number },\n provider?: string,\n ): Promise<void> {\n if (result.refreshToken) {\n await this.storeCmsTokens({\n accessToken: result.accessToken,\n refreshToken: result.refreshToken,\n expiresIn: result.expiresIn,\n });\n return;\n }\n // Marker first: if the write fails nothing is stored in memory either.\n await this.options.storage?.setItem(STORAGE_KEY_EXTERNAL_SESSION, provider ?? EXTERNAL_MARKER_DEFAULT);\n this.autoAnonymousArmed = false;\n await this.store.setExternalAccess(result.accessToken, result.expiresIn);\n await this.syncAnonymousMarker(false);\n }\n\n /** Keep the persisted anonymous-session marker in line with the session (writes only on change). */\n private async syncAnonymousMarker(anonymous: boolean): Promise<void> {\n if (this.anonymousMarker === anonymous || !this.options.storage) return;\n if (anonymous) await this.options.storage.setItem(STORAGE_KEY_ANONYMOUS_SESSION, '1');\n else await this.options.storage.removeItem(STORAGE_KEY_ANONYMOUS_SESSION);\n this.anonymousMarker = anonymous;\n }\n\n /** Whether the stored session is anonymous: the token claim, else (cold start) the persisted marker. */\n private async storedSessionIsAnonymous(): Promise<boolean> {\n if (this.isAnonymous()) return true;\n if (this.anonymousMarker !== null || !this.options.storage) return this.anonymousMarker === true;\n return (await this.options.storage.getItem(STORAGE_KEY_ANONYMOUS_SESSION)) === '1';\n }\n\n private async hasExternalSession(): Promise<boolean> {\n if (!this.options.storage) return false;\n return (await this.options.storage.getItem(STORAGE_KEY_EXTERNAL_SESSION)) !== null;\n }\n\n private async clearExternalMarker(): Promise<void> {\n await this.options.storage?.removeItem(STORAGE_KEY_EXTERNAL_SESSION);\n }\n\n /** Re-exchange through the host's provider. Null = no session (and it is ended when the provider says so). */\n private async runExternalReExchange(): Promise<string | null> {\n const provider = this.options.externalTokenProvider;\n const token = provider ? await provider() : null;\n if (!token) {\n await this.store.clear();\n await this.clearExternalMarker();\n return null;\n }\n try {\n const marker = await this.options.storage?.getItem(STORAGE_KEY_EXTERNAL_SESSION);\n const provider = marker && marker !== EXTERNAL_MARKER_DEFAULT ? marker : this.options.externalProvider;\n const result = await this.exchange(token, provider);\n if (result.refreshToken) {\n await this.applyExchange(result, provider);\n } else {\n this.store.setAccessToken(result.accessToken, result.expiresIn);\n }\n return result.accessToken;\n } catch (e) {\n // The provider's token was rejected: the external session is over.\n const code = e instanceof ProblemError ? e.raw.code : undefined;\n if (\n code === 'INVALID_EXTERNAL_TOKEN' ||\n code === 'IDENTITY_DEACTIVATED' ||\n code === 'ACCOUNT_DEACTIVATED'\n ) {\n await this.store.clear();\n await this.clearExternalMarker();\n }\n throw e;\n }\n }\n\n /**\n * Returns a valid access token, refreshing transparently when it is near\n * expiry. Returns null when there is no session (anonymous). This is the\n * function wired into `HttpClient.getAccessToken`.\n */\n async getValidAccessToken(): Promise<string | null> {\n if (this.store.isAccessValid()) return this.store.getAccessToken();\n if (this.store.getRefreshToken()) {\n try {\n return await this.refresh();\n } catch {\n return null;\n }\n }\n if (await this.hasExternalSession()) {\n try {\n return await this.refresh();\n } catch {\n return null;\n }\n }\n if (this.autoAnonymousArmed) return this.autoSignInAnonymously();\n return null;\n }\n\n /** `anonymousAuth: 'auto'` lazy creation; a failure disarms it until the next logout. */\n private async autoSignInAnonymously(): Promise<string | null> {\n try {\n await this.signInAnonymously();\n return this.store.getAccessToken();\n } catch {\n return null;\n } finally {\n this.autoAnonymousArmed = false;\n }\n }\n\n /**\n * Local session end (no server call), shared by logout, deleteAccount, a lost\n * anonymous identity and a verification-pending upgrade. `rearmAuto`: in\n * `anonymousAuth: 'auto'` the next token need creates a new anonymous user.\n */\n private async endLocalSession(rearmAuto: boolean): Promise<void> {\n this.lastUpgradeOutcome = null;\n this.autoAnonymousArmed = rearmAuto && this.options.anonymousAuth === 'auto';\n await this.syncAnonymousMarker(false);\n await this.store.clear();\n }\n\n /** Rotate the access token. De-duplicated: concurrent callers share one `/refresh`. */\n async refresh(): Promise<string | null> {\n if (this.refreshing) return this.refreshing;\n this.refreshing = this.runRefresh().finally(() => {\n this.refreshing = null;\n });\n return this.refreshing;\n }\n\n private async runRefresh(allowRotatedRetry = true): Promise<string | null> {\n const refreshToken = this.store.getRefreshToken();\n if (!refreshToken) return (await this.hasExternalSession()) ? this.runExternalReExchange() : null;\n const wasAnonymous = this.isAnonymous();\n let result: RefreshResult & { refreshToken?: unknown };\n try {\n result = await this.http.request<RefreshResult>('POST', `${AUTH}/refresh`, {\n body: { refreshToken },\n anonymous: true,\n });\n } catch (e) {\n const code = e instanceof ProblemError && e.status === 401 ? e.raw.code : undefined;\n // QFK2-E73 / T7e — rotation (opt-in per project). ROTATED: another\n // tab/process rotated this token a moment ago; take its successor (shared\n // storage or the cross-tab sync) and retry once. Never a sign-out.\n if (code === 'REFRESH_TOKEN_ROTATED' && allowRotatedRetry) {\n await this.store.waitForRotation(refreshToken);\n if (this.store.isAccessValid()) return this.store.getAccessToken();\n if (!this.store.getRefreshToken()) return null;\n return this.runRefresh(false);\n }\n // REUSED: a retired token was presented again → the server revoked the\n // whole family; the stored session is dead.\n if (code === 'REFRESH_TOKEN_REUSED' && this.store.getRefreshToken() === refreshToken) {\n await this.endLocalSession(true);\n throw e;\n }\n // QFK2-T322 — an anonymous identity that is gone server-side (inactivity\n // sweep, deactivated, deleted elsewhere) can never sign in again: end the\n // local session. Registered sessions keep the pre-T322 behaviour.\n if (\n isSessionRejected(e) &&\n code !== 'REFRESH_TOKEN_ROTATED' &&\n this.store.getRefreshToken() === refreshToken &&\n (wasAnonymous || (await this.storedSessionIsAnonymous()))\n ) {\n await this.endLocalSession(true);\n }\n throw e;\n }\n if (typeof result.refreshToken === 'string' && result.refreshToken) {\n // Rotation: the response carries the successor; the old token is retired.\n await this.store.setTokens({\n accessToken: result.accessToken,\n refreshToken: result.refreshToken,\n expiresIn: result.expiresIn,\n });\n } else {\n this.store.setAccessToken(result.accessToken, result.expiresIn);\n }\n await this.syncAnonymousMarker(this.isAnonymous());\n return result.accessToken;\n }\n\n async logout(): Promise<void> {\n const refreshToken = this.store.getRefreshToken();\n await this.clearExternalMarker();\n if (refreshToken) {\n try {\n await this.http.request<void>('POST', `${AUTH}/logout`, { body: { refreshToken }, anonymous: true });\n } catch {\n // Best-effort revocation — clear locally regardless.\n }\n }\n await this.endLocalSession(true);\n }\n\n async requestMagicLink(email: string): Promise<{ ok: boolean }> {\n return this.http.request<{ ok: boolean }>('POST', `${AUTH}/magic-link/request`, {\n body: { email },\n anonymous: true,\n });\n }\n\n /**\n * Ask the backend to (re)send the account's verification e-mail. Only sends\n * when the project enabled verification e-mails; always resolves `{ ok: true }`\n * (no account enumeration).\n */\n async requestEmailVerification(email: string): Promise<{ ok: boolean }> {\n return this.http.request<{ ok: boolean }>('POST', `${AUTH}/verify-email/request`, {\n body: { email },\n anonymous: true,\n });\n }\n\n /**\n * Parse the deep-link the backend redirects to after a magic-link confirm\n * (`…#access_token=&refresh_token=&expires_in=`), store the tokens, and\n * return them. Returns null when the URL carries no token fragment. An\n * `upgrade=upgraded|switched` parameter (anonymous upgrade, QFK2-T322) is\n * exposed through `getLastUpgradeOutcome()`.\n */\n async handleMagicLinkCallback(urlOrFragment: string): Promise<AuthTokens | null> {\n const hashIndex = urlOrFragment.indexOf('#');\n const fragment = hashIndex >= 0 ? urlOrFragment.slice(hashIndex + 1) : urlOrFragment;\n const params = new URLSearchParams(fragment);\n const accessToken = params.get('access_token');\n const refreshToken = params.get('refresh_token');\n const expiresIn = params.get('expires_in');\n if (!accessToken || !refreshToken) return null;\n const tokens: AuthTokens = {\n accessToken,\n refreshToken,\n expiresIn: expiresIn ? parseInt(expiresIn, 10) : 900,\n };\n const outcome = params.get('upgrade');\n this.lastUpgradeOutcome = UPGRADE_OUTCOMES.find((o) => o === outcome) ?? null;\n await this.storeCmsTokens(tokens);\n return tokens;\n }\n\n /** Every CMS-token session replaces (and so ends) an external one. */\n private async storeCmsTokens(tokens: AuthTokens): Promise<void> {\n this.autoAnonymousArmed = false; // a new session: no lazy anonymous creation pending\n await this.store.setTokens(tokens);\n await this.clearExternalMarker();\n await this.syncAnonymousMarker(this.isAnonymous());\n }\n\n /** Decode the current access token's claims (project id, subject, …). */\n getClaims(): AccessTokenClaims | null {\n return decodeAccessToken(this.store.getAccessToken());\n }\n\n /**\n * E54 — consumer-tier role ids carried by the current token (premium/special).\n * Empty when anonymous or untiered. Use it to branch UI on tier; the backend\n * still enforces what each tier can actually read/write.\n */\n getRoles(): string[] {\n return this.getClaims()?.roles ?? [];\n }\n\n isAuthenticated(): boolean {\n return this.store.getAccessToken() !== null || this.store.getRefreshToken() !== null;\n }\n\n /** Subscribe to auth-state changes (login / refresh / logout). Returns unsubscribe. */\n subscribe(listener: () => void): () => void {\n return this.store.subscribe(listener);\n }\n\n /**\n * Reactive session snapshot for `useAuth`. Memoized on the store's version so\n * the reference is stable between changes (safe for `useSyncExternalStore`).\n */\n getAuthState(): AuthState {\n const version = this.store.getVersion();\n if (this.authStateCache === null || version !== this.authStateVersion) {\n const claims = this.getClaims();\n this.authStateCache = {\n isAuthenticated: this.isAuthenticated(),\n userId: claims?.sub ?? null,\n roles: claims?.roles ?? [],\n isAnonymous: claims?.anon === true,\n };\n this.authStateVersion = version;\n }\n return this.authStateCache;\n }\n}\n","import { STORAGE_KEY_REFRESH_TOKEN } from '../constants';\nimport type { QafkaCmsStorage } from '../services/storageCore';\n\n/**\n * Holds the end-user session. The short-lived access token lives in memory\n * only; the long-lived refresh token is persisted in secure storage so the\n * session survives app restarts.\n *\n * Observable: `subscribe` is notified on every change (login / refresh / logout\n * / hydrate) and `getVersion` bumps with each, so derived state (e.g. the\n * `useAuth` snapshot) can be memoized without recomputing on every read.\n */\nexport class TokenStore {\n private accessToken: string | null = null;\n private accessExpiresAt = 0;\n private refreshToken: string | null = null;\n private version = 0;\n private readonly listeners = new Set<() => void>();\n /**\n * QFK2-E73 — how long a `REFRESH_TOKEN_ROTATED` answer waits for another\n * tab's successor token (storage write or a cross-tab sync `adopt`) before\n * the single retry.\n */\n rotationWaitMs = 2000;\n\n constructor(\n private readonly storage: Pick<QafkaCmsStorage, 'getItem' | 'setItem' | 'removeItem'>,\n private readonly now: () => number = Date.now,\n ) {}\n\n /** Load the persisted refresh token (call once at SDK init). */\n async hydrate(): Promise<void> {\n this.refreshToken = await this.storage.getItem(STORAGE_KEY_REFRESH_TOKEN);\n this.emit();\n }\n\n async setTokens(tokens: { accessToken: string; refreshToken: string; expiresIn: number }): Promise<void> {\n this.applyAccess(tokens.accessToken, tokens.expiresIn);\n this.refreshToken = tokens.refreshToken;\n await this.storage.setItem(STORAGE_KEY_REFRESH_TOKEN, tokens.refreshToken);\n this.emit();\n }\n\n /** External session: access token only. Drops any CMS refresh token (memory + storage); one notification. */\n async setExternalAccess(accessToken: string, expiresIn: number): Promise<void> {\n await this.storage.removeItem(STORAGE_KEY_REFRESH_TOKEN);\n this.refreshToken = null;\n this.applyAccess(accessToken, expiresIn);\n this.emit();\n }\n\n /**\n * QFK2-E73 — re-read the persisted refresh token (another tab/process may\n * have rotated it in shared storage). Emits only when it changed.\n */\n async reload(): Promise<void> {\n const stored = await this.storage.getItem(STORAGE_KEY_REFRESH_TOKEN);\n if (stored === this.refreshToken) return;\n this.refreshToken = stored;\n this.emit();\n }\n\n /**\n * QFK2-E73 — take over a session state pushed by another tab (web\n * BroadcastChannel sync): `null` = signed out there. Persists the refresh\n * token like {@link setTokens}; one notification.\n */\n async adopt(\n state: { accessToken: string | null; accessExpiresAt: number; refreshToken: string | null } | null,\n ): Promise<void> {\n if (!state || (!state.accessToken && !state.refreshToken)) {\n await this.clear();\n return;\n }\n if (state.refreshToken) await this.storage.setItem(STORAGE_KEY_REFRESH_TOKEN, state.refreshToken);\n else await this.storage.removeItem(STORAGE_KEY_REFRESH_TOKEN);\n this.refreshToken = state.refreshToken;\n this.accessToken = state.accessToken;\n this.accessExpiresAt = state.accessToken ? state.accessExpiresAt : 0;\n this.emit();\n }\n\n /**\n * QFK2-E73 — resolve once the session moved past `staleRefreshToken`: the\n * stored token changed (re-read first), or a valid access token arrived\n * (another tab's sync), or the session ended. Gives up after\n * {@link rotationWaitMs} (re-reading storage once more).\n */\n async waitForRotation(staleRefreshToken: string): Promise<void> {\n const moved = () => this.refreshToken !== staleRefreshToken || this.isAccessValid();\n await this.reload();\n if (moved()) return;\n await new Promise<void>((resolve) => {\n let unsubscribe: () => void = () => {};\n const timer = setTimeout(() => {\n unsubscribe();\n resolve();\n }, this.rotationWaitMs);\n unsubscribe = this.subscribe(() => {\n if (!moved()) return;\n clearTimeout(timer);\n unsubscribe();\n resolve();\n });\n });\n if (!moved()) await this.reload();\n }\n\n setAccessToken(accessToken: string, expiresIn: number): void {\n this.applyAccess(accessToken, expiresIn);\n this.emit();\n }\n\n private applyAccess(accessToken: string, expiresIn: number): void {\n this.accessToken = accessToken;\n this.accessExpiresAt = this.now() + expiresIn * 1000;\n }\n\n getAccessToken(): string | null {\n return this.accessToken;\n }\n\n /** Epoch ms when the access token expires (0 = none). */\n getAccessExpiresAt(): number {\n return this.accessExpiresAt;\n }\n\n isAccessValid(marginMs = 30_000): boolean {\n return this.accessToken !== null && this.now() < this.accessExpiresAt - marginMs;\n }\n\n getRefreshToken(): string | null {\n return this.refreshToken;\n }\n\n async clear(): Promise<void> {\n this.accessToken = null;\n this.accessExpiresAt = 0;\n this.refreshToken = null;\n await this.storage.removeItem(STORAGE_KEY_REFRESH_TOKEN);\n this.emit();\n }\n\n /** Observe auth-state changes. Returns an unsubscribe function. */\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /** Monotonic change counter — bumps on every mutation. */\n getVersion(): number {\n return this.version;\n }\n\n private emit(): void {\n this.version += 1;\n for (const listener of this.listeners) listener();\n }\n}\n","import type { FilterNode } from '../types/filter';\n\n/**\n * Serialize a filter tree for the `?filter=` query param. The backend expects\n * the FilterNode JSON verbatim (including dynamic vars like `$CURRENT_USER`),\n * so this is a plain JSON encode — kept as a named function for a single place\n * to evolve (e.g. validation) and for explicit unit coverage.\n */\nexport function serializeFilter(filter: FilterNode): string {\n return JSON.stringify(filter);\n}\n","import type { ConditionalResponse, HttpClient, RequestOptions } from '../transport/HttpClient';\nimport type { ContentRecord, GetParams, ListParams, ListResult } from '../types/content';\nimport { serializeFilter } from './filter-serialize';\nimport type { UnlockTokenStore } from './unlock-token-store';\n\n/**\n * Content CRUD against `/v1/end-user/content/:collection`. Access policy\n * (PUBLIC vs END_USER), row scoping, and limit clamping are enforced\n * server-side; the client just shapes requests and forwards the opaque cursor.\n *\n * Reads carry the active locale as an explicit `?locale=` query (E55): the\n * ambient locale comes from {@link ContentClientOptions.getLocale}, and a\n * per-request `params.locale` overrides it. The same locale also rides along as\n * `Accept-Language` (HttpClient); the backend resolves query > header > default.\n */\nexport interface ContentClientOptions {\n /** Ambient active locale (typically `() => languageManager.getLanguage()`). */\n getLocale?: () => string | null;\n /** Ambient locale-fallback preference (default off). */\n getLocaleFallback?: () => boolean;\n /** Persisted code-lookup unlock tokens (QFK2-E78); `lookup` stores into it. */\n unlockTokens?: UnlockTokenStore;\n}\n\n/** Result of {@link ContentClient.lookup}. */\nexport interface LookupResult<T = ContentRecord> {\n data: T;\n unlockToken: string;\n}\n\n/** Options of {@link ContentClient.listConditional} / {@link ContentClient.getConditional} (QFK2-E59 D4). */\nexport interface ConditionalReadOptions {\n /** ETag of the copy the caller holds (`If-None-Match`); `null` / absent = unconditional. */\n ifNoneMatch?: string | null;\n}\n\n/** `['a', ' -b ', '']` / `'a,-b'` → `'a,-b'`; nothing left → omitted. */\nexport function joinKeys(keys?: string | readonly string[]): string | undefined {\n if (keys === undefined) return undefined;\n const list = (typeof keys === 'string' ? keys.split(',') : keys).map((k) => k.trim()).filter(Boolean);\n return list.length ? list.join(',') : undefined;\n}\n\nexport class ContentClient {\n constructor(\n private readonly http: HttpClient,\n private readonly opts: ContentClientOptions = {},\n ) {}\n\n list<T = ContentRecord>(collection: string, params: ListParams = {}): Promise<ListResult<T>> {\n return this.http.request<ListResult<T>>('GET', `/content/${collection}`, this.listOptions(params));\n }\n\n get<T = ContentRecord>(collection: string, id: string, params: GetParams = {}): Promise<T> {\n return this.http.request<T>('GET', `/content/${collection}/${id}`, this.getOptions(params));\n }\n\n /**\n * {@link list} as a conditional GET (QFK2-E59 D4): the identical request plus\n * `If-None-Match` when `opts.ifNoneMatch` is set. Resolves\n * `{ notModified: true }` on 304, otherwise the page and its ETag.\n */\n listConditional<T = ContentRecord>(\n collection: string,\n params: ListParams = {},\n opts: ConditionalReadOptions = {},\n ): Promise<ConditionalResponse<ListResult<T>>> {\n return this.http.requestConditional<ListResult<T>>('GET', `/content/${collection}`, {\n ...this.listOptions(params),\n ifNoneMatch: opts.ifNoneMatch,\n });\n }\n\n /** {@link get} as a conditional GET; see {@link listConditional}. */\n getConditional<T = ContentRecord>(\n collection: string,\n id: string,\n params: GetParams = {},\n opts: ConditionalReadOptions = {},\n ): Promise<ConditionalResponse<T>> {\n return this.http.requestConditional<T>('GET', `/content/${collection}/${id}`, {\n ...this.getOptions(params),\n ifNoneMatch: opts.ifNoneMatch,\n });\n }\n\n create<T = ContentRecord>(collection: string, data: Record<string, unknown>): Promise<T> {\n return this.http.request<T>('POST', `/content/${collection}`, {\n body: data,\n withUnlockTokens: true,\n });\n }\n\n update<T = ContentRecord>(collection: string, id: string, data: Record<string, unknown>): Promise<T> {\n return this.http.request<T>('PATCH', `/content/${collection}/${id}`, {\n body: data,\n withUnlockTokens: true,\n });\n }\n\n delete(collection: string, id: string): Promise<void> {\n return this.http.request<void>('DELETE', `/content/${collection}/${id}`, { withUnlockTokens: true });\n }\n\n /**\n * Unlock a code-locked record (QFK2-E78). Wrong/unknown codes reject with a\n * `ProblemError` (404 `LOOKUP_NOT_FOUND`, 400 `LOOKUP_BAD_REQUEST`, 429\n * `LOOKUP_RATE_LIMITED`). On success the token is persisted and sent on every\n * later content request.\n */\n async lookup<T = ContentRecord>(collection: string, code: string, params: GetParams = {}): Promise<LookupResult<T>> {\n const res = await this.http.request<LookupResult<T>>('POST', `/lookup/${collection}`, {\n body: { code },\n withUnlockTokens: true,\n query: {\n locale: this.resolveLocale(params.locale),\n locale_fallback: this.resolveFallback(params.localeFallback),\n expand: joinKeys(params.expand),\n with_title: params.withTitle ? 'true' : undefined,\n },\n });\n // No string `data.id` (unexpected server shape) → nothing to key the token by, so it is not stored.\n const id = (res.data as { id?: unknown } | null)?.id;\n if (this.opts.unlockTokens && typeof id === 'string' && res.unlockToken) {\n await this.opts.unlockTokens.add(collection, id, res.unlockToken);\n }\n return res;\n }\n\n /** Forget all stored unlock tokens (e.g. on sign-out); locked rows lock again. */\n async clearUnlockTokens(): Promise<void> {\n await this.opts.unlockTokens?.clear();\n }\n\n /** Subscribe to unlock-token changes (lookup / clear). Returns unsubscribe. */\n onUnlockChange(listener: () => void): () => void {\n return this.opts.unlockTokens?.subscribe(listener) ?? (() => {});\n }\n\n /** Request options of a list read (shared by {@link list} and {@link listConditional}). */\n private listOptions(params: ListParams): RequestOptions {\n return {\n withUnlockTokens: true,\n query: {\n filter: params.filter ? serializeFilter(params.filter) : undefined,\n limit: params.limit,\n cursor: params.cursor,\n page: params.page,\n locale: this.resolveLocale(params.locale),\n locale_fallback: this.resolveFallback(params.localeFallback),\n sort: joinKeys(params.sort),\n expand: joinKeys(params.expand),\n with_title: params.withTitle ? 'true' : undefined,\n },\n };\n }\n\n /** Request options of a single-record read (shared by {@link get} and {@link getConditional}). */\n private getOptions(params: GetParams): RequestOptions {\n return {\n withUnlockTokens: true,\n query: {\n locale: this.resolveLocale(params.locale),\n locale_fallback: this.resolveFallback(params.localeFallback),\n expand: joinKeys(params.expand),\n with_title: params.withTitle ? 'true' : undefined,\n },\n };\n }\n\n /** Explicit param wins over the ambient locale; both absent → omit the query. */\n private resolveLocale(explicit?: string): string | undefined {\n return explicit ?? this.opts.getLocale?.() ?? undefined;\n }\n\n /** Emit `locale_fallback=true` only when truthy; otherwise omit it. */\n private resolveFallback(explicit?: boolean): true | undefined {\n return (explicit ?? this.opts.getLocaleFallback?.()) ? true : undefined;\n }\n}\n","import { STORAGE_KEY_UNLOCK_TOKENS } from \"../constants\";\nimport type { QafkaCmsStorage } from \"../services/storageCore\";\n\ninterface UnlockEntry {\n collection: string;\n id: string;\n token: string;\n}\n\n/** The server accepts at most 20 tokens per request; keep the newest 20. */\nconst MAX_TOKENS = 20;\n\n/**\n * Holds the unlock tokens returned by `content.lookup` (QFK2-E78). One token\n * per (collection, id), newest 20 kept, persisted in secure storage. Tokens\n * never expire and the server silently ignores stale ones, so nothing is ever\n * pruned on failure. Observable: `subscribe` fires on add / clear.\n */\nexport class UnlockTokenStore {\n private entries: UnlockEntry[] = [];\n /** Serializes storage writes so the last persisted snapshot equals the in-memory state. */\n private writeChain: Promise<void> = Promise.resolve();\n private readonly listeners = new Set<() => void>();\n /** Memoized load: initialize(), getRequestHeaders(), add() and clear() share one read. */\n private hydration: Promise<void> | null = null;\n\n constructor(\n private readonly storage: Pick<\n QafkaCmsStorage,\n \"getItem\" | \"setItem\" | \"removeItem\"\n >,\n ) {}\n\n /**\n * Load persisted tokens. Idempotent: every caller awaits the same read, so it\n * is safe from initialize() and from getRequestHeaders() before initialize().\n * Corrupt storage → empty.\n */\n hydrate(): Promise<void> {\n if (!this.hydration) this.hydration = this.load();\n return this.hydration;\n }\n\n private async load(): Promise<void> {\n try {\n const raw = await this.storage.getItem(STORAGE_KEY_UNLOCK_TOKENS);\n const parsed: unknown = raw ? JSON.parse(raw) : [];\n this.entries = Array.isArray(parsed)\n ? parsed\n .filter(\n (e): e is UnlockEntry =>\n !!e &&\n typeof e.collection === \"string\" &&\n typeof e.id === \"string\" &&\n typeof e.token === \"string\",\n )\n .slice(-MAX_TOKENS)\n : [];\n } catch {\n this.entries = [];\n }\n }\n\n /** Newest-last token list, as sent in `X-Unlock-Token`. */\n tokens(): string[] {\n return this.entries.map((e) => e.token);\n }\n\n async add(collection: string, id: string, token: string): Promise<void> {\n // A lookup before hydration must not be overwritten by the persisted list.\n await this.hydrate();\n this.entries = [\n ...this.entries.filter(\n (e) => !(e.collection === collection && e.id === id),\n ),\n { collection, id, token },\n ].slice(-MAX_TOKENS);\n const snapshot = JSON.stringify(this.entries);\n await this.enqueue(() =>\n this.storage.setItem(STORAGE_KEY_UNLOCK_TOKENS, snapshot),\n );\n this.emit();\n }\n\n async clear(): Promise<void> {\n await this.hydrate();\n this.entries = [];\n await this.enqueue(() =>\n this.storage.removeItem(STORAGE_KEY_UNLOCK_TOKENS),\n );\n this.emit();\n }\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n private enqueue(op: () => Promise<void>): Promise<void> {\n const next = this.writeChain.then(op);\n this.writeChain = next.catch(() => undefined);\n return next;\n }\n\n private emit(): void {\n for (const l of [...this.listeners]) l();\n }\n}\n","import type { AppStateProvider } from '../platform/types';\n\n/**\n * Polling floor (E56 abuse guard): the SDK never polls faster than this, no\n * matter what a consumer passes. A domain that genuinely needs sub-second\n * freshness must opt into SSE (`live: true`), not a tiny poll interval.\n */\nexport const MIN_POLL_INTERVAL_MS = 30_000;\n/** Default cadence when none is set — versions rarely change, so 60s is plenty. */\nexport const DEFAULT_POLL_INTERVAL_MS = 60_000;\n\n/** Effective poll interval: default when unset, clamped up to the floor. */\nexport function resolvePollInterval(requested?: number): number {\n return Math.max(MIN_POLL_INTERVAL_MS, requested ?? DEFAULT_POLL_INTERVAL_MS);\n}\n\ntype TimerHandle = unknown;\n\nexport interface VersionPollerOptions {\n /** One poll cycle (e.g. probe a cheap `/version` endpoint). Errors are swallowed; the next tick retries. */\n check: () => Promise<void> | void;\n /** Requested cadence; clamped by {@link resolvePollInterval} (default 60 s, floor 30 s). */\n intervalMs?: number;\n /**\n * Foreground/background source. With {@link followAppState} (default) the\n * poller pauses in the background and, on return to foreground, checks at\n * once and resumes (jittered). Either way it never starts in the background.\n */\n appState?: AppStateProvider;\n /**\n * `false` = the owner drives pause/resume itself (it calls `stop`/`start`);\n * `appState` then only guards `start()`. Default `true`.\n */\n followAppState?: boolean;\n /** Jitter RNG (deterministic in tests). Default `Math.random`. */\n random?: () => number;\n setTimeout?: (fn: () => void, ms: number) => TimerHandle;\n clearTimeout?: (handle: TimerHandle) => void;\n}\n\n/**\n * Version polling shared by config-sync and the content change hub (E56 rules,\n * QFK2-E76 76.7): interval clamped to the 30 s floor, the first tick jittered\n * across `[0, interval)` so a fleet that restarts or foregrounds together does\n * not poll in lockstep, then a steady interval; paused in the background.\n */\nexport class VersionPoller {\n readonly intervalMs: number;\n private timer: TimerHandle | null = null;\n /** `start()` called and not yet `stop()`ped (survives background pauses). */\n private wanted = false;\n private appStateUnsub: (() => void) | null = null;\n\n constructor(private readonly opts: VersionPollerOptions) {\n this.intervalMs = resolvePollInterval(opts.intervalMs);\n }\n\n /** A tick is scheduled (not paused, not stopped). */\n get running(): boolean {\n return this.timer !== null;\n }\n\n /** Begin polling (first tick jittered). No-op while already running or in the background. */\n start(): void {\n this.wanted = true;\n if (this.opts.appState && this.opts.followAppState !== false && !this.appStateUnsub) {\n this.appStateUnsub = this.opts.appState.subscribe((active) => {\n if (!this.wanted) return;\n if (active) {\n void this.checkNow();\n this.schedule();\n } else {\n this.clear();\n }\n });\n }\n this.schedule();\n }\n\n /** Stop ticking and drop the app-state subscription. */\n stop(): void {\n this.wanted = false;\n this.appStateUnsub?.();\n this.appStateUnsub = null;\n this.clear();\n }\n\n /** Alias of {@link stop}. */\n dispose(): void {\n this.stop();\n }\n\n /** Run one check now (outside the cadence). Never rejects. */\n async checkNow(): Promise<void> {\n try {\n await this.opts.check();\n } catch {\n // transient — the next tick retries\n }\n }\n\n private isForeground(): boolean {\n return this.opts.appState ? this.opts.appState.isActive() : true;\n }\n\n private schedule(): void {\n if (this.timer !== null || !this.isForeground()) return;\n const random = this.opts.random ?? Math.random;\n // Spread the FIRST poll across [0, interval); after it fires settle into the steady interval.\n const firstDelay = Math.floor(random() * this.intervalMs);\n this.arm(firstDelay);\n }\n\n private arm(delay: number): void {\n const set = this.opts.setTimeout ?? ((fn: () => void, ms: number) => setTimeout(fn, ms));\n const handle = set(() => {\n if (this.timer !== handle) return; // cleared meanwhile\n // Re-arm before checking so the cadence does not drift with the check's latency.\n this.timer = null;\n this.arm(this.intervalMs);\n void this.checkNow();\n }, delay);\n this.timer = handle;\n // Keep a background poll from holding the process (Node) / Jest run alive.\n (handle as { unref?: () => void } | null)?.unref?.();\n }\n\n private clear(): void {\n if (this.timer === null) return;\n const clear = this.opts.clearTimeout ?? ((h: TimerHandle) => clearTimeout(h as ReturnType<typeof setTimeout>));\n clear(this.timer);\n this.timer = null;\n }\n}\n","import type { ConnectSse, SseConnection } from '../platform/types';\n\n/** A clean SSE close sooner than this after connect counts as an \"immediate\" close. */\nexport const SSE_RAPID_CLOSE_MS = 5_000;\n/** After this many consecutive immediate closes, give up on SSE (→ `onFallback`). */\nexport const SSE_MAX_RAPID_CLOSES = 3;\nconst SSE_RECONNECT_BASE_MS = 1_000;\nconst SSE_RECONNECT_MAX_MS = 8_000;\n/** Reconnect delays are spread ±30 % so a fleet dropped together does not reconnect in lockstep. */\nconst SSE_RECONNECT_JITTER = 0.3;\n/**\n * A connection that delivers no event at all (the server pings every 25 s) for\n * this long is presumed dead (a half-open TCP socket, a proxy that stopped\n * forwarding): it is closed and reopened at once, like a transport recycle.\n */\nexport const SSE_IDLE_TIMEOUT_MS = 60_000;\n\ntype TimerHandle = unknown;\n\nexport interface SseSupervisorOptions {\n connectSse: ConnectSse;\n /** Stream URL, read right before each connect (a hub may change it with its subscription set). */\n url: () => string;\n /** Request headers, resolved right before each connect (fresh token / key). A throw → `onFallback`. */\n headers?: () => Promise<Record<string, string>> | Record<string, string>;\n /** Every event of the current connection, as the transport parsed it (validate it yourself). */\n onMessage: (event: unknown) => void;\n /**\n * SSE is unusable: the connection errored, headers could not be resolved, or\n * it closed immediately {@link SSE_MAX_RAPID_CLOSES} times in a row. The owner\n * switches to polling; the supervisor stays idle until the next `start()`.\n */\n onFallback: () => void;\n now?: () => number;\n /** Jitter RNG for the reconnect backoff (deterministic in tests). Default `Math.random`. */\n random?: () => number;\n setTimeout?: (fn: () => void, ms: number) => TimerHandle;\n clearTimeout?: (handle: TimerHandle) => void;\n}\n\n/**\n * One supervised SSE channel (config-sync, content change hub): reconnects a\n * clean close with exponential backoff (1 s, 2 s, … capped at 8 s, each ±30 %\n * jitter) and fresh headers, falls back after repeated immediate closes or an\n * error, and ignores callbacks of connections it has already replaced or\n * stopped. A transport \"recycle\" close (`onClose({ reason: 'recycle' })`, the\n * transport bounding its buffer) and an idle-watchdog close (no event for\n * {@link SSE_IDLE_TIMEOUT_MS}) reconnect at once and are not counted as\n * immediate.\n */\nexport class SseSupervisor {\n private conn: SseConnection | null = null;\n /** Identity of the live connection; cleared on drop (also covers callbacks fired during connect). */\n private token: object | null = null;\n /** Bumped by start/stop so in-flight opens and stale callbacks detect they were superseded. */\n private epoch = 0;\n private openedAt = 0;\n private rapidCloses = 0;\n private reconnectTimer: TimerHandle | null = null;\n private idleTimer: TimerHandle | null = null;\n\n constructor(private readonly opts: SseSupervisorOptions) {}\n\n /** A connection is currently open (or opening at the transport level). */\n get connected(): boolean {\n return this.token !== null;\n }\n\n /** (Re)open the channel: resets the rapid-close streak, replaces any current connection. */\n async start(): Promise<void> {\n this.epoch += 1;\n this.clearReconnect();\n this.rapidCloses = 0;\n await this.open(this.epoch);\n }\n\n /** Close the channel and silence every pending callback / reconnect. */\n stop(): void {\n this.epoch += 1;\n this.clearReconnect();\n this.rapidCloses = 0;\n this.dropConnection();\n }\n\n private now(): number {\n return (this.opts.now ?? Date.now)();\n }\n\n private set(fn: () => void, ms: number): TimerHandle {\n const handle = (this.opts.setTimeout ?? ((f: () => void, t: number) => setTimeout(f, t)))(fn, ms);\n // Keep a pending timer from holding the process (Node) / Jest run alive.\n (handle as { unref?: () => void } | null)?.unref?.();\n return handle;\n }\n\n private clear(handle: TimerHandle): void {\n (this.opts.clearTimeout ?? ((h: TimerHandle) => clearTimeout(h as ReturnType<typeof setTimeout>)))(handle);\n }\n\n /** (Re)arm the idle watchdog of the current connection; it reopens the channel when it fires. */\n private armIdle(epoch: number, token: object): void {\n if (this.idleTimer !== null) this.clear(this.idleTimer);\n this.idleTimer = this.set(() => {\n this.idleTimer = null;\n if (epoch !== this.epoch || this.token !== token) return;\n // Silent for too long: presumed dead. Reopen at once with fresh headers; not \"immediate\".\n this.dropConnection();\n this.rapidCloses = 0;\n void this.open(epoch);\n }, SSE_IDLE_TIMEOUT_MS);\n }\n\n private async open(epoch: number): Promise<void> {\n let headers: Record<string, string> = {};\n try {\n headers = (await this.opts.headers?.()) ?? {};\n } catch {\n // header resolution failed — degrade to polling\n if (epoch === this.epoch) this.opts.onFallback();\n return;\n }\n // Stopped / superseded by a newer start while headers resolved.\n if (epoch !== this.epoch) return;\n this.dropConnection();\n this.openedAt = this.now();\n const token = {};\n this.token = token;\n const isCurrent = () => epoch === this.epoch && this.token === token;\n this.armIdle(epoch, token);\n const conn = this.opts.connectSse(this.opts.url(), headers, {\n onMessage: (event) => {\n if (!isCurrent()) return;\n this.armIdle(epoch, token); // any event, ping included, proves the connection alive\n this.opts.onMessage(event);\n },\n onError: () => {\n if (!isCurrent()) return;\n this.dropConnection(); // connection lost → degrade to polling\n this.opts.onFallback();\n },\n onClose: (info) => {\n if (!isCurrent()) return;\n this.dropConnection();\n if (info?.reason === 'recycle') {\n // Transport-initiated bounded-buffer reconnect: healthy, not \"immediate\".\n this.rapidCloses = 0;\n void this.open(epoch);\n return;\n }\n // Reset the streak when the connection lived a healthy while.\n if (this.now() - this.openedAt >= SSE_RAPID_CLOSE_MS) this.rapidCloses = 0;\n this.rapidCloses += 1;\n if (this.rapidCloses >= SSE_MAX_RAPID_CLOSES) {\n this.opts.onFallback(); // keeps closing immediately — stop hammering\n return;\n }\n const base = Math.min(SSE_RECONNECT_MAX_MS, SSE_RECONNECT_BASE_MS * 2 ** (this.rapidCloses - 1));\n const random = this.opts.random ?? Math.random;\n const delay = Math.round(base * (1 - SSE_RECONNECT_JITTER + 2 * SSE_RECONNECT_JITTER * random()));\n this.clearReconnect();\n this.reconnectTimer = this.set(() => {\n this.reconnectTimer = null;\n if (epoch !== this.epoch) return;\n void this.open(epoch); // headers re-resolve → fresh token / key\n }, delay);\n },\n });\n if (this.token === token) this.conn = conn;\n else conn.close(); // the transport errored/closed synchronously while connecting\n }\n\n private dropConnection(): void {\n const conn = this.conn;\n if (this.idleTimer !== null) this.clear(this.idleTimer);\n this.idleTimer = null;\n this.token = null;\n this.conn = null; // first, so a transport that calls back synchronously from close() is ignored\n conn?.close();\n }\n\n private clearReconnect(): void {\n if (this.reconnectTimer === null) return;\n this.clear(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n}\n","import { END_USER_BASE_PATH, STORAGE_KEY_CONFIG_PREFIX } from '../constants';\nimport type { QafkaCmsStorage } from '../services/storageCore';\nimport type { AppStateProvider, ConnectSse, SseConnection, SseHandlers } from '../platform/types';\nimport { VersionPoller } from '../sync/VersionPoller';\nimport { SseSupervisor } from '../sync/SseSupervisor';\n\n/**\n * Runtime config-sync — one client per customization domain (translations,\n * theme, navigation, remote-config). Same contract for every domain, modelled\n * on the Shopla `react-native-firebase-translations` 5-part pattern\n * (`references/notes/runtime-config-sync-pattern.md`), with Firebase RTDB\n * replaced by an SSE version-watch (E9 realtime) plus a polling fallback.\n *\n * The five parts:\n * 1. build-time default (shipped with the app — instant first paint)\n * 2. secure-storage cache (survives restart, hydrated on start)\n * 3. version-only subscription (SSE pushes a version number, not the payload)\n * 4. snapshot fetch on bump (REST GET when the version advances)\n * 5. polling fallback (periodic snapshot when SSE is unavailable)\n *\n * Backend endpoints (`/v1/end-user/config/:domain` + `…/watch`) are aligned by\n * E9/E10; the SDK codes to this contract today.\n */\n// Polling floor/default and the SSE fall-back rules live in the shared sync\n// helpers (QFK2-E76 76.7); re-exported here so existing imports keep working.\nexport { MIN_POLL_INTERVAL_MS, DEFAULT_POLL_INTERVAL_MS, resolvePollInterval } from '../sync/VersionPoller';\nexport { SSE_RAPID_CLOSE_MS, SSE_MAX_RAPID_CLOSES } from '../sync/SseSupervisor';\n\nexport interface ConfigSnapshot<T> {\n version: number;\n data: T;\n}\n\n// Platform transport/app-state contracts live in `platform/types` (QFK2-E73);\n// re-exported here so existing imports keep working.\nexport type { AppStateProvider, ConnectSse, SseConnection, SseHandlers };\n\nexport interface ConfigSyncOptions<T> {\n domain: string;\n buildTimeDefault: T;\n /**\n * Version of the embedded `buildTimeDefault` (E58). Seeds the client's version\n * so a fresh build supersedes an older cache, and a matching server version is\n * not re-fetched. Omit (→ 0) when nothing is embedded.\n */\n buildTimeVersion?: number;\n apiUrl: string;\n http: { request: <R>(method: 'GET', path: string) => Promise<R> };\n storage: Pick<QafkaCmsStorage, 'getItem' | 'setItem'>;\n connectSse?: ConnectSse;\n /** SSE request headers; a function is resolved (async) right before each connect. */\n headers?: Record<string, string> | (() => Promise<Record<string, string>>);\n pollIntervalMs?: number;\n /** Foreground/background source — pauses polling in the background (E56). */\n appState?: AppStateProvider;\n /** Injectable RNG for poll and SSE-reconnect jitter (deterministic in tests). Default Math.random. */\n random?: () => number;\n}\n\ntype Listener<T> = (data: T) => void;\n\n/** The `{ version }` shape of a config-watch SSE event; anything else is ignored (D7). */\nfunction isVersionEvent(event: unknown): event is { version: number } {\n return typeof event === 'object' && event !== null && typeof (event as { version?: unknown }).version === 'number';\n}\n\nexport class ConfigSyncClient<T> {\n private data: T;\n private version = 0;\n private readonly listeners = new Set<Listener<T>>();\n private stopped = false;\n private appStateUnsub: (() => void) | null = null;\n /** Polling fallback; this client drives pause/resume itself (SSE and polling share AppState). */\n private readonly poller: VersionPoller;\n private readonly sse: SseSupervisor | null;\n\n constructor(private readonly opts: ConfigSyncOptions<T>) {\n this.data = opts.buildTimeDefault;\n this.version = opts.buildTimeVersion ?? 0;\n this.poller = new VersionPoller({\n check: () => this.pollOnce(),\n intervalMs: opts.pollIntervalMs,\n appState: opts.appState,\n followAppState: false,\n random: opts.random,\n });\n const connectSse = opts.connectSse;\n this.sse = connectSse\n ? new SseSupervisor({\n connectSse,\n url: () => `${opts.apiUrl.replace(/\\/$/, '')}${END_USER_BASE_PATH}/config/${opts.domain}/watch`,\n headers: () => {\n const h = opts.headers;\n return (typeof h === 'function' ? h() : h) ?? {};\n },\n onMessage: (event) => {\n if (isVersionEvent(event) && event.version > this.version) {\n void this.fetchAndApply({ emit: true });\n }\n },\n // Error, header failure or repeated immediate closes → poll.\n onFallback: () => this.startPolling(),\n random: opts.random,\n })\n : null;\n }\n\n /** Latest known config (build-time default until `start()` resolves). */\n current(): T {\n return this.data;\n }\n\n subscribe(listener: Listener<T>): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n async start(): Promise<void> {\n this.stopped = false;\n await this.hydrateFromCache();\n // First sync. With nothing local (version 0) pull the full snapshot. With a\n // build-time/cache version already in hand, do a cheap version probe and only\n // fetch when the server is newer — so a cold start with no network still\n // shows the embedded config (E56 version-only + E58 bootstrap).\n if (this.version === 0) {\n await this.fetchAndApply({ emit: false, force: true });\n } else {\n await this.pollOnce();\n }\n await this.beginSync();\n\n // Pause sync in the background; on return to foreground, resume and probe\n // the version immediately so the app shows fresh config (E56).\n if (this.opts.appState) {\n this.appStateUnsub = this.opts.appState.subscribe((active) => {\n if (this.stopped) return;\n if (active) {\n void this.beginSync();\n void this.pollOnce();\n } else {\n this.pauseSync();\n }\n });\n }\n }\n\n stop(): void {\n this.stopped = true;\n this.appStateUnsub?.();\n this.appStateUnsub = null;\n this.pauseSync();\n }\n\n // --- sync lifecycle (paused/resumed by AppState) ------------------------\n\n /** Open the live channel: SSE if configured, otherwise polling. */\n private async beginSync(): Promise<void> {\n if (!this.sse) {\n this.startPolling();\n return;\n }\n await this.sse.start();\n }\n\n /** Tear the live channel down without ending the client (background). */\n private pauseSync(): void {\n this.sse?.stop();\n this.poller.stop();\n }\n\n // --- internals ----------------------------------------------------------\n\n private cacheKey(): string {\n return `${STORAGE_KEY_CONFIG_PREFIX}${this.opts.domain}`;\n }\n\n private async hydrateFromCache(): Promise<void> {\n const raw = await this.opts.storage.getItem(this.cacheKey());\n if (!raw) return;\n try {\n const cached = JSON.parse(raw) as ConfigSnapshot<T>;\n // Only adopt the cache when it is NEWER than what we already have — a fresh\n // build embeds a higher buildTimeVersion and must win over a stale cache.\n if (cached && typeof cached.version === 'number' && cached.version > this.version) {\n this.version = cached.version;\n this.data = cached.data;\n }\n } catch {\n // corrupt cache — ignore, fall back to default\n }\n }\n\n private async fetchAndApply({ emit, force }: { emit: boolean; force?: boolean }): Promise<void> {\n let snapshot: ConfigSnapshot<T>;\n try {\n snapshot = await this.opts.http.request<ConfigSnapshot<T>>('GET', `/config/${this.opts.domain}`);\n } catch {\n return; // transient — a later bump or poll retries\n }\n if (!force && snapshot.version <= this.version) return;\n this.version = snapshot.version;\n this.data = snapshot.data;\n await this.opts.storage.setItem(this.cacheKey(), JSON.stringify(snapshot));\n if (emit) this.emit();\n }\n\n private emit(): void {\n for (const listener of this.listeners) listener(this.data);\n }\n\n /**\n * One poll cycle: probe the cheap `/version` endpoint and only pull the full\n * snapshot when the version actually advanced (E56). This keeps a 60s poll\n * from re-downloading an unchanged KB-sized payload every tick.\n */\n private async pollOnce(): Promise<void> {\n let result: { version: number };\n try {\n result = await this.opts.http.request<{ version: number }>(\n 'GET',\n `/config/${this.opts.domain}/version`,\n );\n } catch {\n return; // transient — the next tick retries\n }\n if (typeof result?.version === 'number' && result.version > this.version) {\n await this.fetchAndApply({ emit: true });\n }\n }\n\n private startPolling(): void {\n // The poller guards foreground too: an SSE `onError` can fire asynchronously\n // after we've already paused for the background, and must not revive polling.\n if (this.stopped) return;\n this.poller.start();\n }\n}\n","import { STORAGE_KEY_LOCALE } from '../constants';\nimport type { QafkaCmsStorage } from '../services/storageCore';\nimport type { I18nData, LocalesData, TranslateParams } from './types';\n\n/**\n * Active-language runtime for the SDK (E55). Holds the user's selected locale,\n * the project's supported-locale set (`locales` domain), and the UI-string map\n * (`i18n` domain), and resolves `t(key)` against them. Framework-agnostic: the\n * React `useLocale`/`useTranslation` hooks subscribe to it via `useSyncExternalStore`.\n *\n * Modelled on Shopla's `react-native-firebase-translations` (active locale +\n * persisted choice + reactive notify), but fed by QafkaCMS config-sync instead\n * of Firebase — `applyLocales`/`applyI18n` are the seams the config-sync clients\n * push into (see {@link QafkaCmsClient}).\n */\nexport interface LanguageManagerDeps {\n storage: Pick<QafkaCmsStorage, 'getItem' | 'setItem'>;\n}\n\nconst DEFAULT_LOCALES: LocalesData = { defaultLocale: 'en', locales: ['en'] };\nconst DEFAULT_I18N: I18nData = { translations: {} };\n\nexport class LanguageManager {\n /** null until the user picks (or `hydrate` restores) a locale; falls back to default. */\n private locale: string | null = null;\n private locales: LocalesData = DEFAULT_LOCALES;\n private i18n: I18nData = DEFAULT_I18N;\n private readonly listeners = new Set<() => void>();\n /** Monotonic change counter — the `useSyncExternalStore` snapshot for the React hooks. */\n private revision = 0;\n\n constructor(private readonly deps: LanguageManagerDeps) {}\n\n /** Snapshot for `useSyncExternalStore`: bumps on every locale / data change. */\n getRevision(): number {\n return this.revision;\n }\n\n /** The active locale, or the project default until one is chosen. */\n getLanguage(): string {\n return this.locale ?? this.locales.defaultLocale;\n }\n\n getDefaultLocale(): string {\n return this.locales.defaultLocale;\n }\n\n getAvailableLocales(): string[] {\n return this.locales.locales;\n }\n\n /** Switch the active locale: update state, persist, and notify subscribers. */\n async setLanguage(locale: string): Promise<void> {\n this.locale = locale;\n await this.deps.storage.setItem(STORAGE_KEY_LOCALE, locale);\n this.emit();\n }\n\n /**\n * Resolve a UI string. Lookup order: active locale → default locale → the key\n * itself (so a missing translation degrades to a visible-but-stable token).\n */\n t(key: string, params?: TranslateParams): string {\n const tables = this.i18n.translations;\n const raw =\n tables[this.getLanguage()]?.[key] ??\n tables[this.locales.defaultLocale]?.[key] ??\n key;\n return params ? interpolate(raw, params) : raw;\n }\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /** Config-sync seam: the `locales` domain snapshot landed. */\n applyLocales(data: LocalesData): void {\n this.locales = data;\n this.emit();\n }\n\n /** Config-sync seam: the `i18n` domain snapshot landed. */\n applyI18n(data: I18nData): void {\n this.i18n = data;\n this.emit();\n }\n\n /** Restore the persisted locale (call once at boot, after storage is ready). */\n async hydrate(): Promise<void> {\n const stored = await this.deps.storage.getItem(STORAGE_KEY_LOCALE);\n if (stored) this.locale = stored;\n }\n\n private emit(): void {\n this.revision++;\n for (const listener of this.listeners) listener();\n }\n}\n\nfunction interpolate(template: string, params: TranslateParams): string {\n let out = template;\n for (const [key, value] of Object.entries(params)) {\n out = out.replace(\n new RegExp(`{{\\\\s*${escapeRegExp(key)}\\\\s*}}`, 'g'),\n String(value),\n );\n }\n return out;\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n","/**\n * `ContentChangesApi.versions` (QFK2-E59 D7), in its own module so a client\n * that never uses `live` does not pull the change hub into its bundle.\n */\n\nconst enc = encodeURIComponent;\n\n/** `ContentChangesApi.versions` over an end-user GET (`request` rejects with a `status`). */\nexport async function fetchContentVersions(\n request: (path: string) => Promise<unknown>,\n collections: readonly string[],\n): Promise<Record<string, string>> {\n if (!collections.length) return {};\n const res = (await request(`/content-changes/version?collections=${collections.map(enc).join(',')}`)) as Record<\n string,\n unknown\n > | null;\n const out: Record<string, string> = {};\n for (const c of collections) {\n const v = res?.[c];\n if (typeof v === 'string' || typeof v === 'number') out[c] = String(v);\n }\n return out;\n}\n","import { HttpClient } from '../transport/HttpClient';\nimport { AuthClient } from '../auth/AuthClient';\nimport { TokenStore } from '../auth/token-store';\nimport { ContentClient } from '../content/ContentClient';\nimport { UnlockTokenStore } from '../content/unlock-token-store';\nimport { ConfigSyncClient } from '../config-sync/ConfigSyncClient';\nimport { LanguageManager } from '../i18n/LanguageManager';\nimport { fetchContentVersions } from '../content-sync/versions';\nimport type { ContentChangeHubOptions, ContentChangesApi, ContentLiveMode } from '../content-sync/ContentChangeHub';\nimport type { I18nData, LocalesData } from '../i18n/types';\nimport type { KeyValueStorage, PlatformAdapter, ProofProvider } from '../platform/types';\nimport type { AnonymousAuthMode } from '../types/auth';\nimport type {\n ContentBundleApi,\n ContentBundleConfig,\n ContentBundleFactory,\n ContentBundleOption,\n} from '../content-bundle/types';\n\n/**\n * Platform-neutral client core (QFK2-E73 §4.2): transport + auth + content\n * (thin tier), plus the language runtime and config-sync (full tier). Every\n * platform need comes in through a {@link PlatformAdapter}; the React Native\n * `QafkaCmsClient` composes this with attestation, push and dev config, and a\n * web / Node client composes it with browser or server adapters.\n */\n\n/** Configuration of a {@link CoreClient}. */\nexport interface CoreConfig {\n /** Backend base URL (no `/v1/...` suffix). */\n apiUrl: string;\n /** Project id (UUID) — `X-Project-Id`. Required unless `publishableKey` is set. */\n projectId?: string;\n /** Publishable key (`qpk_…`). Required unless `projectId` is set. */\n publishableKey?: string;\n /** Optional project label (`X-Project-Slug`). */\n projectSlug?: string;\n /** External identity provider (E44). */\n externalTokenProvider?: () => Promise<string | null>;\n /** Default external provider key (E72). */\n externalProvider?: string;\n /** Anonymous end-users (QFK2-T322): `'auto'` creates one at `initialize()` when no session is stored. */\n anonymousAuth?: AnonymousAuthMode;\n /**\n * `'thin'` (default): transport + auth + content. `'full'`: also the\n * language runtime (`language`) fed by the SDK-managed `locales` / `i18n`\n * config-sync domains.\n */\n tier?: 'thin' | 'full';\n /** Full tier: build-time embedded `locales` / `i18n` snapshots (E58). */\n bootstrap?: {\n i18n?: { version: number; data: I18nData };\n locales?: { version: number; data: LocalesData };\n };\n /** Full tier: poll cadence of the SDK-managed config domains (clamped to the floor). */\n configPollIntervalMs?: number;\n /** Transport of `live` content watches that name no `mode` (QFK2-E76). Default `'auto'`. */\n contentLiveDefault?: ContentLiveMode;\n /**\n * Launch version gate (QFK2-E59 D7), opt-in: stale cached content of a\n * collection with its change signal on is served without a download while\n * the collection's version is unchanged. `true` = `{ maxAgeMs: 24 h }`.\n */\n contentVersionGate?: ContentVersionGateOption;\n /**\n * The app's version (QFK2-E59 V9): sent as `X-App-Version` when it is a\n * valid app version (1–4 numeric segments, e.g. `1.4.2`); tags persisted\n * cache entries. Absent / invalid = no header (\"unknown\" to the server).\n */\n appVersion?: string | null;\n /**\n * Content bundle (QFK2-E59 T466): `locale` / `initial` of `client.bundle`, an\n * offline snapshot of the collections the project put in its bundle. The\n * bundle exists when {@link CoreClientInternals.contentBundle} is injected;\n * platform clients inject it exactly when the app enables `contentBundle`.\n */\n contentBundle?: ContentBundleOption;\n}\n\n/** `contentVersionGate` of the client config: `true`, or a custom upper bound. */\nexport type ContentVersionGateOption = boolean | { maxAgeMs?: number };\n\n/** Resolved launch version gate (`client.contentVersionGate`). */\nexport interface ContentVersionGate {\n /**\n * A version match skips a download only within this long of the last real\n * validation (a 200/304), since policy, schema and draft-only changes do not\n * bump the version.\n */\n readonly maxAgeMs: number;\n}\n\n/** Default upper bound of the version gate: 24 h. */\nexport const CONTENT_VERSION_GATE_DEFAULT_MAX_AGE_MS = 24 * 60 * 60 * 1000;\n\n/** Resolve the config option: off → `null`; `true` / no valid `maxAgeMs` → 24 h. */\nexport function resolveContentVersionGate(option: ContentVersionGateOption | undefined): ContentVersionGate | null {\n if (!option) return null;\n const ms = option === true ? undefined : option.maxAgeMs;\n const valid = typeof ms === 'number' && Number.isFinite(ms) && ms > 0;\n return { maxAgeMs: valid ? ms : CONTENT_VERSION_GATE_DEFAULT_MAX_AGE_MS };\n}\n\n/** Options of {@link CoreClient.createConfigSync}. */\nexport interface ConfigSyncFactoryOptions {\n pollIntervalMs?: number;\n /** Opt into SSE (needs `PlatformAdapter.connectSse`); otherwise the domain polls. */\n live?: boolean;\n buildTimeVersion?: number;\n}\n\n/**\n * The client surface the shared React layer (Provider + hooks) needs. Both the\n * RN `QafkaCmsClient` and a {@link CoreClient} satisfy it structurally.\n */\nexport interface CoreClientLike {\n readonly auth: AuthClient;\n readonly content: ContentClient;\n /** Storage for `persist: true` queries when the client has no {@link cacheStorage}. */\n readonly storage: KeyValueStorage;\n /**\n * QFK2-T471 — the plain store for `persist: true` queries (wins over\n * {@link storage}). Absent = `storage`. The React Native client sets it to\n * `createClient({ cacheStorage })`, keeping `storage` its secure store. A\n * {@link CoreClient} sets it to its `storage` (`platform.cacheStorage ?? sessionStorage`).\n */\n readonly cacheStorage?: KeyValueStorage;\n /** Present on the full tier; `useLocale` / `useTranslation` require it. */\n readonly language?: LanguageManager;\n /** Live content change signals (`live` on the content hooks). Absent = `live` is ignored. */\n readonly contentChanges?: ContentChangesApi;\n /** Launch version gate (QFK2-E59 D7); set → the Provider gates expand-less content reads. */\n readonly contentVersionGate?: ContentVersionGate | null;\n /** Resolved app version (QFK2-E59 V9); the Provider tags persisted cache entries with it. */\n readonly appVersion?: string | null;\n /** Content bundle (QFK2-E59 T466); present only when `contentBundle` is enabled. */\n readonly bundle?: ContentBundleApi;\n initialize(): Promise<void>;\n}\n\nexport interface CoreClient extends CoreClientLike {\n /** @internal Transport, for platform layers (device registration, own-client headers). */\n readonly http: HttpClient;\n /** The platform's proof provider. */\n readonly proof: ProofProvider;\n /**\n * Live content change signals (QFK2-E76): one multiplexed SSE stream (or\n * version polling) per client, created on the first `watch`. Unused = no\n * request, connection or timer. Needs {@link CoreClientInternals.contentHub};\n * without it `watch` warns once and does nothing.\n */\n readonly contentChanges: ContentChangesApi;\n /** Resolved `contentVersionGate` config; `null` = off (the default). */\n readonly contentVersionGate: ContentVersionGate | null;\n /** `appVersion` of the config when valid (sent as `X-App-Version`), else `null`. */\n readonly appVersion: string | null;\n /**\n * Hydrate the stored session and unlock tokens, run the first proof, resume\n * an external session, start the language runtime (full tier), and create\n * an anonymous end-user when `anonymousAuth: 'auto'` and no session exists.\n */\n initialize(): Promise<void>;\n /**\n * Project + proof headers for the caller's own HTTP client, plus\n * `X-Unlock-Token` unless `{ withUnlockTokens: false }`, and `X-App-Version`\n * when set. Runs the first proof and loads unlock tokens first. No\n * `Authorization` / `Content-Type`.\n */\n getRequestHeaders(options?: { withUnlockTokens?: boolean }): Promise<Record<string, string>>;\n /** A config-sync client for one domain, sharing this client's transport and storage. */\n createConfigSync<T>(domain: string, buildTimeDefault: T, options?: ConfigSyncFactoryOptions): ConfigSyncClient<T>;\n}\n\n/** Hooks for platform layers that compose a core client (not for apps). */\nexport interface CoreClientInternals {\n /** Extra config-sync starts run in parallel with the `locales` / `i18n` starts during `initialize()`. */\n configStarts?: () => Array<Promise<void>>;\n /**\n * QFK2-E73 — the session store, built by the platform layer (over\n * `platform.sessionStorage`) so it can mirror the session elsewhere (web:\n * cross-tab BroadcastChannel sync). Default: a new `TokenStore`.\n */\n tokenStore?: TokenStore;\n /**\n * QFK2-E76 — the content change hub factory (`createContentChangeHub`).\n * Injected, not imported, so a browser bundle that never uses `live` does\n * not carry it. RN always passes it; web only with `liveContent`.\n */\n contentHub?: (options: ContentChangeHubOptions) => ContentChangesApi;\n /**\n * QFK2-E59 T466 — the content bundle module (`createContentBundleClient`),\n * injected for the same reason. Injecting it enables `client.bundle`: RN\n * passes it when `contentBundle` is set, web when the site passes `contentBundle()`.\n */\n contentBundle?: ContentBundleFactory;\n}\n\n/** The project-identity rules every client enforces (same messages on every platform). */\nexport function validateCoreConfig(config: { projectId?: string; publishableKey?: string }): void {\n const hasProjectId = typeof config.projectId === 'string' && config.projectId !== '';\n if (config.publishableKey === undefined && !hasProjectId) {\n throw new Error('QafkaCMS: projectId is required (or a publishableKey qpk_…)');\n }\n if (config.publishableKey !== undefined) {\n if (typeof config.publishableKey !== 'string' || !config.publishableKey.startsWith('qpk_')) {\n throw new Error('publishableKey is required (qpk_…)');\n }\n }\n}\n\nexport function createCoreClient(\n config: CoreConfig,\n platform: PlatformAdapter,\n internals: CoreClientInternals = {},\n): CoreClient {\n validateCoreConfig(config);\n if (!config.apiUrl) throw new Error('QafkaCMS: apiUrl is required');\n\n const apiUrl = config.apiUrl;\n const projectId = config.projectId ? config.projectId : undefined;\n const now = platform.now ?? Date.now;\n const sessionStorage = platform.sessionStorage;\n const storage = platform.cacheStorage ?? sessionStorage;\n const proof = platform.proof;\n const anonymousAuth: AnonymousAuthMode = config.anonymousAuth === 'auto' ? 'auto' : 'manual';\n const full = config.tier === 'full';\n\n // Assigned below; the transport getters only run per request.\n let auth: AuthClient;\n let language: LanguageManager | undefined;\n\n const unlockTokens = new UnlockTokenStore(sessionStorage);\n const http = new HttpClient(\n {\n apiUrl,\n projectSlug: config.projectSlug,\n publishableKey: config.publishableKey,\n projectId,\n platformOS: platform.os,\n appVersion: config.appVersion,\n },\n {\n fetch: platform.fetch,\n proof,\n getAccessToken: () => auth.getValidAccessToken(),\n getLocale: () => language?.getLanguage() || null,\n getUnlockTokens: () => unlockTokens.tokens(),\n },\n );\n\n const tokenStore = internals.tokenStore ?? new TokenStore(sessionStorage, now);\n auth = new AuthClient(http, tokenStore, now, {\n externalTokenProvider: config.externalTokenProvider,\n externalProvider: config.externalProvider,\n storage: sessionStorage,\n anonymousAuth,\n });\n\n const createConfigSync = <T>(\n domain: string,\n buildTimeDefault: T,\n options?: ConfigSyncFactoryOptions,\n ): ConfigSyncClient<T> =>\n new ConfigSyncClient<T>({\n domain,\n buildTimeDefault,\n buildTimeVersion: options?.buildTimeVersion,\n apiUrl,\n http: { request: (method, path) => http.request(method, path) },\n storage,\n // SSE is opt-in; without it ConfigSyncClient polls.\n connectSse: options?.live ? platform.connectSse : undefined,\n headers: () => http.securityHeaders(),\n pollIntervalMs: options?.pollIntervalMs,\n appState: platform.appState,\n });\n\n // Full tier: the locale set + UI strings are two config-sync domains the SDK\n // manages itself (build-time defaults mirror the backend domain registry).\n let localesSync: ConfigSyncClient<LocalesData> | null = null;\n let i18nSync: ConfigSyncClient<I18nData> | null = null;\n if (full) {\n language = new LanguageManager({ storage });\n const poll = config.configPollIntervalMs;\n const bootstrap = config.bootstrap;\n localesSync = createConfigSync<LocalesData>(\n 'locales',\n bootstrap?.locales?.data ?? { defaultLocale: 'en', locales: ['en'] },\n { pollIntervalMs: poll, buildTimeVersion: bootstrap?.locales?.version },\n );\n i18nSync = createConfigSync<I18nData>(\n 'i18n',\n bootstrap?.i18n?.data ?? { translations: { en: {} } },\n { pollIntervalMs: poll, buildTimeVersion: bootstrap?.i18n?.version },\n );\n }\n\n const content = new ContentClient(http, {\n getLocale: () => language?.getLanguage() || null,\n unlockTokens,\n });\n\n // QFK2-E76 — built on the first watch, so an app without `live` pays nothing.\n let hub: ContentChangesApi | undefined;\n let warnedNoHub = false;\n const request = (path: string): Promise<unknown> => http.request('GET', path);\n const contentChanges: ContentChangesApi = {\n watch: (target, mode, opts) => {\n if (!internals.contentHub) {\n if (!warnedNoHub) platform.warn?.('[QafkaCMS] live content is not enabled on this client; `live` is ignored');\n warnedNoHub = true;\n return () => {};\n }\n return (hub ??= internals.contentHub({\n apiUrl,\n request,\n headers: () => http.securityHeaders(),\n connectSse: platform.contentSse ?? platform.connectSse,\n appState: platform.appState,\n warn: platform.warn,\n })).watch(target, mode ?? config.contentLiveDefault ?? 'auto', opts);\n },\n status: () => hub?.status() ?? 'idle',\n reset: () => hub?.reset(),\n dispose: () => hub?.dispose(),\n // QFK2-E59 D7 — a plain GET: needs neither a watch nor the hub.\n versions: (collections) => fetchContentVersions(request, collections),\n };\n\n const initialize = async (): Promise<void> => {\n await tokenStore.hydrate();\n await unlockTokens.hydrate();\n await proof.initialize?.();\n\n // E44 — resume an external session (marker, no refresh token) through the\n // host's externalTokenProvider so auth state is live at boot. Best-effort.\n if (!tokenStore.getRefreshToken()) await auth.getValidAccessToken().catch(() => null);\n\n const extraStarts = internals.configStarts ?? (() => []);\n if (language && localesSync && i18nSync) {\n const lang = language;\n const locales = localesSync;\n const i18n = i18nSync;\n await lang.hydrate();\n locales.subscribe((data) => lang.applyLocales(data));\n i18n.subscribe((data) => lang.applyI18n(data));\n await Promise.all([locales.start(), i18n.start(), ...extraStarts()]);\n // start() applies the initial snapshot silently; push it into the manager.\n lang.applyLocales(locales.current());\n lang.applyI18n(i18n.current());\n } else {\n await Promise.all(extraStarts());\n }\n\n // QFK2-T322 — `anonymousAuth: 'auto'`: no stored session → create an\n // anonymous end-user (before the RN device registers, so the device row\n // binds to it). Best-effort: a failure (e.g. anonymous auth disabled) must\n // not wedge boot; the app can retry with auth.signInAnonymously().\n if (anonymousAuth === 'auto' && !auth.isAuthenticated()) {\n await auth.signInAnonymously().catch((err: unknown) => {\n platform.warn?.(\"[QafkaCMS] anonymous sign-in (anonymousAuth: 'auto') failed\", err);\n });\n }\n };\n\n const getRequestHeaders = async (\n options: { withUnlockTokens?: boolean } = {},\n ): Promise<Record<string, string>> => {\n await Promise.all([proof.initialize?.(), unlockTokens.hydrate()]);\n // Same rules as the SDK's own requests; the key is always included since\n // these headers carry no Authorization (the caller decides about it).\n const headers = await http.projectProofHeaders({ withProjectKey: true });\n if (options.withUnlockTokens !== false) {\n const unlock = unlockTokens.tokens();\n if (unlock.length) headers['X-Unlock-Token'] = unlock.join(',');\n }\n if (http.appVersion) headers['X-App-Version'] = http.appVersion;\n return headers;\n };\n\n // QFK2-E59 T466 — content bundle: exists when the module is injected (= enabled). `true` spreads to `{}`;\n // the module stores in `contentBundle.storage ?? cacheStorage` (a plain store, never `sessionStorage`).\n const bundle = internals.contentBundle?.({\n ...(config.contentBundle as ContentBundleConfig),\n apiUrl,\n http,\n platform,\n language,\n });\n\n return {\n auth,\n content,\n storage,\n cacheStorage: storage,\n language,\n bundle,\n http,\n proof,\n contentChanges,\n contentVersionGate: resolveContentVersionGate(config.contentVersionGate),\n appVersion: http.appVersion,\n initialize,\n getRequestHeaders,\n createConfigSync,\n };\n}\n","/**\n * Human-friendly cache durations. Accepts a raw millisecond number or a short\n * suffixed string (`'500ms'`, `'30s'`, `'10m'`, `'1h'`, `'2d'`). Used for\n * per-query TTL so callers can write `ttl: '1h'` instead of `3_600_000`.\n */\nexport type Duration = number | string;\n\nconst UNIT_MS: Record<string, number> = {\n ms: 1,\n s: 1_000,\n m: 60_000,\n h: 3_600_000,\n d: 86_400_000,\n};\n\n/**\n * Normalize a {@link Duration} to milliseconds. `null`/`undefined` → `null`\n * (meaning \"no freshness window\"). Throws on malformed strings so a typo fails\n * loud at call time rather than silently disabling the TTL.\n */\nexport function parseDuration(value: Duration | null | undefined): number | null {\n if (value == null) return null;\n if (typeof value === 'number') {\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`QafkaCMS: invalid duration ${value} (expected a non-negative number of ms)`);\n }\n return value;\n }\n const match = /^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h|d)?$/.exec(value.trim());\n if (!match) {\n throw new Error(`QafkaCMS: invalid duration \"${value}\" (use e.g. 500, '30s', '10m', '1h', '2d')`);\n }\n const amount = parseFloat(match[1]!);\n const unit = match[2] ?? 'ms';\n return amount * UNIT_MS[unit]!;\n}\n","/**\n * A query key identifies a cache entry. Either an opaque string, or an array of\n * JSON-serializable parts (the common case — e.g. `['content', 'posts', { limit: 20 }]`).\n * Array keys are serialized deterministically so that object member order and\n * `undefined` members do not produce distinct cache entries.\n */\nexport type QueryKey = string | readonly unknown[];\n\n/** Stable, order-independent serialization of a {@link QueryKey}. */\nexport function serializeKey(key: QueryKey): string {\n return typeof key === 'string' ? key : stableStringify(key);\n}\n\n/**\n * Like `JSON.stringify` but with sorted object keys and `undefined` members\n * dropped, so `{ a: 1, b: undefined }` and `{ a: 1 }` serialize identically and\n * `{ a: 1, b: 2 }` matches `{ b: 2, a: 1 }`.\n */\nfunction stableStringify(value: unknown): string {\n if (value === undefined) return 'null';\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;\n const obj = value as Record<string, unknown>;\n const parts = Object.keys(obj)\n .filter((k) => obj[k] !== undefined)\n .sort()\n .map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`);\n return `{${parts.join(',')}}`;\n}\n","import type { ConditionalResponse } from '../transport/HttpClient';\n\n/**\n * Conditional fetcher protocol of the {@link QueryCache} (QFK2-E59 D5).\n *\n * A query fetcher receives a {@link FetchContext} carrying the ETag of the data\n * the cache already holds. It may return plain data (today's behavior: no ETag\n * is kept) or a branded result built with {@link conditional}:\n *\n * - `conditional.notModified()` — the server answered 304: keep the cached data\n * (same object), refresh its timestamp, keep the ETag.\n * - `conditional.data(data, etag)` — a full response: store the data and its ETag.\n *\n * The brand is a symbol, so a plain value that happens to look like\n * `{ notModified: true }` is never mistaken for a conditional result.\n */\n\n/** Argument every query fetcher receives. */\nexport interface FetchContext {\n /**\n * ETag of the cached data, or `null` when there is no data (first load,\n * after `setData` / `clear`) or the last result had none. Send it as\n * `If-None-Match` only when non-null.\n */\n etag: string | null;\n}\n\nconst BRAND: unique symbol = Symbol.for('@qafka/cms.conditional');\n\n/** Branded fetcher result: see {@link conditional}. */\nexport type ConditionalResult<T> =\n | { readonly [BRAND]: true; readonly notModified: true }\n | { readonly [BRAND]: true; readonly notModified: false; readonly data: T; readonly etag: string | null };\n\n/** A query fetcher: may ignore `ctx` and return plain data, or use it and return a {@link ConditionalResult}. */\nexport type QueryFetcher<T> = (ctx: FetchContext) => Promise<T | ConditionalResult<T>>;\n\nexport const conditional = {\n /** The server confirmed the cached data is current (HTTP 304). */\n notModified(): ConditionalResult<never> {\n return { [BRAND]: true, notModified: true };\n },\n /** A full response and its ETag (`null` when the server sent none). */\n data<T>(data: T, etag: string | null): ConditionalResult<T> {\n return { [BRAND]: true, notModified: false, data, etag };\n },\n /** Brand a transport {@link ConditionalResponse}. */\n from<T>(res: ConditionalResponse<T>): ConditionalResult<T> {\n return res.notModified ? conditional.notModified() : conditional.data(res.data, res.etag);\n },\n};\n\n/** Whether `value` was built by {@link conditional}. */\nexport function isConditionalResult(value: unknown): value is ConditionalResult<unknown> {\n return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[BRAND] === true;\n}\n","/**\n * Launch version gate of the {@link QueryCache} (QFK2-E59 D7/D8): request\n * batching. Version questions arriving within {@link VERSION_GATE_BATCH_MS}\n * share one `check` call (de-duplicated, at most {@link VERSION_GATE_MAX_SLUGS}\n * slugs per call). The server answers a batch with one refused collection\n * (change signal off, unreadable, unknown) with a 404 for all of it, so a 404\n * batch is retried slug by slug; a slug that 404s alone is \"no gate\" for the\n * batcher's lifetime and never asked again.\n */\n\n/** `QueryCacheOptions.versionGate`: how the cache reads collection versions. */\nexport interface VersionGateOptions {\n /** Current versions of `collections` (`client.contentChanges.versions`); rejects with a `status` on HTTP errors. */\n check: (collections: string[]) => Promise<Record<string, string>>;\n /** A version match skips the fetch only within this long of the last real (200/304) validation. */\n maxAgeMs: number;\n}\n\n/** Version questions within this window share one request. */\nexport const VERSION_GATE_BATCH_MS = 10;\n/** Server limit of collections per version request. */\nexport const VERSION_GATE_MAX_SLUGS = 20;\n\n/** @internal */\nexport interface VersionBatcher {\n /** Current version of `slug`; `null` when unknown (request failed, no gate). Never rejects. */\n get(slug: string): Promise<string | null>;\n /** Whether `slug` was refused alone (404): its entries behave as ungated. */\n isDisabled(slug: string): boolean;\n}\n\ntype Resolve = (v: string | null) => void;\n\n/** @internal Batches {@link VersionGateOptions.check} calls. */\nexport function createVersionBatcher(check: VersionGateOptions['check']): VersionBatcher {\n const disabled = new Set<string>();\n let queue: Map<string, Resolve[]> | null = null;\n\n /** Versions of `slugs` (`null` = unknown). A 404 batch is asked again slug by slug; a lone 404 disables. */\n const ask = async (slugs: string[]): Promise<Array<string | null>> => {\n try {\n const res = (await check(slugs)) as Record<string, unknown> | null;\n return slugs.map((s) => {\n const v = res?.[s];\n return typeof v === 'string' || typeof v === 'number' ? String(v) : null;\n });\n } catch (err) {\n if ((err as { status?: unknown } | null)?.status !== 404) return slugs.map(() => null);\n if (slugs.length > 1) return Promise.all(slugs.map(async (s) => (await ask([s]))[0]!));\n disabled.add(slugs[0]!);\n return [null];\n }\n };\n\n const flush = (batch: Map<string, Resolve[]>): void => {\n queue = null;\n const slugs = [...batch.keys()];\n for (let i = 0; i < slugs.length; i += VERSION_GATE_MAX_SLUGS) {\n const part = slugs.slice(i, i + VERSION_GATE_MAX_SLUGS);\n void ask(part).then((vs) => part.forEach((s, j) => batch.get(s)!.forEach((resolve) => resolve(vs[j]!))));\n }\n };\n\n return {\n get: (slug) =>\n disabled.has(slug)\n ? Promise.resolve(null)\n : new Promise((resolve) => {\n if (!queue) {\n const batch = (queue = new Map());\n setTimeout(() => flush(batch), VERSION_GATE_BATCH_MS);\n }\n const waiting = queue.get(slug);\n if (waiting) waiting.push(resolve);\n else queue.set(slug, [resolve]);\n }),\n isDisabled: (slug) => disabled.has(slug),\n };\n}\n","import { STORAGE_KEY_QUERY_INDEX, STORAGE_KEY_QUERY_PREFIX } from '../constants';\nimport { parseDuration, type Duration } from './duration';\nimport { serializeKey, type QueryKey } from './query-key';\nimport type { CacheStorage } from './cache-storage';\nimport type { QueryOptions, QueryState, QueryStatus } from './types';\nimport { isConditionalResult, type ConditionalResult, type FetchContext, type QueryFetcher } from './conditional';\nimport { createVersionBatcher, type VersionBatcher, type VersionGateOptions } from './version-gate';\nimport { parseAppVersion, validAppVersion } from '../app-version';\n\n/** Collection version the data was validated against (QFK2-E59 D8). */\ninterface GateStamp {\n /** Version read right BEFORE the data was fetched. */\n v: string;\n /** Epoch ms of the last real (200/304) validation; a version match does not move it. */\n validatedAt: number;\n}\n\n/**\n * Persisted shape: data plus the timestamp/TTL so freshness survives restart.\n * `etag` (QFK2-E59 D5), `gate` (the launch version gate, D8) and `appVersion`\n * (the app version the data was fetched with, V9) are written only when known.\n * Envelopes without them (older SDKs) load as-is.\n */\ninterface CacheEnvelope<T> {\n data: T;\n savedAt: number;\n ttl: number | null;\n etag?: string | null;\n gate?: GateStamp | null;\n appVersion?: string;\n}\n\ninterface Entry<T> {\n status: QueryStatus;\n data: T | undefined;\n error: Error | undefined;\n /** Epoch ms of last successful data; `null` when absent/invalidated. */\n savedAt: number | null;\n /** Freshness window in ms; `null` = always stale (revalidate every mount). */\n ttl: number | null;\n isFetching: boolean;\n persist: boolean;\n /** In-flight fetch (always resolves; never rejects) — shared for dedupe. */\n promise: Promise<void> | null;\n /** Last fetcher seen for this key — lets `invalidate`/`refetch` re-run it. */\n fetcher: QueryFetcher<T> | null;\n /** ETag of `data` (QFK2-E59 D5); `null` = unknown → the next fetch is unconditional. */\n etag: string | null;\n /** Collection slug of the version gate (`QueryOptions.gate`); `null` = ungated. */\n gateSlug: string | null;\n /** Version stamp of `data` (QFK2-E59 D8); `null` = unknown → the next stale `ensure` fetches. */\n gate: GateStamp | null;\n /** Bumped to cancel an in-flight fetch and ignore its late result. */\n epoch: number;\n /** Whether a persisted value has been read for this key yet. */\n hydrated: boolean;\n /** Frozen public view, recomputed only on change (stable identity). */\n snapshot: QueryState<T>;\n listeners: Set<() => void>;\n}\n\nexport interface QueryCacheOptions {\n /** Where to persist entries flagged `persist`. Omit → memory-only (no-op across restarts). */\n storage?: CacheStorage;\n /** Clock injection for tests. */\n now?: () => number;\n /** Default TTL applied to queries that do not specify one. */\n defaultTtl?: Duration | null;\n /** Observe fetch errors (logging/telemetry). */\n onError?: (error: Error, key: string) => void;\n /**\n * Launch version gate (QFK2-E59 D8). Entries with `QueryOptions.gate` read\n * their collection's version before each full fetch; a stale one reached\n * through `ensure` whose version is unchanged is refreshed without a fetch.\n * Omit → no gate (the default).\n */\n versionGate?: VersionGateOptions;\n /**\n * The app version requests are sent with (QFK2-E59 V9; the Provider passes\n * `client.appVersion`). Persisted entries are tagged with it; an entry stored\n * under another app version (or with / without one) hydrates stale and\n * without its version-gate stamp, so it revalidates (ETag kept) while its\n * data is still shown. Invalid / omitted = none.\n */\n appVersion?: string | null;\n}\n\n/**\n * Internal construction option (not part of the public {@link QueryCacheOptions}\n * surface): diagnostics sink for the missing-storage warning. The core reads no\n * `__DEV__`; without a sink the warning is silent.\n */\ninterface QueryCacheInternalOptions extends QueryCacheOptions {\n warn?: (message: string) => void;\n}\n\n/** Options of {@link QueryCache.invalidate} / {@link QueryCache.invalidateByPrefix}. */\nexport interface InvalidateOptions {\n /**\n * Defer the refetch of a mounted entry by this many ms (QFK2-E76 D8: spread\n * a realtime signal's refetches). The entry is marked stale at once; one\n * pending timer per key, so repeated invalidations do not fetch twice.\n * Omitted / `0` = refetch now (the default).\n */\n delayMs?: number;\n}\n\nconst IDLE_SNAPSHOT: QueryState<unknown> = Object.freeze({\n data: undefined,\n error: undefined,\n status: 'idle' as const,\n isLoading: false,\n isFetching: false,\n isStale: true,\n updatedAt: null,\n});\n\nconst PERSIST_WARNING =\n '[QafkaCMS] A query requested `persist: true` but this QueryCache has no `storage`: ' +\n 'it works in memory only and will not survive a restart.';\n\n/**\n * Framework-agnostic reactive query cache. The React layer binds to it through\n * `subscribe` / `getSnapshot` (`useSyncExternalStore`); nothing here imports\n * React. Behavior, per key: in-flight de-duplication, TTL freshness,\n * stale-while-revalidate, stale-on-error, race-safe results (epoch guard), and\n * opt-in persistence with the freshness timestamp.\n */\nexport class QueryCache {\n private readonly entries = new Map<string, Entry<unknown>>();\n private readonly persistedKeys = new Set<string>();\n /** Loads the persisted key index once (keys written in earlier sessions). */\n private indexLoad: Promise<void> | null = null;\n /** Serialized index writes, so a slower earlier write cannot overwrite a newer one. */\n private indexWrite: Promise<void> = Promise.resolve();\n /** Pending delayed refetches (one per serialized key). */\n private readonly delayed = new Map<string, ReturnType<typeof setTimeout>>();\n private readonly storage?: CacheStorage;\n private readonly now: () => number;\n private readonly defaultTtl: number | null;\n private readonly onError?: (error: Error, key: string) => void;\n private warnedNoStorage = false;\n private readonly warn?: (message: string) => void;\n private readonly versions: VersionBatcher | null;\n private readonly gateMaxAgeMs: number;\n private readonly appVersion: string | null;\n /** Normalized form of {@link appVersion} (`1.4` = `1.4.0`); `'null'` when none. */\n private readonly appVersionKey: string;\n\n constructor(options: QueryCacheOptions = {}) {\n this.storage = options.storage;\n this.now = options.now ?? Date.now;\n this.defaultTtl = parseDuration(options.defaultTtl ?? null);\n this.onError = options.onError;\n this.warn = (options as QueryCacheInternalOptions).warn;\n const gate = options.versionGate;\n this.versions = gate ? createVersionBatcher(gate.check) : null;\n this.gateMaxAgeMs = gate?.maxAgeMs ?? 0;\n this.appVersion = validAppVersion(options.appVersion);\n this.appVersionKey = String(parseAppVersion(this.appVersion));\n }\n\n // --- reactivity ---------------------------------------------------------\n\n /** Current immutable view for a key. Stable reference between changes. */\n getSnapshot<T>(key: QueryKey): QueryState<T> {\n const entry = this.entries.get(serializeKey(key));\n return (entry ? entry.snapshot : IDLE_SNAPSHOT) as QueryState<T>;\n }\n\n /** Subscribe to changes for a key. Returns an unsubscribe function. */\n subscribe(key: QueryKey, listener: () => void): () => void {\n const entry = this.getOrCreate(serializeKey(key));\n entry.listeners.add(listener);\n return () => {\n entry.listeners.delete(listener);\n };\n }\n\n // --- read / fetch -------------------------------------------------------\n\n /**\n * Ensure data for `key` is loading or loaded. Hydrates from persistence\n * first, returns immediately if fresh, otherwise fetches (deduped). The\n * returned promise resolves once the work settles; data is read via state.\n */\n async ensure<T>(key: QueryKey, fetcher: QueryFetcher<T>, options?: QueryOptions): Promise<void> {\n const sk = serializeKey(key);\n const entry = this.getOrCreate<T>(sk);\n entry.fetcher = fetcher;\n this.applyOptions(entry, options);\n await this.maybeHydrate(entry, sk);\n if (entry.data !== undefined && !this.isStale(entry)) return; // fresh → no network\n return this.runFetch(entry, sk, true);\n }\n\n /** Boot/warm-up prefetch — same semantics as {@link ensure}, no subscriber required. */\n prefetch<T>(key: QueryKey, fetcher: QueryFetcher<T>, options?: QueryOptions): Promise<void> {\n return this.ensure(key, fetcher, options);\n }\n\n /** Force a refetch regardless of freshness (background revalidate over existing data). */\n refetch<T>(key: QueryKey, fetcher?: QueryFetcher<T>): Promise<void> {\n const sk = serializeKey(key);\n const entry = this.entries.get(sk) as Entry<T> | undefined;\n if (!entry) return Promise.resolve();\n if (fetcher) entry.fetcher = fetcher;\n if (!entry.fetcher) return Promise.resolve();\n entry.epoch += 1; // cancel any in-flight\n entry.promise = null;\n return this.runFetch(entry, sk);\n }\n\n /**\n * Refetch every entry that currently has subscribers — used after an identity\n * change so mounted screens reload with the new session. Entries with no\n * listeners are left untouched (they refetch on their next mount).\n */\n refetchActive(): void {\n for (const [sk, entry] of this.entries) {\n if (entry.listeners.size > 0 && entry.fetcher) {\n entry.epoch += 1;\n entry.promise = null;\n void this.runFetch(entry, sk);\n }\n }\n }\n\n // --- mutation / invalidation -------------------------------------------\n\n /**\n * Mark a key stale and, if it has active subscribers, revalidate it — now, or\n * after `opts.delayMs`. An entry without subscribers is only marked stale.\n */\n invalidate(key: QueryKey, opts?: InvalidateOptions): void {\n const sk = serializeKey(key);\n const entry = this.entries.get(sk);\n if (entry) this.invalidateEntry(entry, sk, opts?.delayMs);\n }\n\n /** Invalidate every key whose serialized form matches `predicate`. */\n invalidateWhere(predicate: (key: string) => boolean): void {\n for (const [sk, entry] of this.entries) {\n if (predicate(sk)) this.invalidateEntry(entry, sk);\n }\n }\n\n /**\n * Invalidate every key that has `prefix` as a leading segment (react-query\n * style). `invalidateByPrefix(['content', 'posts'])` refreshes every cached\n * `content.list('posts', …)` regardless of params; a string prefix matches\n * that exact key.\n */\n invalidateByPrefix(prefix: QueryKey, opts?: InvalidateOptions): void {\n const matches = prefixMatcher(prefix);\n for (const [sk, entry] of this.entries) {\n if (matches(sk)) this.invalidateEntry(entry, sk, opts?.delayMs);\n }\n }\n\n /**\n * Whether any entry matching `prefix` (same matching as\n * {@link invalidateByPrefix}) currently has subscribers, i.e. is on screen.\n */\n hasActive(prefix: QueryKey): boolean {\n const matches = prefixMatcher(prefix);\n for (const [sk, entry] of this.entries) {\n if (entry.listeners.size > 0 && matches(sk)) return true;\n }\n return false;\n }\n\n /**\n * Write data directly (optimistic update); cancels any in-flight fetch. The\n * ETag is dropped: the written data is not the server's representation.\n */\n setData<T>(key: QueryKey, data: T): void {\n const sk = serializeKey(key);\n const entry = this.getOrCreate<T>(sk);\n entry.epoch += 1;\n entry.promise = null;\n entry.data = data;\n entry.etag = null;\n entry.gate = null;\n entry.error = undefined;\n entry.status = 'success';\n entry.savedAt = this.now();\n void this.maybePersist(entry, sk);\n this.touch(entry);\n }\n\n /**\n * Reset every entry to idle and drop persisted copies. Call on logout so a\n * previous user's visible set cannot leak. Does NOT auto-refetch — mounted\n * screens re-fetch on their next mount.\n */\n async clear(): Promise<void> {\n for (const timer of this.delayed.values()) clearTimeout(timer);\n this.delayed.clear();\n for (const [, entry] of this.entries) {\n entry.epoch += 1;\n entry.promise = null;\n entry.data = undefined;\n entry.etag = null;\n entry.gate = null;\n entry.error = undefined;\n entry.status = 'idle';\n entry.savedAt = null;\n entry.isFetching = false;\n entry.hydrated = true; // do not re-read the (now-removed) persisted value\n this.touch(entry);\n }\n if (!this.storage) return;\n // Also drop keys persisted in earlier sessions and never touched in this one\n // (a previous user's data must not hydrate for the next one).\n await this.loadIndex();\n await this.indexWrite;\n const keys = [...this.persistedKeys];\n this.persistedKeys.clear();\n try {\n await this.storage.multiRemove([...keys, STORAGE_KEY_QUERY_INDEX]);\n } catch {\n // best-effort — in-memory state is already reset\n }\n }\n\n // --- internals ----------------------------------------------------------\n\n private getOrCreate<T>(sk: string): Entry<T> {\n let entry = this.entries.get(sk) as Entry<T> | undefined;\n if (!entry) {\n entry = {\n status: 'idle',\n data: undefined,\n error: undefined,\n savedAt: null,\n ttl: this.defaultTtl,\n isFetching: false,\n persist: false,\n promise: null,\n fetcher: null,\n etag: null,\n gateSlug: null,\n gate: null,\n epoch: 0,\n hydrated: false,\n snapshot: IDLE_SNAPSHOT as QueryState<T>,\n listeners: new Set(),\n };\n this.entries.set(sk, entry as Entry<unknown>);\n }\n return entry;\n }\n\n private applyOptions<T>(entry: Entry<T>, options?: QueryOptions): void {\n if (!options) return;\n if (options.ttl !== undefined) entry.ttl = parseDuration(options.ttl);\n if (options.persist !== undefined) entry.persist = options.persist;\n if (options.gate !== undefined) entry.gateSlug = options.gate || null;\n }\n\n private isStale<T>(entry: Entry<T>): boolean {\n if (entry.savedAt == null) return true;\n if (entry.ttl == null) return true;\n return this.now() - entry.savedAt >= entry.ttl;\n }\n\n /**\n * Fetch (deduped). `gated` = reached through `ensure`: a version-gated entry\n * whose version is unchanged may skip the fetcher (QFK2-E59 D8). Forced\n * paths (`invalidate*`, `refetch*`) always fetch, still recording the version.\n */\n private runFetch<T>(entry: Entry<T>, sk: string, gated = false): Promise<void> {\n if (entry.promise) return entry.promise; // dedupe\n const fetcher = entry.fetcher;\n if (!fetcher) return Promise.resolve();\n const myEpoch = entry.epoch;\n entry.isFetching = true;\n if (entry.data === undefined) entry.status = 'loading';\n this.touch(entry);\n\n const promise = (async () => {\n try {\n // Version BEFORE data: the stored version can never be newer than the data it stamps.\n const slug = this.gateSlugOf(entry);\n const version = slug ? await this.versions!.get(slug) : null;\n if (entry.epoch !== myEpoch) return; // superseded while asking\n if (gated && version !== null && this.gateHolds(entry, version)) {\n // Unchanged since the last real validation: no fetch; validatedAt stays.\n entry.error = undefined;\n entry.status = 'success';\n entry.savedAt = this.now();\n await this.maybePersist(entry, sk);\n return;\n }\n // ETag only alongside data: a 304 must never be the answer to \"I have nothing\".\n const ctx: FetchContext = { etag: entry.data !== undefined ? entry.etag : null };\n const result = await fetcher(ctx);\n if (entry.epoch !== myEpoch) return; // superseded/cancelled\n this.applyResult(entry, result);\n entry.gate = version !== null ? { v: version, validatedAt: entry.savedAt! } : null;\n await this.maybePersist(entry, sk);\n } catch (err) {\n if (entry.epoch !== myEpoch) return;\n const error = err instanceof Error ? err : new Error(String(err));\n entry.error = error;\n // Stale-on-error: keep showing existing data; only flip to error when empty.\n entry.status = entry.data !== undefined ? 'success' : 'error';\n this.onError?.(error, sk);\n } finally {\n if (entry.epoch === myEpoch) {\n entry.isFetching = false;\n entry.promise = null;\n this.touch(entry);\n } else if (entry.promise === null) {\n // Superseded by an op that cleared the in-flight handle without\n // starting a replacement fetch (e.g. invalidate with no subscribers);\n // clear the now-orphaned fetching flag so the entry doesn't stick.\n entry.isFetching = false;\n this.touch(entry);\n }\n }\n })();\n\n entry.promise = promise;\n return promise;\n }\n\n /**\n * Store a fetcher result (QFK2-E59 D5). Branded `notModified` keeps the data\n * (same object) and ETag and only refreshes the timestamp; branded data\n * stores data + ETag; a plain value is today's behavior with no ETag.\n */\n private applyResult<T>(entry: Entry<T>, result: T | ConditionalResult<T>): void {\n if (isConditionalResult(result)) {\n if (result.notModified) {\n if (entry.data === undefined) throw new Error('QafkaCMS: not-modified result for a query with no cached data');\n } else {\n entry.data = result.data as T;\n entry.etag = result.etag;\n }\n } else {\n entry.data = result;\n entry.etag = null;\n }\n entry.error = undefined;\n entry.status = 'success';\n entry.savedAt = this.now();\n }\n\n /** The entry's gate slug when the gate applies to it (configured, set, not refused). */\n private gateSlugOf<T>(entry: Entry<T>): string | null {\n const slug = entry.gateSlug;\n return slug && this.versions && !this.versions.isDisabled(slug) ? slug : null;\n }\n\n /** Data + stored version equal to `version`, within `maxAgeMs` of the last real validation. */\n private gateHolds<T>(entry: Entry<T>, version: string): boolean {\n const gate = entry.gate;\n if (entry.data === undefined || !gate || gate.v !== version) return false;\n const age = this.now() - gate.validatedAt;\n return age >= 0 && age < this.gateMaxAgeMs;\n }\n\n private invalidateEntry<T>(entry: Entry<T>, sk: string, delayMs?: number): void {\n // Keeps `etag`: the refetch is meant to be answered with a 304 when nothing changed.\n // Drops the gate stamp: an invalidation says the visible rows changed (change\n // signal, unlock / identity change) even when the collection version did not,\n // so the next `ensure` of an unmounted entry must fetch, not trust the stamp.\n entry.gate = null;\n entry.savedAt = null; // → stale\n entry.epoch += 1;\n entry.promise = null;\n const active = entry.listeners.size > 0 && entry.fetcher;\n if (active && delayMs && delayMs > 0) {\n this.touch(entry);\n if (this.delayed.has(sk)) return; // one pending refetch per key — no double fetch\n const timer = setTimeout(() => {\n this.delayed.delete(sk);\n // Skip when it unmounted meanwhile, or fresh data already landed (setData, a remount's fetch).\n if (entry.listeners.size === 0 || !entry.fetcher || entry.savedAt != null) return;\n void this.runFetch(entry, sk);\n }, delayMs);\n (timer as { unref?: () => void }).unref?.();\n this.delayed.set(sk, timer);\n return;\n }\n this.cancelDelayed(sk); // an immediate invalidation supersedes a pending delayed one\n if (active) {\n void this.runFetch(entry, sk);\n } else {\n this.touch(entry);\n }\n }\n\n private cancelDelayed(sk: string): void {\n const timer = this.delayed.get(sk);\n if (timer === undefined) return;\n clearTimeout(timer);\n this.delayed.delete(sk);\n }\n\n private async maybeHydrate<T>(entry: Entry<T>, sk: string): Promise<void> {\n if (entry.hydrated) return;\n entry.hydrated = true;\n if (!entry.persist || !this.storage) return;\n try {\n const raw = await this.storage.getItem(STORAGE_KEY_QUERY_PREFIX + sk);\n if (!raw) return;\n const env = JSON.parse(raw) as CacheEnvelope<T>;\n if (env && typeof env.savedAt === 'number' && 'data' in env) {\n // Fetched under another app version (V9): the server may filter it differently\n // now → show it, but stale and without the gate stamp (the ETag still holds).\n const sameApp = this.sameAppVersion(env.appVersion);\n entry.data = env.data;\n entry.etag = typeof env.etag === 'string' && env.etag ? env.etag : null;\n entry.gate = sameApp ? readGate(env.gate) : null;\n entry.savedAt = sameApp ? env.savedAt : null;\n entry.ttl = env.ttl ?? entry.ttl;\n entry.status = 'success';\n const isNew = this.track(STORAGE_KEY_QUERY_PREFIX + sk);\n this.touch(entry);\n if (isNew) await this.writeIndex(); // keys persisted by an SDK without the index\n }\n } catch {\n // corrupt cache — ignore and fall through to a network fetch\n }\n }\n\n private async maybePersist<T>(entry: Entry<T>, sk: string): Promise<void> {\n if (!entry.persist) return;\n if (!this.storage) {\n this.warnNoStorage();\n return;\n }\n if (entry.data === undefined || entry.savedAt == null) return;\n const env: CacheEnvelope<T> = { data: entry.data, savedAt: entry.savedAt, ttl: entry.ttl };\n if (entry.etag) env.etag = entry.etag;\n if (entry.gate) env.gate = entry.gate;\n if (this.appVersion) env.appVersion = this.appVersion;\n const storageKey = STORAGE_KEY_QUERY_PREFIX + sk;\n // Key tracking and the data write start synchronously (before any await): writes\n // keep the order of their results, and a concurrent clear() sees the key.\n const isNew = this.track(storageKey);\n try {\n await this.storage.setItem(storageKey, JSON.stringify(env));\n } catch {\n // best-effort persistence — a write failure must not break the in-memory cache\n }\n if (isNew) await this.writeIndex();\n }\n\n /** Read the persisted key index once into `persistedKeys`. */\n private loadIndex(): Promise<void> {\n const storage = this.storage;\n if (!storage) return Promise.resolve();\n if (!this.indexLoad) {\n this.indexLoad = (async () => {\n try {\n const raw = await storage.getItem(STORAGE_KEY_QUERY_INDEX);\n const keys: unknown = raw ? JSON.parse(raw) : [];\n if (Array.isArray(keys)) {\n for (const k of keys) {\n if (typeof k === 'string' && k.startsWith(STORAGE_KEY_QUERY_PREFIX)) this.persistedKeys.add(k);\n }\n }\n } catch {\n // corrupt index — start from what this session knows\n }\n })();\n }\n return this.indexLoad;\n }\n\n /** Remember a persisted key in memory; true when it was not known yet. */\n private track(storageKey: string): boolean {\n if (this.persistedKeys.has(storageKey)) return false;\n this.persistedKeys.add(storageKey);\n return true;\n }\n\n /** Write the stored key index (after merging the earlier-session index); serialized. */\n private async writeIndex(): Promise<void> {\n const storage = this.storage;\n if (!storage) return;\n await this.loadIndex();\n this.indexWrite = this.indexWrite.then(async () => {\n try {\n await storage.setItem(STORAGE_KEY_QUERY_INDEX, JSON.stringify([...this.persistedKeys]));\n } catch {\n // best-effort\n }\n });\n await this.indexWrite;\n }\n\n private touch<T>(entry: Entry<T>): void {\n entry.snapshot = Object.freeze({\n data: entry.data,\n error: entry.error,\n status: entry.status,\n isLoading: entry.status === 'loading',\n isFetching: entry.isFetching,\n isStale: this.isStale(entry),\n updatedAt: entry.savedAt,\n });\n for (const listener of entry.listeners) listener();\n }\n\n /** Whether a persisted tag names this cache's app version (both absent counts as equal). */\n private sameAppVersion(tag: unknown): boolean {\n return String(parseAppVersion(tag)) === this.appVersionKey;\n }\n\n private warnNoStorage(): void {\n if (this.warnedNoStorage) return;\n this.warnedNoStorage = true;\n this.warn?.(PERSIST_WARNING);\n }\n}\n\n/** A persisted gate stamp, or `null` when absent / malformed. */\nfunction readGate(raw: unknown): GateStamp | null {\n const g = raw as Partial<GateStamp> | null | undefined;\n if (!g || typeof g.v !== 'string' || typeof g.validatedAt !== 'number') return null;\n return { v: g.v, validatedAt: g.validatedAt };\n}\n\n/**\n * Serialized-key matcher for a react-query style prefix: an array matches\n * itself and every key that has it as a leading sub-array (segment-wise, so\n * `['content', 'post']` does not match `['content', 'posts', …]`); a string\n * matches that exact key.\n */\nfunction prefixMatcher(prefix: QueryKey): (key: string) => boolean {\n const full = serializeKey(prefix);\n if (typeof prefix === 'string') return (k) => k === full;\n const open = full.slice(0, -1); // drop trailing ']' → match this array as a leading sub-array\n return (k) => k === full || k.startsWith(`${open},`) || k.startsWith(`${open}]`);\n}\n","/**\n * Plain key/value store for cached data: `persist: true` queries, config-sync\n * snapshots, the saved locale, the content bundle. Cached content can be large\n * and is not secret, so it does not belong in the Keychain /\n * EncryptedSharedPreferences. The host app injects one (AsyncStorage, MMKV, …);\n * the SDK ships no JS dependency for it (dependency policy).\n *\n * The surface mirrors AsyncStorage so it can be passed straight through:\n * React Native: `createClient({ …, cacheStorage: AsyncStorage })` (QFK2-T471;\n * without it the RN SDK keeps cached data in its secure store),\n * `contentBundle: { storage: AsyncStorage }` for the bundle alone.\n * Web: the session mode picks the store (`PlatformAdapter.cacheStorage`).\n */\nexport interface CacheStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n multiRemove(keys: string[]): Promise<void>;\n}\n\n/**\n * In-memory fallback used when no `cacheStorage` is configured. Persistence\n * becomes a no-op across restarts, but the cache API stays fully functional so\n * code paths do not branch on \"is persistence available\".\n */\nexport function createMemoryCacheStorage(): CacheStorage {\n const map = new Map<string, string>();\n return {\n async getItem(key) {\n return map.has(key) ? map.get(key)! : null;\n },\n async setItem(key, value) {\n map.set(key, value);\n },\n async removeItem(key) {\n map.delete(key);\n },\n async multiRemove(keys) {\n for (const k of keys) map.delete(k);\n },\n };\n}\n","import type { CacheStorage } from './cache-storage';\nimport {\n STORAGE_KEY_CONFIG_PREFIX,\n STORAGE_KEY_LOCALE,\n STORAGE_KEY_QUERY_INDEX,\n STORAGE_KEY_QUERY_PREFIX,\n} from '../constants';\n\n/**\n * QFK2-T471 D4 — the keys an earlier SDK kept in the secure store that now\n * belong in the app's plain `cacheStorage`: persisted queries and their index,\n * config-sync snapshots and the saved locale. Session keys never move.\n */\nexport function isSecureMigratableKey(key: string): boolean {\n return (\n key.startsWith(STORAGE_KEY_QUERY_PREFIX) ||\n key === STORAGE_KEY_QUERY_INDEX ||\n key.startsWith(STORAGE_KEY_CONFIG_PREFIX) ||\n key === STORAGE_KEY_LOCALE\n );\n}\n\n/**\n * The plain store, reading through to the secure store for cache keys an\n * earlier SDK version wrote there (QFK2-T471 D4), so switching an app to\n * `cacheStorage` loses neither its cache nor its saved locale.\n *\n * - `getItem`: the plain value when there is one. Otherwise, for a cache key\n * (once per key per session) the secure copy is read, written to the plain\n * store, removed from the secure store and returned. A failed plain write\n * still returns it and keeps the secure copy.\n * - `setItem`: plain write; for a cache key the secure copy is removed (once per\n * key per session, best effort).\n * - `removeItem` / `multiRemove`: cache keys leave both stores, so a cleared\n * cache (e.g. on logout) cannot come back from an old copy. Secure store\n * errors are swallowed.\n * - A `setItem` / `removeItem` that arrives while a secure read is in flight\n * wins: the old value is not written over it (per-key generation counter).\n *\n * Other keys (e.g. the content bundle's) go to the plain store only.\n */\nexport function createSecureMigrationStorage(plain: CacheStorage, secure: CacheStorage): CacheStorage {\n /** Cache keys whose secure copy is gone or was handled this session. */\n const settled = new Set<string>();\n /** Bumped by every write / remove of a key: an in-flight move compares it. */\n const generation = new Map<string, number>();\n const bump = (key: string) => generation.set(key, (generation.get(key) ?? 0) + 1);\n /** Remove the secure copies of cache keys (errors swallowed); they stay settled for the session. */\n const dropSecure = async (keys: string[]): Promise<void> => {\n if (!keys.length) return;\n for (const k of keys) settled.add(k);\n try {\n await (keys.length === 1 ? secure.removeItem(keys[0]!) : secure.multiRemove(keys));\n } catch {\n // best effort: a leftover secure copy is harmless (read at most once more, then removed)\n }\n };\n\n return {\n async getItem(key) {\n const gen = generation.get(key); // taken before any await: a write during either read wins\n const value = await plain.getItem(key);\n if (!isSecureMigratableKey(key) || settled.has(key)) return value;\n if (value !== null) {\n settled.add(key); // written by this SDK, which already removed any secure copy\n return value;\n }\n let old: string | null;\n try {\n old = await secure.getItem(key);\n } catch {\n return null;\n }\n // Written or removed meanwhile: that newer state wins over the old copy.\n if (generation.get(key) !== gen) return plain.getItem(key);\n if (old === null) {\n settled.add(key);\n return null;\n }\n try {\n await plain.setItem(key, old);\n } catch {\n return old; // keep the secure copy; a later read tries again\n }\n await dropSecure([key]);\n return old;\n },\n\n async setItem(key, value) {\n bump(key);\n const result = await plain.setItem(key, value);\n if (isSecureMigratableKey(key) && !settled.has(key)) await dropSecure([key]);\n return result;\n },\n\n // The secure copy goes even when the plain remove throws: a sign-out must not\n // leave per-user cache behind to be moved back on the next start.\n async removeItem(key) {\n bump(key);\n try {\n await plain.removeItem(key);\n } finally {\n if (isSecureMigratableKey(key)) await dropSecure([key]);\n }\n },\n\n async multiRemove(keys) {\n for (const k of keys) bump(k);\n try {\n await plain.multiRemove(keys);\n } finally {\n await dropSecure(keys.filter(isSecureMigratableKey));\n }\n },\n };\n}\n","import { END_USER_BASE_PATH } from '../constants';\nimport type { InvalidateOptions } from '../cache/QueryCache';\nimport type { QueryKey } from '../cache/query-key';\nimport type { AppStateProvider, ConnectSse } from '../platform/types';\nimport { SseSupervisor } from '../sync/SseSupervisor';\nimport { fetchContentVersions } from './versions';\nimport { VersionPoller, resolvePollInterval } from '../sync/VersionPoller';\n\n/**\n * Transport of a live content watch (QFK2-E76 §9.1). `'auto'` and `'sse'`:\n * SSE when the platform has a transport, polling otherwise or after SSE keeps\n * failing (polling is always the fallback). `'poll'`: version polling only.\n */\nexport type ContentLiveMode = 'auto' | 'sse' | 'poll';\n\n/** What the hub is doing right now (`client.contentChanges.status()`, debug only). */\nexport type ContentChangesStatus = 'sse' | 'polling' | 'idle';\n\n/** One live watch: a collection's lists + records, or one record (`id`), plus extra collections (`also`, §8.3). */\nexport interface ContentWatchTarget {\n collection: string;\n id?: string;\n /** Collections whose changes also refresh this target (e.g. an expanded relation). */\n also?: readonly string[];\n}\n\n/** Where a change signal lands: a `QueryCache` (or anything with its `invalidateByPrefix`). */\nexport interface ContentInvalidationTarget {\n invalidateByPrefix(prefix: QueryKey, opts?: InvalidateOptions): void;\n}\n\nexport interface ContentWatchOptions {\n /** The cache to invalidate on a change (the React hooks pass the Provider's cache). */\n cache?: ContentInvalidationTarget;\n /** Requested poll cadence while polling (default 60 s, floor 30 s; the smallest watcher wins). */\n pollIntervalMs?: number;\n}\n\n/** Public face of the hub on a client (`client.contentChanges`). Lazy: nothing runs until `watch`. */\nexport interface ContentChangesApi {\n /** Start watching; returns the unsubscribe. `mode` defaults to the client's `contentLiveDefault`. */\n watch(target: ContentWatchTarget, mode?: ContentLiveMode, opts?: ContentWatchOptions): () => void;\n status(): ContentChangesStatus;\n /** Identity changed: forget versions and reconnect with fresh headers. */\n reset(): void;\n /** Drop every watch and close the connection / poller. */\n dispose(): void;\n /**\n * Current version of each collection (QFK2-E59 D7): one\n * `GET /content-changes/version?collections=…` (≤20 per call, server limit).\n * Collections the answer lacks are omitted. Rejects with a `status` on HTTP\n * errors; one refused collection (change signal off, unreadable) 404s the\n * whole request. Needs no watch and opens no connection.\n */\n versions(collections: readonly string[]): Promise<Record<string, string>>;\n}\n\n/** Server limits per connection (D5): more than this rides polling instead (with one warning). */\nexport const CONTENT_WATCH_MAX_COLLECTIONS = 20;\nexport const CONTENT_WATCH_MAX_ITEMS = 50;\n/** Subscription-set changes within this window coalesce into one reconnect. */\nexport const CONTENT_WATCH_DEBOUNCE_MS = 250;\n/**\n * A change missed while disconnected surfaces in the reconnect `hello`, which\n * the whole fleet receives at about the same time (a server restart drops\n * everyone): those invalidations are spread over this window.\n */\nexport const CONTENT_HELLO_SPREAD_MS = 5_000;\n\ntype TimerHandle = unknown;\n\nexport interface ContentChangeHubOptions {\n /** Backend base URL (no `/v1` suffix). */\n apiUrl: string;\n /** GET an end-user path (e.g. `/content-changes/version?…`); rejects with a `status` on HTTP errors. */\n request: (path: string) => Promise<unknown>;\n /** Headers of the SSE request (fresh token / key per connect). */\n headers: () => Promise<Record<string, string>>;\n /** SSE transport; absent = polling only. */\n connectSse?: ConnectSse;\n appState?: AppStateProvider;\n warn?: (message: string) => void;\n random?: () => number;\n setTimeout?: (fn: () => void, ms: number) => TimerHandle;\n clearTimeout?: (handle: TimerHandle) => void;\n}\n\ninterface Sub {\n t: ContentWatchTarget;\n mode: ContentLiveMode;\n cache?: ContentInvalidationTarget;\n poll?: number;\n}\n\nconst enc = encodeURIComponent;\n\nconst isNotFound = (err: unknown): boolean => (err as { status?: unknown } | null)?.status === 404;\n\n/**\n * One multiplexed change channel per client (QFK2-E76 §9.2). Watches are\n * reference-counted; a change of the watched set reconnects once, debounced\n * ({@link CONTENT_WATCH_DEBOUNCE_MS}). A signal carries no data: the hub\n * invalidates the matching query-cache prefixes (`['content', c]`,\n * `['content-item', c]`, `['content-item', c, id]`) with the server's jitter,\n * and the cache refetches only mounted entries, with the user's own\n * credentials. Paused in the background; never throws into the app (a\n * collection the server refuses is warned about once and dropped). Built as a\n * closure (not a class) so the browser bundle minifies its internals.\n */\nexport function createContentChangeHub(o: ContentChangeHubOptions): ContentChangesApi {\n const subs = new Set<Sub>();\n /** Last seen version per collection (opaque, compared with `!==`). */\n const known = new Map<string, string>();\n /** Collections the server refused (404): no longer put on the wire. */\n const disabled = new Set<string>();\n const warned = new Set<string>();\n const random = o.random ?? Math.random;\n const setT = o.setTimeout ?? ((fn: () => void, ms: number) => setTimeout(fn, ms));\n const clearT = o.clearTimeout ?? ((h: TimerHandle) => clearTimeout(h as ReturnType<typeof setTimeout>));\n let sse: SseSupervisor | undefined;\n let sseUrl = '';\n let sseOn = false;\n /** SSE fell back; retried on the next set change, foreground or reset. */\n let sseFailed = false;\n let poller: VersionPoller | undefined;\n let pollSet: string[] = [];\n let applied = '';\n let timer: TimerHandle | undefined;\n let appUnsub: (() => void) | undefined;\n\n const active = () => !o.appState || o.appState.isActive();\n\n const warnOnce = (key: string, message: string) => {\n if (warned.has(key)) return;\n warned.add(key);\n o.warn?.(message);\n };\n\n const cancel = () => {\n if (timer !== undefined) clearT(timer);\n timer = undefined;\n };\n\n const schedule = () => {\n cancel();\n timer = setT(() => {\n timer = undefined;\n apply();\n }, CONTENT_WATCH_DEBOUNCE_MS);\n };\n\n /** Background (or nothing on the wire): close SSE, stop polling; keep the watches. */\n const pause = () => {\n sse?.stop();\n poller?.stop();\n sseOn = false;\n applied = '';\n };\n\n const stop = () => {\n cancel();\n pause();\n pollSet = [];\n appUnsub?.();\n appUnsub = undefined;\n };\n\n /** What goes on the wire: the SSE URL (or none) and the collections to poll. */\n const plan = () => {\n const cols = new Set<string>();\n const items = new Map<string, string>(); // \"c:id\" (URL-encoded parts) → c\n let interval = Infinity;\n let wantSse = false;\n for (const s of subs) {\n const { collection: c, id, also } = s.t;\n if (!disabled.has(c)) (id ? items.set(`${enc(c)}:${enc(id)}`, c) : cols.add(c));\n for (const a of also ?? []) if (!disabled.has(a)) cols.add(a);\n interval = Math.min(interval, resolvePollInterval(s.poll));\n wantSse ||= s.mode !== 'poll';\n }\n const itemList = [...items].filter(([, c]) => !cols.has(c)); // a watched collection covers its records\n const colList = [...cols];\n let url: string | null = null;\n let poll = [...colList, ...itemList.map(([, c]) => c)];\n if (wantSse && o.connectSse && !sseFailed) {\n const onCols = colList.slice(0, CONTENT_WATCH_MAX_COLLECTIONS);\n const onItems = itemList.slice(0, CONTENT_WATCH_MAX_ITEMS);\n poll = [...colList.slice(CONTENT_WATCH_MAX_COLLECTIONS), ...itemList.slice(CONTENT_WATCH_MAX_ITEMS).map(([, c]) => c)];\n if (poll.length) warnOnce('', '[QafkaCMS] live: over 20 collections / 50 records; the rest polls');\n const q: string[] = [];\n if (onCols.length) q.push(`collections=${onCols.map(enc).join(',')}`);\n if (onItems.length) q.push(`items=${onItems.map(([k]) => k).join(',')}`);\n if (q.length) url = `${o.apiUrl.replace(/\\/$/, '')}${END_USER_BASE_PATH}/content-changes/watch?${q.join('&')}`;\n }\n poll = [...new Set(poll)];\n return { url, poll, interval: interval === Infinity ? resolvePollInterval() : interval };\n };\n\n /**\n * Put the plan on the wire. Polling probes at once when `catchUp` is set or\n * a polled collection has no baseline yet (first watch, a new collection,\n * SSE → poll); later probes follow the jittered cadence.\n */\n const apply = (catchUp = false): void => {\n if (!subs.size) return stop();\n if (o.appState && !appUnsub) {\n appUnsub = o.appState.subscribe((on) => {\n if (!on) return pause();\n sseFailed = false;\n apply(true); // polling catches up now; SSE catches up via `hello`\n });\n }\n if (!active()) return pause();\n const p = plan();\n const key = JSON.stringify(p);\n if (key === applied) return;\n applied = key;\n\n sseOn = !!p.url;\n if (p.url) {\n sseUrl = p.url;\n sse ??= new SseSupervisor({\n connectSse: o.connectSse!,\n url: () => sseUrl,\n headers: o.headers,\n onMessage,\n onFallback: fallback,\n random: o.random,\n setTimeout: o.setTimeout,\n clearTimeout: o.clearTimeout,\n });\n void sse.start();\n } else {\n sse?.stop();\n }\n\n pollSet = p.poll;\n if (!p.poll.length) return poller?.stop();\n if (poller?.intervalMs !== p.interval) {\n poller?.stop();\n poller = new VersionPoller({\n check,\n intervalMs: p.interval,\n appState: o.appState,\n followAppState: false,\n random: o.random,\n setTimeout: o.setTimeout,\n clearTimeout: o.clearTimeout,\n });\n }\n if (!poller.running) poller.start();\n if (catchUp || p.poll.some((c) => !known.has(c))) void check();\n };\n\n function fallback(): void {\n sse?.stop();\n sseFailed = true;\n applied = '';\n apply(true); // catch up at once (and find refused collections)\n }\n\n // --- signals --------------------------------------------------------------\n\n function onMessage(e: unknown): void {\n const ev = (e ?? {}) as { type?: unknown; collection?: unknown; id?: unknown; v?: unknown; spreadMs?: unknown; versions?: unknown };\n const { type, collection: c, spreadMs: spread } = ev;\n if (type === 'hello' && ev.versions && typeof ev.versions === 'object') {\n for (const [col, v] of Object.entries(ev.versions)) saw(col, v, CONTENT_HELLO_SPREAD_MS);\n } else if (type === 'changed' && typeof c === 'string') {\n if (typeof ev.v === 'string' || typeof ev.v === 'number') known.set(c, String(ev.v));\n changed(c, typeof ev.id === 'string' ? ev.id : undefined, typeof spread === 'number' && spread > 0 ? spread : 0);\n } else if (type === 'error') {\n fallback();\n }\n }\n\n /**\n * Record a version; the first one is the baseline. A change from a known one\n * means a missed signal → invalidate, spread over `spread` ms (a reconnect\n * `hello`; polling is already jittered per client).\n */\n function saw(c: string, raw: unknown, spread = 0): void {\n if (typeof raw !== 'string' && typeof raw !== 'number') return;\n const prev = known.get(c);\n known.set(c, String(raw));\n if (prev !== undefined && prev !== String(raw)) changed(c, undefined, spread);\n }\n\n function changed(c: string, id: string | undefined, spread: number): void {\n const delayMs = spread ? Math.floor(random() * spread) : 0;\n const done = new Set<string>();\n const caches: ContentInvalidationTarget[] = [];\n for (const { t, cache } of subs) {\n if (!cache) continue;\n if (!((t.collection === c && (!t.id || id === undefined || id === t.id)) || t.also?.includes(c))) continue;\n let i = caches.indexOf(cache);\n if (i < 0) i = caches.push(cache) - 1;\n const prefixes: QueryKey[] = t.id\n ? [['content-item', t.collection, t.id]]\n : [['content', t.collection], ['content-item', t.collection]];\n for (const prefix of prefixes) {\n const k = i + JSON.stringify(prefix);\n if (done.has(k)) continue;\n done.add(k);\n cache.invalidateByPrefix(prefix, { delayMs });\n }\n }\n }\n\n // --- polling --------------------------------------------------------------\n\n async function record(cols: string[]): Promise<void> {\n const res = (await o.request(`/content-changes/version?collections=${cols.map(enc).join(',')}`)) as Record<\n string,\n unknown\n > | null;\n for (const c of cols) saw(c, res?.[c]);\n }\n\n async function check(): Promise<void> {\n let dropped = false;\n for (let i = 0; i < pollSet.length; i += CONTENT_WATCH_MAX_COLLECTIONS) {\n const chunk = pollSet.slice(i, i + CONTENT_WATCH_MAX_COLLECTIONS);\n try {\n await record(chunk);\n } catch (err) {\n if (!isNotFound(err)) continue; // transient — the next tick retries\n // One refused collection fails the whole batch (uniform 404): find it.\n for (const c of chunk) {\n try {\n if (chunk.length === 1) throw err;\n await record([c]);\n } catch (e) {\n if (!isNotFound(e)) continue;\n disabled.add(c);\n warnOnce(c, `[QafkaCMS] live disabled for ${c}: enable change signal in the collection settings`);\n dropped = true;\n }\n }\n }\n }\n if (dropped) {\n sseFailed = false; // the refused collection may be why SSE failed: retry without it\n schedule();\n }\n }\n\n return {\n watch(target, mode = 'auto', opts = {}) {\n const sub: Sub = { t: target, mode, cache: opts.cache, poll: opts.pollIntervalMs };\n subs.add(sub);\n schedule();\n return () => {\n if (subs.delete(sub)) schedule();\n };\n },\n status: () => (sseOn ? 'sse' : poller?.running ? 'polling' : 'idle'),\n reset() {\n known.clear();\n disabled.clear();\n sseFailed = false;\n if (!subs.size) return;\n cancel();\n applied = '';\n apply();\n },\n dispose() {\n subs.clear();\n stop();\n },\n versions: (collections) => fetchContentVersions(o.request, collections),\n };\n}\n","import { compareAppVersion, parseAppVersion, type AppVersionTuple } from '../app-version';\nimport type { BundleCollectionAppVersion, BundleComponentInfo, BundleFieldMeta, BundleFile } from './types';\n\n/**\n * Client-side app-version filtering of bundle rows (QFK2-E59 T466 B3). The\n * bundle is the anonymous view for every app version; the server leaves the\n * T467 filter to the SDK and ships the rules in the file. The rules mirror the\n * API's `content/app-version-read.ts`:\n *\n * - Rows (V6): a row is outside the range when its min field is above the\n * client version or its max field below it. A null, empty or invalid value\n * does not restrict. Unknown client version: `'hide'` keeps only rows no\n * bound restricts, `'show'` (default) keeps every row.\n * - Blocks (V7): a component is hidden when its `minAppVersion` is above the\n * client version, or (unknown client) its `appVersionUnknown` is `'hide'`.\n *\n * Blocks with field metadata (`componentFields` / `zoneFields` of the\n * collection and of each listed component), exactly like the API's V7 strip:\n * a COMPONENT field holding a hidden component reads as `null` (repeatable\n * too), a DYNAMIC_ZONE drops blocks whose `__component` is hidden, and kept\n * component instances are walked with their own component's metadata. Only\n * declared composite fields are touched; a localized value (locale map) is\n * handled per locale.\n *\n * Fallback without metadata (a collection with no composite field, or a file\n * of an older API): every array is scanned and an object item whose\n * `__component` is hidden is dropped; a non-array object whose `__component`\n * is hidden becomes `null`; kept values are walked recursively. A COMPONENT\n * value carries no `__component`, so there a hidden component held directly\n * by a COMPONENT field cannot be recognised and stays.\n */\n\nconst MAX_DEPTH = 32;\nconst EMPTY: never[] = [];\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\n/** Ids of the components `appVersion` must not see (V7). */\nexport function hiddenBundleComponents(\n components: Record<string, BundleComponentInfo> | null | undefined,\n appVersion: string | null,\n): Set<string> {\n const client = parseAppVersion(appVersion);\n const out = new Set<string>();\n for (const [id, c] of Object.entries(components ?? {})) {\n const min = parseAppVersion(c?.minAppVersion);\n if (!min) continue;\n if (client ? compareAppVersion(min, client) > 0 : c.appVersionUnknown === 'hide') out.add(id);\n }\n return out;\n}\n\nfunction rowVisible(row: Record<string, unknown>, rule: BundleCollectionAppVersion, client: AppVersionTuple | null) {\n const bounds: Array<[string, 1 | -1]> = [];\n if (rule.minField) bounds.push([rule.minField, 1]);\n if (rule.maxField) bounds.push([rule.maxField, -1]);\n if (!bounds.length || (!client && rule.unknown !== 'hide')) return true;\n return bounds.every(([field, sign]) => {\n const v = parseAppVersion(row[field]);\n // min: v ≤ client (sign 1); max: v ≥ client (sign -1).\n return !v || (client !== null && sign * compareAppVersion(v, client) <= 0);\n });\n}\n\nfunction strip(value: unknown, hidden: ReadonlySet<string>, depth: number): unknown {\n if (depth > MAX_DEPTH) return value;\n if (Array.isArray(value)) {\n let changed = false;\n const out: unknown[] = [];\n for (const item of value) {\n if (isObject(item) && typeof item.__component === 'string' && hidden.has(item.__component)) {\n changed = true;\n continue;\n }\n const next = strip(item, hidden, depth + 1);\n if (next !== item) changed = true;\n out.push(next);\n }\n return changed ? out : value;\n }\n if (!isObject(value)) return value;\n if (typeof value.__component === 'string' && hidden.has(value.__component)) return null;\n let out: Record<string, unknown> | undefined;\n for (const [k, v] of Object.entries(value)) {\n const next = strip(v, hidden, depth + 1);\n if (next !== v) (out ??= { ...value })[k] = next;\n }\n return out ?? value;\n}\n\ntype Components = Record<string, BundleComponentInfo> | null | undefined;\n\nconst hasMeta = (m: BundleFieldMeta | null | undefined): m is BundleFieldMeta =>\n !!m && (!!m.componentFields || !!m.zoneFields);\n\n/** A localized value: every entry null or `{ value, state }` (the API's locale map). */\nfunction isLocaleMap(v: unknown): v is Record<string, { value?: unknown } | null> {\n if (!isObject(v)) return false;\n const entries = Object.values(v);\n return (\n entries.length > 0 &&\n entries.every((e) => e === null || (isObject(e) && typeof e.state === 'string' && 'value' in e))\n );\n}\n\n/** `fn` on the value, or on each locale's `value` of a locale map. */\nfunction perLocale(v: unknown, fn: (v: unknown) => unknown): unknown {\n if (!isLocaleMap(v)) return fn(v);\n let out: Record<string, unknown> | undefined;\n for (const [loc, e] of Object.entries(v)) {\n if (!e) continue;\n const next = fn(e.value);\n if (next !== e.value) (out ??= { ...v })[loc] = { ...e, value: next };\n }\n return out ?? v;\n}\n\n/** The declared composite fields of `obj` stripped (same object when nothing changes). */\nfunction stripFields(\n obj: Record<string, unknown>,\n meta: BundleFieldMeta,\n hidden: ReadonlySet<string>,\n components: Components,\n depth: number,\n): Record<string, unknown> {\n let out: Record<string, unknown> | undefined;\n const set = (k: string, fn: (v: unknown) => unknown) => {\n if (!(k in obj)) return;\n const next = perLocale(obj[k], fn);\n if (next !== obj[k]) (out ??= { ...obj })[k] = next;\n };\n for (const [k, f] of Object.entries(meta.componentFields ?? {})) {\n set(k, (v) => {\n if (v === null || v === undefined || !f || typeof f.componentId !== 'string') return v;\n if (hidden.has(f.componentId)) return null;\n if (!Array.isArray(v)) return instance(v, f.componentId, hidden, components, depth);\n const items = v.map((it) => instance(it, f.componentId, hidden, components, depth));\n return items.some((it, i) => it !== v[i]) ? items : v;\n });\n }\n for (const k of meta.zoneFields ?? []) {\n set(k, (v) => {\n if (!Array.isArray(v)) return v;\n let changed = false;\n const kept: unknown[] = [];\n for (const item of v) {\n const cid = isObject(item) ? item.__component : undefined;\n if (typeof cid === 'string' && hidden.has(cid)) {\n changed = true;\n continue;\n }\n const next = typeof cid === 'string' ? instance(item, cid, hidden, components, depth) : item;\n if (next !== item) changed = true;\n kept.push(next);\n }\n return changed ? kept : v;\n });\n }\n return out ?? obj;\n}\n\n/** One component instance, walked with its component's metadata (none = no composite fields). */\nfunction instance(v: unknown, cid: string, hidden: ReadonlySet<string>, components: Components, depth: number) {\n const meta = components?.[cid];\n if (!isObject(v) || depth >= MAX_DEPTH || !hasMeta(meta)) return v;\n return stripFields(v, meta, hidden, components, depth + 1);\n}\n\n/**\n * A row with every hidden block removed (see the module doc); the same object\n * when nothing changes. `meta` (the collection's field metadata) and\n * `components` (the file's map) select the exact, API-equal path; without\n * `meta` the `__component` heuristic runs.\n */\nexport function stripHiddenBundleBlocks(\n row: Record<string, unknown>,\n hidden: ReadonlySet<string>,\n meta?: BundleFieldMeta | null,\n components?: Components,\n): Record<string, unknown> {\n if (!hidden.size) return row;\n if (hasMeta(meta)) return stripFields(row, meta, hidden, components, 0);\n let out: Record<string, unknown> | undefined;\n for (const [k, v] of Object.entries(row)) {\n const next = strip(v, hidden, 0);\n if (next !== v) (out ??= { ...row })[k] = next;\n }\n return out ?? row;\n}\n\n/** The collection's rows for `appVersion`: rows out of range dropped, hidden blocks stripped. */\nexport function filterBundleRows(\n file: BundleFile,\n collection: string,\n appVersion: string | null,\n): Array<Record<string, unknown>> {\n const col = file.collections[collection];\n if (!col || !Array.isArray(col.rows)) return EMPTY;\n const client = parseAppVersion(appVersion);\n const rule = col.appVersion;\n const rows = rule ? col.rows.filter((r) => rowVisible(r, rule, client)) : col.rows;\n const hidden = hiddenBundleComponents(file.components, appVersion);\n return hidden.size ? rows.map((r) => stripHiddenBundleBlocks(r, hidden, col, file.components)) : rows;\n}\n","import { STORAGE_PREFIX } from '../constants';\nimport { ProblemError, toProblemError } from '../transport/problem-details';\nimport { filterBundleRows } from './filter';\nimport type { KeyValueStorage } from '../platform/types';\nimport type {\n BundleFile,\n ContentBundleApi,\n ContentBundleClientOptions,\n ContentBundleManifest,\n ContentBundleStatus,\n ContentBundleSyncResult,\n} from './types';\n\n/** Index of the persisted files: the current locale and the version stored per locale. */\ninterface BundleIndex {\n current: string | null;\n files: Record<string, number>;\n}\n\n/** Persisted index of the bundle files. */\nexport const STORAGE_KEY_BUNDLE_INDEX = `${STORAGE_PREFIX}bundle-index`;\n/** Persisted bundle file (the downloaded JSON text), one key per locale. */\nexport const STORAGE_KEY_BUNDLE_PREFIX = `${STORAGE_PREFIX}bundle:`;\n\nconst fileKey = (locale: string) => `${STORAGE_KEY_BUNDLE_PREFIX}${locale}`;\n/** No persistence: the bundle lives in memory (plus `initial`) for this session. */\nconst NO_STORAGE: KeyValueStorage = {\n getItem: async () => null,\n setItem: async () => undefined,\n removeItem: async () => undefined,\n multiRemove: async () => undefined,\n};\nconst EMPTY: never[] = [];\nconst ORIGIN_RE = /^([a-z][a-z\\d+.-]*:)\\/\\/([^/?#]*)/i;\n\n/** A value with the B5 shape (formatVersion 1, numeric version, string locale, collections object). */\nexport function isBundleFile(v: unknown): v is BundleFile {\n const f = v as BundleFile | null;\n return (\n typeof f === 'object' &&\n f !== null &&\n f.formatVersion === 1 &&\n typeof f.version === 'number' &&\n typeof f.locale === 'string' &&\n typeof f.collections === 'object' &&\n f.collections !== null\n );\n}\n\n/** `scheme://host[:port]`, lower-cased, default port dropped; `null` for a relative URL. */\nfunction originOf(url: string): string | null {\n const m = ORIGIN_RE.exec(url);\n if (!m) return null;\n const scheme = m[1]!.toLowerCase();\n let host = m[2]!.toLowerCase();\n if ((scheme === 'https:' && host.endsWith(':443')) || (scheme === 'http:' && host.endsWith(':80'))) {\n host = host.slice(0, host.lastIndexOf(':'));\n }\n return `${scheme}//${host}`;\n}\n\n/**\n * Resolve the signed download URL against the API base: a relative URL (an\n * API path, the local fallback) and an absolute URL on the API's origin are\n * \"same origin\" and carry the end-user security headers; any other host (CDN /\n * storage) gets a plain GET, so no project key or token leaks to it.\n */\nexport function resolveBundleUrl(apiUrl: string, url: string): { href: string; sameOrigin: boolean } {\n const api = originOf(apiUrl) ?? '';\n if (url.startsWith('//')) url = `${api.slice(0, api.indexOf('//'))}${url}`;\n const origin = originOf(url);\n if (origin) return { href: url, sameOrigin: origin === api };\n return { href: `${api}${url.startsWith('/') ? '' : '/'}${url}`, sameOrigin: true };\n}\n\nfunction toError(e: unknown): Error {\n return e instanceof Error ? e : new Error(String(e));\n}\n\n/**\n * The content bundle client (QFK2-E59 T466 B10) behind `client.bundle`.\n *\n * - `sync()` asks `GET /content-bundle` for the published version and\n * downloads the file only when it differs from the held one (same version +\n * locale = nothing to do; a stored copy of that version is reused).\n * - The file is validated (`formatVersion` 1, `version` = the announced one)\n * before it replaces the held bundle; any failure keeps the previous one and\n * sets `error`.\n * - The JSON text is persisted in a plain key/value store (one key per locale\n * + an index): `contentBundle.storage`, else the platform's `cacheStorage`,\n * never the session (secure) store; with neither it is kept in memory only\n * (dev warning). A write that fails (quota) keeps the bundle in memory and\n * warns; files of older versions are removed. Offline, the last\n * persisted bundle keeps serving. `initial` serves until a newer version is\n * stored. A 404 `CONTENT_BUNDLE_NOT_FOUND` (no bundle published) drops it.\n * - Not tied to the end-user identity: the bundle is the anonymous view, so\n * login / logout never clear it.\n */\nexport function createContentBundleClient(o: ContentBundleClientOptions): ContentBundleApi {\n const { http, platform, language } = o;\n // A plain store only: never `platform.sessionStorage` (RN: Keychain / EncryptedSharedPreferences).\n const plain = o.storage !== undefined ? o.storage : platform.cacheStorage;\n if (plain === undefined) {\n platform.warn?.(\n '[QafkaCMS] contentBundle has no plain storage: the bundle is kept in memory for this app session ' +\n '(plus `initial`). Pass `contentBundle: { storage: AsyncStorage }` (or an MMKV adapter) to keep it offline.',\n );\n }\n const storage = plain ?? NO_STORAGE;\n const appVersion = http.appVersion;\n const listeners = new Set<() => void>();\n\n let file: BundleFile | null = null;\n if (o.initial !== undefined) {\n if (isBundleFile(o.initial)) file = o.initial;\n else platform.warn?.('[QafkaCMS] contentBundle.initial is not a bundle file (formatVersion 1); ignored');\n }\n let memo = new Map<string, { rows: Array<Record<string, unknown>>; byId?: Map<string, Record<string, unknown>> }>();\n let error: Error | null = null;\n let revision = 0;\n let hydrated = false;\n let settled = false;\n let hydration: Promise<void> | null = null;\n let running: { locale: string | null; promise: Promise<ContentBundleSyncResult> } | null = null;\n /** A locale passed to `sync()`; dropped when the active locale changes. */\n let override: string | undefined;\n\n const notify = () => {\n revision++;\n for (const l of [...listeners]) l();\n };\n const setFile = (next: BundleFile | null) => {\n file = next;\n memo = new Map();\n };\n const wanted = (): string | null => override ?? o.locale ?? language?.getLanguage() ?? null;\n\n const readIndex = async (): Promise<BundleIndex> => {\n try {\n const idx = JSON.parse((await storage.getItem(STORAGE_KEY_BUNDLE_INDEX)) ?? 'null') as BundleIndex | null;\n if (idx && typeof idx.files === 'object' && idx.files) return idx;\n } catch {\n /* unreadable index = nothing stored */\n }\n return { current: null, files: {} };\n };\n\n const loadStored = async (locale: string): Promise<BundleFile | null> => {\n try {\n const raw = await storage.getItem(fileKey(locale));\n const parsed: unknown = raw ? JSON.parse(raw) : null;\n return isBundleFile(parsed) ? parsed : null;\n } catch {\n return null;\n }\n };\n\n const ready = (): Promise<void> =>\n (hydration ??= (async () => {\n try {\n const index = await readIndex();\n const want = wanted();\n const locale = want !== null && index.files[want] !== undefined ? want : index.current;\n const stored = locale ? await loadStored(locale) : null;\n // Same locale: the newer one wins (an app update may ship a newer `initial`). Different\n // locales: the stored one, unless `initial` is the wanted locale.\n const better = (s: BundleFile, f: BundleFile) =>\n s.locale === f.locale ? s.version >= f.version : f.locale !== want;\n if (stored && (!file || better(stored, file))) setFile(stored);\n } finally {\n hydrated = true;\n notify();\n }\n })());\n\n const persist = async (next: BundleFile, text: string): Promise<void> => {\n const index = await readIndex();\n // A web storage that hit its quota keeps the value in memory and resolves truthy: drop that copy.\n if ((await storage.setItem(fileKey(next.locale), text)) as unknown) {\n await storage.removeItem(fileKey(next.locale));\n throw new Error('storage quota exceeded');\n }\n const files: Record<string, number> = { [next.locale]: next.version };\n const stale: string[] = [];\n for (const [loc, v] of Object.entries(index.files)) {\n if (loc === next.locale) continue;\n if (v === next.version) files[loc] = v;\n else stale.push(fileKey(loc));\n }\n if (stale.length) await storage.multiRemove(stale);\n await storage.setItem(STORAGE_KEY_BUNDLE_INDEX, JSON.stringify({ current: next.locale, files }));\n };\n\n const download = async (url: string): Promise<string> => {\n const { href, sameOrigin } = resolveBundleUrl(o.apiUrl, url);\n const headers = sameOrigin ? await http.securityHeaders({}, { method: 'GET', path: href }) : {};\n const res = await platform.fetch(href, { method: 'GET', headers });\n if (!res.ok) throw await toProblemError(res);\n return res.text();\n };\n\n const run = async (locale: string | null): Promise<ContentBundleSyncResult> => {\n let m: ContentBundleManifest;\n try {\n m = await http.request<ContentBundleManifest>('GET', '/content-bundle', { query: { locale } });\n } catch (e) {\n if (!(e instanceof ProblemError && e.status === 404 && e.raw.code === 'CONTENT_BUNDLE_NOT_FOUND')) throw e;\n // No bundle published (every collection left it): drop the held and stored copies.\n const had = file !== null;\n setFile(null);\n const index = await readIndex();\n await storage.multiRemove([...Object.keys(index.files).map(fileKey), STORAGE_KEY_BUNDLE_INDEX]);\n return { version: null, changed: had };\n }\n if (!m || typeof m.version !== 'number' || typeof m.url !== 'string') {\n throw new Error('QafkaCMS: invalid content bundle manifest');\n }\n if (file && file.version === m.version && file.locale === m.locale) return { version: m.version, changed: false };\n\n let next = await loadStored(m.locale);\n let text: string | null = null;\n if (!next || next.version !== m.version) {\n text = await download(m.url);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new Error('QafkaCMS: the content bundle file is not valid JSON');\n }\n if (!isBundleFile(parsed)) {\n throw new Error('QafkaCMS: unsupported content bundle file (formatVersion 1 expected)');\n }\n if (parsed.version !== m.version) {\n throw new Error(`QafkaCMS: content bundle version ${parsed.version} ≠ announced ${m.version}`);\n }\n next = parsed;\n }\n setFile(next);\n try {\n if (text !== null) await persist(next, text);\n else {\n const index = await readIndex();\n await storage.setItem(STORAGE_KEY_BUNDLE_INDEX, JSON.stringify({ ...index, current: next.locale }));\n }\n } catch (e) {\n // The new bundle is in use; only the offline copy is missing.\n platform.warn?.('[QafkaCMS] content bundle could not be stored (kept in memory for this session)', e);\n }\n return { version: m.version, changed: true };\n };\n\n const sync = (options: { locale?: string } = {}): Promise<ContentBundleSyncResult> => {\n if (options.locale) override = options.locale;\n const locale = wanted();\n if (running && running.locale === locale) return running.promise;\n const before = running?.promise;\n const promise = (async () => {\n await before?.catch(() => undefined);\n await ready().catch(() => undefined);\n try {\n const result = await run(locale);\n error = null;\n return result;\n } catch (e) {\n throw (error = toError(e));\n }\n })();\n running = { locale, promise };\n const done = () => {\n if (running?.promise === promise) running = null;\n settled = true;\n notify();\n };\n promise.then(done, done);\n notify();\n return promise;\n };\n\n const collection = (name: string) => {\n let m = memo.get(name);\n if (!m) memo.set(name, (m = { rows: file ? filterBundleRows(file, name, appVersion) : EMPTY }));\n return m;\n };\n\n const getRow = <T>(name: string, id: string): T | null => {\n if (!file) return null;\n const m = collection(name);\n m.byId ??= new Map(m.rows.map((r) => [String(r.id), r]));\n return (m.byId.get(String(id)) ?? null) as T | null;\n };\n\n // React snapshots: one object per key until the next change.\n let views = new Map<string, unknown>();\n let viewsRevision = -1;\n const cachedView = <V>(key: string, make: () => V): V => {\n if (viewsRevision !== revision) {\n views = new Map();\n viewsRevision = revision;\n }\n if (!views.has(key)) views.set(key, make());\n return views.get(key) as V;\n };\n const status = (): ContentBundleStatus => ({ version: file?.version ?? null, isLoading: isLoading(), error });\n const isLoading = () => !file && (!hydrated || !settled || running !== null);\n\n const start = (): (() => void) => {\n const kick = () => void sync().catch(() => undefined); // surfaced through `error`\n kick();\n const offApp = platform.appState?.subscribe((active) => active && kick());\n let last = language?.getLanguage() ?? null;\n const offLocale = language?.subscribe(() => {\n const next = language.getLanguage();\n if (next === last) return; // e.g. an i18n-only update\n last = next;\n override = undefined;\n if (!o.locale) kick();\n });\n return () => {\n offApp?.();\n offLocale?.();\n };\n };\n\n return {\n get version() {\n return file?.version ?? null;\n },\n get locale() {\n return file?.locale ?? null;\n },\n get error() {\n return error;\n },\n get isLoading() {\n return isLoading();\n },\n get revision() {\n return revision;\n },\n sync,\n ready,\n rows: <T>(name: string) => collection(name).rows as T[],\n get: getRow,\n view: <T>(name: string) => cachedView(`r\\n${name}`, () => ({ rows: collection(name).rows as T[], ...status() })),\n itemView: <T>(name: string, id: string | null | undefined) =>\n cachedView(`i\\n${name}\\n${id ?? ''}`, () => ({ data: id ? getRow<T>(name, id) : null, ...status() })),\n subscribe: (listener) => {\n void ready();\n listeners.add(listener);\n return () => void listeners.delete(listener);\n },\n start,\n };\n}\n","import type { ColorValue, GradientValue } from '../types/color';\n\nconst HEX = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;\n\nfunction isPlainColor(v: unknown): v is ColorValue {\n if (typeof v === 'string') return HEX.test(v);\n return (\n typeof v === 'object' &&\n v !== null &&\n !Array.isArray(v) &&\n Array.isArray((v as GradientValue).stops)\n );\n}\n\n/**\n * Resolves a stored color value for a scheme. Plain values (hex / gradient)\n * are returned as is; `{ light, dark? }` picks `dark ?? light` for 'dark',\n * otherwise `light`. Invalid input returns `null`.\n */\nexport function resolveColor(value: unknown, scheme: 'light' | 'dark'): ColorValue | null {\n if (isPlainColor(value)) return value;\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;\n const { light, dark } = value as { light?: unknown; dark?: unknown };\n if (!isPlainColor(light)) return null;\n if (scheme === 'dark' && isPlainColor(dark)) return dark;\n return light;\n}\n","import type { KeyValueStorage } from '../platform/types';\n\n/**\n * Native storage contract. Mirrors AsyncStorage's surface for the methods\n * this SDK actually uses (getItem / setItem / removeItem / multiRemove).\n *\n * Adapted from Qafka's `storageCore.ts` (production-proven). Backed by OS-level\n * secure storage: iOS Keychain (no iCloud sync), Android EncryptedSharedPreferences.\n */\nexport interface QafkaCmsStorageNative {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n multiRemove(keys: string[]): Promise<void>;\n}\n\n/** The SDK's storage surface — the platform-neutral {@link KeyValueStorage} under its RN-era name. */\nexport interface QafkaCmsStorage extends KeyValueStorage {}\n\nconst FALLBACK_WARNING =\n '[QafkaCMS] Native QafkaCmsStorage module not registered — falling back to ' +\n 'in-memory storage. Persistence will be lost when the app closes. ' +\n 'This usually means autolinking failed or the app was not rebuilt after ' +\n 'upgrading the SDK.';\n\n/**\n * Wrap a native storage module, or build an in-memory fallback when the native\n * module is missing (e.g. autolinking failed). The fallback reports once through\n * the injected `warn` (the RN singleton passes a `__DEV__`-gated console.warn)\n * so the misconfiguration is visible without spamming the console.\n */\nexport function createStorage(\n native: QafkaCmsStorageNative | null,\n warn?: (message: string) => void,\n): QafkaCmsStorage {\n if (native) {\n return {\n getItem: (key) => native.getItem(key),\n setItem: (key, value) => native.setItem(key, value),\n removeItem: (key) => native.removeItem(key),\n multiRemove: (keys) => native.multiRemove(keys),\n };\n }\n\n const memory = new Map<string, string>();\n let warned = false;\n const warnOnce = () => {\n if (!warned) {\n warn?.(FALLBACK_WARNING);\n warned = true;\n }\n };\n\n return {\n async getItem(key) {\n warnOnce();\n return memory.has(key) ? memory.get(key)! : null;\n },\n async setItem(key, value) {\n warnOnce();\n memory.set(key, value);\n },\n async removeItem(key) {\n warnOnce();\n memory.delete(key);\n },\n async multiRemove(keys) {\n warnOnce();\n for (const k of keys) memory.delete(k);\n },\n };\n}\n","/**\n * Filter DSL — type-only mirror of the backend's `content/filter/filter.parser`.\n * Kept local (not imported from `@qafka/cms-shared-types`) because that package\n * pulls in Prisma + Zod at runtime, which must never enter the RN bundle. These\n * are compile-time types only; no runtime code is duplicated.\n */\nexport type FilterOp =\n | '_eq'\n | '_neq'\n | '_lt'\n | '_lte'\n | '_gt'\n | '_gte'\n | '_in'\n | '_nin'\n | '_null'\n | '_nnull'\n | '_contains'\n | '_icontains'\n | '_starts_with'\n | '_istarts_with';\n\nexport type FieldOps = { [op in FilterOp]?: unknown };\n\n/** Quantifiers over a relation field: `_some` / `_none` take a filter on the target collection (`{}` = any visible linked target). */\nexport type QuantifierOps = { _some?: FilterNode; _none?: FilterNode };\n\nexport type FilterNode =\n | { _and: FilterNode[] }\n | { _or: FilterNode[] }\n | { [field: string]: FieldOps | QuantifierOps };\n\n/** Dynamic var resolved server-side to the authenticated user's id. */\nexport const CURRENT_USER = '$CURRENT_USER';\n\n/** Server-time \"now\" (UTC). Use with `_eq/_neq/_lt/_lte/_gt/_gte` on date fields. */\nexport const NOW = '$NOW';\n\nconst NOW_OFFSET = /^[+-]\\d{1,6}[mhdw]$/;\n\n/**\n * Builds a `$NOW` value, optionally shifted: `now()` → `'$NOW'`, `now('+7d')` → `'$NOW(+7d)'`.\n * Offset units: `m` minutes, `h` hours, `d` days, `w` weeks. Throws on any other shape.\n */\nexport function now(offset?: string): string {\n if (offset === undefined) return NOW;\n if (!NOW_OFFSET.test(offset)) {\n throw new Error(\n `QafkaCMS: invalid now() offset ${JSON.stringify(offset)}; expected a signed count and unit such as '+7d', '-1w', '+2h', '-30m' (units m, h, d, w)`,\n );\n }\n return `$NOW(${offset})`;\n}\n","import { NativeModules, Platform } from 'react-native';\n\n/**\n * Native attestation contract — mirrors the iOS (App Attest / DeviceCheck) and\n * Android (Key Attestation / KeyStore) native modules. Adapted from Qafka's\n * `QafkaAttestation.ts`; the native binary is registered as `QafkaCmsAttestation`.\n *\n * The interface is tenant-agnostic (the challenge comes from the backend), which\n * is why Qafka's native code can be copied verbatim (QFK2-Q6 = A).\n */\nexport interface NativeAttestationApi {\n /** Whether the native module is linked AND the device supports attestation. */\n isSupported(): Promise<boolean>;\n /** Whether the native module is registered at all (false → rebuild needed). */\n isAvailable(): boolean;\n\n // iOS — App Attest\n generateKey(): Promise<string>;\n attestKey(keyId: string, challengeBase64: string): Promise<string>;\n generateAssertion(keyId: string, clientDataBase64: string): Promise<string>;\n\n // Android — Key Attestation\n generateKeyPair(alias: string, challengeBase64: string): Promise<void>;\n getAttestationCertChain(alias: string): Promise<string[]>;\n}\n\ninterface IOSAttestationModule {\n isSupported(): Promise<boolean>;\n generateKey(): Promise<string>;\n attestKey(keyId: string, challengeBase64: string): Promise<string>;\n generateAssertion(keyId: string, clientDataBase64: string): Promise<string>;\n}\n\ninterface AndroidAttestationModule {\n isSupported(): Promise<boolean>;\n generateKeyPair(alias: string, challengeBase64: string): Promise<void>;\n getAttestationCertChain(alias: string): Promise<string[]>;\n}\n\ntype NativeModule = IOSAttestationModule & AndroidAttestationModule;\n\nconst mod: (NativeModule & Partial<QafkaCmsDeviceInfo>) | null =\n (NativeModules as { QafkaCmsAttestation?: NativeModule }).QafkaCmsAttestation ?? null;\n\nexport interface QafkaCmsDeviceInfo {\n bundleId: string;\n appVersion: string;\n deviceModel: string;\n}\n\n/**\n * Static device info exposed as sync constants from the native module. Returns\n * empty strings (not null) when the native module is missing, so callers need\n * no null guards — treat empty as \"unknown\".\n */\nexport function getDeviceInfo(): QafkaCmsDeviceInfo {\n return {\n bundleId: mod?.bundleId ?? '',\n appVersion: mod?.appVersion ?? '',\n deviceModel: mod?.deviceModel ?? '',\n };\n}\n\nexport function isAttestationAvailable(): boolean {\n return mod !== null;\n}\n\n/**\n * The real native-backed attestation API, used as the default `deps.native`\n * for AttestationManager. In tests a mock is injected instead.\n */\nexport const nativeAttestation: NativeAttestationApi = {\n isAvailable: () => mod !== null,\n async isSupported() {\n if (!mod) return false;\n try {\n return await mod.isSupported();\n } catch {\n return false;\n }\n },\n generateKey() {\n if (!mod?.generateKey) throw new Error('iOS only');\n return mod.generateKey();\n },\n attestKey(keyId, challengeBase64) {\n if (!mod?.attestKey) throw new Error('iOS only');\n return mod.attestKey(keyId, challengeBase64);\n },\n generateAssertion(keyId, clientDataBase64) {\n if (!mod?.generateAssertion) throw new Error('iOS only');\n return mod.generateAssertion(keyId, clientDataBase64);\n },\n generateKeyPair(alias, challengeBase64) {\n if (!mod?.generateKeyPair) throw new Error('Android only');\n return mod.generateKeyPair(alias, challengeBase64);\n },\n getAttestationCertChain(alias) {\n if (!mod?.getAttestationCertChain) throw new Error('Android only');\n return mod.getAttestationCertChain(alias);\n },\n};\n\nexport { Platform };\n","import { NativeModules } from 'react-native';\nimport type { QafkaCmsStorageNative } from '@qafka/cms-core';\n\n/**\n * Native storage module — persists key/value pairs in OS-level secure storage.\n * iOS: Keychain Services (kSecAttrSynchronizable=false, no iCloud sync).\n * Android: AndroidX EncryptedSharedPreferences (AES256_GCM).\n *\n * Adapted from Qafka's `QafkaStorage.ts`. Registered natively as\n * `QafkaCmsStorage` (see ios/android native modules).\n */\nconst native: QafkaCmsStorageNative | null =\n (NativeModules as { QafkaCmsStorage?: QafkaCmsStorageNative }).QafkaCmsStorage ?? null;\n\nexport function isStorageAvailable(): boolean {\n return native !== null;\n}\n\nexport function getNativeStorage(): QafkaCmsStorageNative | null {\n return native;\n}\n","import { getNativeStorage } from '../native/QafkaCmsStorage';\nimport { createStorage, type QafkaCmsStorage } from '@qafka/cms-core';\n\n/**\n * Process-wide secure storage singleton. Resolves the native module once at\n * import; falls back to in-memory storage (with a dev warning) when the native\n * module is not linked.\n */\nexport const storage: QafkaCmsStorage = createStorage(getNativeStorage(), (message) => {\n if (typeof __DEV__ !== 'undefined' && __DEV__) console.warn(message);\n});\n","import {\n nativeAttestation,\n isAttestationAvailable,\n type NativeAttestationApi,\n} from '../native/QafkaCmsAttestation';\nimport { storage as defaultStorage } from './storage';\nimport { Platform } from 'react-native';\nimport {\n END_USER_BASE_PATH,\n STORAGE_KEY_ATTESTATION_KEY_ID,\n ANDROID_ATTEST_ALIAS,\n} from '@qafka/cms-core';\n\n/**\n * Device attestation — iOS App Attest + Android Key Attestation.\n *\n * Adapted from Qafka's `AttestationManager.ts` (production-proven). The flow,\n * the stale-key self-heal heuristic, and the session-token refresh strategy are\n * copied verbatim (QFK2-Q6 = A); only the namespace, storage keys, the\n * `/v1/end-user/attest` endpoint, and the `X-Project-Slug` header differ.\n *\n * Native module, secure storage, fetch and the platform are injected so the\n * whole class is unit-testable without the React Native runtime.\n */\nexport interface AttestationConfig {\n apiUrl: string;\n /** Resolves the backend project for the (pre-auth) attestation handshake. */\n projectSlug?: string;\n /** Project publishable key (`qpk_…`) — sent as `X-Project-Key` when set. */\n publishableKey?: string;\n /** Project id (UUID) — sent as `X-Project-Id` when set. */\n projectId?: string;\n /** Dev key (`__DEV__` only) — never present in release builds. */\n apiKey?: string | null;\n debug?: boolean;\n}\n\nexport interface AttestationDeps {\n native: NativeAttestationApi;\n storage: Pick<typeof defaultStorage, 'getItem' | 'setItem' | 'removeItem'>;\n fetch: (url: string, init: { method: string; headers: Record<string, string>; body: string }) => Promise<Response>;\n platformOS: string;\n now: () => number;\n}\n\ninterface SessionToken {\n token: string;\n expiresAt: number;\n}\n\n/** Backend project/attestation error codes — never a stale native key, so never regenerate. */\nconst PROJECT_ERROR_CODES =\n /PROJECT_KEY_REQUIRED|INVALID_PROJECT_KEY|APP_NOT_REGISTERED|PROJECT_MISMATCH|PROJECT_REQUIRED|ATTESTATION_REQUIRED|ATTESTATION_SESSION_EXPIRED/;\n\nconst DEV_BYPASS = 'dev-bypass';\nconst EXPIRY_MARGIN_MS = 60_000;\n\nexport class AttestationManager {\n private readonly config: AttestationConfig;\n private readonly d: AttestationDeps;\n private sessionToken: SessionToken | null = null;\n private keyId: string | null = null;\n /** The attestation/assertion in flight; concurrent callers share it. */\n private inflight: Promise<void> | null = null;\n\n constructor(config: AttestationConfig, deps?: Partial<AttestationDeps>) {\n this.config = config;\n this.d = {\n native: deps?.native ?? nativeAttestation,\n storage: deps?.storage ?? defaultStorage,\n fetch: deps?.fetch ?? ((url, init) => fetch(url, init as RequestInit)),\n platformOS: deps?.platformOS ?? Platform.OS,\n now: deps?.now ?? Date.now,\n };\n }\n\n async initialize(): Promise<void> {\n return this.exclusive(() => this.doInitialize());\n }\n\n /**\n * Run one attestation operation at a time. A second caller joins the one in\n * flight instead of starting its own: attesting a key twice makes Apple\n * refuse it and the stale-key path would mint an extra key.\n */\n private exclusive(op: () => Promise<void>): Promise<void> {\n if (this.inflight) return this.inflight;\n const run = op().finally(() => {\n if (this.inflight === run) this.inflight = null;\n });\n this.inflight = run;\n return run;\n }\n\n private async doInitialize(): Promise<void> {\n const moduleLinked = this.d.native.isAvailable?.() ?? isAttestationAvailable();\n const supported = await this.d.native.isSupported();\n\n if (!supported) {\n const reason = !moduleLinked\n ? 'the QafkaCmsAttestation native module is not registered (rebuild your app after installing the SDK)'\n : 'this device does not support attestation (Android 8.0+ / iOS 14+ required)';\n\n if (typeof __DEV__ !== 'undefined' && __DEV__) {\n console.warn(\n `[QafkaCMS] Attestation unavailable — entering dev-bypass because ${reason}. ` +\n 'Requests will omit the session token.',\n );\n this.sessionToken = { token: DEV_BYPASS, expiresAt: this.d.now() + 30 * 60 * 1000 };\n return;\n }\n throw new Error(`Device attestation is not supported: ${reason}.`);\n }\n\n if (this.d.platformOS === 'ios') {\n await this.initializeIos();\n } else if (this.d.platformOS === 'android') {\n await this.performAndroidAttestation();\n }\n }\n\n /**\n * iOS start: an attested key is reused through an assertion (Apple allows a\n * single attestation per key); without one a new key is attested.\n */\n private async initializeIos(): Promise<void> {\n this.keyId = await this.d.storage.getItem(STORAGE_KEY_ATTESTATION_KEY_ID);\n if (!this.keyId) {\n await this.attestNewIosKey();\n return;\n }\n await this.assertOrReattestIos();\n }\n\n /**\n * Assertion with the stored key. Network, server (5xx) and project errors say\n * nothing about the key: keep it and propagate. Anything else (key unknown to\n * the server, key invalid on this device after a restore) starts a new key.\n */\n private async assertOrReattestIos(): Promise<void> {\n try {\n await this.performIosAssertion();\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (PROJECT_ERROR_CODES.test(msg) || /network|fetch|offline|timed out|\\b5\\d\\d\\b/i.test(msg)) throw err;\n await this.d.storage.removeItem(STORAGE_KEY_ATTESTATION_KEY_ID);\n await this.attestNewIosKey();\n }\n }\n\n /**\n * Generate and attest a new key; it is stored only once the server accepted\n * it, so a failed attempt never leaves an unattested key behind.\n */\n private async attestNewIosKey(): Promise<void> {\n this.keyId = await this.d.native.generateKey();\n try {\n await this.performIosAttestation();\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n // A brand-new key refused by the device: retry once with another key.\n // Never on backend errors (regenerating blindly trips Apple's daily\n // key-creation rate limit). Heuristic from Qafka.\n const looksLikeStaleNativeKey =\n !PROJECT_ERROR_CODES.test(msg) &&\n !/HTTP|\\b401\\b|\\b403\\b|\\b404\\b|\\b5\\d\\d\\b|app not registered|app_not_registered|fetch|network/i.test(msg) &&\n (/invalid|not found|unknown|key|attestation/i.test(msg) ||\n /com\\.apple\\.devicecheck\\.error/i.test(msg) ||\n /android\\.security\\.keystore/i.test(msg));\n if (!looksLikeStaleNativeKey) throw err;\n await this.d.storage.removeItem(STORAGE_KEY_ATTESTATION_KEY_ID);\n this.keyId = await this.d.native.generateKey();\n await this.performIosAttestation();\n }\n await this.d.storage.setItem(STORAGE_KEY_ATTESTATION_KEY_ID, this.keyId);\n }\n\n private async performIosAttestation(): Promise<void> {\n const challenge = await this.requestChallenge('ios');\n const attestationData = await this.d.native.attestKey(this.keyId!, challenge);\n const res = await this.submitAttestation({ platform: 'ios', attestationData, keyId: this.keyId!, challenge });\n this.setSession(res);\n }\n\n private async performIosAssertion(): Promise<void> {\n const challenge = await this.requestChallenge('ios');\n const assertionData = await this.d.native.generateAssertion(this.keyId!, challenge);\n const res = await this.submitAttestation({\n platform: 'ios',\n attestationData: assertionData,\n keyId: this.keyId!,\n challenge,\n isAssertion: true,\n });\n this.setSession(res);\n }\n\n private async performAndroidAttestation(): Promise<void> {\n const challenge = await this.requestChallenge('android');\n await this.d.native.generateKeyPair(ANDROID_ATTEST_ALIAS, challenge);\n const certChain = await this.d.native.getAttestationCertChain(ANDROID_ATTEST_ALIAS);\n const res = await this.submitAttestation({ platform: 'android', certChain, challenge });\n this.setSession(res);\n }\n\n async getSessionToken(): Promise<string | null> {\n if (this.inflight) await this.inflight.catch(() => undefined);\n if (this.sessionToken?.token === DEV_BYPASS) return null;\n if (this.sessionToken && this.d.now() < this.sessionToken.expiresAt - EXPIRY_MARGIN_MS) {\n return this.sessionToken.token;\n }\n try {\n await this.exclusive(() => this.refreshSession());\n return this.sessionToken?.token ?? null;\n } catch {\n return null;\n }\n }\n\n /** Called by the transport when the backend signals a refresh (429 / budget). */\n async refresh(): Promise<string | null> {\n if (this.isDevBypass()) return null;\n try {\n await this.exclusive(() => this.refreshSession());\n return this.sessionToken?.token ?? null;\n } catch {\n return null;\n }\n }\n\n /**\n * Replace the session with a new one started after this call and return its\n * token. Unlike {@link refresh} it rejects on failure, so callers never keep a\n * stale token by accident. `null` only in dev-bypass (there is no session).\n */\n async forceRefresh(): Promise<string | null> {\n if (this.inflight) await this.inflight.catch(() => undefined);\n if (this.isDevBypass()) return null;\n await this.exclusive(() => this.refreshSession());\n return this.sessionToken!.token;\n }\n\n private async refreshSession(): Promise<void> {\n if (this.d.platformOS === 'android') {\n await this.performAndroidAttestation();\n return;\n }\n if (!this.keyId) {\n await this.initializeIos();\n return;\n }\n await this.assertOrReattestIos();\n }\n\n isDevBypass(): boolean {\n return this.sessionToken?.token === DEV_BYPASS;\n }\n\n async reset(): Promise<void> {\n this.sessionToken = null;\n this.keyId = null;\n await this.d.storage.removeItem(STORAGE_KEY_ATTESTATION_KEY_ID);\n }\n\n // --- transport ----------------------------------------------------------\n\n private setSession(res: { sessionToken: string; expiresIn: number }): void {\n this.sessionToken = { token: res.sessionToken, expiresAt: this.d.now() + res.expiresIn * 1000 };\n }\n\n private getHeaders(): Record<string, string> {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.config.projectId) headers['X-Project-Id'] = this.config.projectId;\n if (this.config.publishableKey) headers['X-Project-Key'] = this.config.publishableKey;\n if (this.config.projectSlug) headers['X-Project-Slug'] = this.config.projectSlug;\n if (this.config.apiKey) headers['x-api-key'] = this.config.apiKey;\n return headers;\n }\n\n private async requestChallenge(platform: string): Promise<string> {\n const url = `${this.base()}/challenge`;\n const response = await this.d.fetch(url, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify({ platform }),\n });\n if (!response.ok) throw new Error(`Challenge request failed: HTTP ${response.status}`);\n const data = (await response.json()) as { challenge: string };\n return data.challenge;\n }\n\n private async submitAttestation(body: {\n platform: string;\n attestationData?: string;\n certChain?: string[];\n keyId?: string;\n challenge: string;\n isAssertion?: boolean;\n }): Promise<{ sessionToken: string; expiresIn: number }> {\n const url = this.base();\n const response = await this.d.fetch(url, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify(body),\n });\n if (!response.ok) {\n // RFC 7807 body from the API: `{ type, title, status, detail, code? }`.\n // `error` is the pre-problem-details field, still read as a fallback.\n const errorData = (await response.json().catch(() => ({}))) as {\n code?: string;\n error?: string;\n message?: string;\n detail?: string;\n };\n // Include the machine-readable code so the stale-key heuristic can match it.\n const errorCode = errorData.code ?? errorData.error;\n const code = errorCode ? ` ${errorCode}` : '';\n throw new Error(\n `Attestation failed: ${response.status}${code} — ${errorData.message || errorData.detail || 'Unknown error'}`,\n );\n }\n return (await response.json()) as { sessionToken: string; expiresIn: number };\n }\n\n private base(): string {\n return `${this.config.apiUrl.replace(/\\/$/, '')}${END_USER_BASE_PATH}/attest`;\n }\n}\n","import type { ConnectSse, SseConnection, SseHandlers } from '@qafka/cms-core';\n\n/**\n * Processed-stream budget of one XHR connection. XHR's progressive\n * `responseText` only grows, so a long-lived stream would hold every byte it\n * ever received; past this many characters (≈1 MB) the transport closes the\n * connection at an event boundary and reports `onClose({ reason: 'recycle' })`,\n * and the supervising client reconnects at once (not counted as a rapid close).\n */\nexport const SSE_RECYCLE_AFTER_CHARS = 1_000_000;\n\n/**\n * Cap on a not-yet-terminated event block (64 KB). Real events are tiny; a\n * stream that never sends its blank line (wrong endpoint, hostile proxy) would\n * otherwise grow the buffer without bound, so it is closed with `onError`.\n */\nexport const SSE_MAX_PENDING_CHARS = 65_536;\n\nexport interface XhrSseConnectorOptions {\n /** Override of {@link SSE_RECYCLE_AFTER_CHARS} (tests). */\n recycleAfterChars?: number;\n /** XHR constructor (tests). Default: the global `XMLHttpRequest`. */\n XMLHttpRequest?: typeof XMLHttpRequest;\n}\n\n/** Normalize CRLF / CR to LF, keeping a trailing lone `\\r` (its `\\n` may be in the next chunk). */\nfunction normalizeNewlines(text: string): { text: string; held: string } {\n const held = text.endsWith('\\r') ? '\\r' : '';\n const body = held ? text.slice(0, -1) : text;\n return { text: body.replace(/\\r\\n?/g, '\\n'), held };\n}\n\n/** The joined `data:` field of one SSE event block, or `null` when it carries none. */\nfunction blockData(block: string): string | null {\n const lines: string[] = [];\n for (const line of block.split('\\n')) {\n if (line === 'data') {\n lines.push('');\n } else if (line.startsWith('data:')) {\n const value = line.slice('data:'.length);\n lines.push(value.startsWith(' ') ? value.slice(1) : value);\n }\n // `event:` / `id:` / `retry:` / `:comment` lines are not used by the SDK.\n }\n return lines.length ? lines.join('\\n') : null;\n}\n\n/**\n * SSE transport for React Native. RN ships no native EventSource, so we read a\n * `text/event-stream` response incrementally off XMLHttpRequest's progressive\n * `responseText` — the same approach Qafka's BackendService uses for chat\n * streaming. Only complete blocks (terminated by a blank line) are dispatched;\n * an incomplete tail waits for the next chunk. Each block's `data:` lines are\n * joined and parsed as JSON; non-JSON payloads and comments are ignored. A\n * non-`text/event-stream` 2xx response or an unterminated block over\n * {@link SSE_MAX_PENDING_CHARS} → `onError`.\n *\n * After the connection ended (error, clean end, recycle, or `close()`) no\n * further handler fires — an aborted XHR's own events are swallowed.\n */\nexport function createXhrSseConnector(options: XhrSseConnectorOptions = {}): ConnectSse {\n const recycleAfter = options.recycleAfterChars ?? SSE_RECYCLE_AFTER_CHARS;\n return (url, headers, handlers: SseHandlers): SseConnection => {\n const Xhr = options.XMLHttpRequest ?? XMLHttpRequest;\n const xhr = new Xhr();\n /** Index into `responseText` up to which input has been consumed. */\n let consumed = 0;\n /** Normalized text not yet forming a complete block. */\n let pending = '';\n /** A trailing `\\r` held back from normalization. */\n let heldCr = '';\n let done = false;\n let typeChecked = false;\n\n const end = () => {\n done = true;\n try {\n xhr.abort();\n } catch {\n // already closed\n }\n };\n\n const fail = (err: Error) => {\n if (done) return;\n end();\n handlers.onError(err);\n };\n\n const dispatch = (block: string) => {\n const data = blockData(block);\n if (!data) return;\n let event: unknown;\n try {\n event = JSON.parse(data);\n } catch {\n return; // non-JSON keep-alive / comment payload\n }\n try {\n handlers.onMessage(event);\n } catch {\n // a consumer bug must not kill the stream reader\n }\n };\n\n /**\n * Once the headers are in: a 2xx that is not an event stream (an HTML\n * captive portal, a misrouted proxy) is an error. A runtime that cannot\n * report the header (`null`) is let through.\n */\n const checkType = (): boolean => {\n if (typeChecked || xhr.readyState < 2 || typeof xhr.getResponseHeader !== 'function') return true;\n typeChecked = true;\n const type = xhr.getResponseHeader('content-type');\n if (type === null || type.toLowerCase().includes('text/event-stream')) return true;\n fail(new Error(`SSE unexpected content-type: ${type}`));\n return false;\n };\n\n const parse = () => {\n if (done || !checkType()) return;\n const text = xhr.responseText;\n if (text.length <= consumed) return;\n const { text: fresh, held } = normalizeNewlines(heldCr + text.slice(consumed));\n consumed = text.length;\n heldCr = held;\n pending += fresh;\n const boundary = pending.lastIndexOf('\\n\\n');\n if (boundary >= 0) {\n const complete = pending.slice(0, boundary);\n pending = pending.slice(boundary + 2);\n for (const block of complete.split('\\n\\n')) {\n if (done) return; // a handler closed the connection\n dispatch(block);\n }\n }\n if (!done && pending.length > SSE_MAX_PENDING_CHARS) {\n fail(new Error('SSE event exceeds 64 KB'));\n return;\n }\n if (boundary < 0) return;\n // Bound the ever-growing responseText: recycle at an event boundary.\n if (!done && consumed - pending.length - heldCr.length >= recycleAfter) {\n end();\n if (handlers.onClose) handlers.onClose({ reason: 'recycle' });\n else handlers.onError(new Error('SSE recycled'));\n }\n };\n\n xhr.open('GET', url);\n xhr.setRequestHeader('Accept', 'text/event-stream');\n for (const [k, v] of Object.entries(headers)) xhr.setRequestHeader(k, v);\n\n xhr.onreadystatechange = () => {\n if (done) return;\n if (xhr.readyState >= 2 && xhr.status >= 400) {\n fail(new Error(`SSE HTTP ${xhr.status}`));\n return;\n }\n if (xhr.readyState === 4 && xhr.status === 0) {\n fail(new Error(`SSE closed (status ${xhr.status})`));\n return;\n }\n if (!checkType()) return;\n if (xhr.readyState >= 3) parse(); // some runtimes deliver text here before/without onprogress\n };\n xhr.onprogress = () => parse();\n xhr.onerror = () => fail(new Error('SSE network error'));\n // Clean end-of-stream (HTTP 2xx, e.g. server closed on revalidation) is a\n // disconnect, not an open: let the client reconnect with fresh headers.\n xhr.onload = () => {\n if (done) return;\n parse(); // flush any final complete blocks\n if (done) return;\n done = true;\n if (handlers.onClose) handlers.onClose();\n else handlers.onOpen?.();\n };\n xhr.send();\n\n return {\n close() {\n if (done) return;\n end();\n },\n };\n };\n}\n\n/** Default SSE transport for React Native (`QafkaCmsClientDeps.connectSse` overrides it). */\nexport const connectSseViaXhr: ConnectSse = createXhrSseConnector();\n","/**\n * Loads the dev-only runtime config bundled with the package\n * (`qafkacms.config.js`). Adapted from Qafka's `runtime-config-loader`.\n *\n * This is the FALLBACK source. The CLI no longer overwrites this package file\n * (node_modules gets wiped on install); it writes the real dev key to the\n * project root `.qafkacms/qafkacms-runtime.js`, which the consumer passes via\n * `config.devConfig` and `resolveRuntimeConfigSource` prefers. The shipped\n * placeholder only guarantees the `require` here never throws. In release builds\n * `__DEV__` dead-code-elimination strips the call site, so no dev key ships.\n */\nexport interface RuntimeProjectEntry {\n /** The project's TEST API key, used by the SDK in dev builds. */\n developmentKey?: string;\n}\n\nexport interface RuntimeConfig {\n defaultProjectId?: string;\n apiUrl?: string;\n projects: Record<string, RuntimeProjectEntry>;\n}\n\n/** Narrow an untyped `require('../../qafkacms.config')` result into RuntimeConfig. */\nexport function normalizeRuntimeConfig(raw: unknown): RuntimeConfig | null {\n if (!raw || typeof raw !== 'object') return null;\n const obj = raw as Record<string, unknown>;\n const projectsRaw = obj.projects;\n const projects: Record<string, RuntimeProjectEntry> = {};\n if (projectsRaw && typeof projectsRaw === 'object') {\n for (const [id, value] of Object.entries(projectsRaw)) {\n if (value && typeof value === 'object') {\n const entry = value as Record<string, unknown>;\n const developmentKey = typeof entry.developmentKey === 'string' ? entry.developmentKey : undefined;\n projects[id] = developmentKey !== undefined ? { developmentKey } : {};\n }\n }\n }\n const out: RuntimeConfig = { projects };\n if (typeof obj.defaultProjectId === 'string') out.defaultProjectId = obj.defaultProjectId;\n if (typeof obj.apiUrl === 'string') out.apiUrl = obj.apiUrl;\n return out;\n}\n\n/**\n * Load the bundled config. Returns null if the require throws (e.g. the\n * placeholder was removed). Resolves to\n * `node_modules/@qafka/react-native-cms/qafkacms.config.js`.\n */\nexport function loadRuntimeConfig(): RuntimeConfig | null {\n try {\n const raw = require('../../qafkacms.config');\n return normalizeRuntimeConfig(raw);\n } catch {\n return null;\n }\n}\n","import {\n normalizeRuntimeConfig,\n type RuntimeConfig,\n} from './runtime-config-loader';\n\n/**\n * Pick the runtime config the SDK should use in dev builds. Adapted from\n * Qafka's `resolve-runtime-config-source`.\n *\n * Precedence: a valid `devConfig` — the consumer's\n * `require('./.qafkacms/qafkacms-runtime')`, passed into `createClient` and\n * shape-validated — wins; otherwise the value bundled in the SDK package\n * (`loadRuntimeConfig()`, a placeholder). Returns null when neither yields a\n * usable config.\n *\n * Why the consumer passes it rather than the SDK requiring it: the dev key\n * lives at the project root (`.qafkacms/qafkacms-runtime.js`, durable +\n * gitignored), and a package cannot reliably `require()` a project-root file\n * through Metro. The consumer's `__DEV__`-gated require resolves the relative\n * path and is dead-code-eliminated from release bundles.\n */\nexport function resolveRuntimeConfigSource(\n devConfig: unknown,\n loaded: RuntimeConfig | null,\n): RuntimeConfig | null {\n const provided = devConfig != null ? normalizeRuntimeConfig(devConfig) : null;\n return provided ?? loaded;\n}\n","import type { RuntimeConfig } from './runtime-config-loader';\n\n/**\n * Resolve the development API key + backend URL the SDK should use. Adapted\n * verbatim from Qafka's `resolve-project-config`.\n *\n * Only called in `__DEV__` builds — Metro strips the call site in production,\n * where the backend identifies the project from the attestation certificate\n * instead of an API key.\n */\nexport interface ProjectConfigProps {\n apiUrl?: string;\n projectId?: string;\n}\n\nexport interface ResolvedProjectConfig {\n apiKey: string | null;\n apiUrl: string | undefined;\n}\n\nexport function resolveProjectConfig(\n props: ProjectConfigProps,\n runtimeConfig: RuntimeConfig | null,\n): ResolvedProjectConfig {\n const apiUrl = props.apiUrl ?? runtimeConfig?.apiUrl ?? undefined;\n\n if (props.projectId) {\n const entry = runtimeConfig?.projects[props.projectId];\n if (!entry) {\n throw new RangeError(\n `QafkaCMS: projectId \"${props.projectId}\" is not in the dev config. ` +\n 'Run `qafka cms project` and pass devConfig (require of .qafkacms/qafkacms-runtime).',\n );\n }\n return { apiKey: entry.developmentKey ?? null, apiUrl };\n }\n\n const defaultId = runtimeConfig?.defaultProjectId;\n if (defaultId) {\n const entry = runtimeConfig?.projects[defaultId];\n return { apiKey: entry?.developmentKey ?? null, apiUrl };\n }\n\n return { apiKey: null, apiUrl };\n}\n","import { NativeModules } from 'react-native';\n\n/**\n * Native push contract (E57) — collects the platform push token with **zero\n * host-app dependencies**:\n *\n * - iOS → raw APNs token via `UNUserNotificationCenter` +\n * `registerForRemoteNotifications`. No Firebase iOS SDK.\n * - Android → FCM token via a **secondary** `FirebaseApp` the SDK initializes\n * programmatically from the tenant's public client config (apiKey / appId /\n * senderId / projectId, delivered by config-sync). The host app's own\n * Firebase, if any, is untouched — we never claim the default app or its\n * `FirebaseMessagingService`, so we only *read* a token, never intercept\n * messages (out of scope for E57).\n *\n * Native module registered as `QafkaCmsPush`. Tenant-agnostic on iOS; on Android\n * the sender config is passed per call so the token is scoped to the right\n * project. Injected as `deps.native` so the manager is unit-testable without RN.\n */\n\n/** Tenant Firebase Android *public* client config (never the secret service account). */\nexport interface AndroidPushConfig {\n apiKey: string;\n /** Firebase Android applicationId (mobilesdk_app_id), e.g. `1:123:android:abc`. */\n appId: string;\n /** FCM sender id (messagingSenderId / project number). */\n senderId: string;\n /** Firebase projectId. */\n projectId: string;\n}\n\nexport type PushPermissionStatus = 'granted' | 'denied' | 'undetermined';\n\nexport interface DeviceInfo {\n /** OS marketing version string, e.g. `iOS 17.4` / `Android 14`. */\n osVersion: string;\n /** Hardware model identifier, e.g. `iPhone15,3` / `Pixel 8`. */\n model: string;\n /** Manufacturer / brand, e.g. `Apple` / `Samsung`. */\n brand: string;\n}\n\nexport interface NativePushApi {\n /** Whether the native module is registered at all (false → rebuild needed). */\n isAvailable(): boolean;\n /** Current OS notification-permission state without prompting. */\n getPermissionStatus(): Promise<PushPermissionStatus>;\n /** Prompt the user for notification permission; resolves with the new state. */\n requestPermission(): Promise<PushPermissionStatus>;\n /**\n * Resolve the current push token. On Android the secondary FirebaseApp is\n * (re)initialized from `androidConfig`; on iOS the argument is ignored. Returns\n * null when permission is missing or the token cannot be obtained.\n */\n getToken(androidConfig?: AndroidPushConfig): Promise<string | null>;\n /** Static device metadata for the device record. */\n getDeviceInfo(): Promise<DeviceInfo>;\n}\n\ninterface NativePushModule {\n getPermissionStatus(): Promise<PushPermissionStatus>;\n requestPermission(): Promise<PushPermissionStatus>;\n getToken(androidConfig?: AndroidPushConfig | null): Promise<string | null>;\n getDeviceInfo(): Promise<DeviceInfo>;\n}\n\nconst mod: NativePushModule | null =\n (NativeModules as { QafkaCmsPush?: NativePushModule }).QafkaCmsPush ?? null;\n\nconst UNKNOWN_INFO: DeviceInfo = { osVersion: '', model: '', brand: '' };\n\nexport function isPushAvailable(): boolean {\n return mod !== null;\n}\n\n/**\n * Real native-backed push API, used as the default `deps.native`. Missing-module\n * calls degrade gracefully (status `undetermined`, token null, empty info) so a\n * host that hasn't rebuilt after install never crashes — it just can't collect a\n * token until the native module is linked.\n */\nexport const nativePush: NativePushApi = {\n isAvailable: () => mod !== null,\n async getPermissionStatus() {\n if (!mod) return 'undetermined';\n try {\n return await mod.getPermissionStatus();\n } catch {\n return 'undetermined';\n }\n },\n async requestPermission() {\n if (!mod) return 'denied';\n return mod.requestPermission();\n },\n async getToken(androidConfig) {\n if (!mod) return null;\n return mod.getToken(androidConfig ?? null);\n },\n async getDeviceInfo() {\n if (!mod) return UNKNOWN_INFO;\n try {\n return await mod.getDeviceInfo();\n } catch {\n return UNKNOWN_INFO;\n }\n },\n};\n","import { Platform } from 'react-native';\nimport { STORAGE_KEY_DEVICE_ID } from '@qafka/cms-core';\nimport { storage as defaultStorage } from '../services/storage';\nimport {\n nativePush,\n type AndroidPushConfig,\n type NativePushApi,\n type PushPermissionStatus,\n} from '../native/QafkaCmsPush';\n\n/**\n * Device registration (E57). Owns the device's identity on this install and\n * keeps the backend `Device` row in sync. Two-phase by design:\n *\n * 1. {@link init} (silent, no permission prompt) — ensure a stable `deviceId`,\n * capture metadata, and register the device with `token` omitted. Runs at\n * boot; the host shows no OS dialog. If permission was already granted in a\n * prior session, the token is (re)fetched here too — covering rotation.\n * 2. {@link requestPermission} (explicit user action) — prompt for notification\n * permission, then fetch the push token and patch the row.\n *\n * Ownership follows the request's identity: the transport attaches the bearer\n * when a session exists, so a logged-in re-register binds the row to that\n * end-user and a logged-out one clears it — hence we re-register on every auth\n * change. The class is fully injected (native, storage, transport, auth) so it\n * unit-tests without the React Native runtime.\n */\nexport interface DeviceRegistrationState {\n permission: PushPermissionStatus;\n /** Stable client-generated id for this install (null until {@link init}). */\n deviceId: string | null;\n /** Current push token (null until permission is granted). */\n token: string | null;\n}\n\nexport interface DeviceRegisterBody {\n deviceId: string;\n platform: 'ios' | 'android';\n provider: 'apns' | 'fcm';\n /** Omitted in phase 1; the backend leaves an existing token untouched. */\n token?: string;\n osVersion?: string;\n model?: string;\n brand?: string;\n}\n\nexport interface DeviceRegistrationConfig {\n debug?: boolean;\n}\n\nexport interface DeviceRegistrationDeps {\n native: NativePushApi;\n storage: Pick<typeof defaultStorage, 'getItem' | 'setItem' | 'removeItem'>;\n /**\n * POST the device to `/v1/end-user/devices`. The transport attaches the three\n * trust axes (bearer if signed in, attestation session token, project slug).\n */\n registerDevice: (body: DeviceRegisterBody) => Promise<unknown>;\n /**\n * Subscribe to auth changes (login / logout / refresh) to re-register so the\n * backend re-binds or clears `endUserId`. Returns an unsubscribe.\n */\n subscribeAuth?: (listener: () => void) => () => void;\n /** Android FCM public client config from config-sync; iOS ignores it. */\n getAndroidPushConfig?: () => AndroidPushConfig | null;\n platformOS: string;\n /** Generate a stable device id (UUID v4). Injectable for deterministic tests. */\n generateDeviceId: () => string;\n}\n\n/** RFC4122 v4 — a device identifier, not a secret, so a non-crypto PRNG is fine. */\nfunction randomUuid(): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = Math.floor(Math.random() * 16);\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\ntype RequiredDeps = Pick<DeviceRegistrationDeps, 'registerDevice'> &\n Partial<DeviceRegistrationDeps>;\n\nexport class DeviceRegistrationManager {\n private readonly config: DeviceRegistrationConfig;\n private readonly d: DeviceRegistrationDeps;\n private state: DeviceRegistrationState = {\n permission: 'undetermined',\n deviceId: null,\n token: null,\n };\n private readonly listeners = new Set<() => void>();\n private unsubscribeAuth: (() => void) | null = null;\n private initialized = false;\n\n constructor(config: DeviceRegistrationConfig, deps: RequiredDeps) {\n this.config = config;\n this.d = {\n native: deps.native ?? nativePush,\n storage: deps.storage ?? defaultStorage,\n registerDevice: deps.registerDevice,\n subscribeAuth: deps.subscribeAuth,\n getAndroidPushConfig: deps.getAndroidPushConfig,\n platformOS: deps.platformOS ?? Platform.OS,\n generateDeviceId: deps.generateDeviceId ?? randomUuid,\n };\n }\n\n /** Phase 1 — silent metadata registration; idempotent across calls. */\n async init(): Promise<void> {\n if (this.initialized) return;\n this.initialized = true;\n\n const deviceId = await this.ensureDeviceId();\n const permission = await this.d.native.getPermissionStatus();\n this.setState({ deviceId, permission });\n\n const token = permission === 'granted' ? await this.fetchToken() : null;\n await this.register(token);\n\n if (this.d.subscribeAuth && !this.unsubscribeAuth) {\n this.unsubscribeAuth = this.d.subscribeAuth(() => {\n // Fire-and-forget: an auth change re-binds endUserId on the backend.\n void this.register(this.state.token).catch((err) => this.warn(err));\n });\n }\n }\n\n /** Phase 2 — prompt for permission, then collect + register the token. */\n async requestPermission(): Promise<PushPermissionStatus> {\n const permission = await this.d.native.requestPermission();\n this.setState({ permission });\n if (permission === 'granted') {\n const token = await this.fetchToken();\n await this.register(token);\n }\n return permission;\n }\n\n getDeviceState(): DeviceRegistrationState {\n return this.state;\n }\n\n /** Observe device-state changes (for the `usePush` hook). Returns unsubscribe. */\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /** Detach the auth subscription. Call when tearing down the client. */\n dispose(): void {\n this.unsubscribeAuth?.();\n this.unsubscribeAuth = null;\n this.listeners.clear();\n }\n\n // --- internals ----------------------------------------------------------\n\n private platform(): 'ios' | 'android' {\n return this.d.platformOS === 'ios' ? 'ios' : 'android';\n }\n\n private provider(): 'apns' | 'fcm' {\n return this.d.platformOS === 'ios' ? 'apns' : 'fcm';\n }\n\n private async ensureDeviceId(): Promise<string> {\n const existing = await this.d.storage.getItem(STORAGE_KEY_DEVICE_ID);\n if (existing) return existing;\n const id = this.d.generateDeviceId();\n await this.d.storage.setItem(STORAGE_KEY_DEVICE_ID, id);\n return id;\n }\n\n private async fetchToken(): Promise<string | null> {\n const androidConfig =\n this.d.platformOS === 'android'\n ? (this.d.getAndroidPushConfig?.() ?? undefined)\n : undefined;\n const token = await this.d.native.getToken(androidConfig);\n if (token) this.setState({ token });\n return token;\n }\n\n private async register(token: string | null): Promise<void> {\n const deviceId = this.state.deviceId ?? (await this.ensureDeviceId());\n const info = await this.d.native.getDeviceInfo();\n const body: DeviceRegisterBody = {\n deviceId,\n platform: this.platform(),\n provider: this.provider(),\n };\n if (token != null) body.token = token;\n if (info.osVersion) body.osVersion = info.osVersion;\n if (info.model) body.model = info.model;\n if (info.brand) body.brand = info.brand;\n\n await this.d.registerDevice(body);\n this.setState({ deviceId, ...(token != null ? { token } : {}) });\n }\n\n private setState(patch: Partial<DeviceRegistrationState>): void {\n this.state = { ...this.state, ...patch };\n for (const listener of this.listeners) listener();\n }\n\n private warn(err: unknown): void {\n if (this.config.debug && typeof console !== 'undefined') {\n // eslint-disable-next-line no-console\n console.warn('[QafkaCMS] device re-registration failed', err);\n }\n }\n}\n","import { AttestationManager } from \"./services/AttestationManager\";\nimport type {\n ConfigSyncClient,\n AppStateProvider,\n ContentBundleApi,\n ContentChangesApi,\n ContentVersionGate,\n} from \"@qafka/cms-core\";\nimport { connectSseViaXhr } from \"./config-sync/sse\";\nimport type { LanguageManager } from \"@qafka/cms-core\";\nimport { loadRuntimeConfig } from \"./config/runtime-config-loader\";\nimport { resolveRuntimeConfigSource } from \"./config/resolve-runtime-config-source\";\nimport { resolveProjectConfig } from \"./config/resolve-project-config\";\nimport { storage as defaultStorage } from \"./services/storage\";\nimport { getDeviceInfo, nativeAttestation } from \"./native/QafkaCmsAttestation\";\nimport { nativePush, type AndroidPushConfig } from \"./native/QafkaCmsPush\";\nimport { DeviceRegistrationManager } from \"./push/DeviceRegistrationManager\";\nimport { Platform, AppState } from \"react-native\";\nimport type { QafkaCmsConfig, QafkaCmsClientDeps } from \"./types/sdk\";\nimport type { QafkaCmsStorage } from \"@qafka/cms-core\";\nimport type { AuthClient } from \"@qafka/cms-core\";\nimport type { ContentClient } from \"@qafka/cms-core\";\nimport { AttestationProof } from \"@qafka/cms-core\";\nimport type { CacheStorage } from \"@qafka/cms-core\";\nimport {\n createCoreClient,\n createContentBundleClient,\n createSecureMigrationStorage,\n createContentChangeHub,\n STORAGE_KEY_BUNDLE_INDEX,\n STORAGE_KEY_BUNDLE_PREFIX,\n validateCoreConfig,\n type CoreClient,\n} from \"@qafka/cms-core\";\n\n/** Development diagnostics: `console.warn` under Metro's `__DEV__` only. */\nfunction devWarn(message: string, ...details: unknown[]): void {\n if (typeof __DEV__ !== \"undefined\" && __DEV__) console.warn(message, ...details);\n}\n\n/** Wrap React Native's AppState as the config-sync foreground/background source. */\nfunction rnAppStateProvider(): AppStateProvider {\n return {\n isActive: () => AppState.currentState === \"active\",\n subscribe: (listener) => {\n const sub = AppState.addEventListener(\"change\", (state) =>\n listener(state === \"active\"),\n );\n return () => sub.remove();\n },\n };\n}\n\n/**\n * Top-level SDK client. Wires the five Foundation layers together and exposes\n * `auth`, `content`, `attestation` and a `createConfigSync` factory. Both trust\n * axes (end-user JWT + device attestation) are injected into the transport, so\n * every request carries whatever credentials are currently available.\n *\n * Construct via {@link createClient}; call {@link initialize} once at app boot.\n */\nexport class QafkaCmsClient {\n readonly attestation: AttestationManager;\n readonly auth: AuthClient;\n readonly content: ContentClient;\n /**\n * Device registration (E57): native push-token collection + the backend\n * `Device` row. Phase 1 (metadata) runs automatically on {@link initialize};\n * the host calls `deviceRegistration.requestPermission()` (or the `usePush`\n * hook) to prompt for notifications and collect the token. Dependency-free on\n * the host: iOS uses raw APNs, Android a SDK-bundled secondary FirebaseApp.\n */\n readonly deviceRegistration: DeviceRegistrationManager;\n /**\n * Active-language runtime (E55): holds the selected locale, the supported\n * locale set (`locales` domain) and UI strings (`i18n` domain), and resolves\n * `t(key)`. Fed by SDK-managed config-sync on {@link initialize}. The React\n * `useLocale`/`useTranslation` hooks subscribe to it.\n */\n readonly language: LanguageManager;\n /**\n * Live content change signals (QFK2-E76): the hub behind `live` on\n * `useContent` / `useContentItem` — one multiplexed SSE stream (XHR) or\n * version polling per client. Nothing runs until something is watched.\n * `status()` → `'sse' | 'polling' | 'idle'` (debug).\n */\n readonly contentChanges: ContentChangesApi;\n /**\n * Resolved `contentVersionGate` config (QFK2-E59): `{ maxAgeMs }`, or `null`\n * when off (the default). The provider gates expand-less content reads on it.\n */\n readonly contentVersionGate: ContentVersionGate | null;\n /**\n * App version sent as `X-App-Version` (QFK2-E59): `config.appVersion`, else\n * the native app version; `null` when none / not a valid app version.\n */\n readonly appVersion: string | null;\n /**\n * Content bundle (QFK2-E59 T466): the offline snapshot of the collections\n * the project put in its bundle — `sync()`, `rows(collection)`,\n * `get(collection, id)`, `subscribe`. Present only with `contentBundle`.\n * Persisted only in `contentBundle.storage`, else {@link cacheStorage} when\n * `createClient({ cacheStorage })` is set (a plain AsyncStorage / MMKV store),\n * never in the secure {@link storage}; without either it lives in memory for\n * the app session. The Provider syncs it at boot, on foreground and on\n * locale change.\n */\n readonly bundle?: ContentBundleApi;\n /** Platform-neutral core (transport, auth, content, language, config-sync) — QFK2-E73. */\n private readonly core: CoreClient;\n private readonly proof: AttestationProof;\n /**\n * Per-project public push client config (E57). Android only — the FCM sender\n * id / app id the SDK needs to mint a token from a secondary FirebaseApp. iOS\n * (raw APNs) needs nothing, so this is only started + read on Android.\n */\n private readonly pushConfigSync: ConfigSyncClient<{\n android?: AndroidPushConfig;\n }>;\n /**\n * The SDK's own native secure storage (iOS Keychain / Android\n * EncryptedSharedPreferences). Holds the session: refresh token, unlock\n * tokens, attestation key id, device id. Without `createClient({ cacheStorage })`\n * it also holds the cached data ({@link cacheStorage} is then this store):\n * keep persisted payloads small (reference data like categories) then.\n */\n readonly storage: QafkaCmsStorage;\n /**\n * Where cached data lives (QFK2-T471): `persist: true` queries (the Provider\n * reads this), config-sync snapshots, the saved locale and, without its own\n * `contentBundle.storage`, the content bundle. With\n * `createClient({ cacheStorage })` it is that plain store, reading through to\n * the secure store once per key so copies an earlier SDK kept there move over;\n * otherwise it is {@link storage}.\n */\n readonly cacheStorage: CacheStorage;\n private warnedNoProof = false;\n\n /**\n * Bundle files never belong in the secure store (up to 20 MB each). Pre-release\n * builds wrote them there: remove such leftovers (one read when none exist).\n */\n private dropSecureBundleCopies(): void {\n const secure = this.storage;\n void (async () => {\n const raw = await secure.getItem(STORAGE_KEY_BUNDLE_INDEX);\n if (raw === null) return;\n let locales: string[] = [];\n try {\n locales = Object.keys((JSON.parse(raw) as { files?: object } | null)?.files ?? {});\n } catch {\n /* unreadable index: remove it alone */\n }\n await secure.multiRemove([\n ...locales.map((l) => `${STORAGE_KEY_BUNDLE_PREFIX}${l}`),\n STORAGE_KEY_BUNDLE_INDEX,\n ]);\n })().catch(() => undefined);\n }\n\n constructor(config: QafkaCmsConfig, deps: QafkaCmsClientDeps = {}) {\n const platformOS = deps.platformOS ?? Platform.OS;\n const now = deps.now ?? Date.now;\n const doFetch =\n deps.fetch ?? ((url, init) => fetch(url, init as RequestInit));\n this.storage = deps.storage ?? defaultStorage;\n // QFK2-T471 — opt-in plain cache store (D1/D2); the secure store itself is used as is.\n const plainCache = config.cacheStorage && config.cacheStorage !== this.storage ? config.cacheStorage : undefined;\n this.cacheStorage = plainCache ? createSecureMigrationStorage(plainCache, this.storage) : this.storage;\n\n // Resolve apiUrl + dev key. The dev key path is `__DEV__`-only; Metro strips\n // it from release builds, where the backend identifies the project from the\n // attestation certificate instead. The durable dev config lives at the\n // project root (`.qafkacms/qafkacms-runtime.js`) and is passed in via\n // `config.devConfig`; the SDK-bundled placeholder is the fallback.\n let apiUrl = config.apiUrl;\n let apiKey = config.apiKey ?? null;\n if (typeof __DEV__ !== \"undefined\" && __DEV__) {\n const runtimeConfig = resolveRuntimeConfigSource(\n config.devConfig,\n loadRuntimeConfig(),\n );\n // `projectId` selects the dev TEST key only when the dev config knows it.\n // An explicit `apiKey` wins (no lookup); an unknown id must not crash dev\n // builds — real devices attest without a key, simulators need the key.\n // The defaultProjectId fallback applies only when no projectId is configured.\n const id = config.projectId;\n if (id && (config.apiKey || !runtimeConfig?.projects[id])) {\n if (!config.apiKey) {\n console.warn(\n `[QafkaCMS] projectId \"${id}\" is not in the dev config — simulator/emulator requests will be ` +\n \"rejected without the project's TEST key. Pass it as apiKey from an env var under __DEV__ \" +\n \"(apiKey: __DEV__ ? process.env.EXPO_PUBLIC_QAFKA_TEST_KEY : undefined), or pass devConfig.\",\n );\n }\n // Only the URL comes from the dev config — never another project's key.\n apiUrl = apiUrl ?? runtimeConfig?.apiUrl;\n } else {\n const resolved = resolveProjectConfig(\n { apiUrl: config.apiUrl, projectId: id },\n runtimeConfig,\n );\n apiUrl = apiUrl ?? resolved.apiUrl;\n apiKey = apiKey ?? resolved.apiKey;\n }\n }\n validateCoreConfig(config);\n const projectId =\n typeof config.projectId === \"string\" && config.projectId !== \"\"\n ? config.projectId\n : undefined;\n if (!apiUrl) {\n throw new Error(\n \"QafkaCMS: apiUrl is required. Pass it to createClient(), or run `qafka cms project` and wire \" +\n \"devConfig: __DEV__ ? require('./.qafkacms/qafkacms-runtime') : undefined.\",\n );\n }\n const devApiKey = apiKey;\n\n const attestation = new AttestationManager(\n {\n apiUrl,\n projectSlug: config.projectSlug,\n publishableKey: config.publishableKey,\n projectId,\n apiKey,\n },\n {\n native: deps.attestationNative ?? nativeAttestation,\n storage: this.storage,\n fetch: doFetch,\n platformOS,\n now,\n },\n );\n this.attestation = attestation;\n\n // Device proof: X-Project-Id (+ X-Project-Key without a Bearer) and the\n // attestation session token, or the dev key in dev-bypass. The dev-bypass\n // gate is the one gate for `x-api-key` (transport + getRequestHeaders).\n this.proof = new AttestationProof(\n {\n projectId,\n publishableKey: config.publishableKey,\n projectSlug: config.projectSlug,\n },\n {\n getSessionToken: () => attestation.getSessionToken(),\n refresh: () => attestation.refresh(),\n getDevApiKey: () => (attestation.isDevBypass() ? devApiKey : null),\n initialize: () => attestation.initialize(),\n },\n );\n\n this.core = createCoreClient(\n {\n apiUrl,\n projectId,\n publishableKey: config.publishableKey,\n projectSlug: config.projectSlug,\n externalTokenProvider: config.externalTokenProvider,\n externalProvider: config.externalProvider,\n anonymousAuth: config.anonymousAuth,\n tier: \"full\",\n // Build-time embedded snapshots (E58): paint real config on a cold\n // start and seed the version so a matching server is not re-fetched.\n bootstrap: config.bootstrap,\n // One poll cadence knob drives the SDK-managed domains; ConfigSyncClient\n // clamps it to the safe floor.\n configPollIntervalMs: config.configPollIntervalMs,\n contentLiveDefault: config.contentLiveDefault,\n contentVersionGate: config.contentVersionGate,\n // QFK2-E59 V9 — the native version unless the app overrides it (`null` = none).\n appVersion: config.appVersion !== undefined ? config.appVersion : getDeviceInfo().appVersion,\n contentBundle: config.contentBundle,\n },\n {\n os: platformOS,\n fetch: doFetch,\n sessionStorage: this.storage,\n // Absent → the core keeps its cache in `sessionStorage` (unchanged behaviour).\n cacheStorage: plainCache ? this.cacheStorage : undefined,\n appState: deps.appState ?? rnAppStateProvider(),\n connectSse: deps.connectSse ?? connectSseViaXhr,\n proof: this.proof,\n now,\n warn: devWarn,\n },\n {\n // Only Android needs the FCM client config; iOS uses raw APNs.\n configStarts: () =>\n platformOS === \"android\" ? [this.pushConfigSync.start()] : [],\n // QFK2-E76 — `live` content hooks (SSE over XHR, polling fallback).\n contentHub: createContentChangeHub,\n // QFK2-E59 T466 — injecting the module enables `client.bundle`.\n contentBundle: config.contentBundle ? createContentBundleClient : undefined,\n },\n );\n this.auth = this.core.auth;\n this.content = this.core.content;\n this.language = this.core.language!;\n this.contentChanges = this.core.contentChanges;\n this.contentVersionGate = this.core.contentVersionGate;\n this.appVersion = this.core.appVersion;\n if (this.core.bundle) {\n this.bundle = this.core.bundle;\n // (Unless the bundle is deliberately stored in the secure store.)\n const own = typeof config.contentBundle === \"object\" ? config.contentBundle.storage : undefined;\n const bundleStore = own !== undefined ? own : plainCache;\n if (bundleStore !== this.storage) this.dropSecureBundleCopies();\n }\n\n // E57 — device registration. The transport attaches the trust axes, so the\n // manager just POSTs the device; re-registering on every auth change keeps\n // the row's `endUserId` in sync with the signed-in identity. The Android FCM\n // sender config arrives via config-sync (wired in initialize()).\n const http = this.core.http;\n this.deviceRegistration = new DeviceRegistrationManager(\n {},\n {\n native: deps.pushNative ?? nativePush,\n storage: this.storage,\n registerDevice: (body) => http.request(\"POST\", \"/devices\", { body }),\n subscribeAuth: (listener) => this.auth.subscribe(listener),\n getAndroidPushConfig: () =>\n this.pushConfigSync.current().android ?? null,\n platformOS,\n },\n );\n\n // E57 — Android FCM client config domain. Started only on Android (see\n // initialize); iOS keeps the build-time default `{}` and never reads it.\n this.pushConfigSync = this.createConfigSync<{\n android?: AndroidPushConfig;\n }>(\"push\", {}, { pollIntervalMs: config.configPollIntervalMs });\n }\n\n /**\n * Hydrate the persisted session, run device attestation, then start the\n * language runtime (restore the saved locale + start the locales/i18n\n * config-sync). Call once at boot.\n */\n async initialize(): Promise<void> {\n await this.core.initialize();\n\n // E57 phase 1 — register the device (metadata, no token, no permission\n // prompt). Best-effort and non-blocking: a failure here must never wedge\n // boot, and the token is collected later via requestPermission().\n void this.deviceRegistration.init().catch((err: unknown) => {\n devWarn(\"[QafkaCMS] device registration (phase 1) failed\", err);\n });\n }\n\n /**\n * Project + proof headers for calling the QafkaCMS API with your own HTTP\n * client: `X-Project-Id` and/or `X-Project-Key`, `X-Project-Slug` (if set), and\n * `X-Session-Token` (release) or `x-api-key` (dev-bypass), plus\n * `X-Unlock-Token` when `content.lookup` has unlocked records (QFK2-E78; pass\n * `{ withUnlockTokens: false }` to leave it out), and `X-App-Version` when\n * {@link appVersion} is set (QFK2-E59). Initialises device\n * attestation and loads the persisted unlock tokens first if that has not\n * happened yet. Contains no `Authorization` or `Content-Type` — add the\n * end-user token and body headers yourself.\n */\n async getRequestHeaders(\n options: { withUnlockTokens?: boolean } = {},\n ): Promise<Record<string, string>> {\n const headers = await this.core.getRequestHeaders(options);\n if (\n this.attestation.isDevBypass() &&\n !headers[\"x-api-key\"] &&\n !this.warnedNoProof &&\n typeof __DEV__ !== \"undefined\" &&\n __DEV__\n ) {\n this.warnedNoProof = true;\n console.warn(\n \"[QafkaCMS] getRequestHeaders(): dev-bypass without a dev API key — the request carries no proof.\",\n );\n }\n return headers;\n }\n\n /**\n * Force a fresh attestation session, then return {@link getRequestHeaders}.\n * On the first-ever call the initial attestation already is fresh, so it\n * attests once; later calls replace the existing session.\n */\n async refreshRequestHeaders(\n options: { withUnlockTokens?: boolean } = {},\n ): Promise<Record<string, string>> {\n const attestedBefore = this.proof.hasStarted();\n await this.proof.initialize();\n if (attestedBefore) await this.attestation.forceRefresh();\n return this.getRequestHeaders(options);\n }\n\n /**\n * Build a config-sync client for one customization domain (translations,\n * theme, navigation, …). Each shares the SDK's transport and storage.\n *\n * Transport defaults to **polling** — config rarely changes and a persistent\n * SSE per domain does not scale (one held connection per app per domain). Pass\n * `live: true` only for a domain that genuinely needs sub-second push (e.g. a\n * kill-switch flag); everything else polls (see E56).\n */\n createConfigSync<T>(\n domain: string,\n buildTimeDefault: T,\n options?: {\n pollIntervalMs?: number;\n live?: boolean;\n buildTimeVersion?: number;\n },\n ): ConfigSyncClient<T> {\n return this.core.createConfigSync<T>(domain, buildTimeDefault, options);\n }\n}\n\n/** Create a QafkaCMS SDK client. */\nexport function createClient(\n config: QafkaCmsConfig,\n deps?: QafkaCmsClientDeps,\n): QafkaCmsClient {\n return new QafkaCmsClient(config, deps);\n}\n","import { createElement, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';\nimport type { CoreClientLike } from '@qafka/cms-core';\nimport { QueryCache, type QueryCacheOptions } from '@qafka/cms-core';\nimport type { Duration } from '@qafka/cms-core';\nimport { QafkaCmsContext, type QafkaCmsContextValue, type QafkaCmsStatus } from './context';\nimport { runBootstrap, type PrefetchResource } from './bootstrap';\nimport { attachAuthCacheReset } from './auth-cache-reset';\nimport { attachUnlockCacheReset } from './unlock-cache-reset';\nimport { attachLocaleCacheReset } from './locale-cache-reset';\n\nexport interface QafkaCmsProviderProps<C extends CoreClientLike = CoreClientLike> {\n /** The SDK client. Create it with `createClient(...)` so dependency injection stays in the app's hands. */\n client: C;\n /** Resources to warm at boot. See {@link PrefetchResource}. */\n prefetch?: readonly PrefetchResource<unknown, C>[];\n /** Default freshness window for queries that do not set their own `ttl`. */\n defaultTtl?: Duration | null;\n /** Cache fetch-error observer (logging/telemetry). */\n onCacheError?: (error: Error, key: string) => void;\n /** Rendered while initializing (incl. gating prefetch). Omit to render children immediately. */\n fallback?: ReactNode;\n /** Rendered on init/gating-prefetch failure. Omit to render children (errors surface via hooks). */\n errorFallback?: ReactNode | ((error: Error, retry: () => void) => ReactNode);\n children?: ReactNode;\n}\n\n/**\n * Shares the SDK client through context, owns the boot lifecycle (`initialize()`\n * + gating prefetch), and provides the reactive query cache the data hooks read.\n *\n * The client is created by the app and passed in; the provider does not build\n * it. Do not also call `client.initialize()` yourself — the provider owns it.\n */\nexport function QafkaCmsProvider<C extends CoreClientLike>(props: QafkaCmsProviderProps<C>): ReactNode {\n const { client, prefetch, defaultTtl, onCacheError, fallback, errorFallback, children } = props;\n\n // Only queries flagged `persist` are written, to the client's cache store\n // (QFK2-T471): `client.cacheStorage` when set (RN: `createClient({ cacheStorage })`,\n // a plain AsyncStorage / MMKV store), else `client.storage` (RN without it: the\n // SDK's secure store; web: the session-mode store).\n // QFK2-E59 D7 — `contentVersionGate` on the client: gated queries ask the collection version first.\n const cache = useMemo(\n () => {\n const gate = client.contentVersionGate;\n const changes = client.contentChanges;\n const options: QueryCacheOptions = { storage: client.cacheStorage ?? client.storage, defaultTtl, onError: onCacheError };\n // QFK2-E59 V9 — persisted entries carry the app version; another version revalidates on hydrate.\n if (client.appVersion) options.appVersion = client.appVersion;\n if (gate && changes && typeof changes.versions === 'function') {\n options.versionGate = { check: (cols) => changes.versions(cols), maxAgeMs: gate.maxAgeMs };\n }\n return new QueryCache(options);\n },\n // A new cache is intentionally tied to the client identity; a swapped client\n // means a different session and a fresh cache.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [client],\n );\n\n const [status, setStatus] = useState<QafkaCmsStatus>('initializing');\n const [error, setError] = useState<Error | null>(null);\n const [bootId, setBootId] = useState(0);\n\n const prefetchRef = useRef(prefetch);\n prefetchRef.current = prefetch;\n\n useEffect(() => {\n let cancelled = false;\n let detachAuthReset: (() => void) | null = null;\n let detachLocaleReset: (() => void) | null = null;\n let detachUnlockReset: (() => void) | null = null;\n let stopBundle: (() => void) | undefined;\n setStatus('initializing');\n setError(null);\n runBootstrap(client, cache, prefetchRef.current ?? [])\n .then(() => {\n if (cancelled) return;\n // Baseline identity + locale AFTER boot (hydrate + prefetch done), so only\n // a later login/logout or locale switch resets the cache — not the initial\n // session/locale restore.\n detachAuthReset = attachAuthCacheReset(client, cache);\n detachLocaleReset = attachLocaleCacheReset(client, cache);\n detachUnlockReset = attachUnlockCacheReset(client, cache);\n // QFK2-E76: a live watch mounted during boot may have connected before the\n // token was hydrated / the device attested; reconnect with the booted\n // identity (the watches are kept; no-op when nothing is watched).\n client.contentChanges?.reset();\n // QFK2-E59 T466: sync the content bundle now, on foreground and on locale change.\n stopBundle = client.bundle?.start();\n setStatus('ready');\n })\n .catch((err: unknown) => {\n if (cancelled) return;\n setError(err instanceof Error ? err : new Error(String(err)));\n setStatus('error');\n });\n return () => {\n cancelled = true;\n detachAuthReset?.();\n detachLocaleReset?.();\n detachUnlockReset?.();\n stopBundle?.();\n };\n }, [client, cache, bootId]);\n\n const retry = useCallback(() => setBootId((n) => n + 1), []);\n const clearCache = useCallback(() => {\n void cache.clear();\n }, [cache]);\n\n const value = useMemo<QafkaCmsContextValue>(\n () => ({ client, cache, status, error, retry, clearCache }),\n [client, cache, status, error, retry, clearCache],\n );\n\n let content: ReactNode = children;\n if (status === 'error' && errorFallback !== undefined) {\n content =\n typeof errorFallback === 'function'\n ? errorFallback(error ?? new Error('QafkaCMS initialization failed'), retry)\n : errorFallback;\n } else if (status === 'initializing' && fallback !== undefined) {\n content = fallback;\n }\n\n return createElement(QafkaCmsContext.Provider, { value }, content);\n}\n","import { createContext, useContext } from 'react';\nimport type { CoreClientLike } from '@qafka/cms-core';\nimport type { QueryCache } from '@qafka/cms-core';\n\n/** Boot lifecycle phase owned by {@link QafkaCmsProvider}. */\nexport type QafkaCmsStatus = 'initializing' | 'ready' | 'error';\n\nexport interface QafkaCmsContextValue<C extends CoreClientLike = CoreClientLike> {\n /** The SDK client instance the app passed to the provider. */\n client: C;\n /** Shared reactive query cache backing the data hooks. */\n cache: QueryCache;\n status: QafkaCmsStatus;\n /** Set when `status === 'error'` (init or a gating prefetch failed). */\n error: Error | null;\n /** Re-run the boot sequence (initialize + gating prefetch). */\n retry: () => void;\n /** Drop all cached data + persisted copies. Call on logout. */\n clearCache: () => void;\n}\n\nexport const QafkaCmsContext = createContext<QafkaCmsContextValue | null>(null);\n\n/** Internal: read the context or throw a clear error when used outside the provider. */\nexport function useQafkaCmsContext<C extends CoreClientLike = CoreClientLike>(): QafkaCmsContextValue<C> {\n const value = useContext(QafkaCmsContext);\n if (!value) {\n throw new Error('QafkaCMS: hooks must be used within a <QafkaCmsProvider>.');\n }\n // The provider stores whatever client the app passed; the platform package\n // narrows `C` to its own client type.\n return value as QafkaCmsContextValue<C>;\n}\n\n/** The SDK client instance. Throws when used outside a {@link QafkaCmsProvider}. */\nexport function useQafkaCmsClient<C extends CoreClientLike = CoreClientLike>(): C {\n return useQafkaCmsContext<C>().client;\n}\n\n/** Boot lifecycle: `{ status, error, retry, clearCache }`. */\nexport function useQafkaCms(): Pick<QafkaCmsContextValue, 'status' | 'error' | 'retry' | 'clearCache'> {\n const { status, error, retry, clearCache } = useQafkaCmsContext();\n return { status, error, retry, clearCache };\n}\n\n/**\n * The shared reactive query cache — for manual invalidation, optimistic writes\n * (`setData`), prefetching, etc. Most apps use {@link useQuery}/`useMutation`\n * and never touch this directly.\n */\nexport function useQafkaCmsCache(): QueryCache {\n return useQafkaCmsContext().cache;\n}\n","import type { CoreClientLike } from '@qafka/cms-core';\nimport type { QueryCache } from '@qafka/cms-core';\nimport type { Duration } from '@qafka/cms-core';\nimport type { QueryKey } from '@qafka/cms-core';\n\n/**\n * A resource the provider warms into the cache at boot. `gate: true` resources\n * block the provider from becoming `ready` (and, when a `fallback` is set, hold\n * the UI) until they settle; the rest are fire-and-forget.\n */\nexport interface PrefetchResource<T = unknown, C extends CoreClientLike = CoreClientLike> {\n key: QueryKey;\n fetch: (client: C) => Promise<T>;\n /** Freshness window for the warmed entry (e.g. `'1h'`). */\n ttl?: Duration | null;\n /** Persist the warmed entry to `cacheStorage`. */\n persist?: boolean;\n /** Block `ready` until this resolves. Default: false (background warm-up). */\n gate?: boolean;\n}\n\n/**\n * Boot sequence: run the client's `initialize()` (token hydrate + attestation),\n * then warm the prefetch list. Gating resources are awaited via `Promise.all`;\n * the rest start in the background. Prefetch never rejects (the cache swallows\n * fetch errors → stale-on-error), so a flaky resource cannot wedge boot; only a\n * failing `initialize()` rejects here, which the provider surfaces as `error`.\n */\nexport async function runBootstrap<C extends CoreClientLike>(\n client: C,\n cache: QueryCache,\n prefetch: readonly PrefetchResource<unknown, C>[],\n): Promise<void> {\n await client.initialize();\n const start = (r: PrefetchResource<unknown, C>): Promise<void> =>\n cache.prefetch(r.key, () => r.fetch(client), { ttl: r.ttl, persist: r.persist });\n\n const gating: PrefetchResource<unknown, C>[] = [];\n for (const resource of prefetch) {\n if (resource.gate) gating.push(resource);\n else void start(resource);\n }\n await Promise.all(gating.map(start));\n}\n","import type { CoreClientLike } from '@qafka/cms-core';\nimport type { QueryCache } from '@qafka/cms-core';\n\n/**\n * Reset the query cache when the end-user identity changes. On login (or user\n * switch) the cache is cleared and active queries refetch with the new token;\n * on logout it is cleared and left empty. A plain token refresh (same identity)\n * leaves the cache intact. The identity key includes `isAnonymous` (QFK2-T322),\n * so an anonymous → account upgrade (same `userId`, new policy set) also clears\n * and refetches.\n *\n * Access is enforced server-side, so the cache must follow the token — this\n * stops a previous identity's scoped data from lingering after login/logout.\n * Live content watches (`client.contentChanges`) reconnect with the new\n * identity's headers too.\n * Returns an unsubscribe function.\n */\nexport function attachAuthCacheReset(client: CoreClientLike, cache: QueryCache): () => void {\n const identityOf = (): string | null => {\n const state = client.auth.getAuthState();\n if (!state.isAuthenticated) return null;\n return `${state.userId ?? '__authenticated__'}:${state.isAnonymous === true}`;\n };\n\n let last = identityOf();\n return client.auth.subscribe(() => {\n const next = identityOf();\n if (next === last) return; // same identity (e.g. a token refresh) → keep cache\n last = next;\n client.contentChanges?.reset(); // QFK2-E76: reconnect live watches with the new identity\n if (next === null) {\n void cache.clear(); // logout → drop everything, no refetch\n } else {\n void cache.clear().then(() => cache.refetchActive()); // login/switch → drop + reload live queries\n }\n });\n}\n","import type { CoreClientLike } from '@qafka/cms-core';\nimport type { QueryCache } from '@qafka/cms-core';\n\n/**\n * Refetch cached content when the unlock-token set changes (successful\n * `content.lookup` or `clearUnlockTokens()`). Access is decided server-side per\n * request token, so every cached entry may now differ: all keys are\n * invalidated and mounted queries revalidate with the new `X-Unlock-Token`.\n * Returns an unsubscribe function.\n */\nexport function attachUnlockCacheReset(client: CoreClientLike, cache: QueryCache): () => void {\n return client.content.onUnlockChange(() => {\n cache.invalidateWhere(() => true);\n });\n}\n","import type { CoreClientLike } from '@qafka/cms-core';\nimport type { QueryCache } from '@qafka/cms-core';\n\n/**\n * Reset the content cache when the active locale changes (E55). Content rows are\n * localized server-side per `?locale=`, so a previous locale's rows must not\n * linger after the user switches language. Invalidating the `content` /\n * `content-item` prefixes drops them and refetches the live queries.\n *\n * Mirrors {@link attachAuthCacheReset}; a no-op set to the same locale is\n * ignored. A client without a language runtime (thin tier) has nothing to\n * follow. Returns an unsubscribe function.\n */\nexport function attachLocaleCacheReset(client: CoreClientLike, cache: QueryCache): () => void {\n const language = client.language;\n if (!language) return () => {};\n let last = language.getLanguage();\n return language.subscribe(() => {\n const next = language.getLanguage();\n if (next === last) return; // same locale (e.g. an i18n-only update) → keep cache\n last = next;\n cache.invalidateByPrefix(['content']);\n cache.invalidateByPrefix(['content-item']);\n });\n}\n","import type { CoreClientLike } from '@qafka/cms-core';\nimport type { LanguageManager } from '@qafka/cms-core';\n\n/** The client's language runtime, or a clear error on a thin-tier client (no `language`). */\nexport function requireLanguage(client: CoreClientLike, hook: string): LanguageManager {\n if (!client.language) {\n throw new Error(\n `QafkaCMS: ${hook}() needs the full tier — this client has no language runtime (client.language).`,\n );\n }\n return client.language;\n}\n","import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';\nimport type { CoreClientLike } from '@qafka/cms-core';\nimport { serializeKey, type QueryKey } from '@qafka/cms-core';\nimport type { ConditionalResult, FetchContext, QueryOptions, QueryState } from '@qafka/cms-core';\nimport { useQafkaCmsContext } from './context';\n\nexport interface UseQueryOptions extends QueryOptions {\n /** When false the query does not fetch; it still serves whatever is cached. Default true. */\n enabled?: boolean;\n}\n\nexport interface UseQueryResult<T> extends QueryState<T> {\n /** Force a background refetch regardless of freshness. */\n refetch: () => Promise<void>;\n}\n\n/**\n * Subscribe a component to a cached query. Reads the shared cache via\n * `useSyncExternalStore` (so any consumer of the same key re-renders together)\n * and triggers a fetch on mount / key change through the cache, which handles\n * de-duplication, TTL, stale-while-revalidate, persistence and races.\n *\n * The fetcher also receives the cache's {@link FetchContext} (`ctx.etag`) and\n * may return a `conditional(...)` result for HTTP conditional revalidation\n * (QFK2-E59 D5); fetchers that take only `client` are unaffected.\n */\nexport function useQuery<T, C extends CoreClientLike = CoreClientLike>(\n key: QueryKey,\n fetcher: (client: C, ctx: FetchContext) => Promise<T | ConditionalResult<T>>,\n options?: UseQueryOptions,\n): UseQueryResult<T> {\n const { cache, client } = useQafkaCmsContext<C>();\n const sk = serializeKey(key);\n const enabled = options?.enabled ?? true;\n const ttl = options?.ttl;\n const persist = options?.persist;\n const gate = options?.gate;\n\n // Keep the latest fetcher without making it a fetch trigger — only the key matters.\n const fetcherRef = useRef(fetcher);\n fetcherRef.current = fetcher;\n\n const subscribe = useCallback((cb: () => void) => cache.subscribe(sk, cb), [cache, sk]);\n const getSnapshot = useCallback(() => cache.getSnapshot<T>(sk), [cache, sk]);\n const state = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n useEffect(() => {\n if (!enabled) return;\n void cache.ensure<T>(sk, (ctx) => fetcherRef.current(client, ctx), { ttl, persist, gate });\n }, [cache, client, sk, enabled, ttl, persist, gate]);\n\n const refetch = useCallback(\n () => cache.refetch<T>(sk, (ctx) => fetcherRef.current(client, ctx)),\n [cache, client, sk],\n );\n\n return { ...state, refetch };\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport type { CoreClientLike } from '@qafka/cms-core';\nimport type { QueryKey } from '@qafka/cms-core';\nimport { useQafkaCmsContext } from './context';\n\nexport interface UseMutationOptions<TVars, TResult> {\n /**\n * Query keys to invalidate on success, **by prefix** (react-query style):\n * `[['content', 'posts']]` refreshes every cached `content.list('posts', …)`.\n * Pass a function to derive keys from the result/vars.\n */\n invalidate?: QueryKey[] | ((result: TResult, vars: TVars) => QueryKey[]);\n onSuccess?: (result: TResult, vars: TVars) => void;\n onError?: (error: Error, vars: TVars) => void;\n}\n\nexport interface UseMutationResult<TVars, TResult> {\n /** Run the mutation. Resolves with the result, rejects on error (also reflected in state). */\n mutate: (vars: TVars) => Promise<TResult>;\n isPending: boolean;\n error: Error | undefined;\n data: TResult | undefined;\n reset: () => void;\n}\n\n/**\n * Write helper with automatic, prefix-based cache invalidation. Pair it with\n * `useContent`/`useQuery`: after the mutation succeeds, the listed query keys\n * are invalidated, so any mounted screen showing that data revalidates and any\n * unmounted one refetches on next mount.\n *\n * const create = useMutation(\n * (c, vars: NewPost) => c.content.create('posts', vars),\n * { invalidate: [['content', 'posts']] },\n * );\n * await create.mutate({ title: 'Hello' });\n *\n * For optimistic updates, write through `useQafkaCmsCache().setData(...)`.\n */\nexport function useMutation<TVars = void, TResult = unknown, C extends CoreClientLike = CoreClientLike>(\n mutationFn: (client: C, vars: TVars) => Promise<TResult>,\n options?: UseMutationOptions<TVars, TResult>,\n): UseMutationResult<TVars, TResult> {\n const { client, cache } = useQafkaCmsContext<C>();\n const [isPending, setIsPending] = useState(false);\n const [error, setError] = useState<Error | undefined>(undefined);\n const [data, setData] = useState<TResult | undefined>(undefined);\n\n // Latest fn/options without rebuilding `mutate`; mounted guard avoids\n // setState-after-unmount when a mutation resolves late.\n const fnRef = useRef(mutationFn);\n fnRef.current = mutationFn;\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const mountedRef = useRef(true);\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n const mutate = useCallback(\n async (vars: TVars): Promise<TResult> => {\n if (mountedRef.current) {\n setIsPending(true);\n setError(undefined);\n }\n try {\n const result = await fnRef.current(client, vars);\n const opts = optionsRef.current;\n const keys = typeof opts?.invalidate === 'function' ? opts.invalidate(result, vars) : opts?.invalidate;\n if (keys) for (const key of keys) cache.invalidateByPrefix(key);\n if (mountedRef.current) {\n setData(result);\n setIsPending(false);\n }\n opts?.onSuccess?.(result, vars);\n return result;\n } catch (err) {\n const e = err instanceof Error ? err : new Error(String(err));\n if (mountedRef.current) {\n setError(e);\n setIsPending(false);\n }\n optionsRef.current?.onError?.(e, vars);\n throw e;\n }\n },\n [client, cache],\n );\n\n const reset = useCallback(() => {\n if (!mountedRef.current) return;\n setIsPending(false);\n setError(undefined);\n setData(undefined);\n }, []);\n\n return { mutate, isPending, error, data, reset };\n}\n","import { useEffect } from 'react';\nimport { conditional } from '@qafka/cms-core';\nimport type { ContentLiveMode, ContentRecord, GetParams, ListParams, ListResult } from '@qafka/cms-core';\nimport { useQuery, type UseQueryOptions, type UseQueryResult } from './useQuery';\nimport { useQafkaCmsContext } from './context';\n\n/**\n * `live` of the content hooks (QFK2-E76 §9.1). `true` = watch with the\n * client's `contentLiveDefault` (default `'auto'`: SSE when available,\n * polling otherwise). Off (absent / `false`) = plain TTL behavior.\n */\nexport type ContentLiveOption =\n | boolean\n | {\n mode?: ContentLiveMode;\n /** Other collections whose changes also refresh this query (e.g. an expanded relation). */\n also?: string[];\n /** Poll cadence while polling (default 60 s, floor 30 s). */\n pollIntervalMs?: number;\n };\n\nexport interface UseContentOptions extends Omit<UseQueryOptions, 'gate'> {\n /** Refresh on server change signals (the collection must enable its change signal). */\n live?: ContentLiveOption;\n}\n\n/**\n * Version-gate slug of a content read (QFK2-E59 D8): the collection, when the\n * client has `contentVersionGate` and the read has no `expand` (an expanded\n * relation changes without bumping this collection's version).\n */\nfunction useGate(collection: string, params: { expand?: string | readonly string[] } | undefined): string | undefined {\n const { client } = useQafkaCmsContext();\n if (!client.contentVersionGate) return undefined;\n const expand = params?.expand;\n return expand === undefined || expand.length === 0 ? collection : undefined;\n}\n\n/** Watch `collection` (/ one record) through `client.contentChanges` while mounted and `live` is on. */\nfunction useLive(collection: string, id: string | null | undefined, live: ContentLiveOption | undefined, on: boolean): void {\n const { client, cache } = useQafkaCmsContext();\n const cfg = live === true ? {} : live || null;\n // A stable string so an equal `live` object written inline does not re-subscribe every render.\n const key = cfg && on ? JSON.stringify([collection, id ?? null, cfg.mode, cfg.also, cfg.pollIntervalMs]) : null;\n useEffect(() => {\n const hub = client.contentChanges;\n if (!key || !hub) return;\n const [c, i, mode, also, pollIntervalMs] = JSON.parse(key) as [\n string,\n string | null,\n ContentLiveMode | undefined,\n string[] | undefined,\n number | undefined,\n ];\n return hub.watch({ collection: c, id: i ?? undefined, also: also ?? undefined }, mode ?? undefined, {\n cache,\n pollIntervalMs: pollIntervalMs ?? undefined,\n });\n }, [client, cache, key]);\n}\n\n/**\n * Cached `content.list` for a collection. The cache key includes the params, so\n * different filters/pages are cached independently and shared across screens.\n * `options.live` also refreshes it on server change signals. Revalidation is a\n * conditional GET (QFK2-E59 D6): when the server answers 304 the cached data\n * (same object) is kept. With `contentVersionGate` on the client, an\n * expand-less read is version-gated (D8).\n */\nexport function useContent<T = ContentRecord>(\n collection: string,\n params?: ListParams,\n options?: UseContentOptions,\n): UseQueryResult<ListResult<T>> {\n const { live, ...queryOptions } = options ?? {};\n useLive(collection, undefined, live, queryOptions.enabled ?? true);\n const gate = useGate(collection, params);\n return useQuery<ListResult<T>>(\n ['content', collection, params ?? {}],\n (client, ctx) => {\n const content = client.content;\n // Structural clients / test doubles without the conditional reads keep the plain path.\n if (typeof content.listConditional !== 'function') return content.list<T>(collection, params);\n return content.listConditional<T>(collection, params, { ifNoneMatch: ctx.etag }).then(conditional.from);\n },\n { ...queryOptions, gate },\n );\n}\n\n/**\n * Cached `content.get` for a single record. Disabled (no fetch) until `id` is\n * truthy, so it is safe to call before the id is known. The cache key includes\n * the params, so an expanded and a plain read are cached independently.\n * `options.live` also refreshes it when this record changes. Revalidation is\n * conditional and version-gated, as in {@link useContent}.\n */\nexport function useContentItem<T = ContentRecord>(\n collection: string,\n id: string | null | undefined,\n params?: GetParams,\n options?: UseContentOptions,\n): UseQueryResult<T> {\n const { live, ...queryOptions } = options ?? {};\n const enabled = (queryOptions.enabled ?? true) && Boolean(id);\n useLive(collection, id, live, enabled);\n const gate = useGate(collection, params);\n return useQuery<T>(\n ['content-item', collection, id ?? null, params ?? {}],\n (client, ctx) => {\n const content = client.content;\n if (typeof content.getConditional !== 'function') return content.get<T>(collection, id as string, params);\n return content\n .getConditional<T>(collection, id as string, params, { ifNoneMatch: ctx.etag })\n .then(conditional.from);\n },\n { ...queryOptions, enabled, gate },\n );\n}\n","import { useSyncExternalStore } from 'react';\nimport type { ContentBundleApi, ContentBundleItemView, ContentBundleView, ContentRecord } from '@qafka/cms-core';\nimport { useQafkaCmsContext } from './context';\n\n/**\n * {@link useBundle}: `{ rows, version, isLoading, error }`. `version` is `null`\n * while no bundle is held (not synced yet, offline first run, none published);\n * `error` is the last sync error (the held rows stay available).\n */\nexport interface UseBundleResult<T> extends ContentBundleView<T> {}\n\n/** {@link useBundleItem}: `{ data, version, isLoading, error }`; `data` is `null` when absent or hidden. */\nexport interface UseBundleItemResult<T> extends ContentBundleItemView<T> {}\n\nconst none = () => () => {};\n/** Without a content bundle: empty, not loading, with an explanatory error. */\nconst off = {\n rows: [],\n data: null,\n version: null,\n isLoading: false,\n error: new Error('QafkaCMS: contentBundle is not enabled on this client'),\n};\n\nfunction useView<V>(make: (b: ContentBundleApi) => V): V {\n const b = useQafkaCmsContext().client.bundle;\n // Subscribing also loads the persisted bundle.\n const get = () => (b ? make(b) : (off as V));\n return useSyncExternalStore(b ? b.subscribe : none, get, get);\n}\n\n/**\n * Rows of one collection from the content bundle (QFK2-E59 T466): the offline\n * snapshot, filtered for `client.appVersion`. Re-renders when a new bundle\n * lands. Needs `createClient({ contentBundle })`; the Provider syncs it.\n */\nexport function useBundle<T = ContentRecord>(collection: string): UseBundleResult<T> {\n return useView((b) => b.view<T>(collection));\n}\n\n/** One row of the content bundle by id (see {@link useBundle}). */\nexport function useBundleItem<T = ContentRecord>(\n collection: string,\n id: string | null | undefined,\n): UseBundleItemResult<T> {\n return useView((b) => b.itemView<T>(collection, id));\n}\n","import type { ContentRecord, GetParams } from '@qafka/cms-core';\nimport type { LookupResult } from '@qafka/cms-core';\nimport { useMutation, type UseMutationResult } from './useMutation';\n\n/** Variables for {@link useLookup}'s `mutate`. */\nexport interface UseLookupVars extends GetParams {\n collection: string;\n code: string;\n}\n\n/**\n * Unlock a code-locked record: `const l = useLookup(); await l.mutate({ collection, code })`.\n * Rejects with a `ProblemError` on a wrong code (404 `LOOKUP_NOT_FOUND`). Cached\n * queries revalidate automatically once the token is stored (Provider-wired).\n */\nexport function useLookup<T = ContentRecord>(): UseMutationResult<UseLookupVars, LookupResult<T>> {\n return useMutation<UseLookupVars, LookupResult<T>>((client, { collection, code, ...params }) =>\n client.content.lookup<T>(collection, code, params),\n );\n}\n","import { useCallback, useSyncExternalStore } from 'react';\nimport type { AuthState } from '@qafka/cms-core';\nimport { useQafkaCmsContext } from './context';\n\n/**\n * Reactive end-user session: `{ isAuthenticated, userId, roles, isAnonymous }`.\n * Re-renders on login / token refresh / logout / anonymous upgrade. Backed by the SDK's `TokenStore` observable\n * (no polling). Branch UI on `roles` for tier-gated screens — the backend still\n * enforces what each tier can actually read/write.\n */\nexport function useAuth(): AuthState {\n const { client } = useQafkaCmsContext();\n const subscribe = useCallback((cb: () => void) => client.auth.subscribe(cb), [client]);\n const getSnapshot = useCallback(() => client.auth.getAuthState(), [client]);\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n","import { useCallback, useSyncExternalStore } from 'react';\nimport { useQafkaCmsClient } from './context';\nimport { requireLanguage } from './require-language';\n\nexport interface UseLocaleResult {\n /** The active locale (the project default until one is chosen). */\n locale: string;\n /** Switch the active locale — persists + propagates app-wide. */\n setLocale: (locale: string) => Promise<void>;\n /** The project's supported locales (`locales` config domain). */\n availableLocales: string[];\n /** The project's default locale. */\n defaultLocale: string;\n}\n\n/**\n * Reactive access to the active language (E55). Re-renders whenever the locale,\n * the supported-locale set, or the UI strings change. Use this for a language\n * switcher; use {@link useTranslation} when you need `t()`.\n */\nexport function useLocale(): UseLocaleResult {\n const language = requireLanguage(useQafkaCmsClient(), 'useLocale');\n const subscribe = useCallback((cb: () => void) => language.subscribe(cb), [language]);\n useSyncExternalStore(\n subscribe,\n () => language.getRevision(),\n () => language.getRevision(),\n );\n const setLocale = useCallback((locale: string) => language.setLanguage(locale), [language]);\n return {\n locale: language.getLanguage(),\n setLocale,\n availableLocales: language.getAvailableLocales(),\n defaultLocale: language.getDefaultLocale(),\n };\n}\n","import { useCallback, useSyncExternalStore } from 'react';\nimport { useQafkaCmsClient } from './context';\nimport { requireLanguage } from './require-language';\nimport type { TranslateParams } from '@qafka/cms-core';\n\nexport interface UseTranslationResult {\n /** Resolve a UI string for the active locale (active → default → key fallback). */\n t: (key: string, params?: TranslateParams) => string;\n /** The active locale. */\n locale: string;\n /** Switch the active locale. */\n setLocale: (locale: string) => Promise<void>;\n}\n\n/**\n * Reactive translation hook (E55) — the SDK counterpart of Shopla's\n * `useTranslations`. `t()` resolves against the `i18n` config domain for the\n * active locale and re-renders when the locale or the strings change.\n */\nexport function useTranslation(): UseTranslationResult {\n const language = requireLanguage(useQafkaCmsClient(), 'useTranslation');\n const subscribe = useCallback((cb: () => void) => language.subscribe(cb), [language]);\n const revision = useSyncExternalStore(\n subscribe,\n () => language.getRevision(),\n () => language.getRevision(),\n );\n const t = useCallback(\n (key: string, params?: TranslateParams) => language.t(key, params),\n // `revision` keeps `t`'s identity fresh after each change so memoized\n // children re-render with the new strings.\n [language, revision],\n );\n const setLocale = useCallback((locale: string) => language.setLanguage(locale), [language]);\n return { t, locale: language.getLanguage(), setLocale };\n}\n","/**\n * React Native view of the shared React layer (QFK2-E73 §4.3). The Provider and\n * hooks in `react/*` are generic over any `CoreClientLike`; the RN package\n * re-exports them narrowed to `QafkaCmsClient`, so the public signatures (and\n * AGENTS.md) stay exactly as before the core split.\n */\nimport type { ReactNode } from 'react';\nimport type { QafkaCmsClient } from './QafkaCmsSdk';\nimport type { QueryKey } from '@qafka/cms-core';\nimport {\n QafkaCmsProvider as SharedQafkaCmsProvider,\n type QafkaCmsProviderProps as SharedQafkaCmsProviderProps,\n} from '@qafka/cms-react';\nimport {\n useQafkaCms as sharedUseQafkaCms,\n useQafkaCmsClient as sharedUseQafkaCmsClient,\n type QafkaCmsContextValue as SharedQafkaCmsContextValue,\n} from '@qafka/cms-react';\nimport { useQuery as sharedUseQuery, type UseQueryOptions, type UseQueryResult } from '@qafka/cms-react';\nimport {\n useMutation as sharedUseMutation,\n type UseMutationOptions,\n type UseMutationResult,\n} from '@qafka/cms-react';\nimport type { PrefetchResource as SharedPrefetchResource } from '@qafka/cms-react';\n\n/**\n * A resource the provider warms into the cache at boot. `gate: true` resources\n * block the provider from becoming `ready` (and, when a `fallback` is set, hold\n * the UI) until they settle; the rest are fire-and-forget.\n */\nexport interface PrefetchResource<T = unknown> extends SharedPrefetchResource<T, QafkaCmsClient> {}\n\nexport interface QafkaCmsContextValue extends SharedQafkaCmsContextValue<QafkaCmsClient> {}\n\nexport interface QafkaCmsProviderProps extends Omit<SharedQafkaCmsProviderProps<QafkaCmsClient>, 'prefetch'> {\n /** Resources to warm at boot. See {@link PrefetchResource}. */\n prefetch?: readonly PrefetchResource[];\n}\n\n/**\n * Shares the SDK client through context, owns the boot lifecycle (`initialize()`\n * + gating prefetch), and provides the reactive query cache the data hooks read.\n *\n * The client is created by the app and passed in; the provider does not build\n * it. Do not also call `client.initialize()` yourself — the provider owns it.\n */\nexport const QafkaCmsProvider: (props: QafkaCmsProviderProps) => ReactNode = SharedQafkaCmsProvider;\n\n/** The SDK client instance. Throws when used outside a {@link QafkaCmsProvider}. */\nexport const useQafkaCmsClient: () => QafkaCmsClient = sharedUseQafkaCmsClient;\n\n/** Boot lifecycle: `{ status, error, retry, clearCache }`. */\nexport const useQafkaCms: () => Pick<QafkaCmsContextValue, 'status' | 'error' | 'retry' | 'clearCache'> =\n sharedUseQafkaCms;\n\n/**\n * Subscribe a component to a cached query. Reads the shared cache via\n * `useSyncExternalStore` (so any consumer of the same key re-renders together)\n * and triggers a fetch on mount / key change through the cache, which handles\n * de-duplication, TTL, stale-while-revalidate, persistence and races.\n */\nexport const useQuery: <T>(\n key: QueryKey,\n fetcher: (client: QafkaCmsClient) => Promise<T>,\n options?: UseQueryOptions,\n) => UseQueryResult<T> = sharedUseQuery;\n\n/**\n * Write helper with automatic, prefix-based cache invalidation. Pair it with\n * `useContent`/`useQuery`: after the mutation succeeds, the listed query keys\n * are invalidated, so any mounted screen showing that data revalidates and any\n * unmounted one refetches on next mount.\n *\n * const create = useMutation(\n * (c, vars: NewPost) => c.content.create('posts', vars),\n * { invalidate: [['content', 'posts']] },\n * );\n * await create.mutate({ title: 'Hello' });\n *\n * For optimistic updates, write through `useQafkaCmsCache().setData(...)`.\n */\nexport const useMutation: <TVars = void, TResult = unknown>(\n mutationFn: (client: QafkaCmsClient, vars: TVars) => Promise<TResult>,\n options?: UseMutationOptions<TVars, TResult>,\n) => UseMutationResult<TVars, TResult> = sharedUseMutation;\n","import { useCallback, useSyncExternalStore } from 'react';\nimport type { DeviceRegistrationState } from '../push/DeviceRegistrationManager';\nimport type { PushPermissionStatus } from '../native/QafkaCmsPush';\nimport type { QafkaCmsClient } from '../QafkaCmsSdk';\nimport { useQafkaCmsContext } from '@qafka/cms-react';\n\nexport interface UsePushResult extends DeviceRegistrationState {\n /**\n * Prompt for notification permission and, if granted, collect + register the\n * push token (phase 2). Safe to call from a button handler — this is where the\n * OS dialog appears, so the host controls *when* the user sees it. Resolves\n * with the resulting permission state.\n */\n requestPermission: () => Promise<PushPermissionStatus>;\n}\n\n/**\n * Reactive push/device state: `{ permission, deviceId, token, requestPermission }`.\n * Re-renders when permission changes or the token is collected/rotated. The\n * device row is registered automatically at boot (phase 1, no prompt); call\n * `requestPermission()` to trigger the OS dialog and collect the token (phase 2).\n */\nexport function usePush(): UsePushResult {\n const { client } = useQafkaCmsContext<QafkaCmsClient>();\n const subscribe = useCallback(\n (cb: () => void) => client.deviceRegistration.subscribe(cb),\n [client],\n );\n const getSnapshot = useCallback(\n () => client.deviceRegistration.getDeviceState(),\n [client],\n );\n const state = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n const requestPermission = useCallback(\n () => client.deviceRegistration.requestPermission(),\n [client],\n );\n return { ...state, requestPermission };\n}\n","import { useColorScheme } from 'react-native';\nimport { resolveColor } from '@qafka/cms-core';\nimport type { ColorValue } from '@qafka/cms-core';\n\n/** `resolveColor` using the device color scheme (unknown scheme = light). */\nexport function useResolvedColor(value: unknown): ColorValue | null {\n const scheme = useColorScheme();\n return resolveColor(value, scheme === 'dark' ? 'dark' : 'light');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0BAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAAAC;AAAA,EAAA;AAAA,qBAAAC;AAAA,EAAA;AAAA,2BAAAC;AAAA,EAAA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AS,YAAY;AAAA,EAC7B;AACA,QAAM,QAAI;AAAA,IACR,CAAC,KAAa,WAA6B,SAAS,EAAE,KAAK,MAAM;AAAA;AAAA;AAAA,IAGjE,CAAC,UAAU,QAAQ;AAAA,EACrB;AACA,QAAM,gBAAY,2BAAY,CAAC,WAAmB,SAAS,YAAY,MAAM,GAAG,CAAC,QAAQ,CAAC;AAC1F,SAAO,EAAE,GAAG,QAAQ,SAAS,YAAY,GAAG,UAAU;AACxD;;;ACYO,IAAMC,oBAAgE;AAGtE,IAAMC,qBAA0C;AAGhD,IAAMC,eACX;AAQK,IAAMC,YAIY;AAgBlB,IAAMC,eAG4B;;;ACrFzC,IAAAC,iBAAkD;AAsB3C,SAAS,UAAyB;AACvC,QAAM,EAAE,OAAO,IAAI,mBAAmC;AACtD,QAAM,gBAAY;AAAA,IAChB,CAAC,OAAmB,OAAO,mBAAmB,UAAU,EAAE;AAAA,IAC1D,CAAC,MAAM;AAAA,EACT;AACA,QAAM,kBAAc;AAAA,IAClB,MAAM,OAAO,mBAAmB,eAAe;AAAA,IAC/C,CAAC,MAAM;AAAA,EACT;AACA,QAAM,YAAQ,qCAAqB,WAAW,aAAa,WAAW;AACtE,QAAM,wBAAoB;AAAA,IACxB,MAAM,OAAO,mBAAmB,kBAAkB;AAAA,IAClD,CAAC,MAAM;AAAA,EACT;AACA,SAAO,EAAE,GAAG,OAAO,kBAAkB;AACvC;;;ACtCA,IAAAC,uBAA+B;AAKxB,SAAS,iBAAiB,OAAmC;AAClE,QAAM,aAAS,qCAAe;AAC9B,SAAO,aAAa,OAAO,WAAW,SAAS,SAAS,OAAO;AACjE;;;A3DoFO,SAAS,aAAqB;AACnC,SAAO;AACT;","names":["QafkaCmsProvider","useMutation","useQafkaCms","useQafkaCmsClient","useQuery","now","claims","provider","storage","now","storage","now","storage","storage","enc","out","EMPTY","storage","native","import_react_native","import_react_native","import_react_native","mod","mod","import_react_native","import_react_native","now","import_react","import_react","import_react","import_react","import_react","import_react","import_react","import_react","QafkaCmsProvider","useQafkaCmsClient","useQafkaCms","useQuery","useMutation","import_react","import_react_native"]}
|