@lpdjs/firestore-repo-service 3.0.20 → 3.0.21

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/sync/admin.ts","../../src/servers/admin/router.ts","../../src/servers/utils/link-base.ts","../../src/servers/auth/firebase-auth.ts","../../src/shared/actor-context.ts","../../src/history/types.ts","../../src/history/inject.ts","../../src/shared/path-template.ts","../../src/repositories/factory.ts","../../src/sync/serializer.ts","../../src/sync/triggers.ts","../../src/sync/constants.ts","../../src/shared/zod-compat.ts","../../src/sync/schema-mapper.ts","../../src/sync/adapters/bigquery-types.ts","../../src/sync/adapters/bigquery.ts","../../src/sync/queue.ts","../../src/sync/worker.ts","../../src/sync/create-sync.ts","../../src/sync/ddl-generator.ts","../../src/sync/migration.ts","../../src/sync/adapters/meilisearch.ts"],"names":["compilePath","path","paramNames","src","c","_match","name","extractPath","req","raw","idx","MiniRouter","_req","res","err","middleware","handler","method","pattern","matchedRoute","params","route","m","i","enrichedReq","finalHandler","index","next","mw","getLinkBase","staticBasePath","region","base","project","resolvedRegion","target","service","host","resolveRegion","first","isAuthExtension","value","DEFAULT_HISTORY_REASON_HEADER","DEFAULT_HISTORY_COMMENT_HEADER","ACTOR_RESOLVER_HEADERS_SYMBOL","ALS_SYMBOL","g","AsyncLocalStorage","readFieldPath","obj","cur","part","pickFirstString","paths","p","val","readHeader","headerFn","createActorResolver","config","contextKeys","userIdFields","userEmailFields","reasonHeader","commentHeader","displayReasonHeader","displayCommentHeader","extrasFn","resolver","user","getFn","key","candidate","reason","comment","extras","DEFAULT_HISTORY_SHADOW_KEY","resolveShadowConfig","shadowOpt","customFields","getHistoryShadowKey","getHistoryIdentityKeys","shadow","extractSegmentParam","segment","parsePathTemplate","rawPath","documentKey","isGroup","segments","s","seg","isEvenSegments","collectionSegments","collectionId","collectionPath","parentKeys","documentPathTemplate","extractParentKeys","refCb","match","buildRepoStaticMeta","parsedPath","systemKeys","k","historyConfig","makeLazyRepo","resolve","overlay","resolved","ensure","_t","prop","serializeValue","options","seen","depth","geo","mapped","item","serializeNestedObject","MAX_FLATTEN_DEPTH","MAX_FLATTEN_KEYS","flattenObject","prefix","result","flatKey","exclude","columnMap","mappedKey","unflattenDocument","doc","rawValue","trimmed","parts","current","serializeDocument","isFlat","sourceDoc","dropped","filtered","v","flat","topLevel","column","escapeHtml","page","title","linkBase","body","safeTitle","safeLinkBase","sendHtml","html","status","sendJson","data","isJsonRequest","isTruthyFlag","normalized","parseDryRun","rawUrl","qIdx","parsed","TRANSIENT_FIRESTORE_CODES","isTransientFirestoreError","code","getPageWithRetry","maxAttempts","baseDelayMs","attempt","delayMs","getActiveQueuesForRepo","info","queues","adapter","exactKey","q","fallback","createadminsyncServer","repoMapping","adapterOrAdapters","handleMessage","repoConfigs","pubsub","topicPrefix","basePath","features","adapters","rawMapping","repoInfos","configuredKeys","hasExplicitRepos","allKeys","repoNames","repoCfg","repo","hasTemplateTriggerPath","activeAdapters","a","historyShadowKey","router","activeForceSyncs","ext","mountPath","realm","expected","lb","safeLb","rows","r","safeName","encodedName","links","adapterBadges","configCheckLink","results","h","exists","e","allHealthy","renderAdapterCard","adapterName","health","statusBadge","extraContent","details","expectedCols","actualSet","extraCols","colRows","extraRows","safeAdapters","collRef","dryRun","scanned","enqueued","handlerErrors","errorSamples","batchSize","query","FieldPath","lastDoc","queueBaselines","collectQueueErrors","queue","stats","entry","computeTotals","statsEntries","minFlushed","totalFailed","deltaFlushed","deltaFailed","effectiveExclude","preExisting","paginatedQuery","pageReadStartedAt","snapshot","docId","serialized","msg","activeQueues","synced","errors","errMsg","errorBlock","summaryLine","consoleBase","tPrefix","checks","msgLower","isApiDisabled","isPermission","isProjectNotFound","isNotFound","conn","category","topicName","topic","allOk","statusIcon","grouped","renderSection","items","fixHtml","overallBadge","DEFAULT_TOPIC_PREFIX","buildDocumentPath","repoName","syncMetaFromConfig","cfg","syncMetaFromRepo","docTemplate","createSyncTriggers","onDocumentWritten","triggers","topicCache","getTopic","t","publish","syncEvent","entries","repoConfigsMap","meta","documentPath","resolvedGroupPath","effectiveTriggerOptions","hasTriggerOptions","triggerHandler","event","before","after","beforeExists","afterExists","SYNC_VERSION_COLUMN","TYPE_MAP","getTypeName","schema","v4Type","v3Type","getInnerType","getShape","WRAPPER_TYPES","unwrap","nullable","inner","LOGICAL_MAP","zodTypeToLogical","flattenSchema","shape","dialect","parentNullable","excludeSet","primaryKey","columns","field","fieldSchema","fullKey","typeName","isNullable","nestedShape","logical","isPK","colName","zodSchemaToColumns","normalizeBigQueryType","type","upper","isBigQueryTypeCompatible","existing","desired","b","BigQueryDialect","id","bigqueryDialect","storageNsCache","loadStorageNs","formatChangeSequenceNumber","version","n","isRetryableStorageError","withRetry","fn","maxRetries","baseMs","cap","delay","SchemaTypeMismatchError","tableName","existingType","desiredType","_BigQueryAdapter","targetName","ids","missing","col","repoConfig","actualCols","expectedSet","extra","matched","healthy","metadata","f","fields","table","qi","pk","cols","notNull","opts","optionsClause","ddl","stmt","sql","cached","writer","timestampColumns","cdc","row","esc","d","ms","out","ns","bqSchema","storageSchema","protoDescriptor","destinationTable","connection","BigQueryAdapter","_SyncQueue","interval","events","fullBatchesOnly","batch","upsertsById","deleteIds","evt","upserts","SyncQueue","migratedTargets","ensureMigratedTarget","migrationKey","sqlAdapter","newCols","createSyncWorker","deps","rawAdapter","rawAdaptersList","flushIntervalMs","autoMigrate","maxDlqAttempts","workerOptions","getAdaptersForRepo","allowed","getQueue","queueKey","dlTopicName","dlTopic","dlTopicEnsured","ensureDlTopic","onFlushError","error","attempts","payload","targetAdapters","createHandler","handlerFn","promises","visited","lazyProxy","factory","instance","_","createFirestoreSync","adminConfig","triggerOptions","worker","handlers","activeRepoNames","adminHandler","createTableDDL","addColumnsDDL","generateDDL","statements","tableDef","existingCols","loadMeilisearchClient","MeiliSearch","areMeiliSettingsEqual","curVal","MeilisearchAdapter","shouldUnflatten","docs","_primaryKey","r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A,CAAK,MAAA,CAAO,SAAA,EAAU,CACxCsd,EAAYtd,CAAAA,EAAK,MAAA,GAAW,WAAA,EAAeA,CAAAA,GAAQ,CAAA,EACrD,CAAA,KAAA,GAAW,OAAO,IAAA,CAAK,OAAO,MAAA,EAAW,UAAA,CAAY,CACnD,IAAMA,CAAAA,CAAM,MAAM,IAAA,CAAK,MAAA,CAAO,QAAO,CACrCsd,CAAAA,CAAYtd,CAAAA,EAAK,MAAA,GAAW,WAAA,EAAeA,CAAAA,GAAQ,CAAA,EACrD,CACA,IAAI0V,CAAAA,CACJ,OAAI,OAAO,IAAA,CAAK,MAAA,CAAO,UAAA,EAAe,UAAA,GAEpCA,CAAAA,CAAAA,CADU,MAAM,IAAA,CAAK,MAAA,CAAO,UAAA,EAAW,GAC1B,UAAA,CAAA,CAER,CAAE,OAAA,CAAS4H,CAAAA,CAAW,QAAA5H,CAAQ,CACvC,CAAA,MAAS,CAAA,CAAQ,CACf,OAAO,CAAE,OAAA,CAAS,MAAO,KAAA,CAAO,CAAA,EAAG,OAAA,EAAW,MAAA,CAAO,CAAC,CAAE,CAC1D,CACF,CACF,EAkBO,SAAS6H,EAAAA,CAEdlX,CAAAA,CAAoE,CACpE,OAAO,IAAM,IAAIuW,EAAAA,CAAsBvW,CAAO,CAChD","file":"index.js","sourcesContent":["/**\n * Sync Admin — optional HTTP endpoint for inspecting and managing the\n * Firestore → SQL sync pipeline.\n *\n * Features (gated by `featuresFlag`):\n * - **healthCheck** — compare expected Zod-derived columns vs actual SQL columns\n * - **manualSync** — force re-sync all documents in a Firestore collection\n *\n * @example\n * ```typescript\n * const sync = createFirestoreSync(repos, {\n * // …deps, adapter, etc.\n * admin: {\n * auth: { type: \"basic\", username: \"admin\", password: \"secret\" },\n * featuresFlag: { healthCheck: true, manualSync: true },\n * },\n * });\n *\n * export const adminsync = onRequest(sync.adminHandler!);\n * ```\n */\n\nimport { FieldPath } from \"firebase-admin/firestore\";\nimport { z } from \"zod\";\nimport type { AnyReq, AnyRes, RouteParams } from \"../servers/admin/router\";\nimport { MiniRouter } from \"../servers/admin/router\";\nimport { isAuthExtension } from \"../servers/auth\";\nimport { makeLazyRepo } from \"../repositories/factory\";\nimport { getLinkBase, resolveRegion } from \"../servers/utils/link-base\";\nimport type { SyncQueue } from \"./queue\";\nimport { getHistoryShadowKey } from \"../history/inject\";\nimport { serializeDocument } from \"./serializer\";\nimport type {\n adminsyncConfig,\n PubSubClientDep,\n RepoSyncConfig,\n SyncAdapter,\n SyncEvent,\n SyncHealthResult,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\ntype Req = AnyReq & { params: RouteParams };\n\ninterface RepoInfo {\n name: string;\n schema: z.ZodObject<any> | null;\n documentKey: string;\n tableName: string;\n isGroup: boolean;\n repoCfg: RepoSyncConfig<string> | undefined;\n repo: any;\n adapters: SyncAdapter[];\n historyShadowKey: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// HTML & request helpers\n// ---------------------------------------------------------------------------\n\nfunction escapeHtml(value: unknown): string {\n return String(value ?? \"\")\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\nfunction page(title: string, linkBase: string, body: string): string {\n const safeTitle = escapeHtml(title);\n const safeLinkBase = escapeHtml(linkBase);\n return `<!DOCTYPE html>\n<html lang=\"en\"><head>\n<meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<title>${safeTitle} — Sync Admin</title>\n<style>\n *{box-sizing:border-box;margin:0;padding:0}\n body{font-family:system-ui,-apple-system,sans-serif;background:#f5f5f5;color:#1a1a1a;padding:2rem}\n a{color:#0969da;text-decoration:none}a:hover{text-decoration:underline}\n h1{margin-bottom:1rem}h2{margin:1.5rem 0 .75rem}\n table{border-collapse:collapse;width:100%;margin-bottom:1rem}\n th,td{text-align:left;padding:.5rem .75rem;border:1px solid #d0d7de}\n th{background:#f6f8fa;font-weight:600}\n tr:nth-child(even){background:#fafbfc}\n .badge{display:inline-block;padding:.15rem .5rem;border-radius:1rem;font-size:.8rem;font-weight:600}\n .badge-ok{background:#dafbe1;color:#1a7f37}\n .badge-warn{background:#fff8c5;color:#9a6700}\n .badge-err{background:#ffebe9;color:#cf222e}\n .btn{display:inline-block;padding:.4rem 1rem;border:1px solid #d0d7de;border-radius:.375rem;\n background:#fff;cursor:pointer;font-size:.85rem;text-decoration:none;color:#1a1a1a}\n .btn:hover{background:#f3f4f6}.btn-primary{background:#0969da;color:#fff;border-color:#0969da}\n .btn-primary:hover{background:#0860ca}\n nav{margin-bottom:1.5rem}nav a{margin-right:1rem}\n .card{background:#fff;border:1px solid #d0d7de;border-radius:.5rem;padding:1.25rem;margin-bottom:1rem}\n pre{background:#f6f8fa;padding:1rem;border-radius:.375rem;overflow-x:auto;font-size:.85rem}\n .muted{color:#656d76;font-size:.85rem}\n</style>\n</head><body>\n<nav><a href=\"${safeLinkBase}/\">← Dashboard</a></nav>\n<h1>${safeTitle}</h1>\n${body}\n</body></html>`;\n}\n\nfunction sendHtml(res: AnyRes, html: string, status = 200): void {\n res.status(status).set(\"Content-Type\", \"text/html; charset=utf-8\").send(html);\n}\n\nfunction sendJson(res: AnyRes, data: unknown, status = 200): void {\n res\n .status(status)\n .set(\"Content-Type\", \"application/json\")\n .send(JSON.stringify(data, null, 2));\n}\n\nfunction isJsonRequest(req: AnyReq): boolean {\n const accept = (req.headers?.[\"accept\"] ?? \"\") as string;\n return accept.includes(\"application/json\");\n}\n\nfunction isTruthyFlag(value: unknown): boolean {\n if (value === true || value === 1) return true;\n if (Array.isArray(value)) return value.some(isTruthyFlag);\n if (typeof value === \"string\") {\n const normalized = value.trim().toLowerCase();\n return (\n normalized === \"true\" ||\n normalized === \"1\" ||\n normalized === \"yes\" ||\n normalized === \"on\"\n );\n }\n return false;\n}\n\nfunction parseDryRun(req: AnyReq): boolean {\n if (req.query && isTruthyFlag(req.query[\"dryRun\"])) {\n return true;\n }\n\n const rawUrl = req.url ?? req.originalUrl ?? \"\";\n const qIdx = rawUrl.indexOf(\"?\");\n if (qIdx !== -1) {\n const params = new URLSearchParams(rawUrl.slice(qIdx + 1));\n if (isTruthyFlag(params.get(\"dryRun\"))) {\n return true;\n }\n }\n\n const body = req.body;\n if (body && typeof body === \"object\") {\n if (isTruthyFlag((body as Record<string, unknown>)[\"dryRun\"])) {\n return true;\n }\n } else if (typeof body === \"string\" && body.trim().length > 0) {\n const trimmed = body.trim();\n if (trimmed.startsWith(\"{\")) {\n try {\n const parsed = JSON.parse(trimmed);\n if (\n parsed &&\n typeof parsed === \"object\" &&\n isTruthyFlag((parsed as Record<string, unknown>)[\"dryRun\"])\n ) {\n return true;\n }\n } catch {\n // Ignore malformed JSON bodies\n }\n } else {\n const params = new URLSearchParams(trimmed);\n if (isTruthyFlag(params.get(\"dryRun\"))) {\n return true;\n }\n }\n }\n\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Firestore read retry & queue helpers\n// ---------------------------------------------------------------------------\n\n/** gRPC status codes eligible for retry on Firestore page reads. */\nconst TRANSIENT_FIRESTORE_CODES = new Set<number | string>([\n 4, // DEADLINE_EXCEEDED\n 8, // RESOURCE_EXHAUSTED\n 10, // ABORTED\n 13, // INTERNAL\n 14, // UNAVAILABLE\n \"4\",\n \"8\",\n \"10\",\n \"13\",\n \"14\",\n \"DEADLINE_EXCEEDED\",\n \"RESOURCE_EXHAUSTED\",\n \"ABORTED\",\n \"INTERNAL\",\n \"UNAVAILABLE\",\n]);\n\nfunction isTransientFirestoreError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const code = (err as { code?: unknown }).code;\n return (\n (typeof code === \"number\" || typeof code === \"string\") &&\n TRANSIENT_FIRESTORE_CODES.has(code)\n );\n}\n\nasync function getPageWithRetry<T>(\n getFn: () => Promise<T>,\n maxAttempts = 3,\n baseDelayMs = 100,\n): Promise<T> {\n let attempt = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n attempt++;\n try {\n return await getFn();\n } catch (err) {\n if (attempt >= maxAttempts || !isTransientFirestoreError(err)) {\n throw err;\n }\n const delayMs = baseDelayMs * 2 ** (attempt - 1);\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n }\n}\n\nfunction getActiveQueuesForRepo(\n info: RepoInfo,\n queues: Map<string, SyncQueue>,\n): Array<{ adapterName: string; queue: SyncQueue }> {\n const seen = new Set<SyncQueue>();\n const result: Array<{ adapterName: string; queue: SyncQueue }> = [];\n\n for (const adapter of info.adapters) {\n const exactKey = `${info.name}:${adapter.name}`;\n const q = queues.get(exactKey);\n if (q && !seen.has(q)) {\n seen.add(q);\n result.push({ adapterName: adapter.name ?? \"default\", queue: q });\n }\n }\n\n if (result.length === 0) {\n const fallback = queues.get(info.name);\n if (fallback && !seen.has(fallback)) {\n seen.add(fallback);\n result.push({\n adapterName: info.adapters[0]?.name ?? \"default\",\n queue: fallback,\n });\n }\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create the sync admin HTTP handler.\n */\nexport function createadminsyncServer(\n repoMapping: Record<string, any>,\n adapterOrAdapters: SyncAdapter | SyncAdapter[],\n queues: Map<string, SyncQueue>,\n handleMessage: (event: SyncEvent) => Promise<void>,\n config: adminsyncConfig,\n repoConfigs: Record<string, RepoSyncConfig<string> | undefined>,\n pubsub?: PubSubClientDep,\n topicPrefix?: string,\n): (req: any, res: any) => Promise<void> {\n const basePath = (config.basePath ?? \"/\").replace(/\\/$/, \"\") || \"\";\n const features = config.featuresFlag ?? {};\n const region = resolveRegion(config.httpsOptions?.region);\n\n const adapters: SyncAdapter[] = Array.isArray(adapterOrAdapters)\n ? adapterOrAdapters\n : [adapterOrAdapters];\n\n const rawMapping: Record<string, any> | undefined = (repoMapping as any)\n ?.rawMapping;\n const repoInfos: RepoInfo[] = [];\n\n const configuredKeys = Object.keys(repoConfigs ?? {});\n const hasExplicitRepos = configuredKeys.length > 0;\n const allKeys = rawMapping ? Object.keys(rawMapping) : Object.keys(repoMapping);\n const repoNames = hasExplicitRepos\n ? configuredKeys.filter((name) => allKeys.includes(name) || name in repoMapping)\n : allKeys;\n\n for (const name of repoNames) {\n const repoCfg = repoConfigs[name];\n const repo = rawMapping\n ? makeLazyRepo(rawMapping[name], () => (repoMapping as Record<string, any>)[name])\n : (repoMapping as Record<string, any>)[name];\n\n const isGroup = !!(repo as any)._isGroup;\n const collectionPath = (repo as any)._collectionPath as string | undefined;\n const hasTemplateTriggerPath =\n typeof collectionPath === \"string\" && collectionPath.includes(\"/\");\n if (\n !hasExplicitRepos &&\n isGroup &&\n !repoCfg?.triggerPath &&\n !hasTemplateTriggerPath\n ) {\n continue;\n }\n\n const activeAdapters = repoCfg?.adapters && repoCfg.adapters.length > 0\n ? adapters.filter((a) => repoCfg.adapters!.includes(a.name))\n : adapters;\n\n const historyShadowKey =\n typeof (repo as any)._historyShadowKey === \"string\"\n ? ((repo as any)._historyShadowKey as string)\n : getHistoryShadowKey((repo as any)._historyConfig);\n\n repoInfos.push({\n name,\n schema: (repo as any).schema ?? null,\n documentKey:\n (repo as any)._systemKeys?.[0] ?? (repo as any).documentKey ?? \"docId\",\n tableName: repoCfg?.tableName ?? name,\n isGroup,\n repoCfg,\n repo,\n adapters: activeAdapters,\n historyShadowKey,\n });\n }\n\n const router = new MiniRouter();\n const activeForceSyncs = new Set<string>();\n\n // -- Auth middleware -----------------------------------------------------\n if (config.auth) {\n if (isAuthExtension(config.auth)) {\n const ext = config.auth;\n for (const route of ext.routes) {\n const mountPath = `${basePath}${route.path}`;\n if (route.method === \"GET\") router.get(mountPath, route.handler);\n else router.post(mountPath, route.handler);\n }\n router.use(ext.middleware);\n } else if (typeof config.auth === \"function\") {\n router.use(config.auth as any);\n } else {\n const realm = config.auth.realm ?? \"Sync Admin\";\n const expected =\n \"Basic \" +\n Buffer.from(`${config.auth.username}:${config.auth.password}`).toString(\n \"base64\",\n );\n router.use((req, res, next) => {\n const authorization = (req as any).headers?.[\"authorization\"] ?? \"\";\n if (authorization !== expected) {\n res\n .status(401)\n .set(\"WWW-Authenticate\", `Basic realm=\"${realm}\"`)\n .set(\"Content-Type\", \"text/plain\")\n .send(\"Unauthorized\");\n return;\n }\n next();\n });\n }\n }\n\n // -- Dashboard ----------------------------------------------------------\n router.get(`${basePath}/`, (req, res) => {\n const lb = getLinkBase(req, basePath, region);\n const safeLb = escapeHtml(lb);\n const rows = repoInfos\n .map((r) => {\n const safeName = escapeHtml(r.name);\n const encodedName = encodeURIComponent(r.name);\n const links: string[] = [];\n if (features.healthCheck)\n links.push(`<a class=\"btn\" href=\"${safeLb}/${encodedName}/health\">Health</a>`);\n if (features.manualSync)\n links.push(\n `<a class=\"btn btn-primary\" href=\"${safeLb}/${encodedName}/force-sync\">Force Sync</a>`,\n );\n const adapterBadges = r.adapters\n .map((a) => `<span class=\"badge badge-ok\">${escapeHtml(a.name)}</span>`)\n .join(\" \");\n\n return `<tr>\n <td><strong>${safeName}</strong></td>\n <td>${escapeHtml(r.tableName)}</td>\n <td>${adapterBadges || '<span class=\"badge badge-warn\">none</span>'}</td>\n <td>${r.isGroup ? '<span class=\"badge badge-warn\">group</span>' : '<span class=\"badge badge-ok\">collection</span>'}</td>\n <td>${r.schema ? \"✓\" : \"✗\"}</td>\n <td>${links.join(\" \")}</td>\n </tr>`;\n })\n .join(\"\\n\");\n\n const configCheckLink = features.configCheck\n ? `<p style=\"margin-top:.5rem\"><a class=\"btn\" href=\"${safeLb}/config-check\">⚙ Config Check</a></p>`\n : \"\";\n\n const html = page(\n \"Sync Dashboard\",\n lb,\n `<div class=\"card\">\n <table>\n <thead><tr><th>Repository</th><th>Target Name</th><th>Adapters</th><th>Type</th><th>Schema</th><th>Actions</th></tr></thead>\n <tbody>${rows}</tbody>\n </table>\n ${configCheckLink}\n </div>`,\n );\n sendHtml(res, html);\n });\n router.get(`${basePath}`, (req, res) => {\n const lb = getLinkBase(req, basePath, region);\n res.status(302).set(\"Location\", `${lb}/`).send(\"\");\n });\n\n // -- Health Check -------------------------------------------------------\n if (features.healthCheck) {\n router.get(`${basePath}/:repoName/health`, async (req: Req, res) => {\n const lb = getLinkBase(req, basePath, region);\n const info = repoInfos.find((r) => r.name === req.params.repoName);\n if (!info) {\n sendHtml(\n res,\n page(\"Not Found\", lb, `<p>Unknown repo: ${escapeHtml(req.params.repoName)}</p>`),\n 404,\n );\n return;\n }\n\n const results: Array<{\n adapterName: string;\n health: SyncHealthResult;\n }> = [];\n\n for (const adapter of info.adapters) {\n if (typeof adapter.healthCheck === \"function\") {\n const h = await adapter.healthCheck({\n targetName: info.tableName,\n primaryKey: info.documentKey,\n schema: info.schema ?? undefined,\n repoConfig: info.repoCfg,\n });\n results.push({ adapterName: adapter.name, health: h });\n } else {\n try {\n const exists = await adapter.targetExists(info.tableName);\n results.push({\n adapterName: adapter.name,\n health: {\n healthy: exists,\n targetName: info.tableName,\n targetExists: exists,\n error: exists ? null : `Target \"${info.tableName}\" does not exist`,\n },\n });\n } catch (e: any) {\n results.push({\n adapterName: adapter.name,\n health: {\n healthy: false,\n targetName: info.tableName,\n targetExists: false,\n error: e?.message ?? String(e),\n },\n });\n }\n }\n }\n\n const allHealthy =\n results.length > 0 && results.every((r) => r.health.healthy);\n\n if (isJsonRequest(req)) {\n sendJson(res, {\n repo: info.name,\n targetName: info.tableName,\n healthy: allHealthy,\n adapters: results.map((r) => ({\n name: r.adapterName,\n ...r.health,\n })),\n });\n return;\n }\n\n const renderAdapterCard = (r: {\n adapterName: string;\n health: SyncHealthResult;\n }) => {\n const { adapterName, health } = r;\n const statusBadge = health.healthy\n ? '<span class=\"badge badge-ok\">Healthy</span>'\n : '<span class=\"badge badge-err\">Unhealthy</span>';\n\n let extraContent = \"\";\n const details = health.details as any;\n if (details?.expected && Array.isArray(details.expected)) {\n const expectedCols = details.expected;\n const actualSet = new Set(details.actual ?? []);\n const extraCols = (details.extra ?? []) as string[];\n const colRows = expectedCols\n .map((c: any) => {\n const status = actualSet.has(c.name)\n ? '<span class=\"badge badge-ok\">OK</span>'\n : '<span class=\"badge badge-err\">MISSING</span>';\n return `<tr><td>${escapeHtml(c.name)}</td><td>${escapeHtml(c.type)}</td><td>${c.nullable ? \"Yes\" : \"No\"}</td><td>${c.isPrimaryKey ? \"✓\" : \"\"}</td><td>${status}</td></tr>`;\n })\n .join(\"\\n\");\n const extraRows = extraCols\n .map(\n (c: string) =>\n `<tr><td>${escapeHtml(c)}</td><td colspan=\"3\" class=\"muted\">not in schema</td><td><span class=\"badge badge-warn\">EXTRA</span></td></tr>`,\n )\n .join(\"\\n\");\n\n extraContent = `<h2>Columns</h2>\n <table>\n <thead><tr><th>Column</th><th>SQL Type</th><th>Nullable</th><th>PK</th><th>Status</th></tr></thead>\n <tbody>${colRows}${extraRows}</tbody>\n </table>`;\n } else if (details?.numberOfDocuments !== undefined) {\n extraContent = `<h2>Index Stats</h2>\n <table>\n <tr><th>Documents Count</th><td>${escapeHtml(details.numberOfDocuments)}</td></tr>\n <tr><th>Indexing in Progress</th><td>${details.isIndexing ? '<span class=\"badge badge-warn\">Yes</span>' : '<span class=\"badge badge-ok\">No</span>'}</td></tr>\n <tr><th>Primary Key</th><td><code>${escapeHtml(details.primaryKey ?? \"default\")}</code></td></tr>\n </table>`;\n }\n\n return `<div class=\"card\" style=\"margin-top:1rem\">\n <h2>Adapter: <code>${escapeHtml(adapterName)}</code> ${statusBadge}</h2>\n <p>Target: <code>${escapeHtml(health.targetName)}</code> ${!health.targetExists ? '<span class=\"badge badge-err\">NOT FOUND</span>' : \"\"}</p>\n ${health.error ? `<p class=\"badge badge-err\" style=\"margin-top:.5rem\">Error: ${escapeHtml(health.error)}</p>` : \"\"}\n ${extraContent}\n </div>`;\n };\n\n const html = page(\n `Health: ${info.name}`,\n lb,\n `<div class=\"card\">\n <p>Overall status for <strong>${escapeHtml(info.name)}</strong>: ${allHealthy ? '<span class=\"badge badge-ok\">Healthy</span>' : '<span class=\"badge badge-err\">Issues detected</span>'}</p>\n </div>\n ${results.map(renderAdapterCard).join(\"\\n\")}`,\n );\n sendHtml(res, html);\n });\n }\n\n // -- Force Sync ---------------------------------------------------------\n if (features.manualSync) {\n router.get(`${basePath}/:repoName/force-sync`, (req: Req, res) => {\n const lb = getLinkBase(req, basePath, region);\n const info = repoInfos.find((r) => r.name === req.params.repoName);\n if (!info) {\n sendHtml(\n res,\n page(\"Not Found\", lb, `<p>Unknown repo: ${escapeHtml(req.params.repoName)}</p>`),\n 404,\n );\n return;\n }\n\n const safeName = escapeHtml(info.name);\n const safeAdapters = info.adapters.map((a) => escapeHtml(a.name)).join(\", \");\n const html = page(\n `Force Sync: ${info.name}`,\n lb,\n `<div class=\"card\">\n <p>This will read <strong>all</strong> documents from the <code>${safeName}</code> Firestore collection\n and upsert them into all active target storage adapters (${safeAdapters}).</p>\n <p class=\"muted\" style=\"margin:.75rem 0\">This may take a while for large collections.</p>\n <form method=\"POST\" action=\"${escapeHtml(lb)}/${encodeURIComponent(info.name)}/force-sync\">\n <label style=\"display:block;margin-bottom:.75rem\">\n <input type=\"checkbox\" name=\"dryRun\" value=\"true\"> Dry run (scan &amp; validate serialization only, no writes)\n </label>\n <button type=\"submit\" class=\"btn btn-primary\">Start Force Sync</button>\n </form>\n </div>`,\n );\n sendHtml(res, html);\n });\n\n router.post(`${basePath}/:repoName/force-sync`, async (req: Req, res) => {\n const lb = getLinkBase(req, basePath, region);\n const info = repoInfos.find((r) => r.name === req.params.repoName);\n if (!info) {\n sendJson(res, { error: `Unknown repo: ${req.params.repoName}` }, 404);\n return;\n }\n\n const collRef = info.repo.ref;\n if (!collRef) {\n sendJson(\n res,\n { error: `No collection reference for \"${info.name}\"` },\n 400,\n );\n return;\n }\n\n if (activeForceSyncs.has(info.name)) {\n if (isJsonRequest(req)) {\n sendJson(\n res,\n {\n error: `Force sync is already running for \"${info.name}\"`,\n repo: info.name,\n },\n 409,\n );\n return;\n }\n sendHtml(\n res,\n page(\n `Force Sync: ${info.name}`,\n lb,\n `<div class=\"card\">\n <p class=\"badge badge-warn\">Already Running</p>\n <p>A force sync is already in progress for <strong>${escapeHtml(info.name)}</strong>. Please wait for it to finish before starting another.</p>\n </div>`,\n ),\n 409,\n );\n return;\n }\n\n activeForceSyncs.add(info.name);\n try {\n const dryRun = parseDryRun(req);\n let scanned = 0;\n let enqueued = 0;\n let handlerErrors = 0;\n const errorSamples: string[] = [];\n const batchSize = 500;\n const orderedRef =\n typeof collRef.orderBy === \"function\"\n ? collRef.orderBy(FieldPath.documentId())\n : collRef;\n const query = orderedRef.limit(batchSize);\n let lastDoc: any = null;\n\n const queueBaselines = new Map<\n SyncQueue,\n {\n adapterName: string;\n flushedEvents: number;\n failedEvents: number;\n lastErrorSeq: number;\n }\n >();\n\n const collectQueueErrors = (): void => {\n for (const [queue, base] of queueBaselines.entries()) {\n if (typeof (queue as any).getStats !== \"function\") continue;\n const stats = queue.getStats();\n for (const entry of stats.recentErrors) {\n if (entry.seq > base.lastErrorSeq) {\n if (errorSamples.length < 5) {\n errorSamples.push(\n `[${base.adapterName}] flush failed (${entry.count} event(s)): ${entry.message}`,\n );\n }\n }\n }\n base.lastErrorSeq = stats.errorSeq;\n }\n };\n\n const computeTotals = (): { synced: number; errors: number } => {\n if (dryRun) {\n return { synced: 0, errors: handlerErrors };\n }\n const statsEntries = Array.from(queueBaselines.entries()).filter(\n ([q]) => typeof (q as any).getStats === \"function\",\n );\n if (statsEntries.length === 0) {\n return { synced: enqueued, errors: handlerErrors };\n }\n let minFlushed = enqueued;\n let totalFailed = 0;\n for (const [queue, base] of statsEntries) {\n const stats = queue.getStats();\n const deltaFlushed = Math.max(\n 0,\n stats.flushedEvents - base.flushedEvents,\n );\n const deltaFailed = Math.max(\n 0,\n stats.failedEvents - base.failedEvents,\n );\n if (deltaFlushed < minFlushed) minFlushed = deltaFlushed;\n totalFailed += deltaFailed;\n }\n return {\n synced: minFlushed,\n errors: handlerErrors + totalFailed,\n };\n };\n\n const effectiveExclude = info.historyShadowKey\n ? Array.from(\n new Set([\n ...(info.repoCfg?.exclude ?? []),\n info.historyShadowKey,\n ]),\n )\n : info.repoCfg?.exclude;\n\n try {\n if (!dryRun) {\n // Drain any pre-existing buffered events before snapshotting baselines\n // so prior traffic is not attributed to this force-sync run.\n const preExisting = getActiveQueuesForRepo(info, queues);\n for (const { adapterName, queue } of preExisting) {\n await queue.flush();\n if (typeof (queue as any).getStats === \"function\") {\n const s = queue.getStats();\n queueBaselines.set(queue, {\n adapterName,\n flushedEvents: s.flushedEvents,\n failedEvents: s.failedEvents,\n lastErrorSeq: s.errorSeq,\n });\n } else {\n queueBaselines.set(queue, {\n adapterName,\n flushedEvents: 0,\n failedEvents: 0,\n lastErrorSeq: 0,\n });\n }\n }\n }\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const paginatedQuery = lastDoc ? query.startAfter(lastDoc) : query;\n let pageReadStartedAt = Date.now();\n const snapshot = await getPageWithRetry<{\n empty: boolean;\n docs: any[];\n }>(() => {\n pageReadStartedAt = Date.now();\n return paginatedQuery.get();\n });\n if (snapshot.empty || snapshot.docs.length === 0) break;\n\n for (const doc of snapshot.docs) {\n scanned++;\n let docId = String(doc.id ?? \"unknown\");\n try {\n const data = doc.data() as Record<string, unknown>;\n docId = String(data?.[info.documentKey] ?? doc.id);\n const serialized = serializeDocument(data, {\n exclude: effectiveExclude,\n columnMap: info.repoCfg?.columnMap,\n flat: info.repoCfg?.flat,\n transformDoc: info.repoCfg?.transformDoc,\n });\n\n if (!dryRun) {\n await handleMessage({\n operation: \"UPSERT\",\n repoName: info.name,\n docId,\n data: serialized,\n timestamp: new Date(pageReadStartedAt).toISOString(),\n version: pageReadStartedAt,\n });\n enqueued++;\n }\n } catch (e: any) {\n handlerErrors++;\n const msg = e?.message ?? String(e);\n console.error(\n `[ForceSync:${info.name}] doc=${docId} failed:`,\n e,\n );\n if (errorSamples.length < 5) {\n errorSamples.push(`${docId}: ${msg}`);\n }\n }\n }\n\n // Apply backpressure: flush all active adapter queues at the end of\n // each page before reading the next page from Firestore.\n if (!dryRun) {\n const activeQueues = getActiveQueuesForRepo(info, queues);\n for (const { adapterName, queue } of activeQueues) {\n if (!queueBaselines.has(queue)) {\n queueBaselines.set(queue, {\n adapterName,\n flushedEvents: 0,\n failedEvents: 0,\n lastErrorSeq: 0,\n });\n }\n await queue.flush();\n }\n collectQueueErrors();\n }\n\n lastDoc = snapshot.docs[snapshot.docs.length - 1];\n if (snapshot.docs.length < batchSize) break;\n }\n } catch (e: any) {\n if (!dryRun) {\n for (const { adapterName, queue } of getActiveQueuesForRepo(\n info,\n queues,\n )) {\n if (!queueBaselines.has(queue)) {\n queueBaselines.set(queue, {\n adapterName,\n flushedEvents: 0,\n failedEvents: 0,\n lastErrorSeq: 0,\n });\n }\n }\n collectQueueErrors();\n }\n const { synced, errors } = computeTotals();\n const errMsg = e?.message ?? String(e);\n if (isJsonRequest(req)) {\n sendJson(\n res,\n {\n error: errMsg,\n ...(dryRun && { dryRun: true }),\n scanned,\n synced,\n errors,\n ...(errorSamples.length > 0 && { errorSamples }),\n },\n 500,\n );\n return;\n }\n sendHtml(\n res,\n page(\n `Force Sync: ${info.name}`,\n lb,\n `<div class=\"card\">\n <p class=\"badge badge-err\">Error: ${escapeHtml(errMsg)}</p>\n <p>Scanned ${scanned} docs, synced ${synced} docs before failure (${errors} errors).</p>\n </div>`,\n ),\n 500,\n );\n return;\n }\n\n const { synced, errors } = computeTotals();\n\n if (isJsonRequest(req)) {\n sendJson(res, {\n ...(dryRun && { dryRun: true }),\n repo: info.name,\n table: info.tableName,\n scanned,\n synced,\n errors,\n ...(errorSamples.length > 0 && { errorSamples }),\n });\n return;\n }\n\n const errorBlock =\n errorSamples.length > 0\n ? `<details style=\"margin-top:1rem\"><summary>First ${errorSamples.length} error(s)</summary>\n <pre style=\"white-space:pre-wrap\">${errorSamples\n .map((s) => escapeHtml(s))\n .join(\"\\n\\n\")}</pre></details>`\n : \"\";\n\n const safeAdapters = info.adapters\n .map((a) => escapeHtml(a.name))\n .join(\", \");\n\n const statusBadge = dryRun\n ? `<p class=\"badge ${errors > 0 ? \"badge-warn\" : \"badge-ok\"}\">${errors > 0 ? \"Dry run completed with errors\" : \"Dry run complete\"}</p>`\n : `<p class=\"badge ${errors > 0 ? \"badge-warn\" : \"badge-ok\"}\">${errors > 0 ? \"Completed with errors\" : \"Complete\"}</p>`;\n\n const summaryLine = dryRun\n ? `<p>Dry run scanned <strong>${scanned}</strong> documents (0 synced, no writes performed).</p>`\n : `<p>Scanned <strong>${scanned}</strong> documents, synced <strong>${synced}</strong> documents to targets (${safeAdapters}).</p>`;\n\n const html = page(\n `Force Sync: ${info.name}`,\n lb,\n `<div class=\"card\">\n ${statusBadge}\n ${summaryLine}\n ${errors > 0 ? `<p class=\"badge badge-warn\">${errors} error(s)</p>` : \"\"}\n ${errorBlock}\n </div>`,\n );\n sendHtml(res, html);\n } finally {\n activeForceSyncs.delete(info.name);\n }\n });\n }\n\n // -- Config Check -------------------------------------------------------\n if (features.configCheck) {\n router.get(`${basePath}/config-check`, async (req, res) => {\n const lb = getLinkBase(req, basePath, region);\n const project =\n process.env[\"GCLOUD_PROJECT\"] ??\n process.env[\"GOOGLE_CLOUD_PROJECT\"] ??\n process.env[\"GCP_PROJECT\"] ??\n \"unknown\";\n const consoleBase = `https://console.cloud.google.com`;\n const tPrefix = topicPrefix ?? \"firestore-sync\";\n\n interface CheckResult {\n name: string;\n category: \"bigquery\" | \"meilisearch\" | \"pubsub\" | \"firestore\" | \"storage\";\n status: \"ok\" | \"error\" | \"warn\";\n message: string;\n fix?: { gcloud?: string; console?: string; hint?: string };\n }\n\n const checks: CheckResult[] = [];\n\n // Check each configured adapter\n for (const adapter of adapters) {\n if (adapter.name === \"bigquery\") {\n try {\n await adapter.targetExists(\"__nonexistent_health_check__\");\n checks.push({\n name: \"BigQuery API\",\n category: \"bigquery\",\n status: \"ok\",\n message: \"BigQuery API is reachable\",\n });\n } catch (e: any) {\n const msg = e?.message ?? String(e);\n const msgLower = msg.toLowerCase();\n const isApiDisabled =\n msgLower.includes(\"disabled\") ||\n msgLower.includes(\"has not been used\") ||\n msgLower.includes(\"accessnotconfigured\");\n const isPermission =\n msgLower.includes(\"permission\") ||\n msg.includes(\"403\") ||\n msgLower.includes(\"access denied\");\n const isProjectNotFound =\n msgLower.includes(\"project\") && msgLower.includes(\"not found\");\n const isNotFound =\n msgLower.includes(\"not found\") || msg.includes(\"404\");\n\n if (isApiDisabled) {\n checks.push({\n name: \"BigQuery API\",\n category: \"bigquery\",\n status: \"error\",\n message: \"BigQuery API is not enabled\",\n fix: {\n gcloud: `gcloud services enable bigquery.googleapis.com --project=${project}`,\n console: `${consoleBase}/apis/library/bigquery.googleapis.com?project=${project}`,\n },\n });\n } else if (isProjectNotFound) {\n checks.push({\n name: \"BigQuery Project\",\n category: \"bigquery\",\n status: \"error\",\n message: msg,\n fix: {\n hint:\n \"The GCP project does not exist or the credentials don't have access to it.\",\n console: `${consoleBase}/home/dashboard`,\n },\n });\n } else if (isPermission) {\n checks.push({\n name: \"BigQuery API\",\n category: \"bigquery\",\n status: \"error\",\n message: `Permission denied: ${msg}`,\n fix: {\n hint: \"Grant the service account BigQuery Data Editor + BigQuery Job User roles\",\n console: `${consoleBase}/iam-admin/iam?project=${project}`,\n },\n });\n } else if (isNotFound) {\n checks.push({\n name: \"BigQuery Dataset\",\n category: \"bigquery\",\n status: \"error\",\n message: `Dataset not found: ${msg}`,\n fix: {\n hint: \"Create the dataset first\",\n gcloud: `bq mk --dataset ${project}:YOUR_DATASET_ID`,\n console: `${consoleBase}/bigquery?project=${project}`,\n },\n });\n } else {\n checks.push({\n name: \"BigQuery API\",\n category: \"bigquery\",\n status: \"ok\",\n message:\n \"BigQuery API is reachable (table lookup returned expected error)\",\n });\n }\n }\n } else if (adapter.name === \"meilisearch\" || typeof (adapter as any).checkConnection === \"function\") {\n try {\n const conn = typeof (adapter as any).checkConnection === \"function\"\n ? await (adapter as any).checkConnection()\n : { healthy: await adapter.targetExists(\"__nonexistent__\") };\n checks.push({\n name: \"Meilisearch API\",\n category: \"meilisearch\",\n status: conn.healthy ? \"ok\" : \"error\",\n message: conn.healthy\n ? `Meilisearch is reachable${conn.version ? ` (v${conn.version})` : \"\"}`\n : `Meilisearch connection error: ${conn.error ?? \"unknown\"}`,\n ...(conn.error && {\n fix: {\n hint: \"Ensure Meilisearch is running and host/apiKey options are valid.\",\n },\n }),\n });\n } catch (e: any) {\n checks.push({\n name: \"Meilisearch API\",\n category: \"meilisearch\",\n status: \"error\",\n message: `Meilisearch error: ${e?.message ?? String(e)}`,\n });\n }\n }\n }\n\n // Per-repo target existence\n for (const info of repoInfos) {\n for (const adapter of info.adapters) {\n const category = adapter.name === \"bigquery\" ? \"bigquery\" : adapter.name === \"meilisearch\" ? \"meilisearch\" : \"storage\";\n try {\n const exists = await adapter.targetExists(info.tableName);\n checks.push({\n name: `[${adapter.name}] Target: ${info.tableName}`,\n category,\n status: exists ? \"ok\" : \"warn\",\n message: exists\n ? `Target \\`${info.tableName}\\` exists`\n : `Target \\`${info.tableName}\\` does not exist yet`,\n ...(!exists && {\n fix: {\n hint: `Target will be auto-created on first sync if autoMigrate is enabled.`,\n },\n }),\n });\n } catch (e: any) {\n checks.push({\n name: `[${adapter.name}] Target: ${info.tableName}`,\n category,\n status: \"error\",\n message: e?.message ?? String(e),\n });\n }\n }\n }\n\n // --- Pub/Sub checks ---\n if (pubsub) {\n for (const info of repoInfos) {\n const topicName = `${tPrefix}-${info.name}`;\n try {\n const topic = (pubsub as any).topic(topicName);\n if (typeof topic.exists === \"function\") {\n const [exists] = await topic.exists();\n checks.push({\n name: `Topic: ${topicName}`,\n category: \"pubsub\",\n status: exists ? \"ok\" : \"error\",\n message: exists\n ? `Topic \\`${topicName}\\` exists`\n : `Topic \\`${topicName}\\` does not exist`,\n ...(!exists && {\n fix: {\n gcloud: `gcloud pubsub topics create ${topicName} --project=${project}`,\n console: `${consoleBase}/cloudpubsub/topic/list?project=${project}`,\n },\n }),\n });\n } else {\n checks.push({\n name: `Topic: ${topicName}`,\n category: \"pubsub\",\n status: \"warn\",\n message:\n \"Cannot verify topic existence (PubSub client doesn't expose .exists())\",\n fix: {\n gcloud: `gcloud pubsub topics create ${topicName} --project=${project}`,\n console: `${consoleBase}/cloudpubsub/topic/list?project=${project}`,\n },\n });\n }\n } catch (e: any) {\n const msg = e?.message ?? String(e);\n const isApiDisabled =\n msg.includes(\"disabled\") || msg.includes(\"has not been used\");\n checks.push({\n name: isApiDisabled ? \"Pub/Sub API\" : `Topic: ${topicName}`,\n category: \"pubsub\",\n status: \"error\",\n message: isApiDisabled ? \"Pub/Sub API is not enabled\" : msg,\n fix: isApiDisabled\n ? {\n gcloud: `gcloud services enable pubsub.googleapis.com --project=${project}`,\n console: `${consoleBase}/apis/library/pubsub.googleapis.com?project=${project}`,\n }\n : {\n gcloud: `gcloud pubsub topics create ${topicName} --project=${project}`,\n console: `${consoleBase}/cloudpubsub/topic/list?project=${project}`,\n },\n });\n if (isApiDisabled) break;\n }\n }\n } else {\n checks.push({\n name: \"Pub/Sub Client\",\n category: \"pubsub\",\n status: \"warn\",\n message: \"PubSub client not available for config check\",\n });\n }\n\n // --- JSON response ---\n if (isJsonRequest(req)) {\n const allOk = checks.every((c) => c.status === \"ok\");\n sendJson(res, { project, healthy: allOk, checks });\n return;\n }\n\n // --- HTML response ---\n const statusIcon = (s: string) =>\n s === \"ok\"\n ? '<span class=\"badge badge-ok\">OK</span>'\n : s === \"warn\"\n ? '<span class=\"badge badge-warn\">WARN</span>'\n : '<span class=\"badge badge-err\">ERROR</span>';\n\n const grouped = {\n bigquery: checks.filter((c) => c.category === \"bigquery\"),\n meilisearch: checks.filter((c) => c.category === \"meilisearch\"),\n pubsub: checks.filter((c) => c.category === \"pubsub\"),\n firestore: checks.filter((c) => c.category === \"firestore\"),\n storage: checks.filter((c) => c.category === \"storage\"),\n };\n\n const renderSection = (title: string, items: CheckResult[]) => {\n if (items.length === 0) return \"\";\n const rows = items\n .map((c) => {\n let fixHtml = \"\";\n if (c.fix) {\n const parts: string[] = [];\n if (c.fix.hint) parts.push(`<p class=\"muted\">${escapeHtml(c.fix.hint)}</p>`);\n if (c.fix.gcloud) parts.push(`<pre>$ ${escapeHtml(c.fix.gcloud)}</pre>`);\n if (c.fix.console)\n parts.push(\n `<p><a href=\"${escapeHtml(c.fix.console)}\" target=\"_blank\">Open GCP Console →</a></p>`,\n );\n fixHtml = `<div style=\"margin-top:.5rem\">${parts.join(\"\")}</div>`;\n }\n return `<tr>\n <td>${statusIcon(c.status)}</td>\n <td><strong>${escapeHtml(c.name)}</strong><br><span class=\"muted\">${escapeHtml(c.message)}</span>${fixHtml}</td>\n </tr>`;\n })\n .join(\"\\n\");\n return `<h2>${escapeHtml(title)}</h2>\n <table><thead><tr><th style=\"width:80px\">Status</th><th>Check</th></tr></thead>\n <tbody>${rows}</tbody></table>`;\n };\n\n const allOk = checks.every((c) => c.status === \"ok\");\n const overallBadge = allOk\n ? '<span class=\"badge badge-ok\">All checks passed</span>'\n : '<span class=\"badge badge-warn\">Some issues found</span>';\n\n const html = page(\n \"Config Check\",\n lb,\n `<div class=\"card\">\n <p>Project: <code>${escapeHtml(project)}</code> ${overallBadge}</p>\n ${renderSection(\"BigQuery\", grouped.bigquery)}\n ${renderSection(\"Meilisearch\", grouped.meilisearch)}\n ${renderSection(\"Pub/Sub\", grouped.pubsub)}\n ${renderSection(\"Other Targets\", grouped.storage)}\n ${renderSection(\"Firestore\", grouped.firestore)}\n </div>`,\n );\n sendHtml(res, html);\n });\n }\n\n // -- Request handler ----------------------------------------------------\n return async (req: any, res: any): Promise<void> => {\n await router.handle(req, res);\n };\n}\n\n","/**\n * Minimal zero-dependency HTTP router for Firebase Functions.\n * Compatible with any Express-like (req, res) handler.\n *\n * Supports:\n * - Named path parameters (e.g. \"/repos/:name/:id\")\n * - GET, POST, DELETE methods\n * - Global middleware (before each route)\n * - 404 / error fallbacks\n *\n * @example\n * ```typescript\n * import { MiniRouter } from \"@lpdjs/firestore-repo-service/servers/admin\";\n *\n * // Create router\n * const router = new MiniRouter();\n *\n * // Add global middleware (executed before every route)\n * router.use(async (req, res, next) => {\n * console.log(`${req.method} ${req.url}`);\n * await next();\n * });\n *\n * // Auth middleware\n * router.use((req, res, next) => {\n * if (!req.headers?.authorization) {\n * res.status(401).send(\"Unauthorized\");\n * return;\n * }\n * next();\n * });\n *\n * // Define routes with path parameters\n * router.get(\"/users\", async (req, res) => {\n * res.json({ users: await getAllUsers() });\n * });\n *\n * router.get(\"/users/:id\", async (req, res) => {\n * const user = await getUser(req.params.id); // Access path params\n * if (!user) {\n * res.status(404).send(\"User not found\");\n * return;\n * }\n * res.json(user);\n * });\n *\n * router.post(\"/users\", async (req, res) => {\n * const user = await createUser(req.body);\n * res.status(201).json(user);\n * });\n *\n * router.delete(\"/users/:id\", async (req, res) => {\n * await deleteUser(req.params.id);\n * res.status(204).end();\n * });\n *\n * // Custom 404 handler\n * router.onNotFound((req, res) => {\n * res.status(404).json({ error: \"Route not found\", path: req.url });\n * });\n *\n * // Custom error handler\n * router.onError((err, req, res) => {\n * console.error(\"Error:\", err);\n * res.status(500).json({ error: \"Internal server error\" });\n * });\n *\n * // Use with Firebase Functions\n * export const api = onRequest(async (req, res) => {\n * await router.handle(req, res);\n * });\n * ```\n */\n\nexport type AnyReq = {\n method?: string;\n url?: string;\n /** Express originalUrl — preserved before any router stripping, contains the full path including the Firebase Functions prefix */\n originalUrl?: string;\n path?: string;\n headers?: Record<string, string | string[] | undefined>;\n body?: unknown;\n query?: Record<string, string | string[] | undefined>;\n};\n\nexport type AnyRes = {\n status: (code: number) => AnyRes;\n set: (key: string, value: string) => AnyRes;\n send: (body: string) => void;\n json: (body: unknown) => void;\n end: () => void;\n};\n\nexport type RouteParams = Record<string, string>;\n\nexport type RouteHandler = (\n req: AnyReq & { params: RouteParams },\n res: AnyRes,\n) => void | Promise<void>;\n\nexport type Middleware = (\n req: AnyReq & { params: RouteParams },\n res: AnyRes,\n next: () => void | Promise<void>,\n) => void | Promise<void>;\n\n// ---------------------------------------------------------------------------\n// Route matching\n// ---------------------------------------------------------------------------\n\ninterface CompiledRoute {\n method: string;\n pattern: RegExp;\n paramNames: string[];\n handler: RouteHandler;\n}\n\nfunction compilePath(path: string): { pattern: RegExp; paramNames: string[] } {\n const paramNames: string[] = [];\n const src = path\n .replace(/[.*+?^${}()|[\\]\\\\]/g, (c) => (c === \":\" ? c : `\\\\${c}`))\n .replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, (_match, name: string) => {\n paramNames.push(name);\n return \"([^/]+)\";\n });\n\n return { pattern: new RegExp(`^${src}$`), paramNames };\n}\n\nfunction extractPath(req: AnyReq): string {\n const raw = req.path ?? req.url ?? \"/\";\n const idx = raw.indexOf(\"?\");\n return idx === -1 ? raw : raw.slice(0, idx);\n}\n\n// ---------------------------------------------------------------------------\n// Router class\n// ---------------------------------------------------------------------------\n\nexport class MiniRouter {\n private routes: CompiledRoute[] = [];\n private middlewares: Middleware[] = [];\n private notFoundHandler: RouteHandler = (_req, res) => {\n res.status(404).send(\"Not Found\");\n };\n private errorHandler: (err: unknown, req: AnyReq, res: AnyRes) => void = (\n err,\n _req,\n res,\n ) => {\n console.error(\"[MiniRouter]\", err);\n res.status(500).send(\"Internal Server Error\");\n };\n\n // ── Route registration ────────────────────────────────────────────────────\n\n use(middleware: Middleware): this {\n this.middlewares.push(middleware);\n return this;\n }\n\n get(path: string, handler: RouteHandler): this {\n return this.addRoute(\"GET\", path, handler);\n }\n\n post(path: string, handler: RouteHandler): this {\n return this.addRoute(\"POST\", path, handler);\n }\n\n put(path: string, handler: RouteHandler): this {\n return this.addRoute(\"PUT\", path, handler);\n }\n\n patch(path: string, handler: RouteHandler): this {\n return this.addRoute(\"PATCH\", path, handler);\n }\n\n delete(path: string, handler: RouteHandler): this {\n return this.addRoute(\"DELETE\", path, handler);\n }\n\n onNotFound(handler: RouteHandler): this {\n this.notFoundHandler = handler;\n return this;\n }\n\n onError(handler: (err: unknown, req: AnyReq, res: AnyRes) => void): this {\n this.errorHandler = handler;\n return this;\n }\n\n private addRoute(method: string, path: string, handler: RouteHandler): this {\n const { pattern, paramNames } = compilePath(path);\n this.routes.push({\n method: method.toUpperCase(),\n pattern,\n paramNames,\n handler,\n });\n return this;\n }\n\n // ── Dispatch ──────────────────────────────────────────────────────────────\n\n async handle(req: AnyReq, res: AnyRes): Promise<void> {\n const method = (req.method ?? \"GET\").toUpperCase();\n const path = extractPath(req);\n\n // Find matching route\n let matchedRoute: CompiledRoute | null = null;\n let params: RouteParams = {};\n\n for (const route of this.routes) {\n if (route.method !== method) continue;\n const m = path.match(route.pattern);\n if (m) {\n matchedRoute = route;\n params = {};\n route.paramNames.forEach((name, i) => {\n params[name] = decodeURIComponent(m[i + 1] ?? \"\");\n });\n break;\n }\n }\n\n const enrichedReq = Object.assign(req, { params });\n\n // Run middleware chain → then handler\n const handler = matchedRoute ? matchedRoute.handler : this.notFoundHandler;\n\n try {\n await this.runMiddlewareChain(enrichedReq, res, handler);\n } catch (err) {\n this.errorHandler(err, req, res);\n }\n }\n\n private async runMiddlewareChain(\n req: AnyReq & { params: RouteParams },\n res: AnyRes,\n finalHandler: RouteHandler,\n ): Promise<void> {\n let index = 0;\n\n const next = async (): Promise<void> => {\n if (index < this.middlewares.length) {\n const mw = this.middlewares[index++]!;\n await mw(req, res, next);\n } else {\n await finalHandler(req, res);\n }\n };\n\n await next();\n }\n}\n","/**\n * Compute the URL prefix used to build absolute paths from inside a\n * Firebase HTTPS function. Handles three deployment shapes uniformly:\n *\n * 1. **Firebase emulator** (`FUNCTIONS_EMULATOR=true`) — exposes functions at\n * `http://localhost:5001/{project}/{region}/{functionTarget}/...`. The\n * handler receives `req.url` *without* this prefix, so we rebuild it from\n * `GCLOUD_PROJECT`, `FUNCTION_REGION`, `FUNCTION_TARGET`.\n *\n * 2. **Cloud Functions v2 default URL** (`*.cloudfunctions.net/{name}`) —\n * Cloud Run terminates routing at the service name, so links must include\n * the `K_SERVICE` prefix. Detected via the `host` header containing\n * `cloudfunctions.net`.\n *\n * 3. **Custom domain / Hosting rewrite** — the proxy strips the prefix\n * before reaching the handler, so links are relative to the configured\n * `staticBasePath`.\n *\n * @param req The incoming request (needs `headers.host` / `hostname`).\n * @param staticBasePath The user-configured base path (e.g. `\"/api\"`).\n * @param region Explicit deployment region (e.g. `\"europe-west1\"`).\n * Used **only** in the emulator branch to build the\n * `/{project}/{region}/{target}` prefix; when omitted it\n * falls back to `FUNCTION_REGION` then `\"us-central1\"`.\n * Pass it (e.g. from `httpsOptions.region`) whenever the\n * function is deployed outside `us-central1`, since the\n * emulator does not reliably expose the region via env.\n * @returns A path prefix (no trailing slash) suitable for prepending to\n * `req.url` to build a same-function absolute URL.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getLinkBase(\n req: any,\n staticBasePath: string,\n region?: string,\n): string {\n const base = staticBasePath === \"/\" ? \"\" : staticBasePath.replace(/\\/$/, \"\");\n\n if (process.env[\"FUNCTIONS_EMULATOR\"] === \"true\") {\n const project =\n process.env[\"GCLOUD_PROJECT\"] ??\n process.env[\"GOOGLE_CLOUD_PROJECT\"] ??\n \"demo-project\";\n const resolvedRegion =\n region ?? process.env[\"FUNCTION_REGION\"] ?? \"us-central1\";\n // FUNCTION_TARGET uses dots (e.g. \"sync.functions.adminsync\") but the\n // emulator URL uses hyphens (\"sync-functions-adminsync\").\n const target = (process.env[\"FUNCTION_TARGET\"] ?? \"\").replace(/\\./g, \"-\");\n return `/${project}/${resolvedRegion}/${target}${base}`;\n }\n\n // Cloud Functions v2: K_SERVICE = function name = URL path prefix.\n // Only add it when accessed via cloudfunctions.net (not custom domains).\n // Cloud Run (Gen 2) lowercases service names, but K_SERVICE may still\n // carry the original mixed-case export name — normalise to lowercase\n // so that generated links match the canonical URL.\n const service = process.env[\"K_SERVICE\"];\n const host: string =\n req?.hostname ?? req?.headers?.[\"host\"] ?? \"\";\n if (service && typeof host === \"string\" && host.includes(\"cloudfunctions.net\")) {\n return `/${service.toLowerCase()}${base}`;\n }\n\n return base;\n}\n\n/**\n * Normalise the `region` field of a Firebase `HttpsOptions` (which may be a\n * single region, an array, a CEL `Expression`, or a `ResetValue`) into a single\n * concrete region string for {@link getLinkBase}. Returns `undefined` for\n * anything that is not a plain string at config time.\n */\nexport function resolveRegion(region: unknown): string | undefined {\n if (typeof region === \"string\") return region;\n if (Array.isArray(region)) {\n const first = region[0];\n return typeof first === \"string\" ? first : undefined;\n }\n return undefined;\n}\n","/**\n * Firebase Auth helper for the admin & CRUD servers.\n *\n * Returns an {@link AuthExtension} ready to plug into `servers.admin()` or\n * `servers.crud()`. Supports two transport modes:\n *\n * - **`cookie`** — session cookie pattern (default for admin UIs). Mounts\n * `/__login`, `/__session`, `/__logout` routes; the page lets the user sign\n * in client-side with the Firebase JS SDK and exchanges the resulting ID\n * token for an HttpOnly session cookie via Firebase Admin SDK.\n * - **`bearer`** — verifies `Authorization: Bearer <idToken>` on every request\n * (default for REST APIs). No login routes mounted.\n * - **`both`** — accept either cookie or bearer.\n *\n * The helper is **agnostic** about authorization: pass an `allow` callback\n * returning whatever role/context shape you need. The result is exposed as\n * `req.user.context` to downstream middlewares and route handlers.\n *\n * @example Admin (cookie + role trio)\n * ```ts\n * import { firebaseAuth } from \"@lpdjs/firestore-repo-service/servers/auth\";\n * import { getAuth } from \"firebase-admin/auth\";\n *\n * servers.admin({\n * auth: firebaseAuth({\n * getAuth,\n * mode: \"cookie\",\n * apiKey: process.env.FIREBASE_WEB_API_KEY!,\n * authDomain: process.env.FIREBASE_AUTH_DOMAIN!,\n * allow: ({ email, claims }) => {\n * if (claims.superAdmin) return { role: \"superAdmin\" };\n * if (email?.endsWith(\"@solarpush.io\")) return { role: \"admin\" };\n * if (email) return { role: \"viewer\" };\n * return null;\n * },\n * }),\n * repos: { ... },\n * });\n * ```\n *\n * @example CRUD (bearer + business rules per repo)\n * ```ts\n * servers.crud({\n * auth: firebaseAuth({ getAuth, mode: \"bearer\", allow: (u) => u }),\n * repos: {\n * comments: {\n * repo: repos.comments,\n * rules: {\n * list: () => true,\n * get: ({ user, doc }) => doc.public || doc.authorId === user.uid,\n * create: ({ user }) => !!user.uid,\n * update: ({ user, doc }) => user.uid === doc.authorId,\n * delete: ({ user, doc }) => user.claims.role === \"moderator\",\n * },\n * },\n * },\n * });\n * ```\n */\n\nimport type { AnyReq, Middleware, RouteHandler } from \"../admin/router\";\nimport { getLinkBase } from \"../utils/link-base\";\nimport { renderLoginPage } from \"./login-page\";\nimport {\n createLogoutHandler,\n createSessionHandler,\n parseCookies,\n SESSION_COOKIE_DEFAULT,\n} from \"./session\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal Firebase Admin Auth surface needed by this helper.\n * Avoids a hard import of `firebase-admin/auth` so the package stays\n * decoupled from a specific firebase-admin version.\n */\nexport interface FirebaseAdminAuthLike {\n verifyIdToken(\n idToken: string,\n checkRevoked?: boolean,\n ): Promise<DecodedIdTokenLike>;\n verifySessionCookie(\n sessionCookie: string,\n checkRevoked?: boolean,\n ): Promise<DecodedIdTokenLike>;\n createSessionCookie(\n idToken: string,\n sessionCookieOptions: { expiresIn: number },\n ): Promise<string>;\n revokeRefreshTokens(uid: string): Promise<void>;\n}\n\nexport interface DecodedIdTokenLike {\n uid: string;\n email?: string;\n email_verified?: boolean;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [claim: string]: any;\n}\n\n/** Identity attached to every authenticated request as `req.user`. */\nexport interface AuthUser<TContext = unknown> {\n uid: string;\n email: string | null;\n emailVerified: boolean;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n claims: Record<string, any>;\n /** Result of the user-supplied `allow()` callback. */\n context: TContext;\n}\n\n/** A route descriptor mounted by `firebaseAuth` before the protected chain. */\nexport interface AuthRoute {\n method: \"GET\" | \"POST\";\n path: string;\n handler: RouteHandler;\n}\n\n/**\n * Returned by {@link firebaseAuth}. Servers detect this shape (vs.\n * `BasicAuthConfig` / raw `Middleware`) and mount the routes before pushing\n * the middleware onto the chain.\n */\nexport interface AuthExtension {\n readonly __authExtension: true;\n middleware: Middleware;\n /** Auxiliary routes (login page, session, logout). Empty in pure bearer mode. */\n routes: AuthRoute[];\n /** Path used to redirect unauthenticated browser requests. */\n loginPath: string;\n}\n\nexport type FirebaseAuthMode = \"cookie\" | \"bearer\" | \"both\";\n\n/** Provider configuration for the bundled login page. */\nexport interface FirebaseAuthLoginPageConfig {\n /** Page title. Default: \"Admin sign-in\". */\n title?: string;\n /**\n * Providers shown on the login page.\n * Default: `[\"password\", \"google\"]`.\n */\n providers?: (\"password\" | \"google\")[];\n}\n\nexport interface FirebaseAuthConfig<TContext = unknown> {\n /** Lazy getter for the Firebase Admin Auth instance. */\n getAuth: () => FirebaseAdminAuthLike;\n\n /** Transport mode. Default: `\"cookie\"`. */\n mode?: FirebaseAuthMode;\n\n /**\n * Authorization callback. Receives the verified token claims and returns:\n * - a context object → request is allowed, exposed as `req.user.context`,\n * - `null` → request is rejected (401 / redirect to login).\n *\n * If omitted, the default policy allows any authenticated user with\n * `context = null`.\n */\n allow?: (\n user: Omit<AuthUser, \"context\">,\n ) => TContext | null | Promise<TContext | null>;\n\n // ── Cookie mode options ────────────────────────────────────────────────\n /**\n * Whether to mount the bundled `/__login`, `/__session`, `/__logout`\n * routes. Default: `true` for `cookie`/`both`, `false` for `bearer`.\n */\n loginPage?: boolean | FirebaseAuthLoginPageConfig;\n\n /**\n * Firebase Web API key required by the JS SDK on the login page.\n * Mandatory when `loginPage` is enabled. Find it in your Firebase Console\n * under Project Settings → General → Web app config.\n */\n apiKey?: string;\n\n /**\n * Firebase Auth domain (e.g. `my-project.firebaseapp.com`).\n * Mandatory when `loginPage` is enabled.\n */\n authDomain?: string;\n\n /** Cookie name. Default: `__admin_session`. */\n cookieName?: string;\n\n /** Session cookie TTL in days. Default: `5` (Firebase max is 14). */\n sessionTtlDays?: number;\n\n /**\n * Cookie `Secure` flag. Default: `true`. Set to `false` only for local\n * development over HTTP.\n */\n secureCookie?: boolean;\n\n /** Cookie `SameSite`. Default: `\"Lax\"`. */\n sameSite?: \"Strict\" | \"Lax\" | \"None\";\n\n /**\n * Deployment region (e.g. `\"europe-west1\"`). Used to build the login page's\n * same-function URLs **under the Firebase emulator**, which does not reliably\n * expose the region via env — without it the emulator prefix falls back to\n * `us-central1`, so the session POST 404s when deployed elsewhere. Has no\n * effect in production (the prefix is derived from the request there). When\n * created via `servers.admin/crud()` this defaults to `httpsOptions.region`.\n */\n region?: string;\n\n /**\n * Firebase Auth emulator host (e.g. `127.0.0.1:9099`). When set, the login\n * page's client SDK is pointed at the emulator via `connectAuthEmulator`,\n * matching the Admin SDK (which already targets the emulator when\n * `FIREBASE_AUTH_EMULATOR_HOST` is set). Defaults to that env var, so local\n * `firebase emulators:start` runs work out of the box; pass `\"\"` to force it\n * off.\n */\n authEmulatorHost?: string;\n\n /**\n * Enable the built-in CSRF defense: state-changing requests\n * (`POST`/`PUT`/`PATCH`/`DELETE`) authenticated by **session cookie** must\n * carry an `Origin`/`Referer` header matching the request host. Bearer\n * requests are exempt (a browser never auto-attaches an `Authorization`\n * header, so they are not CSRF-able).\n *\n * **Defaults to `true` only when `sameSite: \"None\"`** (and not in `bearer`\n * mode). With the default `Lax`/`Strict` cookie the browser already blocks\n * the session cookie on cross-site mutations, so the check is unnecessary\n * and is left off to avoid false positives behind proxies whose `Host`\n * differs from the public origin (e.g. Cloud Functions v2 / Cloud Run).\n * Set to `true` to force the check on regardless of `sameSite`, or `false`\n * to disable it even with `sameSite: \"None\"` (only if you implement your\n * own CSRF protection upstream).\n */\n csrfProtection?: boolean;\n\n /**\n * Behaviour when authentication fails or `allow()` returns `null`.\n * - `\"redirect\"` (default in cookie mode) → 302 to the login page,\n * - `\"401\"` (default in bearer mode) → JSON 401 response.\n */\n onUnauthenticated?: \"redirect\" | \"401\";\n\n /**\n * Routes that should bypass the auth middleware (matched against the path\n * after the basePath stripping). The auxiliary login routes are always\n * public regardless of this option.\n */\n publicPaths?: (string | RegExp)[];\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction defaultLoginPage(mode: FirebaseAuthMode): boolean {\n return mode === \"cookie\" || mode === \"both\";\n}\n\nfunction defaultUnauth(mode: FirebaseAuthMode): \"redirect\" | \"401\" {\n return mode === \"bearer\" ? \"401\" : \"redirect\";\n}\n\nfunction pathOf(req: AnyReq): string {\n const raw = req.path ?? req.url ?? \"/\";\n const idx = raw.indexOf(\"?\");\n return idx === -1 ? raw : raw.slice(0, idx);\n}\n\nfunction queryAction(req: AnyReq): string | null {\n const q = (req as { query?: Record<string, unknown> }).query;\n if (q && typeof q.__action === \"string\") return q.__action;\n // Fallback: parse from URL when query parsing isn't done by the runtime.\n const url = req.url ?? \"\";\n const idx = url.indexOf(\"?\");\n if (idx === -1) return null;\n const params = new URLSearchParams(url.slice(idx + 1));\n return params.get(\"__action\");\n}\n\nfunction methodOf(req: AnyReq): string {\n return String(req.method ?? \"GET\").toUpperCase();\n}\n\n/**\n * Strip a redirect / `next` target down to a safe **same-origin path**.\n *\n * Rejects protocol-relative (`//evil.com`), backslash-escaped (`/\\evil.com`)\n * and absolute (`https://…`) targets that would let an attacker turn the\n * post-login redirect into an open redirect / phishing vector (issue #07).\n * Anything suspicious collapses to `\"/\"`.\n */\nfunction sanitizeNextPath(next: string): string {\n if (typeof next !== \"string\" || next.length === 0) return \"/\";\n if (!next.startsWith(\"/\")) return \"/\";\n if (next.startsWith(\"//\") || next.startsWith(\"/\\\\\")) return \"/\";\n if (next.includes(\"://\")) return \"/\";\n return next;\n}\n\nfunction headerOf(req: AnyReq, name: string): string | undefined {\n const raw = req.headers?.[name];\n if (Array.isArray(raw)) return raw[0];\n return typeof raw === \"string\" ? raw : undefined;\n}\n\nconst CSRF_SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/**\n * Same-origin check used as a CSRF defense for state-changing requests.\n * Compares the request `Origin` (or `Referer`) host against the request host.\n * Returns `true` only when they match. A missing/invalid Origin fails closed.\n */\nfunction isSameOriginRequest(req: AnyReq): boolean {\n const originHeader = headerOf(req, \"origin\") ?? headerOf(req, \"referer\");\n if (!originHeader) return false;\n const host = headerOf(req, \"x-forwarded-host\") ?? headerOf(req, \"host\");\n if (!host) return false;\n try {\n return new URL(originHeader).host === host;\n } catch {\n return false;\n }\n}\n\nfunction isPublic(\n path: string,\n patterns: (string | RegExp)[] | undefined,\n): boolean {\n if (!patterns || patterns.length === 0) return false;\n for (const p of patterns) {\n if (typeof p === \"string\") {\n if (path === p || path.startsWith(p + \"/\")) return true;\n } else if (p.test(path)) {\n return true;\n }\n }\n return false;\n}\n\nfunction wantsHtml(req: AnyReq): boolean {\n const accept = String(req.headers?.accept ?? \"\");\n // Strict: only real browser navigations advertise `text/html`. Treating\n // `*/*` or a missing Accept header as HTML caused curl, healthchecks and\n // server-to-server fetches to receive a 200 login page instead of a clear\n // 401 (issue #16).\n return accept.includes(\"text/html\");\n}\n\nfunction extractBearer(req: AnyReq): string | null {\n const raw = req.headers?.authorization;\n const header = Array.isArray(raw) ? raw[0] : raw;\n if (!header) return null;\n const m = /^Bearer\\s+(.+)$/i.exec(header);\n return m ? m[1]!.trim() : null;\n}\n\nfunction rejectUnauthenticated(\n req: AnyReq,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n res: any,\n policy: \"redirect\" | \"401\",\n loginPath: string,\n): void {\n if (policy === \"redirect\" && wantsHtml(req)) {\n const target = encodeURIComponent(req.url ?? \"/\");\n res\n .status(302)\n .set(\"Location\", `${loginPath}?next=${target}`)\n .set(\"Cache-Control\", \"no-store\")\n .end();\n return;\n }\n res\n .status(401)\n .set(\"Content-Type\", \"application/json; charset=utf-8\")\n .send(JSON.stringify({ success: false, error: \"Unauthorized\" }));\n}\n\n// ---------------------------------------------------------------------------\n// Public factory\n// ---------------------------------------------------------------------------\n\n/**\n * Build a Firebase Auth extension for use with `servers.admin()` or\n * `servers.crud()`. See module-level docs for the full design and examples.\n */\nexport function firebaseAuth<TContext = unknown>(\n config: FirebaseAuthConfig<TContext>,\n): AuthExtension {\n const mode: FirebaseAuthMode = config.mode ?? \"cookie\";\n const cookieName = config.cookieName ?? SESSION_COOKIE_DEFAULT;\n const ttlDays = config.sessionTtlDays ?? 5;\n const secure = config.secureCookie ?? true;\n const sameSite = config.sameSite ?? \"Lax\";\n // The Origin/Referer (CSRF) check is only needed when `SameSite=None`:\n // with the default `Lax` (or `Strict`) the browser already refuses to send\n // the session cookie on cross-site state-changing requests, so a cross-site\n // POST/PUT/DELETE is unauthenticated and harmless. Enforcing the Origin\n // check unconditionally also breaks legitimate same-origin requests on\n // platforms where the container's `Host` differs from the public origin\n // (e.g. Cloud Functions v2 / Cloud Run, where `Host` is the internal\n // `*.run.app` host while `Origin` is the `*.cloudfunctions.net` domain).\n // Can be forced on/off explicitly via `csrfProtection`.\n const csrfProtection =\n config.csrfProtection ?? (mode !== \"bearer\" && sameSite === \"None\");\n if (mode !== \"bearer\" && sameSite === \"None\") {\n console.warn(\n \"[firebaseAuth] `sameSite: \\\"None\\\"` disables the browser's built-in \" +\n \"SameSite CSRF protection. \" +\n (csrfProtection\n ? \"The same-origin (Origin/Referer) check is active as the primary \" +\n \"defense — ensure state-changing requests are sent same-origin or \" +\n \"carry a bearer token.\"\n : \"`csrfProtection` is disabled — your endpoints are CSRF-exposed.\"),\n );\n }\n const onUnauth = config.onUnauthenticated ?? defaultUnauth(mode);\n const loginEnabled =\n config.loginPage === undefined\n ? defaultLoginPage(mode)\n : config.loginPage !== false;\n\n const loginPath = \"/__login\";\n const sessionPath = \"/__session\";\n const logoutPath = \"/__logout\";\n\n // ── Auxiliary handlers (kept in `routes` for hosting deployments\n // where users can mount them at known paths, AND invoked in-band by the\n // middleware on `?__action=session|logout` so vanilla Cloud Functions\n // — where there is no separate URL prefix per route — work too). ──────\n const sessionHandler = createSessionHandler({\n getAuth: config.getAuth,\n cookieName,\n ttlDays,\n secure,\n sameSite,\n });\n const logoutHandler = createLogoutHandler({\n getAuth: config.getAuth,\n cookieName,\n secure,\n sameSite,\n });\n\n function renderInlineLogin(\n req: AnyReq,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n res: any,\n error: string | null = null,\n status = 200,\n ): void {\n // Validate lazily (at request time) so module loading during Firebase CLI\n // analysis doesn't throw before env vars are injected.\n if (!config.apiKey || !config.authDomain) {\n throw new Error(\n \"[firebaseAuth] `apiKey` and `authDomain` are required when `loginPage` is enabled. \" +\n \"Find both in the Firebase Console under Project Settings → General → Web app config.\",\n );\n }\n const pageCfg: FirebaseAuthLoginPageConfig =\n typeof config.loginPage === \"object\" ? config.loginPage : {};\n // Build a same-function absolute URL: the function's external prefix\n // (Cloud Functions name, emulator project/region/target, or \"\" for\n // custom domains) + the in-router request path. The browser otherwise\n // resolves form actions relative to the public URL, which doesn't\n // include the function name on Cloud Functions.\n const prefix = getLinkBase(req, \"/\", config.region);\n const inner = req.url ?? \"/\";\n // Sanitize to a same-origin path so a crafted request URL (e.g.\n // `//evil.com/...` on a custom domain where the prefix is empty) cannot\n // turn the post-login redirect or the form action into an open redirect\n // (issue #07).\n const fullPath = sanitizeNextPath(\n `${prefix}${inner.startsWith(\"/\") ? inner : `/${inner}`}`,\n );\n const sep = fullPath.includes(\"?\") ? \"&\" : \"?\";\n const sessionAction = `${fullPath}${sep}__action=session`;\n const html = renderLoginPage({\n title: pageCfg.title ?? \"Admin sign-in\",\n providers: pageCfg.providers ?? [\"password\", \"google\"],\n apiKey: config.apiKey!,\n authDomain: config.authDomain!,\n sessionPath: sessionAction,\n next: fullPath,\n error,\n authEmulatorHost:\n config.authEmulatorHost ?? process.env[\"FIREBASE_AUTH_EMULATOR_HOST\"],\n });\n res\n .status(status)\n .set(\"Content-Type\", \"text/html; charset=utf-8\")\n .set(\"Cache-Control\", \"no-store\")\n .send(html);\n }\n\n // ── Auxiliary routes ─────────────────────────────────────────────────────\n const routes: AuthRoute[] = [];\n if (loginEnabled) {\n routes.push({\n method: \"GET\",\n path: loginPath,\n handler: (req, res) => {\n const error = (req.query?.error as string | undefined) ?? null;\n renderInlineLogin(req, res, error);\n },\n });\n routes.push({\n method: \"POST\",\n path: sessionPath,\n handler: sessionHandler,\n });\n routes.push({\n method: \"POST\",\n path: logoutPath,\n handler: logoutHandler,\n });\n }\n\n const publicPaths: (string | RegExp)[] = [\n ...(config.publicPaths ?? []),\n loginPath,\n sessionPath,\n logoutPath,\n ];\n\n // ── Middleware ───────────────────────────────────────────────────────────\n const middleware: Middleware = async (req, res, next) => {\n const path = pathOf(req);\n const method = methodOf(req);\n\n // 0. CSRF defense for cookie sessions (only active when `SameSite=None`,\n // or when `csrfProtection` is explicitly forced on — see config). With\n // the default Lax/Strict cookie the browser already blocks the session\n // cookie on cross-site state-changing requests, so this is skipped to\n // avoid breaking legitimate same-origin requests behind proxies. When\n // active it runs FIRST so it also protects the in-band\n // `?__action=logout|session` shortcut below (issues #05, #06).\n if (\n csrfProtection &&\n mode !== \"bearer\" &&\n !CSRF_SAFE_METHODS.has(method) &&\n !extractBearer(req) &&\n !isSameOriginRequest(req)\n ) {\n res\n .status(403)\n .set(\"Content-Type\", \"application/json; charset=utf-8\")\n .send(\n JSON.stringify({\n success: false,\n error: \"Origin check failed (possible CSRF)\",\n }),\n );\n return;\n }\n\n // 1. In-band action endpoints. The bundled login page posts the session\n // exchange (and logout) to the CURRENT url with `?__action=session`\n // (resp. `logout`) rather than to the mounted `/__session` route,\n // because on vanilla Cloud Functions the helper cannot reliably know\n // the function's public URL prefix to address a separate route. These\n // actions are inherently public (login/logout need no prior auth) and\n // are protected against cross-site abuse by the same-origin guard\n // above (issue #06).\n if (loginEnabled && method === \"POST\") {\n const action = queryAction(req);\n if (action === \"session\") {\n await sessionHandler(req, res);\n return;\n }\n if (action === \"logout\") {\n await logoutHandler(req, res);\n return;\n }\n }\n\n // 2. Public paths (mounted login routes, user-supplied allowlist).\n if (isPublic(path, publicPaths)) {\n await next();\n return;\n }\n\n let decoded: DecodedIdTokenLike | null = null;\n try {\n const auth = config.getAuth();\n\n // Try bearer first when allowed (cheaper, no cookie parsing).\n if (mode === \"bearer\" || mode === \"both\") {\n const token = extractBearer(req);\n if (token) {\n decoded = await auth.verifyIdToken(token, true);\n }\n }\n\n // Fall back to cookie when allowed.\n if (!decoded && (mode === \"cookie\" || mode === \"both\")) {\n const cookieHeader = req.headers?.cookie;\n const raw = Array.isArray(cookieHeader)\n ? cookieHeader.join(\"; \")\n : cookieHeader;\n const cookies = parseCookies(typeof raw === \"string\" ? raw : \"\");\n const session = cookies[cookieName];\n if (session) {\n decoded = await auth.verifySessionCookie(session, true);\n }\n }\n } catch {\n decoded = null;\n }\n\n if (!decoded) {\n rejectUnauthenticated(req, res);\n return;\n }\n\n const baseUser: Omit<AuthUser, \"context\"> = {\n uid: decoded.uid,\n email: typeof decoded.email === \"string\" ? decoded.email : null,\n emailVerified: !!decoded.email_verified,\n claims: decoded as Record<string, unknown>,\n };\n\n let context: TContext | null;\n try {\n context = config.allow\n ? await config.allow(baseUser)\n : (null as TContext | null);\n } catch {\n context = null;\n }\n\n if (config.allow && context === null) {\n rejectUnauthenticated(req, res);\n return;\n }\n\n (req as AnyReq & { user?: AuthUser<TContext> }).user = {\n ...baseUser,\n context: context as TContext,\n };\n\n await next();\n };\n\n /**\n * Reject according to the configured policy:\n * - cookie/both + GET HTML browser request → render the login page inline\n * on the SAME URL with a `401` status (works on Cloud Functions where\n * there's no separate `/__login` route reachable from the public URL).\n * A 401 keeps the response HTTP-compliant for monitoring/healthchecks\n * while browsers still render the page (issue #16).\n * - bearer mode or non-HTML clients → JSON 401.\n */\n function rejectUnauthenticated(\n req: AnyReq,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n res: any,\n ): void {\n if (\n onUnauth === \"redirect\" &&\n loginEnabled &&\n methodOf(req) === \"GET\" &&\n wantsHtml(req)\n ) {\n renderInlineLogin(req, res, null, 401);\n return;\n }\n res\n .status(401)\n .set(\"Content-Type\", \"application/json; charset=utf-8\")\n .send(JSON.stringify({ success: false, error: \"Unauthorized\" }));\n }\n\n return {\n __authExtension: true,\n middleware,\n routes,\n loginPath,\n };\n}\n\n/**\n * Type guard: detect an {@link AuthExtension} (vs. legacy\n * `BasicAuthConfig` / `Middleware`).\n */\nexport function isAuthExtension(value: unknown): value is AuthExtension {\n return (\n !!value &&\n typeof value === \"object\" &&\n (value as { __authExtension?: unknown }).__authExtension === true\n );\n}\n\n/**\n * Helper for explicitly opening a CRUD operation when the server has\n * `auth` defined (bypasses the default-deny policy).\n *\n * @example\n * ```ts\n * rules: { list: allowAll, get: allowAll }\n * ```\n */\nexport const allowAll = (): true => true;\n","/**\n * Request-scoped & programmatic actor context backed by `AsyncLocalStorage`.\n *\n * Uses a `globalThis[Symbol.for(...)]` singleton so separate tsup bundles\n * (`dist/index`, `dist/servers/hono`, `dist/servers/crud`, `dist/history`,\n * `dist/servers/index`) always share the exact same `AsyncLocalStorage`\n * instance.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Context, MiddlewareHandler } from \"hono\";\n\n/** Actor & audit metadata captured for history writes. */\nexport interface HistoryActor {\n userId?: string | null;\n userEmail?: string | null;\n reason?: string | null;\n comment?: string | null;\n extras?: Record<string, unknown>;\n}\n\n/** Function resolving the current actor lazily from a Hono `Context`. */\nexport type ActorResolver = (c: Context) => HistoryActor | null | undefined;\n\n/**\n * Declarative configuration for {@link createActorResolver} so projects can\n * customize context keys, nested user property paths, and request headers\n * without writing a full resolver from scratch.\n */\nexport interface ActorResolverFieldConfig {\n /**\n * Hono context keys inspected in order via `c.get(key)`.\n * Default: `[\"user\", \"docsUser\"]`.\n */\n contextKeys?: string[];\n /**\n * Property paths on the user object checked in order for `userId`.\n * Supports dot-notation (e.g. `\"baseUser.id\"`).\n * Default: `[\"uid\", \"id\", \"sub\"]`.\n */\n userIdFields?: string[];\n /**\n * Property paths on the user object checked in order for `userEmail`.\n * Supports dot-notation (e.g. `\"baseUser.email\"`).\n * Default: `[\"email\"]`.\n */\n userEmailFields?: string[];\n /**\n * HTTP header name for change reason, or `false` to disable header lookup.\n * Default: `\"x-history-reason\"`.\n */\n reasonHeader?: string | false;\n /**\n * HTTP header name for change comment, or `false` to disable header lookup.\n * Default: `\"x-history-comment\"`.\n */\n commentHeader?: string | false;\n /**\n * Optional extractor to populate `actor.extras` from `(c, user)`.\n */\n extras?: (\n c: Context,\n user: Record<string, unknown> | null,\n ) => Record<string, unknown> | undefined;\n}\n\n/**\n * Accepted by `HonoServerOptions.actorResolver`, `ApiRegistryOptions.actorResolver`,\n * `CrudServerOptions.actorResolver`, and `CreateServersDeps.actorResolver`:\n * either a custom resolver function or a declarative field-mapping config.\n */\nexport type ActorResolverOption = ActorResolver | ActorResolverFieldConfig;\n\n/** Canonical default HTTP header name for change reason. */\nexport const DEFAULT_HISTORY_REASON_HEADER = \"X-History-Reason\";\n\n/** Canonical default HTTP header name for change comment. */\nexport const DEFAULT_HISTORY_COMMENT_HEADER = \"X-History-Comment\";\n\n/** Resolved history audit header names exposed by an `actorResolver`. */\nexport interface ResolvedHistoryHeaderNames {\n reasonHeader: string | false;\n commentHeader: string | false;\n}\n\nconst ACTOR_RESOLVER_HEADERS_SYMBOL = Symbol.for(\n \"@lpdjs/firestore-repo-service:actorResolverHeaders\",\n);\n\ninterface ActorStore {\n c?: Context;\n resolver?: ActorResolver;\n override?: Partial<HistoryActor>;\n}\n\nconst ALS_SYMBOL = Symbol.for(\"@lpdjs/firestore-repo-service:actorContext\");\nconst g = globalThis as Record<\n symbol,\n AsyncLocalStorage<ActorStore> | undefined\n>;\nconst actorStorage = (g[ALS_SYMBOL] ??= new AsyncLocalStorage<ActorStore>());\n\n/** Safely traverse a dot-notation path (e.g. `\"baseUser.email\"`) on an object. */\nfunction readFieldPath(\n obj: Record<string, unknown>,\n path: string,\n): unknown {\n if (!path.includes(\".\")) return obj[path];\n let cur: unknown = obj;\n for (const part of path.split(\".\")) {\n if (!cur || typeof cur !== \"object\") return undefined;\n cur = (cur as Record<string, unknown>)[part];\n }\n return cur;\n}\n\n/** Pick the first non-empty string/number value across candidate paths. */\nfunction pickFirstString(\n obj: Record<string, unknown>,\n paths: string[],\n): string | null {\n for (const p of paths) {\n const val = readFieldPath(obj, p);\n if (typeof val === \"string\" && val.length > 0) return val;\n if (typeof val === \"number\") return String(val);\n }\n return null;\n}\n\n/** Read an HTTP header safely from a Hono `Context` (tolerates minimal mocks). */\nfunction readHeader(c: Context, name: string | false): string | undefined {\n if (name === false) return undefined;\n const headerFn = (c as any)?.req?.header;\n if (typeof headerFn !== \"function\") return undefined;\n const val = headerFn.call((c as any).req, name);\n return typeof val === \"string\" && val.length > 0 ? val : undefined;\n}\n\n/**\n * Build an {@link ActorResolver} from a declarative field/header configuration.\n *\n * @example\n * ```ts\n * const actorResolver = createActorResolver({\n * contextKeys: [\"authUser\", \"user\"],\n * userIdFields: [\"docId\", \"uid\"],\n * userEmailFields: [\"baseUser.email\", \"email\"],\n * reasonHeader: \"x-audit-reason\",\n * });\n * ```\n */\nexport function createActorResolver(\n config: ActorResolverFieldConfig = {},\n): ActorResolver {\n const contextKeys = config.contextKeys ?? [\"user\", \"docsUser\"];\n const userIdFields = config.userIdFields ?? [\"uid\", \"id\", \"sub\"];\n const userEmailFields = config.userEmailFields ?? [\"email\"];\n const reasonHeader =\n config.reasonHeader === undefined ? \"x-history-reason\" : config.reasonHeader;\n const commentHeader =\n config.commentHeader === undefined\n ? \"x-history-comment\"\n : config.commentHeader;\n const displayReasonHeader: string | false =\n config.reasonHeader === undefined\n ? DEFAULT_HISTORY_REASON_HEADER\n : config.reasonHeader;\n const displayCommentHeader: string | false =\n config.commentHeader === undefined\n ? DEFAULT_HISTORY_COMMENT_HEADER\n : config.commentHeader;\n const extrasFn = config.extras;\n\n const resolver: ActorResolver = (c: Context): HistoryActor | null => {\n let user: Record<string, unknown> | null = null;\n const getFn = (c as any)?.get;\n if (typeof getFn === \"function\") {\n for (const key of contextKeys) {\n const candidate = getFn.call(c, key);\n if (candidate && typeof candidate === \"object\") {\n user = candidate as Record<string, unknown>;\n break;\n }\n }\n }\n\n const reason = readHeader(c, reasonHeader);\n const comment = readHeader(c, commentHeader);\n const extras = extrasFn ? extrasFn(c, user) : undefined;\n\n if (!user) {\n if (reason === undefined && comment === undefined && !extras) {\n return null;\n }\n return {\n ...(reason !== undefined ? { reason } : {}),\n ...(comment !== undefined ? { comment } : {}),\n ...(extras ? { extras } : {}),\n };\n }\n\n return {\n userId: pickFirstString(user, userIdFields),\n userEmail: pickFirstString(user, userEmailFields),\n ...(reason !== undefined ? { reason } : {}),\n ...(comment !== undefined ? { comment } : {}),\n ...(extras ? { extras } : {}),\n };\n };\n\n Object.defineProperty(resolver, ACTOR_RESOLVER_HEADERS_SYMBOL, {\n value: {\n reasonHeader: displayReasonHeader,\n commentHeader: displayCommentHeader,\n } satisfies ResolvedHistoryHeaderNames,\n enumerable: false,\n configurable: false,\n });\n\n return resolver;\n}\n\n/**\n * Inspect an {@link ActorResolverOption} (declarative config object, resolver\n * created via {@link createActorResolver}, custom function, or `undefined`)\n * and return the effective history audit header names for OpenAPI / CORS.\n */\nexport function getActorResolverHeaders(\n option?: ActorResolverOption,\n): ResolvedHistoryHeaderNames {\n if (!option) {\n return {\n reasonHeader: DEFAULT_HISTORY_REASON_HEADER,\n commentHeader: DEFAULT_HISTORY_COMMENT_HEADER,\n };\n }\n if (typeof option === \"function\") {\n const meta = (option as any)[ACTOR_RESOLVER_HEADERS_SYMBOL] as\n | ResolvedHistoryHeaderNames\n | undefined;\n if (meta) return { ...meta };\n return {\n reasonHeader: DEFAULT_HISTORY_REASON_HEADER,\n commentHeader: DEFAULT_HISTORY_COMMENT_HEADER,\n };\n }\n return {\n reasonHeader:\n option.reasonHeader === undefined\n ? DEFAULT_HISTORY_REASON_HEADER\n : option.reasonHeader,\n commentHeader:\n option.commentHeader === undefined\n ? DEFAULT_HISTORY_COMMENT_HEADER\n : option.commentHeader,\n };\n}\n\n/**\n * Default actor resolver compatible with Firebase JWT / `firebaseBearerAuth` /\n * custom auth middlewares setting `c.get(\"user\")` or `c.get(\"docsUser\")`.\n */\nexport const defaultActorResolver: ActorResolver = createActorResolver();\n\n/** Normalize either a function resolver or a declarative config object. */\nexport function normalizeActorResolver(\n option?: ActorResolverOption,\n): ActorResolver | undefined {\n if (!option) return undefined;\n return typeof option === \"function\" ? option : createActorResolver(option);\n}\n\n/**\n * Hono middleware mounted automatically at the top of `HonoServer`.\n * Stores `{ c, resolver }` in `AsyncLocalStorage` so downstream repository\n * writes resolve the authenticated user lazily after auth middlewares run.\n */\nexport function createActorContextMiddleware(\n resolver?: ActorResolverOption,\n): MiddlewareHandler {\n const normalized = normalizeActorResolver(resolver);\n return async (c, next) => {\n await actorStorage.run({ c, resolver: normalized }, async () => {\n await next();\n });\n };\n}\n\n/**\n * Resolve the active {@link HistoryActor} for the current async execution\n * context, or `null` when outside any scope or when no actor is available.\n */\nexport function getCurrentActor(): HistoryActor | null {\n const store = actorStorage.getStore();\n if (!store) return null;\n\n let fromReq: HistoryActor | null | undefined = null;\n if (store.c) {\n try {\n fromReq = (store.resolver ?? defaultActorResolver)(store.c);\n } catch {\n fromReq = null;\n }\n }\n\n if (!fromReq && !store.override) return null;\n\n const merged: HistoryActor = { ...(fromReq ?? {}) };\n if (store.override) {\n if (store.override.userId !== undefined) {\n merged.userId = store.override.userId;\n }\n if (store.override.userEmail !== undefined) {\n merged.userEmail = store.override.userEmail;\n }\n if (store.override.reason !== undefined) {\n merged.reason = store.override.reason;\n }\n if (store.override.comment !== undefined) {\n merged.comment = store.override.comment;\n }\n if (store.override.extras !== undefined) {\n merged.extras = {\n ...(fromReq?.extras ?? {}),\n ...store.override.extras,\n };\n }\n }\n\n return merged;\n}\n\n/**\n * Execute `fn` within an isolated actor scope — ideal for crons, Pub/Sub\n * workers, scripts, and unit tests.\n *\n * @example\n * ```ts\n * await withActor({ userId: \"cron:invoicing\", reason: \"monthly-run\" }, async () => {\n * await repos.invoices.create(payload);\n * });\n * ```\n */\nexport function withActor<T>(actor: HistoryActor, fn: () => T): T {\n return actorStorage.run({ override: { ...actor } }, fn);\n}\n\n/**\n * Enrich or override actor metadata (`reason`, `comment`, `extras`, …) for the\n * current active request / `withActor` scope without touching repository calls.\n *\n * Safe no-op returning `false` when called outside any active ALS scope.\n */\nexport function setRequestActorMeta(meta: Partial<HistoryActor>): boolean {\n const store = actorStorage.getStore();\n if (!store) return false;\n\n const prev = store.override ?? {};\n const nextOverride: Partial<HistoryActor> = { ...prev, ...meta };\n if (prev.extras || meta.extras) {\n nextOverride.extras = {\n ...(prev.extras ?? {}),\n ...(meta.extras ?? {}),\n };\n }\n store.override = nextOverride;\n return true;\n}\n","/**\n * Types and interfaces for the history (change-log) module.\n *\n * The package writes history entries in **schema v2** (1 Firestore document\n * per `update`/`create`/`delete` event, with a `changes` map keyed by field\n * name). It reads both v1 (legacy: 1 doc per modified field) and v2 by\n * normalising them into a unified {@link HistoryEntry} shape.\n */\n\nimport type { Timestamp } from \"firebase-admin/firestore\";\nimport type {\n DocumentOptions,\n onDocumentWritten,\n} from \"firebase-functions/v2/firestore\";\n\n/**\n * Cloud Functions v2 options forwarded to `onDocumentWritten()` for history triggers.\n * The `document` field is omitted because the library sets it itself from the collection path.\n */\nexport type TriggerOptions = Omit<DocumentOptions, \"document\">;\nexport type HistoryTriggerOptions = TriggerOptions;\n\n/* ------------------------------------------------------------------------- */\n/* Public unified shape */\n/* ------------------------------------------------------------------------- */\n\nexport type HistoryOperation = \"create\" | \"update\" | \"delete\" | \"custom\";\n\n/**\n * Structured payload attached to `operation: \"custom\"` history entries\n * (business actions independent of model fields, e.g. manual invoice creation,\n * PDF export, email sent, etc.).\n */\nexport interface HistoryCustomData {\n /** Human-readable title (e.g. `\"Création de la facture\"`). */\n title: string;\n /** Optional human-readable description (e.g. `\"Facture #F-2026-042 créée manuellement\"`). */\n description?: string;\n /** Optional business action key for filtering/grouping/icons (e.g. `\"invoice_create_manually\"`). */\n key?: string;\n /** Optional front-end visibility flag (default: `true`). */\n display?: boolean;\n /** Optional arbitrary structured business payload (e.g. `{ invoiceId, amount }`). */\n data?: Record<string, unknown>;\n}\n\n/** Input payload accepted by `repo.history.recordCustom(...)`. */\nexport interface HistoryCustomInput extends HistoryCustomData {\n /**\n * Optional metadata overrides (`reason`, `comment`, `extras`, `userId`,\n * `userEmail`). Automatically merged on top of the active ALS actor.\n */\n meta?: HistoryMeta;\n}\n\n/**\n * Detected JS/Firestore type of a value as stored in a history entry.\n * Matches the values returned by {@link valueType}.\n */\nexport type HistoryValueType =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"timestamp\"\n | \"date\"\n | \"array\"\n | \"object\"\n | \"null\"\n | \"undefined\";\n\n/** A single field change inside a history entry. */\nexport interface HistoryFieldChange {\n oldValue: unknown;\n newValue: unknown;\n type: { old: HistoryValueType; new: HistoryValueType };\n}\n\n/** Captured metadata for a history entry. */\nexport interface HistoryMeta {\n userId?: string | null;\n userEmail?: string | null;\n reason?: string | null;\n comment?: string | null;\n /** Free-form extra fields copied from the source document. */\n extras?: Record<string, unknown>;\n}\n\n/**\n * Unified history entry returned by `repo.history.list(...)`.\n * Both v1 and v2 documents are normalised into this shape.\n */\nexport interface HistoryEntry<T = Record<string, unknown>> {\n /** Stable id of the underlying Firestore history document (the v1+v2 storage doc). */\n historyDocId: string;\n /** Id of the entity this entry belongs to. */\n historyToObjectId: string;\n /** When the change was recorded. */\n historySetAt: Timestamp;\n /** Source schema version. v1 = legacy (1 doc/field), v2 = current (1 doc/update). */\n schemaVersion: 1 | 2;\n /** v2 only — v1 is always normalised to \"update\". */\n operation: HistoryOperation;\n /** Captured author / context information. */\n meta: HistoryMeta;\n /** Present on `operation: \"custom\"` entries (business actions independent of model fields). */\n custom?: HistoryCustomData;\n /** Per-field changes. Keys are field names of T. */\n changes: { [K in keyof T & string]?: HistoryFieldChange } & {\n [field: string]: HistoryFieldChange;\n };\n}\n\n/* ------------------------------------------------------------------------- */\n/* Storage-level shapes (what is actually written / read in Firestore) */\n/* ------------------------------------------------------------------------- */\n\n/** v2 document layout. */\nexport interface V2HistoryDoc {\n schemaVersion: 2;\n historyDocId: string;\n historyToObjectId: string;\n historySetAt: Timestamp;\n operation: HistoryOperation;\n meta: HistoryMeta;\n /** Present on `operation: \"custom\"` entries. */\n custom?: HistoryCustomData;\n changes: Record<string, HistoryFieldChange>;\n /** Optional TTL marker (Firestore deletes the doc after this date). */\n expiresAt?: Timestamp;\n /** Set when the doc had to be truncated to fit the 1 MiB limit. */\n _truncated?: boolean;\n}\n\n/** v1 document layout (legacy — read-only support). */\nexport interface V1HistoryDoc {\n // schemaVersion is absent in v1.\n schemaVersion?: undefined;\n historyDocId: string;\n historyToObjectId: string;\n historyUserId?: string;\n historyUserEmail?: string;\n historySetAt: Timestamp;\n field: string;\n changes: { oldValue: unknown; newValue: unknown };\n types?: { oldValue: string; newValue: string };\n // Extra freeform metadata seen in legacy code.\n historyDetails?: Record<string, unknown> | null;\n extraHistoryDetails?: {\n comment?: string;\n reason?: string;\n toKey?: string;\n force?: boolean;\n } | null;\n extraContentKeys?: Record<string, unknown> | null;\n objectType?: string;\n}\n\n/* ------------------------------------------------------------------------- */\n/* Configuration */\n/* ------------------------------------------------------------------------- */\n\n/** Default top-level shadow field name stored on Firestore documents for auto-injected history metadata. */\nexport const DEFAULT_HISTORY_SHADOW_KEY = \"_historyMeta\";\n\n/**\n * Customize (or disable via `false`) the sub-field names stored inside the\n * shadow metadata object on Firestore documents.\n */\nexport interface HistoryShadowFieldsConfig {\n /** Key inside the shadow object for author userId, or `false` to omit. Default: `\"userId\"`. */\n userId?: string | false;\n /** Key inside the shadow object for author userEmail, or `false` to omit. Default: `\"userEmail\"`. */\n userEmail?: string | false;\n /** Key inside the shadow object for change reason, or `false` to omit. Default: `\"reason\"`. */\n reason?: string | false;\n /** Key inside the shadow object for change comment, or `false` to omit. Default: `\"comment\"`. */\n comment?: string | false;\n /** Key inside the shadow object for extras map, or `false` to omit. Default: `\"extras\"`. */\n extras?: string | false;\n}\n\n/**\n * Configuration for the internal shadow field used to transport actor metadata\n * to Firestore `onDocumentWritten` triggers without modifying Zod schemas.\n */\nexport interface HistoryShadowConfig {\n /**\n * Top-level field name stored on the Firestore document (not required in the\n * Zod schema, automatically excluded from diffs and sync, and stripped on read).\n * Default: `\"_historyMeta\"`.\n */\n key?: string;\n /**\n * Customize or disable individual sub-field names inside the shadow object.\n * Default: `{ userId: \"userId\", userEmail: \"userEmail\", reason: \"reason\", comment: \"comment\", extras: \"extras\" }`.\n */\n fields?: HistoryShadowFieldsConfig;\n}\n\n/**\n * Fallback author values written when no actor is active in `AsyncLocalStorage`\n * (crons, scripts, admin UI, public routes).\n */\nexport interface HistoryFallbackActor {\n userId?: string | null;\n userEmail?: string | null;\n}\n\n/**\n * Per-repo history configuration. Attached on the repository config under\n * the `history` key. All meta sub-keys must reference fields that exist on\n * the model (compile-time enforced by {@link HistoryConfigForModel}).\n */\nexport interface HistoryConfigBase {\n /** Master switch — when false/absent, no triggers are generated and no `repo.history` API is exposed. */\n enabled: boolean;\n /** Subcollection name used to store history docs. Default: \"history\". */\n subcollection?: string;\n /**\n * Automatically inject actor metadata from `AsyncLocalStorage` into the\n * shadow field on repository writes (`create`, `set`, `update`, `batch`,\n * `transaction`, `bulk`). Default: `true` when `enabled: true`.\n */\n autoInjectMeta?: boolean;\n /**\n * Shadow field configuration (zero Zod schema changes).\n *\n * - Omitted or `true` (when `meta` is absent): uses `\"_historyMeta\"` with default sub-fields.\n * - `string`: shorthand for `{ key: \"<customKey>\" }`.\n * - `HistoryShadowConfig`: customize both `key` and nested `fields`.\n * - `false`: disable shadow metadata injection/reading.\n */\n shadow?: boolean | string | HistoryShadowConfig;\n /**\n * Fallback actor written when no actor is active in `AsyncLocalStorage` so\n * previous author metadata never leaks onto subsequent writes.\n * Default: `{ userId: null, userEmail: null }`.\n */\n fallbackActor?: HistoryFallbackActor;\n /**\n * Optional Firestore TTL configuration. When set, every written history doc\n * gets an `expiresAt` Timestamp at `now + days`. You still need to enable\n * the TTL policy on the `expiresAt` field via gcloud / console.\n */\n ttl?: { days: number };\n /**\n * Cloud Functions v2 options forwarded to `onDocumentWritten()` for this\n * repository's history trigger (e.g. `region`, `vpcConnector`, `memory`, etc.).\n */\n triggerOptions?: HistoryTriggerOptions;\n}\n\n/**\n * Strongly-typed history config bound to a model `T`.\n *\n * - `meta.*` keys must be keyof T (or string for `extras` entries).\n * - `include` / `exclude` accept keyof T.\n */\nexport interface HistoryConfigForModel<T> extends HistoryConfigBase {\n meta?: {\n /** Field on T that holds the author user id. */\n userId?: keyof T & string;\n /** Field on T that holds the author email. */\n userEmail?: keyof T & string;\n /** Field on T that holds an optional change reason. */\n reason?: keyof T & string;\n /** Field on T that holds an optional change comment. */\n comment?: keyof T & string;\n /** Free-form extra field names copied verbatim into `meta.extras`. */\n extras?: (keyof T & string)[];\n };\n /** When set, only these top-level fields are diffed. */\n include?: (keyof T & string)[];\n /** Always excluded from the diff (in addition to meta + system keys). */\n exclude?: (keyof T & string)[];\n /**\n * Optional async hook to enrich/mutate an entry before it's written.\n * Return `null` to drop the entry entirely.\n */\n onBeforeWrite?: (\n entry: V2HistoryDoc,\n ctx: { repoName: string; docId: string; before: T | null; after: T | null },\n ) => V2HistoryDoc | null | Promise<V2HistoryDoc | null>;\n}\n\n/* ------------------------------------------------------------------------- */\n/* Read API options */\n/* ------------------------------------------------------------------------- */\n\nexport interface HistoryListOptions<T = unknown> {\n /** Max number of normalised entries to return. Default: 50. */\n limit?: number;\n /** Cursor for pagination (use `historySetAt` of the last received entry). */\n cursor?: Timestamp;\n /** Sort direction on `historySetAt`. Default: \"desc\". */\n direction?: \"asc\" | \"desc\";\n /** Restrict to entries that touch any of these fields (post-filter). */\n fields?: (keyof T & string)[];\n /** Restrict to entries with these operations (v2 only — v1 is always \"update\"). */\n operations?: HistoryOperation[];\n}\n\nexport interface HistoryRawListOptions {\n limit?: number;\n cursor?: Timestamp;\n direction?: \"asc\" | \"desc\";\n}\n\n/* ------------------------------------------------------------------------- */\n/* Trigger factory configuration */\n/* ------------------------------------------------------------------------- */\n\n/**\n * Firestore trigger constructors injected by the consumer.\n * Mirrors the DI pattern used by `createSyncTriggers`.\n */\nexport interface HistoryFirestoreTriggersDep {\n // Either onDocumentWritten alone is enough; we keep the more granular ones\n // available so the worker can stay efficient.\n onDocumentWritten: typeof onDocumentWritten;\n}\n\n/** Per-repo override at the `createHistoryTriggers` call site. */\nexport interface HistoryTriggerRepoOverride {\n /**\n * Explicit Firestore document path pattern. Required for collection-group\n * repositories whose path cannot be auto-detected.\n * @example \"residences/{residenceId}/workshops/{docId}\"\n */\n triggerPath?: string;\n /**\n * Cloud Functions v2 options forwarded to `onDocumentWritten()` for this\n * repository's history trigger. Overrides global `triggerOptions`.\n */\n triggerOptions?: HistoryTriggerOptions;\n}\n\nexport interface HistoryTriggersConfig<M = Record<string, any>> {\n deps: HistoryFirestoreTriggersDep;\n /** Defaults applied to every repo unless overridden. */\n defaults?: { ttl?: { days: number } };\n /**\n * Cloud Functions v2 options forwarded to `onDocumentWritten()` for every\n * history trigger handler. Use to configure `region`, `vpcConnector`,\n * `memory`, `cpu`, `timeoutSeconds`, `maxInstances`, `secrets`, etc.\n */\n triggerOptions?: HistoryTriggerOptions;\n /** Per-repo overrides keyed by repo name in the mapping. */\n repos?: Partial<Record<keyof M & string, HistoryTriggerRepoOverride>>;\n}\n","/**\n * Shadow metadata injection, resolution, and read-stripping helpers for the\n * history module.\n *\n * Writes actor metadata from the cross-bundle `AsyncLocalStorage` context into\n * a configurable shadow object (default `_historyMeta`) on Firestore documents\n * without requiring any changes to model Zod schemas.\n */\n\nimport { getCurrentActor } from \"../shared/actor-context\";\nimport {\n DEFAULT_HISTORY_SHADOW_KEY,\n type HistoryConfigForModel,\n} from \"./types\";\n\nexport interface ResolvedShadowFields {\n userId: string | false;\n userEmail: string | false;\n reason: string | false;\n comment: string | false;\n extras: string | false;\n}\n\nexport interface ResolvedShadowConfig {\n key: string;\n fields: ResolvedShadowFields;\n}\n\n/**\n * Resolve the effective shadow storage configuration for a repository's\n * `history` config, or `null` when shadow storage is inactive.\n *\n * Shadow storage is active whenever `history.enabled` is `true`, `shadow` is\n * not `false`, and either `meta` is omitted or `shadow` is explicitly provided.\n */\nexport function resolveShadowConfig(\n config: HistoryConfigForModel<any> | undefined | null,\n): ResolvedShadowConfig | null {\n if (!config?.enabled) return null;\n if (config.shadow === false) return null;\n if (config.meta && config.shadow === undefined) return null;\n\n const shadowOpt = config.shadow;\n const key =\n typeof shadowOpt === \"string\" && shadowOpt.trim().length > 0\n ? shadowOpt.trim()\n : typeof shadowOpt === \"object\" &&\n shadowOpt !== null &&\n typeof shadowOpt.key === \"string\" &&\n shadowOpt.key.trim().length > 0\n ? shadowOpt.key.trim()\n : DEFAULT_HISTORY_SHADOW_KEY;\n\n const customFields =\n typeof shadowOpt === \"object\" && shadowOpt !== null\n ? shadowOpt.fields\n : undefined;\n\n return {\n key,\n fields: {\n userId: customFields?.userId ?? \"userId\",\n userEmail: customFields?.userEmail ?? \"userEmail\",\n reason: customFields?.reason ?? \"reason\",\n comment: customFields?.comment ?? \"comment\",\n extras: customFields?.extras ?? \"extras\",\n },\n };\n}\n\n/**\n * Return the active shadow key for a repository's history config, or `null`\n * when shadow storage is inactive.\n */\nexport function getHistoryShadowKey(\n config: HistoryConfigForModel<any> | undefined | null,\n): string | null {\n return resolveShadowConfig(config)?.key ?? null;\n}\n\n/**\n * Return the reserved identity/shadow keys that must be stripped from incoming\n * CRUD payloads (anti-spoofing) and omitted from Create/Update OpenAPI schemas.\n */\nexport function getHistoryIdentityKeys(\n config: HistoryConfigForModel<any> | undefined | null,\n): string[] {\n const shadow = resolveShadowConfig(config);\n return shadow ? [shadow.key] : [];\n}\n\n/**\n * Strip the internal shadow field from a document returned by repository\n * read/write methods (`get`, `query`, `paginate`, `create`, `set`, `update`,\n * `transaction.get`). Zero-overhead no-op when `shadowKey` is `null` or absent.\n */\nexport function stripHistoryShadowField<T>(\n value: T,\n shadowKey: string | null | undefined,\n): T {\n if (!shadowKey || !value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n const rec = value as Record<string, unknown>;\n if (!(shadowKey in rec)) return value;\n\n const { [shadowKey]: _dropped, ...rest } = rec;\n return rest as T;\n}\n\n/**\n * Inject the current ALS actor metadata into the configurable shadow field on\n * a Firestore write payload (`create`, `set`, `update`, `batch`, `transaction`,\n * `bulk`).\n *\n * Always writes explicit `null` for absent `reason`, `comment`, `extras`, and\n * applies `fallbackActor` when no actor is active so previous write metadata\n * never leaks — including across Firestore `set(..., { merge: true })`.\n */\nexport function injectHistoryMeta(\n payload: Record<string, unknown>,\n historyConfig: HistoryConfigForModel<any> | undefined,\n): void {\n if (!historyConfig?.enabled || historyConfig.autoInjectMeta === false) return;\n\n const shadow = resolveShadowConfig(historyConfig);\n if (!shadow) return;\n\n const actor = getCurrentActor();\n const fallback = historyConfig.fallbackActor ?? {};\n const userId =\n actor?.userId !== undefined ? actor.userId : (fallback.userId ?? null);\n const userEmail =\n actor?.userEmail !== undefined\n ? actor.userEmail\n : (fallback.userEmail ?? null);\n const reason = actor?.reason ?? null;\n const comment = actor?.comment ?? null;\n const extras =\n actor?.extras && Object.keys(actor.extras).length > 0 ? actor.extras : null;\n\n const shadowObj: Record<string, unknown> = {};\n const { fields } = shadow;\n if (fields.userId !== false) shadowObj[fields.userId] = userId;\n if (fields.userEmail !== false) shadowObj[fields.userEmail] = userEmail;\n if (fields.reason !== false) shadowObj[fields.reason] = reason;\n if (fields.comment !== false) shadowObj[fields.comment] = comment;\n if (fields.extras !== false) shadowObj[fields.extras] = extras;\n\n payload[shadow.key] = shadowObj;\n}\n","import { randomBytes } from \"node:crypto\";\nimport type { DocumentReference, Firestore } from \"firebase-admin/firestore\";\n\nconst ID_CHARS =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n/**\n * Generate a random 20-char alphanumeric ID matching Firestore's native format.\n *\n * Uses a CSPRNG (`crypto.randomBytes`) with rejection sampling (dropping the\n * biased tail `>= 62*4`) to keep the distribution uniform across the 62-char\n * alphabet.\n */\nexport function generateFirestoreId(): string {\n let id = \"\";\n while (id.length < 20) {\n const bytes = randomBytes(20);\n for (let i = 0; i < bytes.length && id.length < 20; i++) {\n const byte = bytes[i]!;\n if (byte >= ID_CHARS.length * 4) continue; // drop biased tail (248..255)\n id += ID_CHARS.charAt(byte % ID_CHARS.length);\n }\n }\n return id;\n}\n\n/** Extract parameter name from a `{param}` segment, or `null` if static. */\nfunction extractSegmentParam(segment: string): string | null {\n const match = segment.match(/^\\{([^}]+)\\}$/);\n return match?.[1]?.trim() || null;\n}\n\n/**\n * Parsed metadata from a repository `path` configuration string.\n */\nexport interface ParsedPathTemplate {\n /** Raw path string as configured on the repository */\n rawPath: string;\n /**\n * Target Firestore collection ID (last collection segment, e.g. `\"prev_events\"`\n * from `\"prevention/prev_rules/prev_workshops/{workshopId}/prev_events\"`).\n * Used for `db.collectionGroup(collectionId)`.\n */\n collectionId: string;\n /**\n * Collection path (without trailing document segment). Used for `db.collection(...)`\n * on non-group repositories (`isGroup: false`).\n */\n collectionPath: string;\n /**\n * Ordered list of dynamic `{param}` parent keys extracted from the path\n * (excluding fixed transit segments like `\"prev_rules\"` and the trailing\n * `documentKey`).\n */\n parentKeys: string[];\n /**\n * Full Firestore document path pattern including trailing `/{documentKey}`\n * (e.g. `\"prevention/prev_rules/prev_workshops/{workshopId}/prev_events/{docId}\"`),\n * or `null` when `isGroup: true` and `rawPath` is a bare single-segment\n * collection name without a path template.\n */\n documentPathTemplate: string | null;\n /** `true` when `rawPath` contains `/` or `{...}` template placeholders */\n hasTemplate: boolean;\n}\n\n/**\n * Parse a repository `path` into collection ID, ordered dynamic parent keys,\n * and full document path template.\n *\n * Supports:\n * - Bare collection names: `\"users\"`, `\"res_events\"`\n * - Odd-segment collection templates: `\"residences/{residenceId}/res_events\"`,\n * `\"prevention/prev_rules/prev_workshops/{workshopId}/prev_events\"`\n * - Even-segment document templates: `\"residences/{residenceId}/res_events/{docId}\"`\n */\nexport function parsePathTemplate(\n rawPath: string,\n documentKey = \"docId\",\n isGroup = false,\n): ParsedPathTemplate {\n if (typeof rawPath !== \"string\" || !rawPath.trim()) {\n return {\n rawPath: rawPath ?? \"\",\n collectionId: \"\",\n collectionPath: \"\",\n parentKeys: [],\n documentPathTemplate: null,\n hasTemplate: false,\n };\n }\n\n const segments = rawPath\n .split(\"/\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n if (segments.length === 0) {\n return {\n rawPath,\n collectionId: rawPath,\n collectionPath: rawPath,\n parentKeys: [],\n documentPathTemplate: null,\n hasTemplate: false,\n };\n }\n\n if (segments.length === 1) {\n const seg = segments[0]!;\n return {\n rawPath,\n collectionId: seg,\n collectionPath: seg,\n parentKeys: [],\n documentPathTemplate: isGroup ? null : `${seg}/{${documentKey}}`,\n hasTemplate: rawPath.includes(\"{\") && rawPath.includes(\"}\"),\n };\n }\n\n // Multi-segment path:\n // - Even number of segments (col/doc/col/{docId}) -> last segment is the document ID placeholder\n // - Odd number of segments (col/doc/col) -> last segment is the target collection\n const isEvenSegments = segments.length % 2 === 0;\n const collectionSegments = isEvenSegments ? segments.slice(0, -1) : segments;\n const collectionId = collectionSegments[collectionSegments.length - 1]!;\n const collectionPath = collectionSegments.join(\"/\");\n\n // Parent segments are all segments before the target collection segment\n const parentSegments = collectionSegments.slice(0, -1);\n const parentKeys = parentSegments\n .map(extractSegmentParam)\n .filter((p): p is string => p !== null);\n\n const documentPathTemplate = isEvenSegments\n ? segments.join(\"/\")\n : `${collectionPath}/{${documentKey}}`;\n\n return {\n rawPath,\n collectionId,\n collectionPath,\n parentKeys,\n documentPathTemplate,\n hasTemplate: true,\n };\n}\n\n/**\n * Build a Firestore `DocumentReference` from a `documentPathTemplate`\n * (e.g. `\"prevention/prev_rules/prev_workshops/{workshopId}/prev_events/{docId}\"`)\n * and positional dynamic arguments (`[workshopId, docId]`).\n *\n * Static transit segments (like `\"prev_rules\"`) are preserved automatically.\n */\nexport function buildDocumentRefFromTemplate(\n db: Firestore,\n documentPathTemplate: string,\n args: unknown[],\n): DocumentReference {\n const segments = documentPathTemplate\n .split(\"/\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n let argIndex = 0;\n const resolvedSegments: string[] = [];\n\n for (const seg of segments) {\n const paramName = extractSegmentParam(seg);\n if (paramName !== null) {\n const val = args[argIndex++];\n if (typeof val !== \"string\" || val.trim() === \"\") {\n throw new Error(\n `Missing or empty path parameter \"${paramName}\" when resolving document reference for \"${documentPathTemplate}\".`,\n );\n }\n resolvedSegments.push(val);\n } else {\n resolvedSegments.push(seg);\n }\n }\n\n const anyDb = db as any;\n\n // Try walking db.collection(seg0).doc(seg1).collection(seg2).doc(seg3)...\n // so mocks that spy on .collection().doc() work identically to hand-written refCb.\n if (typeof anyDb?.collection === \"function\" && resolvedSegments.length >= 2) {\n let cur: any = anyDb;\n let walked = true;\n for (let i = 0; i < resolvedSegments.length; i += 2) {\n const colName = resolvedSegments[i]!;\n const docId = resolvedSegments[i + 1]!;\n if (typeof cur?.collection !== \"function\") {\n walked = false;\n break;\n }\n const colRef = cur.collection(colName);\n if (typeof colRef?.doc !== \"function\") {\n walked = false;\n break;\n }\n cur = colRef.doc(docId);\n }\n if (walked && cur && cur !== anyDb) {\n return cur as DocumentReference;\n }\n }\n\n // Fallback: db.doc(fullPath)\n const fullPath = resolvedSegments.join(\"/\");\n if (typeof anyDb?.doc === \"function\") {\n return anyDb.doc(fullPath) as DocumentReference;\n }\n\n // Last-resort fallback for minimal single-collection test mocks\n if (typeof anyDb?.collection === \"function\" && resolvedSegments.length >= 2) {\n const colPath = resolvedSegments.slice(0, -1).join(\"/\");\n const docId = resolvedSegments[resolvedSegments.length - 1]!;\n const colRef = anyDb.collection(colPath);\n if (typeof colRef?.doc === \"function\") {\n return colRef.doc(docId) as DocumentReference;\n }\n return colRef as DocumentReference;\n }\n\n throw new Error(\n `Cannot resolve DocumentReference for \"${fullPath}\": Firestore instance does not expose .collection() or .doc().`,\n );\n}\n\nexport interface ExtractPathArgsOptions {\n pathKey?: string | null;\n documentKey?: string | null;\n parentKeys?: string[];\n documentPathTemplate?: string | null;\n isGroup?: boolean;\n}\n\n/**\n * Extract the dynamic document reference arguments from a stored document.\n *\n * Unlike naive odd-segment splitting, this helper skips fixed transit document\n * segments (such as `\"prev_rules\"` in `\"prevention/prev_rules/prev_workshops/w1/prev_events/e1\"`)\n * by matching against `documentPathTemplate` or `parentKeys`.\n */\nexport function extractPathArgsFromDoc(\n doc: Record<string, unknown> | null | undefined,\n options: ExtractPathArgsOptions = {},\n): string[] | undefined {\n if (!doc || typeof doc !== \"object\") return undefined;\n\n const {\n pathKey,\n documentKey = \"docId\",\n parentKeys,\n documentPathTemplate,\n isGroup,\n } = options;\n\n const fullPath =\n pathKey && typeof doc[pathKey] === \"string\" && doc[pathKey]\n ? (doc[pathKey] as string)\n : undefined;\n\n // 1. If we have both fullPath and a matching documentPathTemplate, extract only `{param}` positions\n if (fullPath && documentPathTemplate) {\n const pathSegments = fullPath.split(\"/\").filter(Boolean);\n const tplSegments = documentPathTemplate.split(\"/\").filter(Boolean);\n if (pathSegments.length === tplSegments.length) {\n const extracted: string[] = [];\n for (let i = 0; i < tplSegments.length; i++) {\n if (extractSegmentParam(tplSegments[i]!) !== null) {\n extracted.push(pathSegments[i]!);\n }\n }\n if (extracted.length > 0) {\n return extracted;\n }\n }\n }\n\n // 2. If parentKeys are known and non-empty\n if (parentKeys && parentKeys.length > 0) {\n const expectedCount = parentKeys.length + 1;\n\n if (fullPath) {\n const segments = fullPath.split(\"/\").filter(Boolean);\n const oddSegments: string[] = [];\n for (let i = 1; i < segments.length; i += 2) {\n oddSegments.push(segments[i]!);\n }\n if (oddSegments.length >= expectedCount) {\n return oddSegments.slice(oddSegments.length - expectedCount);\n }\n }\n\n // Fallback: extract parentKeys + documentKey directly from document fields\n const docIdVal = documentKey ? doc[documentKey] : undefined;\n if (typeof docIdVal === \"string\" && docIdVal.trim() !== \"\") {\n const parentVals: string[] = [];\n let allPresent = true;\n for (const pk of parentKeys) {\n const v = doc[pk];\n if (typeof v === \"string\" && v.trim() !== \"\") {\n parentVals.push(v);\n } else {\n allPresent = false;\n break;\n }\n }\n if (allPresent) {\n return [...parentVals, docIdVal];\n }\n }\n }\n\n // 3. Fallback when fullPath is present\n if (fullPath) {\n const segments = fullPath.split(\"/\").filter(Boolean);\n const oddSegments: string[] = [];\n for (let i = 1; i < segments.length; i += 2) {\n oddSegments.push(segments[i]!);\n }\n if (oddSegments.length > 0) {\n // For non-group repos without parentKeys (e.g. under a fixed transit doc), only the last docId is dynamic\n if (!isGroup && (!parentKeys || parentKeys.length === 0)) {\n return [oddSegments[oddSegments.length - 1]!];\n }\n return oddSegments;\n }\n }\n\n return undefined;\n}\n","import type {\n CollectionReference,\n Firestore,\n Query,\n} from \"firebase-admin/firestore\";\nimport {\n getHistoryIdentityKeys,\n getHistoryShadowKey,\n} from \"../history/inject\";\nimport { createHistoryMethods, type HistoryMethods } from \"../history/read\";\nimport { createAggregateMethods } from \"../methods/aggregate\";\nimport { createBatchMethods } from \"../methods/batch\";\nimport { createBulkMethods } from \"../methods/bulk\";\nimport { createCrudMethods } from \"../methods/crud\";\nimport { createGetMethods } from \"../methods/get\";\nimport { createQueryMethods } from \"../methods/query\";\nimport { createPopulateMethods } from \"../methods/relations\";\nimport { createSystemMethods } from \"../methods/system\";\nimport { createTransactionMethods } from \"../methods/transaction\";\nimport {\n buildDocumentRefFromTemplate,\n parsePathTemplate,\n} from \"../shared/path-template\";\nimport type { RepositoryConfig } from \"../shared/types\";\nimport type { ConfiguredRepository } from \"./types\";\n\n/**\n * Extract parent-key parameter names from a refCb function.\n * For `(db, postId, docId) => …` this returns `[\"postId\"]` (everything\n * between the first param – the Firestore `db` – and the last param – the\n * document's own ID).\n * Returns an empty array when the function has ≤ 2 params (db + docId).\n * @internal\n */\nfunction extractParentKeys(refCb: unknown): string[] {\n if (typeof refCb !== \"function\") return [];\n const src = refCb.toString();\n const match = src.match(/^\\s*(?:function\\s*\\w*\\s*)?\\(([^)]*)\\)/);\n if (!match?.[1]) return [];\n const params = match[1]\n .split(\",\")\n .map((p) => p.trim().replace(/\\s*[:=].*$/, \"\").trim())\n .filter(Boolean);\n // (db, docId) → 0 parents; (db, parentId, docId) → 1 parent; etc.\n if (params.length <= 2) return [];\n return params.slice(1, -1);\n}\n\n/**\n * Build the **static** repository metadata that server/trigger builders read at\n * definition time (schema, system keys, path/group flags, history settings,\n * relational keys) directly from a raw repository **config** — i.e. without\n * resolving Firestore. Mirrors the same fields exposed by the resolved\n * repository, so it can back a {@link makeLazyRepo} overlay.\n */\nexport function buildRepoStaticMeta(config: any): Record<string, unknown> {\n const documentKey = (config?.documentKey as string | undefined) ?? \"docId\";\n const isGroup = !!config?.isGroup;\n const parsedPath = parsePathTemplate(\n typeof config?.path === \"string\" ? config.path : \"\",\n documentKey,\n isGroup,\n );\n const parentKeys =\n parsedPath.parentKeys.length > 0\n ? parsedPath.parentKeys\n : isGroup\n ? extractParentKeys(config?.refCb)\n : [];\n\n const systemKeys = [\n config?.documentKey,\n config?.pathKey,\n config?.createdKey,\n config?.updatedKey,\n ].filter((k): k is string => typeof k === \"string\");\n const historyConfig =\n config?.history && typeof config.history === \"object\"\n ? config.history\n : undefined;\n return {\n schema: config?.schema,\n _systemKeys: systemKeys,\n _pathKey: (config?.pathKey as string | undefined) ?? null,\n _isGroup: isGroup,\n _createdKey: (config?.createdKey as string | undefined) ?? null,\n _parentKeys: parentKeys,\n _documentPathTemplate: parsedPath.documentPathTemplate,\n _collectionId:\n typeof config?.path === \"string\" ? parsedPath.collectionId : null,\n relationalKeys: config?.relationalKeys,\n _historyConfig: historyConfig,\n _historyShadowKey: getHistoryShadowKey(historyConfig),\n _historyIdentityKeys: getHistoryIdentityKeys(historyConfig),\n _historySubcollection: historyConfig?.enabled\n ? (historyConfig.subcollection ?? \"history\")\n : undefined,\n // Collection path of a non-group repo (== resolved `ref.path`). Lets\n // trigger builders derive the document path without resolving the db.\n _collectionPath:\n typeof config?.path === \"string\" ? parsedPath.collectionPath : null,\n };\n}\n\n/**\n * Wrap a repository behind a lazy Proxy: **static** metadata (see\n * {@link buildRepoStaticMeta}) is served from `config` without resolving\n * Firestore, while every dynamic access (`ref`, `get`, `query`, `history.*`, …)\n * resolves the real repository on first use via `resolve()` and memoizes it.\n *\n * Lets server builders read static config at module-load time without forcing\n * `getFirestore()` — the db is only touched when a request handler actually\n * uses a repository method.\n */\nexport function makeLazyRepo<R>(config: any, resolve: () => R): R {\n const overlay = buildRepoStaticMeta(config);\n let resolved: R | undefined;\n const ensure = (): R => {\n const res = resolved ??= resolve();\n if (!res) {\n const path = (overlay as any)._collectionPath || \"unknown\";\n throw new Error(`[makeLazyRepo] Failed to resolve repository for path \"${path}\". The repository mapping resolved to undefined. This almost always indicates a circular import where the repository was exported as undefined.`);\n }\n return res;\n };\n return new Proxy(overlay as any, {\n get(_t, prop) {\n if (typeof prop === \"string\" && prop in overlay) {\n return (overlay as any)[prop];\n }\n return (ensure() as any)[prop];\n },\n has(_t, prop) {\n if (typeof prop === \"string\" && prop in overlay) return true;\n return prop in (ensure() as any);\n },\n }) as R;\n}\n\n/**\n * Creates a configured repository instance with all methods\n */\nexport function createRepository<\n T extends RepositoryConfig<any, any, any, any, any, any, any, any, any, any, any>,\n>(\n db: Firestore,\n config: T,\n allRepositories: Record<string, any> = {},\n): ConfiguredRepository<T> {\n const documentKey = config.documentKey as string;\n const parsedPath = parsePathTemplate(\n config.path,\n documentKey,\n !!config.isGroup,\n );\n const parentKeys =\n parsedPath.parentKeys.length > 0\n ? parsedPath.parentKeys\n : config.isGroup\n ? extractParentKeys(config.refCb)\n : [];\n\n // Create collection reference\n const collectionRef: CollectionReference | Query = config.isGroup\n ? db.collectionGroup(parsedPath.collectionId)\n : db.collection(parsedPath.collectionPath);\n\n // Keep actual collection for create operations\n const actualCollection = config.isGroup\n ? null\n : db.collection(parsedPath.collectionPath);\n\n // Create document reference function (auto-generated from path template when refCb is omitted)\n const documentRef =\n typeof config.refCb === \"function\"\n ? (...args: any[]) => (config.refCb as any)(db, ...args)\n : (...args: any[]) =>\n buildDocumentRefFromTemplate(\n db,\n parsedPath.documentPathTemplate ??\n `${parsedPath.collectionPath}/{${documentKey}}`,\n args,\n );\n\n // History config & shadow metadata resolution\n const historyConfig = (config as any).history as\n | { enabled: boolean; [k: string]: any }\n | undefined;\n const historyShadowKey = getHistoryShadowKey(historyConfig as any);\n const historyIdentityKeys = getHistoryIdentityKeys(historyConfig as any);\n\n // Create all method groups\n const getMethods = createGetMethods(\n collectionRef as Query,\n config.foreignKeys,\n actualCollection,\n documentRef,\n documentKey,\n historyShadowKey,\n );\n const queryMethods = createQueryMethods(\n collectionRef as Query,\n config.queryKeys,\n config.relationalKeys as Record<string, any> | undefined,\n allRepositories,\n historyShadowKey,\n );\n const aggregateMethods = createAggregateMethods(collectionRef as Query);\n const crudMethods = createCrudMethods(\n actualCollection,\n documentRef,\n documentKey,\n config.pathKey as string | undefined,\n config.createdKey as string | undefined,\n config.updatedKey as string | undefined,\n parentKeys,\n parsedPath.documentPathTemplate,\n historyConfig as any,\n );\n const batchMethods = createBatchMethods(\n db,\n documentRef,\n config.documentKey as string,\n config.pathKey as string | undefined,\n config.createdKey as string | undefined,\n config.updatedKey as string | undefined,\n historyConfig as any,\n );\n const transactionMethods = createTransactionMethods(\n db,\n documentRef,\n config.documentKey as string,\n config.pathKey as string | undefined,\n config.createdKey as string | undefined,\n config.updatedKey as string | undefined,\n historyConfig as any,\n );\n const bulkMethods = createBulkMethods(\n db,\n config.createdKey as string | undefined,\n config.updatedKey as string | undefined,\n historyConfig as any,\n );\n const systemMethods = createSystemMethods(\n db,\n collectionRef,\n config.documentKey as string,\n config.pathKey as string | undefined,\n config.createdKey as string | undefined,\n config.updatedKey as string | undefined,\n );\n const populateMethods = createPopulateMethods(config, allRepositories);\n\n // History namespace (opt-in via config.history.enabled)\n const history: HistoryMethods<any> | null =\n historyConfig?.enabled\n ? (createHistoryMethods(\n documentRef,\n [\n config.documentKey as string,\n config.pathKey as string | undefined,\n config.createdKey as string | undefined,\n config.updatedKey as string | undefined,\n ].filter((k): k is string => typeof k === \"string\"),\n (config as any).path ?? \"(unknown)\",\n historyConfig as any,\n ) as HistoryMethods<any>)\n : null;\n\n return {\n ref: collectionRef,\n documentRef,\n get: getMethods,\n query: queryMethods,\n aggregate: aggregateMethods,\n ...crudMethods,\n batch: batchMethods,\n transaction: transactionMethods,\n bulk: bulkMethods,\n system: systemMethods,\n ...populateMethods,\n ...(history ? { history } : {}),\n // Expose the configured history subcollection name (when history is enabled)\n // so external consumers (admin UI, etc.) can display / link it correctly.\n _historySubcollection: history\n ? (historyConfig?.subcollection ?? \"history\")\n : undefined,\n // Expose the raw history config so trigger builders (createHistoryTriggers)\n // can introspect `enabled`, `meta`, `include`, `exclude`, `ttl`, `subcollection`.\n // The public `history` key is intentionally the methods namespace, not the\n // config — this private field bridges the two without breaking that API.\n _historyConfig: historyConfig,\n _historyShadowKey: historyShadowKey,\n _historyIdentityKeys: historyIdentityKeys,\n // Pass through the Zod schema if one was attached via createRepositoryConfig(schema)\n schema: (config as any).schema,\n // Pass through relational keys built by buildRepositoryRelations\n relationalKeys: (config as any).relationalKeys,\n // Auto-managed keys that should never be accepted in user-provided payloads\n _systemKeys: [\n config.documentKey as string,\n config.pathKey as string | undefined,\n config.createdKey as string | undefined,\n config.updatedKey as string | undefined,\n ].filter((k): k is string => typeof k === \"string\"),\n // Expose pathKey name so server handlers can extract path args from documents\n _pathKey: (config.pathKey as string | undefined) ?? null,\n // Whether this is a collectionGroup repository\n _isGroup: !!config.isGroup,\n // Parent key field names auto-detected from path template or refCb signature\n _parentKeys: parentKeys,\n // Full document path template (e.g. \"prevention/prev_rules/prev_workshops/{workshopId}/prev_events/{docId}\")\n _documentPathTemplate: parsedPath.documentPathTemplate,\n // Resolved collection ID and collection path\n _collectionId: parsedPath.collectionId,\n _collectionPath: parsedPath.collectionPath,\n // Expose createdKey so server handlers can inject it when using set() for creates\n _createdKey: (config.createdKey as string | undefined) ?? null,\n } as unknown as ConfiguredRepository<T>;\n}\n","import type { RepoSyncConfig } from \"./types\";\n\n/**\n * Convert a single Firestore value into a SQL-safe primitive or JSON-serializable value.\n *\n * Complex types (arrays, GeoPoints, binary) become JSON strings in flat mode.\n * In non-flat mode (`stringifyArrays: false`), arrays and nested objects stay structured.\n * Primitives pass through unchanged.\n */\nexport function serializeValue(\n value: unknown,\n options?: { stringifyArrays?: boolean },\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): unknown {\n if (value === null || value === undefined) return null;\n\n // Firestore Timestamp (duck-typed: has .toDate())\n if (\n typeof value === \"object\" &&\n typeof (value as Record<string, unknown>).toDate === \"function\"\n ) {\n return ((value as { toDate(): Date }).toDate()).toISOString();\n }\n\n if (value instanceof Date) return value.toISOString();\n\n if (Buffer.isBuffer(value)) return value.toString(\"base64\");\n\n if (value instanceof Uint8Array) {\n return Buffer.from(value).toString(\"base64\");\n }\n\n // Firestore GeoPoint (duck-typed: has latitude & longitude)\n if (\n typeof value === \"object\" &&\n \"latitude\" in (value as object) &&\n \"longitude\" in (value as object)\n ) {\n const geo = value as { latitude: number; longitude: number };\n if (options?.stringifyArrays === false) {\n return { lat: geo.latitude, lng: geo.longitude };\n }\n return JSON.stringify({ lat: geo.latitude, lng: geo.longitude });\n }\n\n // Arrays\n if (Array.isArray(value)) {\n const mapped = value.map((item) =>\n serializeValue(item, options, seen, depth + 1),\n );\n return options?.stringifyArrays === false ? mapped : JSON.stringify(mapped);\n }\n\n // Plain objects (when inside nested serialization)\n if (\n typeof value === \"object\" &&\n value !== null &&\n options?.stringifyArrays === false\n ) {\n return serializeNestedObject(\n value as Record<string, unknown>,\n new Set(),\n {},\n seen,\n depth + 1,\n );\n }\n\n // string | number | boolean — pass through\n // Plain objects in flat mode are handled by flattenObject in serializeDocument\n return value;\n}\n\n/**\n * Recursively flatten a nested object into a flat key-value map\n * using underscore-separated keys: `{ address: { street: \"x\" } }` → `{ address_street: \"x\" }`.\n * Arrays and non-plain-object values are serialized as leaves.\n *\n * Guards against pathological inputs that would otherwise crash the worker\n * (and trigger an infinite PubSub redelivery loop, see issue #11):\n * - **Cycles** (`obj.self = obj`) → emitted once as a `{ __cycle: true }` marker.\n * - **Excessive depth** → truncated past {@link MAX_FLATTEN_DEPTH}.\n * - **Excessive width** → stops emitting past {@link MAX_FLATTEN_KEYS}\n * (BigQuery caps tables at 10k columns).\n */\nconst MAX_FLATTEN_DEPTH = 32;\nconst MAX_FLATTEN_KEYS = 5000;\n\nfunction flattenObject(\n obj: Record<string, unknown>,\n prefix: string,\n result: Record<string, unknown>,\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): void {\n if (depth > MAX_FLATTEN_DEPTH) {\n result[prefix || \"_truncated\"] = JSON.stringify({ __truncated: true });\n return;\n }\n if (seen.has(obj)) {\n result[prefix || \"_cycle\"] = JSON.stringify({ __cycle: true });\n return;\n }\n seen.add(obj);\n\n for (const [key, value] of Object.entries(obj)) {\n if (Object.keys(result).length >= MAX_FLATTEN_KEYS) break;\n const flatKey = prefix ? `${prefix}__${key}` : key;\n\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !Buffer.isBuffer(value) &&\n !(value instanceof Uint8Array) &&\n // Not a Firestore Timestamp\n typeof (value as Record<string, unknown>).toDate !== \"function\" &&\n // Not a GeoPoint\n !(\"latitude\" in (value as object) && \"longitude\" in (value as object))\n ) {\n // Plain object → recurse\n flattenObject(\n value as Record<string, unknown>,\n flatKey,\n result,\n seen,\n depth + 1,\n );\n } else {\n result[flatKey] = serializeValue(value);\n }\n }\n\n // Allow the same object to appear in sibling branches (only direct\n // ancestors form a cycle), so drop it from the path on the way out.\n seen.delete(obj);\n}\n\n/**\n * Recursively serialize a nested object preserving object and array structures,\n * while serializing leaf values (Timestamps, Dates, Buffers, GeoPoints).\n */\nfunction serializeNestedObject(\n obj: Record<string, unknown>,\n exclude: Set<string>,\n columnMap: Record<string, string>,\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): Record<string, unknown> {\n if (depth > MAX_FLATTEN_DEPTH) {\n return { __truncated: true };\n }\n if (seen.has(obj)) {\n return { __cycle: true };\n }\n seen.add(obj);\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (exclude.has(key)) continue;\n const mappedKey = columnMap[key] ?? key;\n\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !Buffer.isBuffer(value) &&\n !(value instanceof Uint8Array) &&\n typeof (value as Record<string, unknown>).toDate !== \"function\" &&\n !(\"latitude\" in (value as object) && \"longitude\" in (value as object))\n ) {\n result[mappedKey] = serializeNestedObject(\n value as Record<string, unknown>,\n new Set(),\n {},\n seen,\n depth + 1,\n );\n } else {\n result[mappedKey] = serializeValue(\n value,\n { stringifyArrays: false },\n seen,\n depth + 1,\n );\n }\n }\n\n seen.delete(obj);\n return result;\n}\n\n/**\n * Reconstructs nested objects from flat double-underscore keys (`address__city` → `address.city`)\n * and parses JSON-stringified arrays back into native arrays.\n */\nexport function unflattenDocument(\n doc: Record<string, unknown>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, rawValue] of Object.entries(doc)) {\n let value = rawValue;\n\n // If array or object was stringified into JSON (e.g. from a flat SQL sync worker event)\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) ||\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\"))\n ) {\n try {\n value = JSON.parse(trimmed);\n } catch {\n // Keep as string if not valid JSON\n }\n }\n }\n\n if (key.startsWith(\"__\") || !key.includes(\"__\")) {\n result[key] = value;\n continue;\n }\n\n const parts = key.split(\"__\").filter(Boolean);\n let current: any = result;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (\n !current[part] ||\n typeof current[part] !== \"object\" ||\n Array.isArray(current[part])\n ) {\n current[part] = {};\n }\n current = current[part];\n }\n current[parts[parts.length - 1]!] = value;\n }\n\n return result;\n}\n\n/**\n * Serialize a full Firestore document.\n *\n * When `flat` is `true` (default):\n * Nested objects are flattened into underscore-separated column names\n * (e.g. `address.street` → `address_street`). Arrays become JSON strings.\n *\n * When `flat` is `false`:\n * Nested objects and native arrays are preserved with leaf types normalized\n * (ideal for Meilisearch and document search engines).\n *\n * Applies optional field exclusions, column renames, and custom `transformDoc`.\n */\nexport function serializeDocument(\n doc: Record<string, unknown>,\n options?: Pick<\n RepoSyncConfig,\n \"exclude\" | \"columnMap\" | \"flat\" | \"transformDoc\"\n >,\n): Record<string, unknown> {\n const isFlat = options?.flat !== false;\n let result: Record<string, unknown>;\n\n if (isFlat) {\n const exclude = new Set(options?.exclude);\n const columnMap = options?.columnMap ?? {};\n\n // Drop excluded top-level keys before flattening so keys starting with\n // \"__\" (e.g. \"__audit\") are reliably excluded without splitting issues.\n let sourceDoc = doc;\n if (exclude.size > 0) {\n let dropped = false;\n const filtered: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(doc)) {\n if (exclude.has(k)) {\n dropped = true;\n continue;\n }\n filtered[k] = v;\n }\n if (dropped) sourceDoc = filtered;\n }\n\n // First flatten the document\n const flat: Record<string, unknown> = {};\n flattenObject(sourceDoc, \"\", flat);\n\n // Then apply excludes and column renames\n result = {};\n for (const [flatKey, value] of Object.entries(flat)) {\n if (exclude.has(flatKey)) continue;\n // Also check top-level prefix for excludes (e.g. exclude \"address\" removes all address_* cols)\n const topLevel = flatKey.split(\"__\")[0]!;\n if (topLevel !== flatKey && exclude.has(topLevel)) continue;\n const column =\n columnMap[flatKey] ??\n (flatKey.includes(\"__\")\n ? columnMap[flatKey.split(\"__\").pop()!]\n : undefined) ??\n flatKey;\n result[column] = value;\n }\n } else {\n const exclude = new Set(options?.exclude);\n const columnMap = (options?.columnMap ?? {}) as Record<string, string>;\n result = serializeNestedObject(doc, exclude, columnMap);\n }\n\n if (typeof options?.transformDoc === \"function\") {\n result = options.transformDoc(result);\n }\n\n return result;\n}\n","/**\n * Firestore Cloud Function triggers that publish {@link SyncEvent}s to\n * Google Cloud PubSub.\n *\n * Dependencies (`firebase-functions`, `@google-cloud/pubsub`) are injected\n * via the `deps` config property — no lazy loading or module resolution issues.\n *\n * Out-of-order delivery is handled at the application level: every event\n * carries a `version` (publish-time `Date.now()` in ms) which is propagated\n * to SQL as the `__sync_version` column. The worker's MERGE only updates a\n * row when the incoming `version` is strictly greater than the stored one —\n * so a stale event delivered after a newer one is silently skipped.\n *\n * @example\n * ```typescript\n * import { createSyncTriggers } from \"@lpdjs/firestore-repo-service/sync\";\n * import * as firestoreTriggers from \"firebase-functions/v2/firestore\";\n * import { PubSub } from \"@google-cloud/pubsub\";\n *\n * const triggers = createSyncTriggers(repos, {\n * deps: { firestoreTriggers, pubsub: new PubSub() },\n * topicPrefix: \"my-sync\",\n * repos: { users: { exclude: [\"password\"] } },\n * });\n *\n * export const { users_onCreate, users_onUpdate, users_onDelete } = triggers;\n * ```\n */\n\nimport { getHistoryShadowKey } from \"../history/inject\";\nimport { parsePathTemplate } from \"../shared/path-template\";\nimport { serializeDocument } from \"./serializer\";\nimport type { RepoSyncConfig, SyncEvent, SyncTriggersConfig } from \"./types\";\n\nconst DEFAULT_TOPIC_PREFIX = \"firestore-sync\";\n\n/**\n * Derive the Firestore document path pattern for a trigger.\n * Returns `null` when the collection path cannot be determined.\n */\nfunction buildDocumentPath(\n repoName: string,\n collectionPath: string | null,\n): string | null {\n if (!collectionPath) {\n console.warn(\n `[SyncTriggers] Cannot determine collection path for \"${repoName}\". Skipping.`,\n );\n return null;\n }\n\n return `${collectionPath}/{docId}`;\n}\n\n/** Static, db-free metadata needed to register a sync trigger. */\ninterface SyncRepoMeta {\n isGroup: boolean;\n documentKey: string;\n /** Collection path of a non-group repo. */\n collectionPath: string | null;\n /** Auto-derived document trigger path template when path is a full template. */\n documentPathTemplate: string | null;\n /** Shadow history field key to exclude automatically from synced payloads. */\n historyShadowKey: string | null;\n}\n\nfunction syncMetaFromConfig(cfg: any): SyncRepoMeta {\n const systemKeys = [\n cfg?.documentKey,\n cfg?.pathKey,\n cfg?.createdKey,\n cfg?.updatedKey,\n ].filter((k): k is string => typeof k === \"string\");\n const rawPath = typeof cfg?.path === \"string\" ? cfg.path : null;\n const parsed = rawPath\n ? parsePathTemplate(rawPath, cfg?.documentKey ?? \"docId\")\n : null;\n return {\n isGroup: !!cfg?.isGroup,\n documentKey: systemKeys[0] ?? \"docId\",\n collectionPath: parsed ? parsed.collectionPath : null,\n documentPathTemplate:\n parsed && (!cfg?.isGroup || parsed.collectionPath.includes(\"/\"))\n ? parsed.documentPathTemplate\n : null,\n historyShadowKey: getHistoryShadowKey(cfg?.history),\n };\n}\n\nfunction syncMetaFromRepo(repo: any): SyncRepoMeta {\n const collectionPath = repo?._collectionPath ?? repo?.ref?.path ?? null;\n const docTemplate =\n typeof repo?._documentPathTemplate === \"string\"\n ? repo._documentPathTemplate\n : null;\n return {\n isGroup: !!repo?._isGroup,\n documentKey: repo?._systemKeys?.[0] ?? \"docId\",\n collectionPath,\n documentPathTemplate:\n docTemplate && (!repo?._isGroup || (collectionPath && collectionPath.includes(\"/\")))\n ? docTemplate\n : null,\n historyShadowKey:\n typeof repo?._historyShadowKey === \"string\"\n ? repo._historyShadowKey\n : getHistoryShadowKey(repo?._historyConfig),\n };\n}\n\n/**\n * Create Firestore Cloud Functions (v2) triggers that publish\n * {@link SyncEvent}s to PubSub for each repository in `repoMapping`.\n *\n * For each non-group repository, three triggers are created:\n * - `{repoName}_onCreate` → publishes an `INSERT` event\n * - `{repoName}_onUpdate` → publishes an `UPSERT` event\n * - `{repoName}_onDelete` → publishes a `DELETE` event\n *\n * Each event carries a monotonic `version` (`Date.now()` in ms) used by\n * the worker to discard out-of-order PubSub deliveries.\n */\nexport function createSyncTriggers<M extends Record<string, any>>(\n repoMapping: M,\n config: SyncTriggersConfig<NoInfer<M>>,\n): Record<string, any> {\n const { onDocumentWritten } = config.deps.firestoreTriggers;\n const pubsub = config.deps.pubsub;\n\n const topicPrefix = config?.topicPrefix ?? DEFAULT_TOPIC_PREFIX;\n const triggers: Record<string, any> = {};\n\n // Cache topic clients so the publisher reuses the same batching state\n // for a given topic across invocations.\n const topicCache = new Map<string, any>();\n function getTopic(topicName: string): any {\n let t = topicCache.get(topicName);\n if (t) return t;\n t = (pubsub as any).topic(topicName);\n topicCache.set(topicName, t);\n return t;\n }\n\n async function publish(\n topicName: string,\n syncEvent: SyncEvent,\n ): Promise<void> {\n const topic = getTopic(topicName);\n await topic.publishMessage({ json: syncEvent });\n }\n\n // Prefer the raw mapping config (exposed by `createRepositoryMapping`) so\n // triggers register WITHOUT resolving Firestore. Falls back to introspecting\n // resolved repositories when a plain repo object is passed.\n const rawMapping: Record<string, any> | undefined = (repoMapping as any)\n ?.rawMapping;\n const entries: [string, SyncRepoMeta][] = rawMapping\n ? Object.entries(rawMapping).map(([name, cfg]) => [\n name,\n syncMetaFromConfig(cfg),\n ])\n : (Object.entries(repoMapping) as [string, any][]).map(([name, repo]) => [\n name,\n syncMetaFromRepo(repo),\n ]);\n\n const repoConfigsMap = config?.repos as\n | Record<string, RepoSyncConfig<string> | undefined>\n | undefined;\n const configuredKeys = Object.keys(repoConfigsMap ?? {});\n const hasExplicitRepos = configuredKeys.length > 0;\n\n for (const [repoName, meta] of entries) {\n if (hasExplicitRepos && (!repoConfigsMap || !(repoName in repoConfigsMap))) {\n continue;\n }\n\n const repoCfg = repoConfigsMap?.[repoName];\n\n let documentPath: string | null;\n\n if (meta.isGroup) {\n const resolvedGroupPath =\n repoCfg?.triggerPath ?? meta.documentPathTemplate;\n if (!resolvedGroupPath) {\n console.warn(\n `[SyncTriggers] Skipping collection-group repo \"${repoName}\". ` +\n \"Provide a triggerPath in the sync repos config for group collections or use a full path template.\",\n );\n continue;\n }\n documentPath = resolvedGroupPath;\n } else {\n documentPath =\n repoCfg?.triggerPath ??\n meta.documentPathTemplate ??\n buildDocumentPath(repoName, meta.collectionPath);\n }\n if (!documentPath) continue;\n\n const documentKey: string = meta.documentKey;\n const effectiveExclude = meta.historyShadowKey\n ? Array.from(new Set([...(repoCfg?.exclude ?? []), meta.historyShadowKey]))\n : repoCfg?.exclude;\n const topicName = `${topicPrefix}-${repoName}`;\n\n const effectiveTriggerOptions = {\n ...config?.triggerOptions,\n ...repoCfg?.triggerOptions,\n };\n const hasTriggerOptions = Object.keys(effectiveTriggerOptions).length > 0;\n\n const triggerHandler = async (event: any) => {\n const before = event.data?.before;\n const after = event.data?.after;\n\n if (!before && !after) return;\n\n const beforeExists = !!before?.exists;\n const afterExists = !!after?.exists;\n\n if (!beforeExists && afterExists) {\n // CREATE -> INSERT\n const data = after.data() as Record<string, unknown> | undefined;\n if (!data) return;\n\n const docId = String(data[documentKey] ?? after.id);\n const serialized = serializeDocument(data, {\n exclude: effectiveExclude,\n columnMap: repoCfg?.columnMap,\n flat: repoCfg?.flat,\n transformDoc: repoCfg?.transformDoc,\n });\n\n const syncEvent: SyncEvent = {\n operation: \"INSERT\",\n repoName,\n docId,\n data: serialized,\n timestamp: new Date().toISOString(),\n version: Date.now(),\n };\n\n await publish(topicName, syncEvent);\n } else if (beforeExists && afterExists) {\n // UPDATE -> UPSERT\n const data = after.data() as Record<string, unknown> | undefined;\n if (!data) return;\n\n const docId = String(data[documentKey] ?? after.id);\n const serialized = serializeDocument(data, {\n exclude: effectiveExclude,\n columnMap: repoCfg?.columnMap,\n flat: repoCfg?.flat,\n transformDoc: repoCfg?.transformDoc,\n });\n\n const syncEvent: SyncEvent = {\n operation: \"UPSERT\",\n repoName,\n docId,\n data: serialized,\n timestamp: new Date().toISOString(),\n version: Date.now(),\n };\n\n await publish(topicName, syncEvent);\n } else if (beforeExists && !afterExists) {\n // DELETE\n const data = before.data() as Record<string, unknown> | undefined;\n const docId = String(data?.[documentKey] ?? before.id);\n\n const syncEvent: SyncEvent = {\n operation: \"DELETE\",\n repoName,\n docId,\n data: null,\n timestamp: new Date().toISOString(),\n version: Date.now(),\n };\n\n await publish(topicName, syncEvent);\n }\n };\n\n triggers[`${repoName}_onSync`] = hasTriggerOptions\n ? onDocumentWritten(\n { document: documentPath, ...effectiveTriggerOptions } as any,\n triggerHandler,\n )\n : onDocumentWritten(documentPath, triggerHandler);\n }\n\n return triggers;\n}\n","/**\n * Internal constants shared between the worker, queue, schema mapper and\n * SQL adapters.\n */\n\n/**\n * Name of the SQL column that stores the publish-time `version` of each\n * sync event. Used by the worker to discard out-of-order PubSub deliveries\n * (the MERGE only updates rows when the incoming version is strictly\n * greater than the stored one).\n *\n * Two underscores prefix avoids collisions with user-defined fields.\n */\nexport const SYNC_VERSION_COLUMN = \"__sync_version\";\n","/**\n * Zod introspection utilities — compatible with Zod 4.\n *\n * Centralizes all internal `_zod.def` accesses so the rest of the codebase\n * never touches Zod internals directly. If a future Zod version changes\n * the internal layout, only this file needs updating.\n */\n\nimport type { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Type-name resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Canonical Zod type names used in the codebase.\n * These match the **Zod 3** naming convention (e.g. \"ZodString\") that the\n * form-gen / admin handlers already rely on, so we don't need to rewrite\n * every `case \"ZodString\":` branch.\n */\ntype ZodTypeName =\n | \"ZodString\"\n | \"ZodNumber\"\n | \"ZodBigInt\"\n | \"ZodBoolean\"\n | \"ZodDate\"\n | \"ZodEnum\"\n | \"ZodNativeEnum\"\n | \"ZodLiteral\"\n | \"ZodObject\"\n | \"ZodArray\"\n | \"ZodOptional\"\n | \"ZodNullable\"\n | \"ZodDefault\"\n | \"ZodCoerce\"\n | \"ZodUnion\"\n | \"ZodUndefined\"\n | \"ZodUnknown\"\n | \"ZodAny\"\n | \"ZodRecord\"\n | string;\n\n/**\n * Map from Zod 4 `_zod.def.type` (lowercase) → Zod 3 `_def.typeName` format.\n * Any key not in this map is capitalised as `Zod${Capitalised}`.\n */\nconst TYPE_MAP: Record<string, ZodTypeName> = {\n string: \"ZodString\",\n number: \"ZodNumber\",\n bigint: \"ZodBigInt\",\n boolean: \"ZodBoolean\",\n date: \"ZodDate\",\n enum: \"ZodEnum\",\n nativeEnum: \"ZodNativeEnum\",\n literal: \"ZodLiteral\",\n object: \"ZodObject\",\n array: \"ZodArray\",\n optional: \"ZodOptional\",\n nullable: \"ZodNullable\",\n default: \"ZodDefault\",\n coerce: \"ZodCoerce\",\n union: \"ZodUnion\",\n undefined: \"ZodUndefined\",\n unknown: \"ZodUnknown\",\n any: \"ZodAny\",\n record: \"ZodRecord\",\n};\n\n/**\n * Get the canonical type name of a Zod schema.\n *\n * Works with both Zod 3 (`_def.typeName`) and Zod 4 (`_zod.def.type`).\n * Returns names in Zod-3 style (\"ZodString\", \"ZodObject\" …) for\n * backward-compatible switch/case usage.\n */\nexport function getTypeName(schema: z.ZodType): ZodTypeName {\n const s = schema as any;\n\n // Zod 4 path\n const v4Type: string | undefined = s._zod?.def?.type;\n if (v4Type)\n return (\n TYPE_MAP[v4Type] ??\n `Zod${v4Type.charAt(0).toUpperCase()}${v4Type.slice(1)}`\n );\n\n // Zod 3 fallback\n const v3Type: string | undefined = s._def?.typeName;\n if (v3Type) return v3Type;\n\n return \"\";\n}\n\n// ---------------------------------------------------------------------------\n// Unwrapping wrappers (Optional / Nullable / Default)\n// ---------------------------------------------------------------------------\n\n/**\n * Get the inner schema from a wrapper type (Optional / Nullable / Default).\n */\nexport function getInnerType(schema: z.ZodType): z.ZodType | undefined {\n const s = schema as any;\n\n // Zod 4: _zod.def.innerType\n if (s._zod?.def?.innerType) return s._zod.def.innerType;\n\n // Zod 3 compat: _def.innerType\n if (s._def?.innerType) return s._def.innerType;\n\n return undefined;\n}\n\n/**\n * Get the **source** schema of an effect / transform / pipe wrapper, i.e. the\n * schema describing what the user actually provides:\n * - Zod 3 `ZodEffects` (`.transform()` / `.refine()` / `.preprocess()`) →\n * `_def.schema`;\n * - Zod 4 `ZodPipe` (the shape `.transform()` compiles to) → the `in` side.\n *\n * Lets form/field introspection see through `z.string().transform(...)` (which\n * should still render as a text input) instead of falling back to a JSON\n * textarea. Returns `undefined` when the schema is not an effect/pipe.\n */\nexport function getEffectInnerType(schema: z.ZodType): z.ZodType | undefined {\n const s = schema as any;\n\n // Zod 4: pipe — prefer the input side (what the user types).\n const pipeIn = s._zod?.def?.in;\n if (pipeIn) return pipeIn as z.ZodType;\n\n // Zod 3: ZodEffects wraps the base schema under `_def.schema`.\n if (s._def?.schema) return s._def.schema as z.ZodType;\n\n return undefined;\n}\n\n/**\n * Get the **element schema** from a `ZodArray`.\n * Returns `undefined` for non-array schemas.\n */\nexport function getArrayElementType(\n schema: z.ZodType,\n): z.ZodType | undefined {\n const s = schema as any;\n\n // Zod 4: _zod.def.element\n if (s._zod?.def?.element) return s._zod.def.element;\n\n // Zod 3: _def.type (ZodArray stores element schema in _def.type)\n if (s._def?.type) return s._def.type;\n\n return undefined;\n}\n\n/**\n * Returns the list of **required** (non-optional) top-level keys of a ZodObject.\n * A key is required when its schema is NOT wrapped in ZodOptional.\n * ZodNullable / ZodDefault fields are still considered required — they must be present.\n */\nexport function getRequiredSchemaKeys(schema: z.ZodObject<any>): string[] {\n const required: string[] = [];\n for (const [key, fieldSchema] of Object.entries(schema.shape)) {\n const typeName = getTypeName(fieldSchema as z.ZodType);\n if (typeName !== \"ZodOptional\") {\n required.push(key);\n }\n }\n return required;\n}\n\n/**\n * Get the default value for a ZodDefault schema.\n * In Zod 3 this was `_def.defaultValue()` (function). In Zod 4 it's a direct value.\n */\nexport function getDefaultValue(schema: z.ZodType): unknown {\n const s = schema as any;\n\n // Zod 4\n if (s._zod?.def?.defaultValue !== undefined) return s._zod.def.defaultValue;\n\n // Zod 3 compat\n const v = s._def?.defaultValue;\n if (typeof v === \"function\") return v();\n return v;\n}\n\n// ---------------------------------------------------------------------------\n// Object shape\n// ---------------------------------------------------------------------------\n\n/**\n * Get the shape of a ZodObject schema (Record<string, ZodType>).\n * Handles both Zod 3 (`_def.shape()` function) and Zod 4 (`.shape` property).\n */\nexport function getShape(schema: z.ZodType): Record<string, z.ZodType> {\n const s = schema as any;\n\n // Direct `.shape` property (Zod 3 & 4 for ZodObject instances)\n if (s.shape && typeof s.shape === \"object\") return s.shape;\n\n // Zod 4: _zod.def.shape\n if (s._zod?.def?.shape && typeof s._zod.def.shape === \"object\")\n return s._zod.def.shape;\n\n // Zod 3 fallback: _def.shape() or _def.shape\n if (s._def?.shape) {\n return typeof s._def.shape === \"function\" ? s._def.shape() : s._def.shape;\n }\n\n return {};\n}\n\n// ---------------------------------------------------------------------------\n// Enum / Literal values\n// ---------------------------------------------------------------------------\n\n/**\n * Get the values of a ZodEnum schema as a string[].\n */\nexport function getEnumValues(schema: z.ZodType): string[] {\n const s = schema as any;\n\n // Zod 4: `.options` or `_zod.def.entries`\n if (Array.isArray(s.options)) return s.options;\n if (s._zod?.def?.entries)\n return Object.values(s._zod.def.entries) as string[];\n\n // Zod 3: `_def.values`\n if (Array.isArray(s._def?.values)) return s._def.values;\n\n return [];\n}\n\n/**\n * Get the value object of a ZodNativeEnum schema.\n */\nexport function getNativeEnumValues(\n schema: z.ZodType,\n): Record<string, unknown> {\n const s = schema as any;\n\n // Zod 4: `_zod.def.entries` or `.enum`\n if (s._zod?.def?.entries) return s._zod.def.entries;\n if (s.enum && typeof s.enum === \"object\") return s.enum;\n\n // Zod 3: `_def.values`\n if (s._def?.values && typeof s._def.values === \"object\") return s._def.values;\n\n return {};\n}\n\n/**\n * Get the value of a ZodLiteral schema.\n */\nexport function getLiteralValue(schema: z.ZodType): unknown {\n const s = schema as any;\n\n // Zod 4: `_zod.def.values[0]`\n if (Array.isArray(s._zod?.def?.values)) return s._zod.def.values[0];\n\n // Zod 3: `_def.value`\n return s._def?.value;\n}\n\n/**\n * Get the member schemas of a ZodUnion (or ZodDiscriminatedUnion).\n * Works with both Zod 3 (`_def.options`) and Zod 4 (`.options` /\n * `_zod.def.options`). Returns an empty array when none can be resolved.\n */\nexport function getUnionOptions(schema: z.ZodType): z.ZodType[] {\n const s = schema as any;\n\n // Zod 4\n if (Array.isArray(s.options)) return s.options as z.ZodType[];\n if (Array.isArray(s._zod?.def?.options))\n return s._zod.def.options as z.ZodType[];\n\n // Zod 3\n if (Array.isArray(s._def?.options)) return s._def.options as z.ZodType[];\n\n return [];\n}\n\n// ---------------------------------------------------------------------------\n// String checks\n// ---------------------------------------------------------------------------\n\n/**\n * Get relevant \"check kinds\" from a ZodString schema.\n * Returns an array of kind strings: \"email\", \"url\", etc.\n */\nexport function getStringChecks(schema: z.ZodType): string[] {\n const s = schema as any;\n const kinds: string[] = [];\n\n // Zod 4: checks with `.format` field\n const v4Checks: any[] | undefined = s._zod?.def?.checks;\n if (Array.isArray(v4Checks)) {\n for (const c of v4Checks) {\n if (c.format) kinds.push(c.format);\n }\n if (kinds.length > 0) return kinds;\n }\n\n // Zod 3: _def.checks with `.kind` field\n const v3Checks: any[] | undefined = s._def?.checks;\n if (Array.isArray(v3Checks)) {\n for (const c of v3Checks) {\n if (c.kind) kinds.push(c.kind);\n }\n }\n\n return kinds;\n}\n","import { z } from \"zod\";\nimport {\n getTypeName,\n getInnerType,\n getShape,\n} from \"../shared/zod-compat\";\nimport { SYNC_VERSION_COLUMN } from \"./constants\";\nimport type { SqlColumn, SqlDialect, LogicalType } from \"./types\";\n\nconst WRAPPER_TYPES = new Set([\"ZodOptional\", \"ZodNullable\", \"ZodDefault\"]);\n\nfunction unwrap(schema: z.ZodType): { inner: z.ZodType; nullable: boolean } {\n let current = schema;\n let nullable = false;\n\n for (;;) {\n const name = getTypeName(current);\n if (!WRAPPER_TYPES.has(name)) break;\n if (name === \"ZodOptional\" || name === \"ZodNullable\") nullable = true;\n const inner = getInnerType(current);\n if (!inner) break;\n current = inner;\n }\n\n return { inner: current, nullable };\n}\n\nconst LOGICAL_MAP: Record<string, LogicalType> = {\n ZodString: \"string\",\n ZodNumber: \"number\",\n ZodBigInt: \"bigint\",\n ZodBoolean: \"boolean\",\n ZodDate: \"timestamp\",\n ZodEnum: \"string\",\n ZodNativeEnum: \"string\",\n ZodLiteral: \"string\",\n};\n\nexport function zodTypeToLogical(schema: z.ZodType): LogicalType {\n const { inner } = unwrap(schema);\n return LOGICAL_MAP[getTypeName(inner)] ?? \"json\";\n}\n\nexport interface ZodSchemaToColumnsOptions {\n primaryKey?: string;\n exclude?: string[];\n columnMap?: Record<string, string>;\n}\n\n/**\n * Recursively flatten a Zod object schema into flat SQL columns.\n * Nested objects produce `parent_child` column names.\n * Arrays and non-object complex types become JSON columns.\n */\nfunction flattenSchema(\n shape: Record<string, z.ZodType>,\n dialect: SqlDialect,\n prefix: string,\n parentNullable: boolean,\n excludeSet: Set<string>,\n columnMap: Record<string, string>,\n primaryKey: string | undefined,\n columns: SqlColumn[],\n): void {\n for (const [field, fieldSchema] of Object.entries(shape)) {\n const fullKey = prefix ? `${prefix}__${field}` : field;\n\n // Exclude check on the original (dotless) path and the flattened key\n if (excludeSet.has(field) || excludeSet.has(fullKey)) continue;\n\n const { inner, nullable } = unwrap(fieldSchema);\n const typeName = getTypeName(inner);\n const isNullable = parentNullable || nullable;\n\n // Nested object → recurse to flatten\n if (typeName === \"ZodObject\") {\n const nestedShape = getShape(inner as z.ZodObject<any>);\n flattenSchema(\n nestedShape,\n dialect,\n fullKey,\n isNullable,\n excludeSet,\n columnMap,\n primaryKey,\n columns,\n );\n continue;\n }\n\n // Arrays and other complex types → JSON\n const logical = LOGICAL_MAP[typeName] ?? \"json\";\n const isPK = fullKey === primaryKey || field === primaryKey;\n const colName = columnMap[fullKey] ?? columnMap[field] ?? fullKey;\n\n columns.push({\n name: colName,\n sqlType: dialect.mapType(logical),\n nullable: isPK ? false : isNullable,\n isPrimaryKey: isPK,\n });\n }\n}\n\n/**\n * Convert a Zod object schema into an array of {@link SqlColumn} definitions\n * suitable for SQL table creation.\n *\n * Nested ZodObject fields are recursively flattened into separate columns\n * with underscore-separated names (e.g. `address.street` → `address_street`).\n * Arrays become JSON columns.\n */\nexport function zodSchemaToColumns(\n schema: z.ZodObject<any>,\n dialect: SqlDialect,\n options: ZodSchemaToColumnsOptions = {},\n): SqlColumn[] {\n const { primaryKey, exclude = [], columnMap = {} } = options;\n const excludeSet = new Set(exclude);\n const shape = getShape(schema);\n const columns: SqlColumn[] = [];\n\n flattenSchema(shape, dialect, \"\", false, excludeSet, columnMap, primaryKey, columns);\n\n // Internal version column used by the worker to discard out-of-order\n // PubSub deliveries (added unconditionally — never excluded).\n if (!columns.some((c) => c.name === SYNC_VERSION_COLUMN)) {\n columns.push({\n name: SYNC_VERSION_COLUMN,\n sqlType: dialect.mapType(\"bigint\"),\n nullable: true,\n isPrimaryKey: false,\n description: \"Monotonic publish version (Date.now() ms). Internal.\",\n });\n }\n\n return columns;\n}\n","/**\n * BigQuery type-name utilities used by the {@link BigQueryAdapter}.\n *\n * - {@link normalizeBigQueryType} canonicalises BigQuery type strings so that\n * `INTEGER`/`INT64`, `FLOAT`/`FLOAT64`, `BOOLEAN`/`BOOL`, etc. compare\n * equal during schema-drift detection.\n * - {@link isBigQueryTypeCompatible} returns whether a desired type can\n * safely keep an existing column of another type — only widenings that\n * BigQuery accepts via `ALTER COLUMN SET DATA TYPE` are allowed.\n */\n\n/**\n * Canonicalise a BigQuery type name returned by `getMetadata().schema`\n * (which may use legacy aliases like `INTEGER` or `FLOAT`) so that it can\n * be compared against the type produced by `BigQueryDialect.mapType()`.\n */\nexport function normalizeBigQueryType(type: string): string {\n const upper = type.toUpperCase();\n switch (upper) {\n case \"INTEGER\":\n return \"INT64\";\n case \"FLOAT\":\n return \"FLOAT64\";\n case \"BOOLEAN\":\n return \"BOOL\";\n default:\n return upper;\n }\n}\n\n/**\n * Whether `desired` is the same as, or a safe widening of, `existing`.\n * The widenings mirror what BigQuery allows via\n * `ALTER COLUMN x SET DATA TYPE …` — see\n * https://cloud.google.com/bigquery/docs/managing-table-schemas#change_column_types\n */\nexport function isBigQueryTypeCompatible(\n existing: string,\n desired: string,\n): boolean {\n const a = normalizeBigQueryType(existing);\n const b = normalizeBigQueryType(desired);\n if (a === b) return true;\n\n const widenings: Record<string, string[]> = {\n INT64: [\"NUMERIC\", \"BIGNUMERIC\", \"FLOAT64\"],\n NUMERIC: [\"BIGNUMERIC\", \"FLOAT64\"],\n DATE: [\"DATETIME\", \"TIMESTAMP\"],\n DATETIME: [\"TIMESTAMP\"],\n };\n return widenings[a]?.includes(b) ?? false;\n}\n","/**\n * BigQuery adapter — streams Firestore changes to BigQuery via the\n * **Storage Write API** in CDC (Change Data Capture) mode.\n *\n * Why CDC over the legacy MERGE approach:\n *\n * - **No DML concurrency limit.** MERGE/DELETE DML is bounded by ≈ 2\n * concurrent statements per table; busy collections triggered\n * `Could not serialize access … due to concurrent update` errors.\n * The Storage Write API has no such bound, so multiple Cloud Function\n * instances can flush in parallel without conflicts.\n * - **Cheaper at scale.** Storage Write is roughly ~50% cheaper than\n * legacy streaming inserts, and free for the first 2 TiB / month.\n * - **Same idempotency model.** Each row carries `_CHANGE_SEQUENCE_NUMBER`\n * built from the existing `__sync_version` column, so out-of-order\n * PubSub deliveries are merged correctly by BigQuery.\n *\n * Requirements:\n *\n * - Destination tables **must** declare a `PRIMARY KEY (...) NOT ENFORCED`\n * constraint and be clustered on that key. {@link BigQueryAdapter.createTable}\n * handles both for tables managed by this library.\n * - Tables should be created with `OPTIONS(max_staleness = INTERVAL …)`\n * so the CDC merge runs in the background instead of on every read\n * — see {@link BigQueryAdapterOptions.maxStaleness}.\n * - Service account needs `bigquery.tables.updateData` (e.g. via the\n * `roles/bigquery.dataEditor` role).\n *\n * @example\n * ```ts\n * import { BigQuery } from \"@google-cloud/bigquery\";\n * import { BigQueryAdapter } from \"@lpdjs/firestore-repo-service/sync/bigquery\";\n *\n * const adapter = new BigQueryAdapter({\n * projectId: \"my-project\",\n * datasetId: \"firestore_sync\",\n * bigquery: new BigQuery({ projectId: \"my-project\" }),\n * maxStaleness: \"INTERVAL 15 MINUTE\",\n * });\n * ```\n */\n\nimport type { BigQuery } from \"@google-cloud/bigquery\";\nimport type { z } from \"zod\";\nimport { SYNC_VERSION_COLUMN } from \"../constants\";\nimport { zodSchemaToColumns } from \"../schema-mapper\";\nimport type {\n LogicalType,\n RepoSyncConfig,\n SqlAdapter,\n SqlColumn,\n SqlDialect,\n SqlTableDef,\n SyncHealthResult,\n} from \"../types\";\nimport {\n isBigQueryTypeCompatible,\n normalizeBigQueryType,\n} from \"./bigquery-types\";\n\n// ---------------------------------------------------------------------------\n// Dialect\n// ---------------------------------------------------------------------------\n\n/** BigQuery SQL dialect mapping. */\nclass BigQueryDialect implements SqlDialect {\n readonly name = \"bigquery\";\n\n mapType(logical: LogicalType): string {\n switch (logical) {\n case \"string\":\n return \"STRING\";\n case \"number\":\n return \"FLOAT64\";\n case \"bigint\":\n return \"INT64\";\n case \"boolean\":\n return \"BOOL\";\n case \"timestamp\":\n return \"TIMESTAMP\";\n case \"json\":\n return \"JSON\";\n case \"text\":\n return \"STRING\";\n }\n }\n\n quoteIdentifier(id: string): string {\n // BigQuery escapes identifiers with backticks; a literal backtick inside\n // an identifier must be doubled. Without this, an identifier containing a\n // backtick (e.g. a column name propagated from a Firestore document key)\n // would break out of the quoting and enable DDL injection.\n return \"`\" + id.replace(/`/g, \"``\") + \"`\";\n }\n}\n\n/** Shared BigQuery dialect singleton. */\nexport const bigqueryDialect: SqlDialect = new BigQueryDialect();\n\n// ---------------------------------------------------------------------------\n// Storage Write API loader (kept loose so `@google-cloud/bigquery-storage`\n// stays an OPTIONAL peer dep)\n// ---------------------------------------------------------------------------\n\ntype StorageNs = {\n managedwriter: {\n WriterClient: new (opts?: any) => any;\n JSONWriter: new (params: { connection: any; protoDescriptor: any }) => any;\n DefaultStream: any;\n };\n adapt: {\n convertBigQuerySchemaToStorageTableSchema(schema: any): any;\n convertStorageSchemaToProto2Descriptor(\n schema: any,\n scope: string,\n ...opts: any[]\n ): any;\n withChangeType(): any;\n withChangeSequenceNumber(): any;\n };\n};\n\nlet storageNsCache: StorageNs | null = null;\nfunction loadStorageNs(): StorageNs {\n if (storageNsCache) return storageNsCache;\n // Lazy require so the library does not pull `@google-cloud/bigquery-storage`\n // unless this adapter is actually instantiated.\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = require(\"@google-cloud/bigquery-storage\");\n storageNsCache = mod as StorageNs;\n return storageNsCache;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Format `__sync_version` (Firestore commit timestamp in microseconds since\n * epoch) as the 16-character hex string required by `_CHANGE_SEQUENCE_NUMBER`.\n *\n * BigQuery compares sequence numbers lexicographically, so a fixed-width hex\n * representation is mandatory for correct ordering.\n */\nfunction formatChangeSequenceNumber(version: unknown): string {\n let n: bigint;\n if (typeof version === \"bigint\") n = version;\n else if (typeof version === \"number\") n = BigInt(version);\n else if (typeof version === \"string\") n = BigInt(version);\n else n = 0n;\n if (n < 0n) n = 0n;\n return n.toString(16).padStart(16, \"0\");\n}\n\n/**\n * Returns true when the Storage Write append failed with a transient gRPC\n * status (UNAVAILABLE, DEADLINE_EXCEEDED, INTERNAL, ABORTED). Caller can\n * safely retry these.\n */\nfunction isRetryableStorageError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const e = err as { code?: number };\n // gRPC codes: 4=DEADLINE_EXCEEDED, 10=ABORTED, 13=INTERNAL, 14=UNAVAILABLE\n return e.code === 4 || e.code === 10 || e.code === 13 || e.code === 14;\n}\n\nasync function withRetry<T>(\n fn: () => Promise<T>,\n maxRetries = 6,\n baseMs = 200,\n): Promise<T> {\n let attempt = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n return await fn();\n } catch (err) {\n attempt++;\n if (!isRetryableStorageError(err) || attempt > maxRetries) throw err;\n const cap = baseMs * Math.pow(2, attempt);\n const delay = Math.random() * cap;\n await new Promise((res) => setTimeout(res, delay));\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal structural shape of `@google-cloud/bigquery`'s `BigQuery` client\n * actually used by the adapter (`.dataset(...)` and `.query(...)`).\n *\n * Why structural and not just `BigQuery`: TypeScript treats classes with\n * private fields nominally. When a consumer's `node_modules` ends up with\n * a *second* copy of `@google-cloud/bigquery` (very common in workspace\n * setups, peer-dep dedup misses, monorepo nesting), the `BigQuery` they\n * import is *technically* a different type than the one this library's\n * `BigQuery` references — even though they are runtime-identical — and\n * assignment fails with `Types have separate declarations of a private\n * property '_universeDomain'`.\n *\n * Accepting a structural superset sidesteps the duplicate-install issue\n * without giving up type safety on the methods we actually call.\n */\nexport interface BigQueryLike {\n dataset(datasetId: string): {\n table(tableName: string): any;\n [key: string]: any;\n };\n query(options: { query: string; params?: unknown[] } | string): Promise<any>;\n}\n\nexport interface BigQueryAdapterOptions {\n /** GCP project id that owns the dataset. */\n projectId: string;\n /** BigQuery dataset id. */\n datasetId: string;\n /**\n * BigQuery client used for DDL operations (createTable, addColumns,\n * getMetadata, executeRaw). Storage Write only handles inserts.\n *\n * Typed as the structural {@link BigQueryLike} (a superset satisfied by\n * `BigQuery` from `@google-cloud/bigquery`) to avoid TypeScript nominal\n * mismatches when the consumer's project ends up with two copies of\n * `@google-cloud/bigquery` in different `node_modules`. Pass\n * `new BigQuery({...})` from your own install — it satisfies this shape\n * structurally.\n */\n bigquery: BigQueryLike | BigQuery;\n /**\n * Optional pre-built Storage Write `WriterClient`. When omitted a new\n * one is created lazily on first use.\n */\n writerClient?: any;\n /**\n * Value passed to `OPTIONS(max_staleness = ...)` on `createTable`.\n *\n * **Why this matters**: in BigQuery CDC mode, Storage Write API rows\n * land in a delta buffer. They become visible to queries only after a\n * MERGE applies them to the base table. Two paths exist:\n *\n * - **Background MERGE** — runs periodically in the background, paid\n * for as part of CDC pricing, and never blocks your readers.\n * - **Read-time MERGE** — every `SELECT` query merges the delta on the\n * fly before returning. Always-fresh reads but every query pays for\n * the merge work.\n *\n * `max_staleness` is the tolerated lag between a write and what reads\n * see. Setting it tells BigQuery: \"background MERGE is fine if reads\n * are at most this stale\". When the threshold is exceeded, the next\n * read triggers a one-shot merge.\n *\n * **The default `INTERVAL 0` means \"always read-time merge\"** — every\n * query forces a full merge of pending CDC writes. That makes reads\n * dramatically slower and more expensive on busy tables, so this\n * library defaults to a 15 minute window in production.\n *\n * Recommended:\n * - `INTERVAL 15 MINUTE` in production (good cost/freshness trade-off).\n * - `INTERVAL 1 MINUTE` in dev for quick visibility.\n * - Set to `null` to omit the option entirely (only do this when you\n * know what you are doing — you'll likely hit slow & expensive reads).\n *\n * @default \"INTERVAL 15 MINUTE\"\n */\n maxStaleness?: string | null;\n}\n\nexport class SchemaTypeMismatchError extends Error {\n constructor(\n readonly tableName: string,\n readonly column: string,\n readonly existingType: string,\n readonly desiredType: string,\n ) {\n super(\n `Schema drift detected on \\`${tableName}\\`: column \\`${column}\\` has ` +\n `type ${existingType} in BigQuery but the current Zod schema maps ` +\n `it to ${desiredType}. BigQuery cannot safely convert between these ` +\n `types — to resolve, either (a) keep the BigQuery type and add a ` +\n `transform in your repo to coerce values, (b) rename the field in ` +\n `your Zod schema (creates a new column), or (c) drop & recreate ` +\n `the table.`,\n );\n this.name = \"SchemaTypeMismatchError\";\n }\n}\n\n/**\n * BigQuery implementation of {@link SqlAdapter} using the Storage Write API\n * in CDC mode. See module-level docstring for the rationale.\n */\nexport class BigQueryAdapter implements SqlAdapter {\n readonly name = \"bigquery\";\n private readonly bigquery: BigQueryLike;\n private readonly projectId: string;\n private readonly datasetId: string;\n private readonly maxStaleness: string | null;\n private writerClient: any;\n /** Cache of `{ writer, primaryKey }` per table name. */\n private readonly writers = new Map<\n string,\n { writer: any; primaryKey: string; timestampColumns?: Set<string> }\n >();\n\n constructor(options: BigQueryAdapterOptions) {\n this.bigquery = options.bigquery;\n this.projectId = options.projectId;\n this.datasetId = options.datasetId;\n this.maxStaleness =\n options.maxStaleness === undefined\n ? \"INTERVAL 15 MINUTE\"\n : options.maxStaleness;\n this.writerClient = options.writerClient;\n }\n\n get dialect(): SqlDialect {\n return bigqueryDialect;\n }\n\n // -------- SyncAdapter implementation ------------------------------------\n\n async targetExists(targetName: string): Promise<boolean> {\n return this.tableExists(targetName);\n }\n\n async upsert(\n targetName: string,\n items: Record<string, unknown>[],\n primaryKey: string,\n ): Promise<void> {\n return this.upsertRows(targetName, items, primaryKey);\n }\n\n async delete(\n targetName: string,\n primaryKey: string,\n ids: string[],\n ): Promise<void> {\n return this.deleteRows(targetName, primaryKey, ids);\n }\n\n async ensureTarget(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n exclude?: string[];\n columnMap?: Record<string, string>;\n }): Promise<void> {\n if (!options.schema) return;\n const { targetName, primaryKey, schema, exclude, columnMap } = options;\n const columns = zodSchemaToColumns(schema, this.dialect, {\n primaryKey,\n exclude,\n columnMap,\n });\n const exists = await this.tableExists(targetName);\n if (!exists) {\n await this.createTable({ tableName: targetName, columns });\n } else {\n const existing = await this.getTableColumnsWithTypes(targetName);\n const missing: typeof columns = [];\n for (const col of columns) {\n const existingType = existing.get(col.name);\n if (existingType === undefined) {\n missing.push(col);\n continue;\n }\n if (!isBigQueryTypeCompatible(existingType, col.sqlType)) {\n throw new SchemaTypeMismatchError(\n targetName,\n col.name,\n existingType,\n col.sqlType,\n );\n }\n }\n if (missing.length > 0) {\n await this.addColumns(targetName, missing);\n await this.onSchemaChange?.(targetName);\n }\n }\n }\n\n async healthCheck(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n repoConfig?: RepoSyncConfig<string>;\n }): Promise<SyncHealthResult> {\n const { targetName, primaryKey, schema, repoConfig } = options;\n if (!schema) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: \"No Zod schema attached to repository\",\n };\n }\n try {\n const exists = await this.tableExists(targetName);\n if (!exists) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: `Table \\`${targetName}\\` does not exist`,\n };\n }\n const actualCols = await this.getTableColumns(targetName);\n const expectedCols = zodSchemaToColumns(schema, this.dialect, {\n primaryKey,\n exclude: repoConfig?.exclude,\n columnMap: repoConfig?.columnMap as Record<string, string> | undefined,\n });\n const actualSet = new Set(actualCols);\n const expectedSet = new Set(expectedCols.map((c) => c.name));\n const missing = expectedCols.filter((c) => !actualSet.has(c.name));\n const extra = actualCols.filter((c) => !expectedSet.has(c));\n const matched = expectedCols.filter((c) => actualSet.has(c.name));\n const healthy = missing.length === 0;\n\n return {\n healthy,\n targetName,\n targetExists: true,\n error: healthy\n ? null\n : `Missing columns: ${missing.map((c) => c.name).join(\", \")}`,\n details: {\n expected: expectedCols.map((c) => ({\n name: c.name,\n type: c.sqlType,\n nullable: c.nullable,\n isPrimaryKey: c.isPrimaryKey,\n })),\n actual: actualCols,\n matched: matched.map((c) => c.name),\n missing: missing.map((c) => ({ name: c.name, type: c.sqlType })),\n extra,\n },\n };\n } catch (e: any) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: e?.message ?? String(e),\n };\n }\n }\n\n // -------- DDL (delegated to @google-cloud/bigquery) ----------------------\n\n async tableExists(tableName: string): Promise<boolean> {\n const [exists] = await this.dataset.table(tableName).exists();\n return exists;\n }\n\n async getTableColumns(tableName: string): Promise<string[]> {\n const [metadata] = await this.dataset.table(tableName).getMetadata();\n const fields: Array<{ name: string }> = metadata.schema?.fields ?? [];\n return fields.map((f) => f.name);\n }\n\n async getTableColumnsWithTypes(\n tableName: string,\n ): Promise<Map<string, string>> {\n const [metadata] = await this.dataset.table(tableName).getMetadata();\n const fields: Array<{ name: string; type: string }> =\n metadata.schema?.fields ?? [];\n const result = new Map<string, string>();\n for (const f of fields) {\n result.set(f.name, normalizeBigQueryType(f.type));\n }\n return result;\n }\n\n async createTable(table: SqlTableDef): Promise<void> {\n const qi = (id: string) => this.dialect.quoteIdentifier(id);\n const pk = table.columns.find((c) => c.isPrimaryKey)?.name;\n if (!pk) {\n throw new Error(\n `BigQueryAdapter requires a primary key on table \\`${table.tableName}\\` ` +\n `(Storage Write CDC mode needs PRIMARY KEY NOT ENFORCED).`,\n );\n }\n const cols = table.columns\n .map((c) => {\n const notNull = c.isPrimaryKey ? \" NOT NULL\" : \"\";\n return ` ${qi(c.name)} ${c.sqlType}${notNull}`;\n })\n .join(\",\\n\");\n\n const opts: string[] = [];\n if (this.maxStaleness !== null) {\n opts.push(`max_staleness = ${this.maxStaleness}`);\n }\n const optionsClause =\n opts.length > 0 ? `\\nOPTIONS(${opts.join(\", \")})` : \"\";\n\n const ddl =\n `CREATE TABLE IF NOT EXISTS ${this.fqn(table.tableName)} (\\n${cols},\\n` +\n ` PRIMARY KEY (${qi(pk)}) NOT ENFORCED\\n)` +\n `\\nCLUSTER BY ${qi(pk)}` +\n `${optionsClause};`;\n\n await this.bigquery.query({ query: ddl });\n }\n\n async addColumns(tableName: string, columns: SqlColumn[]): Promise<void> {\n const qi = (id: string) => this.dialect.quoteIdentifier(id);\n for (const c of columns) {\n const stmt = `ALTER TABLE ${this.fqn(tableName)} ADD COLUMN ${qi(c.name)} ${c.sqlType};`;\n await this.bigquery.query({ query: stmt });\n }\n }\n\n async executeRaw(sql: string): Promise<void> {\n await this.bigquery.query({ query: sql });\n }\n\n /**\n * Invalidate the cached writer for a table. Called by the worker after\n * `addColumns` so the next append rebuilds the proto descriptor against\n * the new schema.\n */\n onSchemaChange(tableName: string): void {\n const cached = this.writers.get(tableName);\n if (cached) {\n try {\n cached.writer.close();\n } catch {\n // ignore — connection may already be torn down\n }\n this.writers.delete(tableName);\n }\n }\n\n // -------- Inserts (Storage Write API) -----------------------------------\n\n async insertRows(\n tableName: string,\n rows: Record<string, unknown>[],\n ): Promise<void> {\n if (rows.length === 0) return;\n // Plain inserts have no PK matching, but in CDC mode every row needs a\n // _CHANGE_TYPE. We treat them as UPSERT.\n const writer = await this.getOrCreateWriter(tableName);\n const timestampColumns = this.writers.get(tableName)?.timestampColumns;\n const cdc = rows.map((row) => ({\n ...this.normalizeRow(row, timestampColumns),\n _CHANGE_TYPE: \"UPSERT\",\n _CHANGE_SEQUENCE_NUMBER: formatChangeSequenceNumber(\n row[SYNC_VERSION_COLUMN],\n ),\n }));\n await this.appendWithRetry(tableName, writer, cdc);\n }\n\n async upsertRows(\n tableName: string,\n rows: Record<string, unknown>[],\n primaryKey: string,\n ): Promise<void> {\n if (rows.length === 0) return;\n const writer = await this.getOrCreateWriter(tableName, primaryKey);\n const timestampColumns = this.writers.get(tableName)?.timestampColumns;\n const cdc = rows.map((row) => ({\n ...this.normalizeRow(row, timestampColumns),\n _CHANGE_TYPE: \"UPSERT\",\n _CHANGE_SEQUENCE_NUMBER: formatChangeSequenceNumber(\n row[SYNC_VERSION_COLUMN],\n ),\n }));\n await this.appendWithRetry(tableName, writer, cdc);\n }\n\n async deleteRows(\n tableName: string,\n primaryKey: string,\n ids: string[],\n ): Promise<void> {\n if (ids.length === 0) return;\n const writer = await this.getOrCreateWriter(tableName, primaryKey);\n // Storage Write CDC requires a value for every NOT-NULL column (the PK)\n // and a `_CHANGE_TYPE`. Other columns may be omitted; missing values are\n // interpreted as NULL. We pass the maximum sequence number so the DELETE\n // wins over any concurrent UPSERT for the same key — tombstones from the\n // queue carry no `__sync_version` of their own.\n const cdc = ids.map((id) => ({\n [primaryKey]: id,\n _CHANGE_TYPE: \"DELETE\",\n _CHANGE_SEQUENCE_NUMBER: \"ffffffffffffffff\",\n }));\n await this.appendWithRetry(tableName, writer, cdc);\n }\n\n // -------- Internal helpers ----------------------------------------------\n\n private get dataset() {\n return this.bigquery.dataset(this.datasetId);\n }\n\n private fqn(tableName: string): string {\n // Escape backticks in both identifier parts to prevent DDL/DML injection\n // (BigQuery doubles backticks to embed a literal one).\n const esc = (s: string) => s.replace(/`/g, \"``\");\n return `\\`${esc(this.datasetId)}.${esc(tableName)}\\``;\n }\n\n /** ISO 8601 timestamp pattern (e.g. 2026-03-29T20:59:27.394Z) */\n private static readonly ISO_TIMESTAMP_RE =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/;\n\n /**\n * Convert a Date or epoch-millis number into the epoch-microseconds string\n * required by the Storage Write API for TIMESTAMP columns.\n *\n * The JSONWriter encodes through protobuf and a TIMESTAMP field is an\n * `int64`. Passing an ISO string would make `Long.fromString` throw\n * `interior hyphen` on the `-` characters.\n */\n private static toEpochMicros(d: Date): string {\n const ms = d.getTime();\n return (BigInt(ms) * 1000n).toString();\n }\n\n /** Convert JS values into shapes accepted by JSONWriter. */\n private normalizeRow(\n row: Record<string, unknown>,\n timestampColumns?: Set<string>,\n ): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(row)) {\n if (v === undefined) continue;\n if (v instanceof Date) {\n // TIMESTAMP column → int64 epoch micros (as string to preserve precision)\n out[k] = BigQueryAdapter.toEpochMicros(v);\n } else if (\n typeof v === \"string\" &&\n this.shouldCoerceTimestamp(k, v, timestampColumns)\n ) {\n // ISO timestamp produced upstream by `serializeDocument` (Firestore\n // Timestamp → ISO string) — convert to epoch micros for protobuf.\n const d = new Date(v);\n if (!Number.isNaN(d.getTime())) {\n out[k] = BigQueryAdapter.toEpochMicros(d);\n } else {\n out[k] = v;\n }\n } else if (typeof v === \"object\" && v !== null) {\n // JSON columns: serialise nested objects/arrays\n out[k] = JSON.stringify(v);\n } else if (typeof v === \"bigint\") {\n out[k] = v.toString();\n } else {\n out[k] = v;\n }\n }\n return out;\n }\n\n /**\n * Decide whether a string value should be coerced to an epoch-micros\n * timestamp.\n *\n * When the destination table's column types are known (writer already\n * built from table metadata), coerce **only** when the column is actually\n * TIMESTAMP/DATETIME/DATE. This prevents a business string that merely\n * looks like an ISO date (a log line, a slug, a formatted id) from being\n * silently rewritten — and avoids type-mismatch write errors on STRING\n * columns (issue #15).\n *\n * When column types are unavailable (e.g. a writer injected directly, or\n * metadata not yet fetched), fall back to the ISO-shape heuristic so\n * behaviour is unchanged.\n */\n private shouldCoerceTimestamp(\n column: string,\n value: string,\n timestampColumns?: Set<string>,\n ): boolean {\n if (timestampColumns) return timestampColumns.has(column);\n return BigQueryAdapter.ISO_TIMESTAMP_RE.test(value);\n }\n\n private async appendWithRetry(\n tableName: string,\n writer: any,\n rows: Record<string, unknown>[],\n ): Promise<void> {\n await withRetry(async () => {\n try {\n const pending = writer.appendRows(rows);\n await pending.getResult();\n } catch (err) {\n // On certain errors (schema drift, broken connection) drop the\n // cached writer so the next call rebuilds it.\n this.onSchemaChange(tableName);\n throw err;\n }\n });\n }\n\n private async getOrCreateWriter(\n tableName: string,\n primaryKey?: string,\n ): Promise<any> {\n const cached = this.writers.get(tableName);\n if (cached) {\n if (primaryKey && cached.primaryKey !== primaryKey) {\n // PK changed — invalidate and rebuild\n this.onSchemaChange(tableName);\n } else {\n return cached.writer;\n }\n }\n\n const ns = loadStorageNs();\n if (!this.writerClient) {\n this.writerClient = new ns.managedwriter.WriterClient({\n projectId: this.projectId,\n });\n }\n\n const [metadata] = await this.dataset.table(tableName).getMetadata();\n const bqSchema = { fields: metadata.schema?.fields ?? [] };\n if (!primaryKey) {\n // Try to recover PK from table constraints if available\n const tableConstraintsPK =\n metadata.tableConstraints?.primaryKey?.columns?.[0];\n primaryKey = tableConstraintsPK ?? bqSchema.fields[0]?.name;\n }\n\n const storageSchema =\n ns.adapt.convertBigQuerySchemaToStorageTableSchema(bqSchema);\n const protoDescriptor = ns.adapt.convertStorageSchemaToProto2Descriptor(\n storageSchema,\n \"Row\",\n ns.adapt.withChangeType(),\n ns.adapt.withChangeSequenceNumber(),\n );\n\n // Track which columns are actually TIMESTAMP-like so `normalizeRow` only\n // coerces ISO-looking strings when the destination column expects a\n // timestamp — a business string that merely *looks* like an ISO date must\n // not be silently converted to epoch micros (see issue #15).\n const timestampColumns = new Set<string>(\n (bqSchema.fields as Array<{ name: string; type?: string }>)\n .filter((f) =>\n [\"TIMESTAMP\", \"DATETIME\", \"DATE\"].includes(\n String(f.type ?? \"\").toUpperCase(),\n ),\n )\n .map((f) => f.name),\n );\n\n const destinationTable = `projects/${this.projectId}/datasets/${this.datasetId}/tables/${tableName}`;\n // Pass `DefaultStream` as `streamId` (not `streamType`): the `_default`\n // stream is implicit on every table, so the client must short-circuit to\n // `${destinationTable}/streams/_default` instead of calling\n // `createWriteStream({ type: DEFAULT })` which BigQuery rejects with\n // `Unable to create a stream with type TYPE_UNSPECIFIED`.\n const connection = await this.writerClient.createStreamConnection({\n streamId: ns.managedwriter.DefaultStream,\n destinationTable,\n });\n\n const writer = new ns.managedwriter.JSONWriter({\n connection,\n protoDescriptor,\n });\n\n this.writers.set(tableName, {\n writer,\n primaryKey: primaryKey ?? \"\",\n timestampColumns,\n });\n return writer;\n }\n\n /** Close all open writer connections. Useful for graceful shutdown. */\n async close(): Promise<void> {\n for (const { writer } of this.writers.values()) {\n try {\n writer.close();\n } catch {\n /* ignore */\n }\n }\n this.writers.clear();\n if (this.writerClient && typeof this.writerClient.close === \"function\") {\n try {\n this.writerClient.close();\n } catch {\n /* ignore */\n }\n }\n }\n}\n","/**\n * Per-repo in-memory batch buffer.\n *\n * Accumulates {@link SyncEvent}s and flushes them in batches to a\n * {@link SqlAdapter}. On flush failure the events are re-published\n * to PubSub for retry (if a PubSub re-publisher is provided).\n */\n\nimport { SYNC_VERSION_COLUMN } from \"./constants\";\nimport type { SyncAdapter, SyncEvent } from \"./types\";\n\nexport interface SyncQueueOptions {\n /** Target adapter to flush data to */\n adapter: SyncAdapter;\n /** SQL table name or Search index UID */\n tableName: string;\n /** Primary key column/field name */\n primaryKey: string;\n /** Max rows per flush (default: 100) */\n batchSize?: number;\n /** Auto-flush interval in ms (default: 5_000). 0 = manual only. */\n flushIntervalMs?: number;\n /** Called on flush failure with the failed events. Typically re-publishes to PubSub. */\n onFlushError?: (events: SyncEvent[], error: unknown) => Promise<void>;\n}\n\nexport interface SyncQueueErrorEntry {\n /** Monotonic error sequence number for this queue instance */\n seq: number;\n /** Error message string */\n message: string;\n /** Number of events in the failed batch */\n count: number;\n /** Epoch millis when the failure occurred */\n timestamp: number;\n}\n\nexport interface SyncQueueStats {\n /** Total events successfully flushed to the adapter */\n flushedEvents: number;\n /** Total events whose flush failed */\n failedEvents: number;\n /** Total batches successfully flushed */\n flushedBatches: number;\n /** Total batches whose flush failed */\n failedBatches: number;\n /** Monotonic sequence counter of recorded flush errors */\n errorSeq: number;\n /** Recent flush error entries (capped ring buffer) */\n recentErrors: SyncQueueErrorEntry[];\n}\n\nexport interface SyncQueueFlushReport {\n /** Events successfully flushed during this flush call */\n flushed: number;\n /** Events that failed during this flush call */\n failed: number;\n /** Error messages recorded during this flush call */\n errors: string[];\n}\n\n/**\n * In-memory buffer that batches sync events per-repo and flushes them\n * to a target adapter.\n */\nexport class SyncQueue {\n private static readonly MAX_RECENT_ERRORS = 50;\n\n private buffer: SyncEvent[] = [];\n private flushing = false;\n private lastFlushFailed = false;\n private flushPromise: Promise<void> | null = null;\n private timer: ReturnType<typeof setInterval> | null = null;\n\n private flushedEvents = 0;\n private failedEvents = 0;\n private flushedBatches = 0;\n private failedBatches = 0;\n private errorSeq = 0;\n private recentErrors: SyncQueueErrorEntry[] = [];\n\n private readonly adapter: SyncAdapter;\n private readonly tableName: string;\n private readonly primaryKey: string;\n private readonly batchSize: number;\n private readonly onFlushError?: SyncQueueOptions[\"onFlushError\"];\n\n constructor(opts: SyncQueueOptions) {\n this.adapter = opts.adapter;\n this.tableName = opts.tableName;\n this.primaryKey = opts.primaryKey;\n this.batchSize = opts.batchSize ?? 100;\n this.onFlushError = opts.onFlushError;\n\n const interval = opts.flushIntervalMs ?? 5_000;\n if (interval > 0) {\n this.timer = setInterval(() => {\n void this.flush().catch((err) => {\n console.error(\n `[SyncQueue] Scheduled flush failed for ${this.tableName}:`,\n err,\n );\n });\n }, interval);\n // Allow the Node process to exit even if the timer is running\n if (typeof this.timer === \"object\" && \"unref\" in this.timer) {\n this.timer.unref();\n }\n }\n }\n\n /** Number of events waiting in the buffer. */\n get size(): number {\n return this.buffer.length;\n }\n\n /** Snapshot cumulative flush statistics for this queue. */\n getStats(): SyncQueueStats {\n return {\n flushedEvents: this.flushedEvents,\n failedEvents: this.failedEvents,\n flushedBatches: this.flushedBatches,\n failedBatches: this.failedBatches,\n errorSeq: this.errorSeq,\n recentErrors: this.recentErrors.map((e) => ({ ...e })),\n };\n }\n\n /** Push one or more events into the buffer. Triggers auto-flush if batchSize reached. */\n enqueue(...events: SyncEvent[]): void {\n this.buffer.push(...events);\n if (\n this.buffer.length >= this.batchSize &&\n !this.flushing &&\n !this.lastFlushFailed\n ) {\n void this._autoFlush().catch((err) => {\n console.error(\n `[SyncQueue] Auto-flush failed for ${this.tableName}:`,\n err,\n );\n });\n }\n }\n\n /**\n * Auto-flush full batches triggered by `enqueue()`.\n * Only drains complete batches of `batchSize` so events trickling in during\n * an async flush are not sent as tiny 1-2 row micro-batches.\n */\n private async _autoFlush(): Promise<void> {\n while (this.flushPromise) {\n await this.flushPromise;\n }\n if (this.buffer.length < this.batchSize || this.lastFlushFailed) return;\n\n this.flushing = true;\n this.flushPromise = this._drain(true).finally(() => {\n this.flushing = false;\n this.flushPromise = null;\n });\n await this.flushPromise;\n }\n\n /**\n * Flush all buffered events to the target adapter.\n * Upserts and deletes are batched separately.\n */\n async flush(): Promise<void> {\n while (this.flushPromise) {\n await this.flushPromise;\n }\n if (this.buffer.length === 0) return;\n\n this.flushing = true;\n this.flushPromise = this._drain(false).finally(() => {\n this.flushing = false;\n this.flushPromise = null;\n });\n await this.flushPromise;\n }\n\n /**\n * Flush all buffered events and return the delta of flushed/failed counts\n * and error messages recorded while draining.\n */\n async flushWithReport(): Promise<SyncQueueFlushReport> {\n const before = this.getStats();\n await this.flush();\n const after = this.getStats();\n return {\n flushed: after.flushedEvents - before.flushedEvents,\n failed: after.failedEvents - before.failedEvents,\n errors: after.recentErrors\n .filter((e) => e.seq > before.errorSeq)\n .map((e) => e.message),\n };\n }\n\n /**\n * Drain the buffer. When `fullBatchesOnly` is true, stops once fewer than\n * `batchSize` events remain so partial batches wait for explicit `flush()`\n * or the periodic timer.\n */\n private async _drain(fullBatchesOnly: boolean): Promise<void> {\n try {\n while (\n fullBatchesOnly\n ? this.buffer.length >= this.batchSize\n : this.buffer.length > 0\n ) {\n const progressed = await this._doFlush();\n if (!progressed) break;\n }\n } finally {\n this.flushing = false;\n }\n }\n\n /**\n * Flush a single batch (up to `batchSize` events) to the adapter.\n */\n private async _doFlush(): Promise<boolean> {\n // Drain the buffer atomically\n const batch = this.buffer.splice(0, this.batchSize);\n if (batch.length === 0) return false;\n\n try {\n const upsertsById = new Map<string, Record<string, unknown>>();\n const deleteIds: string[] = [];\n\n for (const evt of batch) {\n if (evt.operation === \"DELETE\") {\n deleteIds.push(evt.docId);\n // A delete supersedes any pending upsert in the same batch.\n upsertsById.delete(evt.docId);\n } else if (evt.data) {\n // Multiple updates to the same doc within a single batch:\n // Keep only the row with the highest __sync_version per docId.\n const existing = upsertsById.get(evt.docId);\n if (!existing) {\n upsertsById.set(evt.docId, evt.data);\n } else {\n const a = Number(existing[SYNC_VERSION_COLUMN] ?? 0);\n const b = Number(evt.data[SYNC_VERSION_COLUMN] ?? 0);\n if (b >= a) upsertsById.set(evt.docId, evt.data);\n }\n }\n }\n\n const upserts = Array.from(upsertsById.values());\n\n if (upserts.length > 0) {\n if (typeof this.adapter.upsert === \"function\") {\n await this.adapter.upsert(this.tableName, upserts, this.primaryKey);\n } else if (typeof (this.adapter as any).upsertRows === \"function\") {\n await (this.adapter as any).upsertRows(this.tableName, upserts, this.primaryKey);\n }\n }\n if (deleteIds.length > 0) {\n if (typeof this.adapter.delete === \"function\") {\n await this.adapter.delete(\n this.tableName,\n this.primaryKey,\n deleteIds,\n );\n } else if (typeof (this.adapter as any).deleteRows === \"function\") {\n await (this.adapter as any).deleteRows(\n this.tableName,\n this.primaryKey,\n deleteIds,\n );\n }\n }\n\n this.flushedEvents += batch.length;\n this.flushedBatches++;\n this.lastFlushFailed = false;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.failedEvents += batch.length;\n this.failedBatches++;\n this.errorSeq++;\n this.recentErrors.push({\n seq: this.errorSeq,\n message: msg,\n count: batch.length,\n timestamp: Date.now(),\n });\n if (this.recentErrors.length > SyncQueue.MAX_RECENT_ERRORS) {\n this.recentErrors.shift();\n }\n\n if (this.onFlushError) {\n await this.onFlushError(batch, err);\n } else {\n // Re-insert at the front so we retry next flush\n this.buffer.unshift(...batch);\n this.lastFlushFailed = true;\n console.error(`[SyncQueue] Flush failed for ${this.tableName}:`, err);\n return false;\n }\n }\n return true;\n }\n\n /** Stop the auto-flush timer and flush remaining events. */\n async shutdown(): Promise<void> {\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n await this.flush();\n }\n}\n","/**\n * PubSub worker — creates a Cloud Function that receives {@link SyncEvent}\n * messages from PubSub, routes them to per-repo / per-adapter {@link SyncQueue}s, and\n * flushes batches to the configured {@link SyncAdapter}s.\n *\n * Dependencies (`firebase-functions`, `@google-cloud/pubsub`) are injected\n * via the `deps` config property.\n */\n\nimport { z } from \"zod\";\nimport { SchemaTypeMismatchError } from \"./adapters/bigquery\";\nimport { SYNC_VERSION_COLUMN } from \"./constants\";\nimport { SyncQueue } from \"./queue\";\nimport { zodSchemaToColumns } from \"./schema-mapper\";\nimport type {\n RepoSyncConfig,\n SyncAdapter,\n SyncEvent,\n SyncWorkerConfig,\n} from \"./types\";\n\nexport { SchemaTypeMismatchError };\n\n// ---------------------------------------------------------------------------\n// Migration tracking\n// ---------------------------------------------------------------------------\n\n/** Set of `${repoName}:${adapter.name}` pairs that have already been migrated. */\nconst migratedTargets = new Set<string>();\n\nasync function ensureMigratedTarget(\n repoName: string,\n adapter: SyncAdapter,\n schema: z.ZodObject<any>,\n tableName: string,\n primaryKey: string,\n exclude?: string[],\n columnMap?: Record<string, string>,\n): Promise<void> {\n const migrationKey = `${repoName}:${adapter.name}`;\n if (migratedTargets.has(migrationKey)) return;\n\n if (typeof adapter.ensureTarget === \"function\") {\n await adapter.ensureTarget({\n targetName: tableName,\n primaryKey,\n schema,\n exclude,\n columnMap,\n });\n } else if (\"dialect\" in adapter && typeof (adapter as any).createTable === \"function\") {\n const sqlAdapter = adapter as any;\n const columns = zodSchemaToColumns(schema, sqlAdapter.dialect, {\n primaryKey,\n exclude,\n columnMap,\n });\n const exists = await sqlAdapter.tableExists(tableName);\n if (!exists) {\n await sqlAdapter.createTable({ tableName, columns });\n } else {\n const existing = new Set(await sqlAdapter.getTableColumns(tableName));\n const newCols = columns.filter((c: any) => !existing.has(c.name));\n if (newCols.length > 0) {\n await sqlAdapter.addColumns(tableName, newCols);\n await sqlAdapter.onSchemaChange?.(tableName);\n }\n }\n }\n\n migratedTargets.add(migrationKey);\n}\n\n// ---------------------------------------------------------------------------\n// Worker factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a PubSub-triggered Cloud Function that syncs Firestore changes\n * to target storage adapters.\n *\n * Returns an object with:\n * - `createHandler` — creates a Cloud Function for a PubSub topic\n * - `handleMessage` — process a SyncEvent directly (for testing)\n * - `queues` — internal SyncQueue map (for testing / manual flush)\n * - `shutdown()` — flush all queues and stop timers\n */\nexport function createSyncWorker<M extends Record<string, any>>(\n repoMapping: M,\n config: SyncWorkerConfig<NoInfer<M>>,\n) {\n const {\n deps,\n adapter: rawAdapter,\n adapters: rawAdaptersList,\n batchSize = 100,\n flushIntervalMs = 5_000,\n autoMigrate = false,\n topicPrefix = \"firestore-sync\",\n maxDlqAttempts = 5,\n workerOptions,\n repos: repoConfigs = {} as Record<\n string,\n RepoSyncConfig<string> | undefined\n >,\n } = config;\n\n // Normalize adapters list\n const normalizedRawAdapters: any[] = rawAdaptersList\n ? rawAdaptersList\n : Array.isArray(rawAdapter)\n ? rawAdapter\n : rawAdapter\n ? [rawAdapter]\n : [];\n\n const adapters: SyncAdapter[] = normalizedRawAdapters.map((a) =>\n typeof a === \"function\" ? a() : a,\n );\n\n function getAdaptersForRepo(repoName: string): SyncAdapter[] {\n const repoCfg = repoConfigs[repoName];\n if (repoCfg?.adapters && repoCfg.adapters.length > 0) {\n const allowed = new Set(repoCfg.adapters);\n return adapters.filter((a) => allowed.has(a.name));\n }\n return adapters;\n }\n\n // Build per-repo/per-adapter queues lazily\n const queues = new Map<string, SyncQueue>();\n\n function getQueue(\n repoName: string,\n adapter: SyncAdapter,\n primaryKey: string,\n ): SyncQueue {\n const queueKey = `${repoName}:${adapter.name}`;\n let q = queues.get(queueKey);\n if (q) return q;\n\n const repoCfg = repoConfigs[repoName];\n const tableName = repoCfg?.tableName ?? repoName;\n\n // Per-adapter DLQ topic for isolated failure recovery\n const dlTopicName = `${topicPrefix}-${repoName}-${adapter.name}-dlq`;\n const dlTopic = deps.pubsub.topic(dlTopicName);\n let dlTopicEnsured = false;\n\n const ensureDlTopic = async (): Promise<void> => {\n if (dlTopicEnsured) return;\n try {\n await dlTopic.create();\n console.info(\n `[SyncWorker:${adapter.name}] Created DLQ topic \"${dlTopicName}\"`,\n );\n } catch (e: unknown) {\n if ((e as { code?: number })?.code !== 6) throw e; // 6 = ALREADY_EXISTS\n }\n dlTopicEnsured = true;\n };\n\n const onFlushError = async (\n events: SyncEvent[],\n error: unknown,\n ): Promise<void> => {\n console.error(\n `[SyncWorker:${adapter.name}] Flush failed for \"${repoName}\" (${events.length} events):`,\n error,\n );\n await ensureDlTopic();\n\n await Promise.all(\n events.map((evt) => {\n const attempts = (evt.attempts ?? 0) + 1;\n if (maxDlqAttempts > 0 && attempts > maxDlqAttempts) {\n console.error(\n `[SyncWorker:${adapter.name}] Dropping event for \"${repoName}\" after ${attempts - 1} DLQ attempts:`,\n { docId: evt.docId, operation: evt.operation },\n );\n return Promise.resolve();\n }\n const payload: SyncEvent = {\n ...evt,\n attempts,\n firstFailedAt: evt.firstFailedAt ?? Date.now(),\n };\n return dlTopic.publishMessage({ json: payload });\n }),\n );\n };\n\n q = new SyncQueue({\n adapter,\n tableName,\n primaryKey,\n batchSize,\n flushIntervalMs,\n onFlushError,\n });\n queues.set(queueKey, q);\n // Also alias by repoName for single-adapter convenience\n if (!queues.has(repoName)) {\n queues.set(repoName, q);\n }\n return q;\n }\n\n // Message handler (works with or without Cloud Functions wrapper)\n async function handleMessage(syncEvent: SyncEvent): Promise<void> {\n const { repoName } = syncEvent;\n const repo = (repoMapping as Record<string, any>)[repoName];\n if (!repo) {\n console.warn(`[SyncWorker] Unknown repo \"${repoName}\", skipping event`);\n return;\n }\n\n const documentKey: string =\n (repo as any)._systemKeys?.[0] ?? (repo as any).documentKey ?? \"docId\";\n\n const repoCfg = repoConfigs[repoName];\n const columnMap = repoCfg?.columnMap as Record<string, string> | undefined;\n const primaryKey = columnMap?.[documentKey] ?? documentKey;\n\n if (syncEvent.data) {\n syncEvent.data[SYNC_VERSION_COLUMN] = syncEvent.version ?? Date.now();\n }\n\n const targetAdapters = getAdaptersForRepo(repoName);\n for (const adapter of targetAdapters) {\n if (autoMigrate) {\n const schema: z.ZodObject<any> | undefined =\n (repo as any).schema ?? undefined;\n if (schema) {\n const tableName = repoCfg?.tableName ?? repoName;\n await ensureMigratedTarget(\n repoName,\n adapter,\n schema,\n tableName,\n primaryKey,\n repoCfg?.exclude,\n columnMap,\n );\n }\n }\n\n const queue = getQueue(repoName, adapter, primaryKey);\n queue.enqueue(syncEvent);\n }\n }\n\n // Cloud Function v2 PubSub handler\n function createHandler(topicName: string) {\n const handlerFn = async (event: any) => {\n const data: SyncEvent = event.data?.message?.json ?? event.data?.json;\n if (!data) {\n console.warn(\"[SyncWorker] Received empty PubSub message\");\n return;\n }\n await handleMessage(data);\n\n // Flush all queues associated with this repo\n const targetAdapters = getAdaptersForRepo(data.repoName);\n for (const adapter of targetAdapters) {\n const queueKey = `${data.repoName}:${adapter.name}`;\n const q = queues.get(queueKey);\n if (q) await q.flush();\n }\n };\n\n if (workerOptions) {\n return deps.pubsubHandler.onMessagePublished(\n { topic: topicName, ...workerOptions },\n handlerFn,\n );\n }\n return deps.pubsubHandler.onMessagePublished(topicName, handlerFn);\n }\n\n return {\n /** Process a SyncEvent directly (for testing or custom PubSub integration). */\n handleMessage,\n /** Create a Cloud Function handler for a specific PubSub topic. */\n createHandler,\n /** Internal queue map (for testing). */\n queues,\n /** Flush all queues and stop timers. */\n async shutdown(): Promise<void> {\n const promises: Promise<void>[] = [];\n const visited = new Set<SyncQueue>();\n for (const q of queues.values()) {\n if (!visited.has(q)) {\n visited.add(q);\n promises.push(q.shutdown());\n }\n }\n await Promise.all(promises);\n },\n };\n}\n","/**\n * Unified wrapper — combines triggers + worker + admin into a single call.\n *\n * @example\n * ```typescript\n * import { onDocumentWritten } from \"firebase-functions/v2/firestore\";\n * import * as pubsubHandler from \"firebase-functions/v2/pubsub\";\n * import { PubSub } from \"@google-cloud/pubsub\";\n *\n * const sync = createFirestoreSync(repos, {\n * deps: { firestoreTriggers: { onDocumentWritten }, pubsubHandler, pubsub: new PubSub() },\n * adapters: [bigqueryAdapter, meilisearchAdapter],\n * topicPrefix: \"firestore-sync\",\n * autoMigrate: true,\n * admin: {\n * auth: { type: \"basic\", username: \"admin\", password: \"secret\" },\n * featuresFlag: { healthCheck: true, manualSync: true },\n * },\n * repos: {\n * users: { exclude: [\"documentPath\"], columnMap: { docId: \"user_id\" } },\n * posts: { columnMap: { docId: \"post_id\" } },\n * },\n * });\n *\n * // Triggers + PubSub handlers\n * export const { users_onSync, posts_onSync, sync_users, sync_posts } = sync.functions;\n *\n * // Admin endpoint — wrap with onRequest yourself or pass onRequest in config\n * export const adminsync = onRequest(sync.adminHandler!);\n * ```\n */\n\nimport { createadminsyncServer } from \"./admin\";\nimport type { SyncQueue } from \"./queue\";\nimport { createSyncTriggers } from \"./triggers\";\nimport type {\n FirestoreSyncConfig,\n OrFactory,\n RepoSyncConfig,\n SyncAdapter,\n SyncEvent,\n} from \"./types\";\nimport { createSyncWorker } from \"./worker\";\n\nconst DEFAULT_TOPIC_PREFIX = \"firestore-sync\";\n\n/**\n * Wraps a value-or-factory into a lazy proxy that only instantiates\n * when a property is first accessed. If the value is already an instance,\n * returns it as-is (zero overhead).\n */\nfunction lazyProxy<T extends object>(v: OrFactory<T>): T {\n if (typeof v !== \"function\") return v;\n const factory = v as () => T;\n let instance: T | undefined;\n return new Proxy({} as T, {\n get(_, prop) {\n if (!instance) instance = factory();\n return (instance as any)[prop];\n },\n has(_, prop) {\n if (!instance) instance = factory();\n return prop in (instance as object);\n },\n });\n}\n\nexport function createFirestoreSync<M extends Record<string, any>>(\n repoMapping: M,\n config: FirestoreSyncConfig<NoInfer<M>>,\n) {\n const {\n deps,\n adapter: rawAdapter,\n adapters: rawAdaptersList,\n topicPrefix = DEFAULT_TOPIC_PREFIX,\n batchSize,\n flushIntervalMs,\n autoMigrate,\n admin: adminConfig,\n workerOptions,\n triggerOptions,\n repos: repoConfigs,\n } = config;\n\n // Resolve lazy deps\n const pubsub = lazyProxy(deps.pubsub);\n\n const rawAdapters = rawAdaptersList\n ? rawAdaptersList\n : Array.isArray(rawAdapter)\n ? rawAdapter\n : rawAdapter\n ? [rawAdapter]\n : [];\n\n const adapters: SyncAdapter[] = rawAdapters.map((a) => lazyProxy(a as any));\n\n // Create triggers (Firestore → PubSub)\n const triggers = createSyncTriggers(repoMapping, {\n deps: { firestoreTriggers: deps.firestoreTriggers, pubsub },\n topicPrefix,\n triggerOptions,\n repos: repoConfigs,\n });\n\n // Create worker (PubSub → Target Adapters)\n const worker = createSyncWorker(repoMapping, {\n deps: { pubsubHandler: deps.pubsubHandler, pubsub },\n adapters,\n batchSize,\n flushIntervalMs,\n autoMigrate,\n topicPrefix,\n workerOptions,\n repos: repoConfigs,\n });\n\n // Auto-create a PubSub handler per active repo\n const handlers: Record<string, any> = {};\n const repoConfigsMap = repoConfigs as\n | Record<string, RepoSyncConfig<string> | undefined>\n | undefined;\n const rawMapping = (repoMapping as any)?.rawMapping;\n const configuredKeys = Object.keys(repoConfigsMap ?? {});\n const hasExplicitRepos = configuredKeys.length > 0;\n const allKeys = rawMapping ? Object.keys(rawMapping) : Object.keys(repoMapping);\n const activeRepoNames = hasExplicitRepos\n ? configuredKeys.filter((name) => allKeys.includes(name) || name in repoMapping)\n : allKeys;\n\n for (const repoName of activeRepoNames) {\n const rawMapping = (repoMapping as any)?.rawMapping;\n const isGroup = rawMapping\n ? !!rawMapping[repoName]?.isGroup\n : !!(repoMapping[repoName] as any)?._isGroup;\n const rawPath: string | undefined = rawMapping\n ? rawMapping[repoName]?.path\n : (repoMapping[repoName] as any)?._collectionPath;\n const hasTemplateTriggerPath =\n typeof rawPath === \"string\" && rawPath.includes(\"/\");\n if (\n !hasExplicitRepos &&\n isGroup &&\n !repoConfigsMap?.[repoName]?.triggerPath &&\n !hasTemplateTriggerPath\n ) {\n continue;\n }\n\n handlers[`sync_${repoName}`] = worker.createHandler(\n `${topicPrefix}-${repoName}`,\n );\n }\n\n // Optional admin endpoint\n let adminHandler: ((req: any, res: any) => Promise<void>) | null = null;\n if (adminConfig) {\n adminHandler = createadminsyncServer(\n repoMapping,\n adapters,\n worker.queues as Map<string, SyncQueue>,\n worker.handleMessage as (event: SyncEvent) => Promise<void>,\n adminConfig,\n (repoConfigs ?? {}) as Record<string, RepoSyncConfig<string> | undefined>,\n pubsub,\n topicPrefix,\n );\n // If onRequest is provided, wrap it as a Cloud Function automatically.\n // Otherwise expose the raw handler so the user can wrap it.\n handlers[\"adminsync\"] = adminConfig.onRequest\n ? adminConfig.httpsOptions\n ? adminConfig.onRequest(adminConfig.httpsOptions, adminHandler)\n : adminConfig.onRequest(adminHandler)\n : adminHandler;\n }\n\n const result = {\n /** All Cloud Functions (triggers + handlers + optional admin) — spread into exports */\n functions: { ...triggers, ...handlers } as Record<string, any>,\n /**\n * Raw admin HTTP handler — wrap with `onRequest()` yourself if you\n * didn't pass `onRequest` in the admin config.\n * @example\n * ```ts\n * export const adminsync = onRequest(sync.adminHandler!);\n * ```\n */\n adminHandler: adminHandler as\n | ((req: any, res: any) => Promise<void>)\n | null,\n /** Process a SyncEvent directly (for testing) */\n handleMessage: worker.handleMessage as (event: SyncEvent) => Promise<void>,\n /** Internal queue map (for testing) */\n queues: worker.queues as Map<string, SyncQueue>,\n /** Flush all queues and stop timers */\n shutdown: worker.shutdown as () => Promise<void>,\n };\n\n // Hide non-function properties from Firebase's recursive discovery.\n // Only `functions` is enumerable — the rest is accessible but invisible to Object.keys().\n for (const key of [\n \"adminHandler\",\n \"handleMessage\",\n \"queues\",\n \"shutdown\",\n ] as const) {\n Object.defineProperty(result, key, { enumerable: false });\n }\n\n return result;\n}\n","/**\n * DDL generator — produces CREATE TABLE / ALTER TABLE statements from\n * SqlColumn definitions and a SqlDialect.\n *\n * `generateDDL()` is the public entry point: it walks a repository mapping,\n * converts each repo's Zod schema to columns, and returns the full DDL\n * as a single string.\n */\n\nimport { z } from \"zod\";\nimport { zodSchemaToColumns } from \"./schema-mapper\";\nimport type {\n GenerateDDLConfig,\n RepoSyncConfig,\n SqlColumn,\n SqlDialect,\n SqlTableDef,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Low-level DDL helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Generate a CREATE TABLE statement from a table definition.\n * Uses the dialect for identifier quoting and type mapping.\n *\n * NOTE: This produces preview/export DDL with unqualified table names.\n * For actual execution, use `adapter.createTable()` which handles\n * dataset/schema qualification internally.\n */\nexport function createTableDDL(\n dialect: SqlDialect,\n table: SqlTableDef,\n): string {\n const cols = table.columns\n .map((c) => {\n const notNull = c.isPrimaryKey ? \" NOT NULL\" : \"\";\n return ` ${dialect.quoteIdentifier(c.name)} ${c.sqlType}${notNull}`;\n })\n .join(\",\\n\");\n\n return `CREATE TABLE IF NOT EXISTS ${dialect.quoteIdentifier(table.tableName)} (\\n${cols}\\n);`;\n}\n\n/**\n * Generate ALTER TABLE ADD COLUMN statements for columns missing from an\n * existing table.\n *\n * NOTE: This produces preview/export DDL with unqualified table names.\n * For actual execution, use `adapter.addColumns()` which handles\n * dataset/schema qualification internally.\n */\nexport function addColumnsDDL(\n dialect: SqlDialect,\n tableName: string,\n columns: SqlColumn[],\n): string {\n return columns\n .map(\n (c) =>\n `ALTER TABLE ${dialect.quoteIdentifier(tableName)} ADD COLUMN ${dialect.quoteIdentifier(c.name)} ${c.sqlType};`,\n )\n .join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// High-level DDL generation\n// ---------------------------------------------------------------------------\n\n/**\n * Walk a full repository mapping and produce DDL for every repo that has a\n * Zod schema attached.\n *\n * @param repoMapping - Object whose values expose `.schema` (ZodObject)\n * @param dialect - Target SQL dialect\n * @param config - Optional per-repo overrides (table name, exclusions…)\n * @returns Complete DDL string (one CREATE TABLE per repo, separated by newlines)\n */\nexport function generateDDL<M extends Record<string, any>>(\n repoMapping: M,\n dialect: SqlDialect,\n config?: GenerateDDLConfig<NoInfer<M>>,\n): string {\n const statements: string[] = [];\n\n for (const [repoName, repo] of Object.entries(repoMapping) as [\n string,\n any,\n ][]) {\n const schema: z.ZodObject<any> | undefined =\n repo.schema ?? (repo as any)._schema ?? undefined;\n if (!schema) continue;\n\n const repoCfg = (\n config?.repos as Record<string, RepoSyncConfig<string>> | undefined\n )?.[repoName];\n const tableName = repoCfg?.tableName ?? repoName;\n\n // Detect documentKey from repo metadata\n const documentKey: string =\n (repo as any)._systemKeys?.[0] ?? (repo as any).documentKey ?? \"docId\";\n\n const columns = zodSchemaToColumns(schema, dialect, {\n primaryKey: documentKey,\n exclude: repoCfg?.exclude,\n columnMap: repoCfg?.columnMap as Record<string, string> | undefined,\n });\n\n const tableDef: SqlTableDef = { tableName, columns };\n statements.push(createTableDDL(dialect, tableDef));\n }\n\n return statements.join(\"\\n\\n\");\n}\n","/**\n * Migration manager — generates DDL and optionally auto-migrates SQL tables\n * to match the Zod schemas defined in a repository mapping.\n *\n * Migrations are **additive only**: new columns are added, existing columns\n * are never dropped or modified.\n */\n\nimport { z } from \"zod\";\nimport { zodSchemaToColumns } from \"./schema-mapper\";\nimport type {\n GenerateDDLConfig,\n RepoSyncConfig,\n SqlAdapter,\n SqlColumn,\n SqlTableDef,\n} from \"./types\";\n\nexport interface MigrateResult {\n /** Tables that were created from scratch */\n created: string[];\n /** Tables that had columns added */\n altered: string[];\n /** Tables that were already up-to-date */\n upToDate: string[];\n /** Tables skipped (no schema available) */\n skipped: string[];\n}\n\n/**\n * Auto-migrate all repos: create missing tables, add missing columns.\n *\n * @returns Summary of what was done per table.\n */\nexport async function autoMigrate<M extends Record<string, any>>(\n repoMapping: M,\n adapter: SqlAdapter,\n config?: GenerateDDLConfig<NoInfer<M>>,\n): Promise<MigrateResult> {\n const result: MigrateResult = {\n created: [],\n altered: [],\n upToDate: [],\n skipped: [],\n };\n\n for (const [repoName, repo] of Object.entries(repoMapping) as [\n string,\n any,\n ][]) {\n const schema: z.ZodObject<any> | undefined =\n (repo as any).schema ?? undefined;\n if (!schema) {\n result.skipped.push(repoName);\n continue;\n }\n\n const repoCfg = (\n config?.repos as Record<string, RepoSyncConfig<string>> | undefined\n )?.[repoName];\n const tableName = repoCfg?.tableName ?? repoName;\n const documentKey: string =\n (repo as any)._systemKeys?.[0] ?? (repo as any).documentKey ?? \"docId\";\n\n const columns = zodSchemaToColumns(schema, adapter.dialect, {\n primaryKey: documentKey,\n exclude: repoCfg?.exclude,\n columnMap: repoCfg?.columnMap as Record<string, string> | undefined,\n });\n\n const tableDef: SqlTableDef = { tableName, columns };\n const exists = await adapter.tableExists(tableName);\n\n if (!exists) {\n await adapter.createTable(tableDef);\n result.created.push(tableName);\n } else {\n const existingCols = new Set(await adapter.getTableColumns(tableName));\n const newCols: SqlColumn[] = columns.filter(\n (c) => !existingCols.has(c.name),\n );\n\n if (newCols.length > 0) {\n await adapter.addColumns(tableName, newCols);\n result.altered.push(tableName);\n } else {\n result.upToDate.push(tableName);\n }\n }\n }\n\n return result;\n}\n","/**\n * Meilisearch adapter — streams Firestore changes to Meilisearch indexes.\n *\n * @example\n * ```ts\n * import { MeilisearchAdapter } from \"@lpdjs/firestore-repo-service/sync/meilisearch\";\n *\n * const adapter = new MeilisearchAdapter({\n * host: \"http://localhost:7700\",\n * apiKey: \"masterKey\",\n * indexesSettings: {\n * users: {\n * filterableAttributes: [\"role\", \"status\", \"createdAt\"],\n * sortableAttributes: [\"createdAt\", \"name\"],\n * searchableAttributes: [\"name\", \"email\"],\n * },\n * },\n * });\n * ```\n */\n\nimport type { z } from \"zod\";\nimport { unflattenDocument } from \"../serializer\";\nimport type {\n ExtractRepoFieldPaths,\n RepoSyncConfig,\n SyncAdapter,\n SyncHealthResult,\n} from \"../types\";\n\n/**\n * Minimal structural shape of a Meilisearch client.\n */\nexport interface MeilisearchLike {\n index(indexUid: string): {\n addDocuments(documents: any[], options?: { primaryKey?: string }): Promise<any>;\n deleteDocuments(documentIds: string[] | number[]): Promise<any>;\n getStats(): Promise<any>;\n getRawInfo(): Promise<any>;\n updateSettings(settings: any): Promise<any>;\n [key: string]: any;\n };\n getIndex(indexUid: string): Promise<any>;\n createIndex(indexUid: string, options?: { primaryKey?: string }): Promise<any>;\n isHealthy?(): Promise<any>;\n health?(): Promise<any>;\n getVersion?(): Promise<any>;\n}\n\nexport interface MeilisearchIndexSettings<Fields extends string = string> {\n /**\n * Fields displayed in the returned documents. Defaults to `[\"*\"]`.\n */\n displayedAttributes?: (Fields | \"*\")[];\n /**\n * Alias for `displayedAttributes` (Algolia-style naming).\n */\n retrievableAttributes?: (Fields | \"*\")[];\n /**\n * Alias for `displayedAttributes`.\n */\n attributesToRetrieve?: (Fields | \"*\")[];\n /**\n * Fields that are searched for query words. Defaults to `[\"*\"]`.\n */\n searchableAttributes?: (Fields | \"*\")[];\n /**\n * Fields that can be filtered using the `filter` search parameter.\n */\n filterableAttributes?: Fields[];\n /**\n * Fields that can be sorted using the `sort` search parameter.\n */\n sortableAttributes?: Fields[];\n /**\n * Custom ranking rules for search result scoring.\n */\n rankingRules?: string[];\n /**\n * List of words ignored during search queries.\n */\n stopWords?: string[];\n /**\n * Custom synonyms map.\n */\n synonyms?: Record<string, string[]>;\n /**\n * Field used to deduplicate search results.\n */\n distinctAttribute?: Fields | null;\n /**\n * Typo tolerance settings.\n */\n typoTolerance?: Record<string, any>;\n /**\n * Faceting settings.\n */\n faceting?: Record<string, any>;\n /**\n * Pagination limits (e.g. `maxTotalHits`).\n */\n pagination?: { maxTotalHits?: number; [key: string]: any };\n /**\n * Custom separator tokens.\n */\n separatorTokens?: string[];\n /**\n * Custom non-separator tokens.\n */\n nonSeparatorTokens?: string[];\n /**\n * Custom dictionary words.\n */\n dictionary?: string[];\n /**\n * Proximity precision mode (\"byWord\" or \"byAttribute\").\n */\n proximityPrecision?: \"byWord\" | \"byAttribute\";\n /**\n * Maximum search duration before timeout in ms.\n */\n searchCutoffMs?: number;\n [key: string]: any;\n}\n\n/**\n * Typed index settings map constrained to the repos in repository mapping `M`.\n * Field attributes autocomplete and check dot-notation nested paths.\n */\nexport type TypedMeilisearchIndexesSettings<M> = {\n [K in string & keyof M]?: MeilisearchIndexSettings<ExtractRepoFieldPaths<M[K]>>;\n};\n\nexport interface MeilisearchAdapterOptions<\n M extends Record<string, any> = Record<string, any>,\n> {\n /**\n * Host URL of the Meilisearch instance (e.g. `http://localhost:7700` or `https://ms-xxxx.meilisearch.io`).\n * Required if `client` is not provided.\n */\n host?: string;\n /**\n * API Key (e.g. master key or admin key) with permissions to read/write indexes.\n */\n apiKey?: string;\n /**\n * Existing pre-built Meilisearch client instance.\n */\n client?: MeilisearchLike | any;\n /**\n * Custom index settings per target index name (e.g. filterableAttributes, sortableAttributes).\n * When typed with repository mapping `M`, keys are constrained to repo names and attributes\n * are typed with dot-notation field paths.\n */\n indexesSettings?: string extends keyof M\n ? Record<string, MeilisearchIndexSettings>\n : TypedMeilisearchIndexesSettings<M>;\n /**\n * Whether to automatically unflatten double-underscore keys (`address__city` → `address.city`)\n * and parse stringified JSON arrays back into native arrays.\n * Default: `true`.\n */\n unflatten?: boolean;\n /**\n * Optional custom document transformation before indexing in Meilisearch.\n */\n transformDoc?: (doc: Record<string, unknown>) => Record<string, unknown>;\n}\n\n/** Lazy-loader for the optional `meilisearch` peer dependency. */\nfunction loadMeilisearchClient(options: MeilisearchAdapterOptions<any>): MeilisearchLike {\n if (options.client) return options.client;\n if (!options.host) {\n throw new Error(\n \"MeilisearchAdapter requires either a `client` instance or a `host` option.\",\n );\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { MeiliSearch } = require(\"meilisearch\");\n return new MeiliSearch({\n host: options.host,\n apiKey: options.apiKey,\n });\n } catch (err: any) {\n throw new Error(\n `Failed to load the \"meilisearch\" package. Please install it with:\\n` +\n ` bun add meilisearch # or npm install meilisearch\\n` +\n `Original error: ${err?.message ?? String(err)}`,\n );\n }\n}\n\nfunction areMeiliSettingsEqual(current: any, desired: any): boolean {\n if (!current || !desired) return false;\n for (const [key, value] of Object.entries(desired)) {\n if (value === undefined) continue;\n const curVal = current[key];\n if (Array.isArray(value)) {\n if (!Array.isArray(curVal)) return false;\n if (value.length !== curVal.length) return false;\n for (let i = 0; i < value.length; i++) {\n if (value[i] !== curVal[i]) return false;\n }\n } else if (typeof value === \"object\" && value !== null) {\n if (JSON.stringify(value) !== JSON.stringify(curVal)) return false;\n } else {\n if (value !== curVal) return false;\n }\n }\n return true;\n}\n\n/**\n * SyncAdapter implementation for Meilisearch.\n */\nexport class MeilisearchAdapter<\n M extends Record<string, any> = Record<string, any>,\n> implements SyncAdapter {\n readonly name = \"meilisearch\";\n private _client: MeilisearchLike | null = null;\n private readonly options: MeilisearchAdapterOptions<M>;\n\n constructor(options: MeilisearchAdapterOptions<M>) {\n this.options = options;\n if (options.client) {\n this._client = options.client;\n }\n }\n\n /** Configured index settings */\n get indexesSettings(): MeilisearchAdapterOptions<M>[\"indexesSettings\"] {\n return this.options.indexesSettings;\n }\n\n /** Resolved Meilisearch client instance. */\n get client(): MeilisearchLike {\n if (!this._client) {\n this._client = loadMeilisearchClient(this.options);\n }\n return this._client;\n }\n\n // ---------------------------------------------------------------------------\n // SyncAdapter Methods\n // ---------------------------------------------------------------------------\n\n async targetExists(targetName: string): Promise<boolean> {\n try {\n await this.client.getIndex(targetName);\n return true;\n } catch (err: any) {\n if (\n err?.code === \"index_not_found\" ||\n err?.cause?.code === \"index_not_found\" ||\n err?.statusCode === 404 ||\n err?.status === 404 ||\n err?.response?.status === 404 ||\n err?.cause?.status === 404 ||\n err?.cause?.statusCode === 404 ||\n err?.cause?.response?.status === 404\n ) {\n return false;\n }\n throw err;\n }\n }\n\n async upsert(\n targetName: string,\n items: Record<string, unknown>[],\n primaryKey: string,\n ): Promise<void> {\n if (items.length === 0) return;\n const shouldUnflatten = this.options.unflatten !== false;\n const docs = items.map((item) => {\n let doc = shouldUnflatten ? unflattenDocument(item) : item;\n if (typeof this.options.transformDoc === \"function\") {\n doc = this.options.transformDoc(doc);\n }\n return doc;\n });\n const index = this.client.index(targetName);\n await index.addDocuments(docs, { primaryKey });\n }\n\n async delete(\n targetName: string,\n _primaryKey: string,\n ids: string[],\n ): Promise<void> {\n if (ids.length === 0) return;\n const index = this.client.index(targetName);\n await index.deleteDocuments(ids);\n }\n\n async ensureTarget(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n exclude?: string[];\n columnMap?: Record<string, string>;\n }): Promise<void> {\n const { targetName, primaryKey } = options;\n const exists = await this.targetExists(targetName);\n if (!exists) {\n await this.client.createIndex(targetName, { primaryKey });\n }\n\n const rawSettings = this.options.indexesSettings?.[targetName];\n if (rawSettings) {\n const { retrievableAttributes, attributesToRetrieve, ...rest } = rawSettings;\n const settings = {\n ...rest,\n displayedAttributes:\n rest.displayedAttributes ?? retrievableAttributes ?? attributesToRetrieve,\n };\n if (settings.displayedAttributes === undefined) {\n delete (settings as any).displayedAttributes;\n }\n\n const index = this.client.index(targetName);\n if (typeof index.getSettings === \"function\") {\n try {\n const current = await index.getSettings();\n if (areMeiliSettingsEqual(current, settings)) {\n return;\n }\n } catch {\n // If reading current settings fails, fallback to updating\n }\n }\n\n await index.updateSettings(settings);\n }\n }\n\n async healthCheck(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n repoConfig?: RepoSyncConfig<string>;\n }): Promise<SyncHealthResult> {\n const { targetName } = options;\n try {\n const exists = await this.targetExists(targetName);\n if (!exists) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: `Meilisearch index \"${targetName}\" does not exist`,\n };\n }\n const index = this.client.index(targetName);\n const stats = await index.getStats();\n const rawInfo = typeof index.getRawInfo === \"function\" ? await index.getRawInfo() : {};\n\n return {\n healthy: true,\n targetName,\n targetExists: true,\n error: null,\n details: {\n numberOfDocuments: stats?.numberOfDocuments ?? 0,\n isIndexing: stats?.isIndexing ?? false,\n fieldDistribution: stats?.fieldDistribution ?? {},\n primaryKey: rawInfo?.primaryKey ?? options.primaryKey,\n },\n };\n } catch (err: any) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: err?.message ?? String(err),\n };\n }\n }\n\n /** Verify overall connection and connectivity to the Meilisearch instance. */\n async checkConnection(): Promise<{\n healthy: boolean;\n version?: string;\n error?: string;\n }> {\n try {\n let isHealthy = true;\n if (typeof this.client.isHealthy === \"function\") {\n const res = await this.client.isHealthy();\n isHealthy = res?.status === \"available\" || res === true;\n } else if (typeof this.client.health === \"function\") {\n const res = await this.client.health();\n isHealthy = res?.status === \"available\" || res === true;\n }\n let version: string | undefined;\n if (typeof this.client.getVersion === \"function\") {\n const v = await this.client.getVersion();\n version = v?.pkgVersion;\n }\n return { healthy: isHealthy, version };\n } catch (e: any) {\n return { healthy: false, error: e?.message ?? String(e) };\n }\n }\n}\n\n/**\n * Type-safe factory helper for creating a Meilisearch adapter bound to a repository mapping `M`.\n * Provides full autocompletion and strict type checking on repository names and nested field paths.\n *\n * @example\n * ```ts\n * const adapter = defineMeilisearchAdapter<typeof repos>({\n * client: createMeilisearchClient(),\n * indexesSettings: {\n * adminUsers: {\n * searchableAttributes: [\"docId\", \"baseUser.email\"],\n * },\n * },\n * });\n * ```\n */\nexport function defineMeilisearchAdapter<\n M extends Record<string, any> = Record<string, any>,\n>(options: MeilisearchAdapterOptions<M>): () => MeilisearchAdapter<M> {\n return () => new MeilisearchAdapter<M>(options);\n}\n"]}
1
+ {"version":3,"sources":["../../src/sync/admin.ts","../../src/servers/admin/router.ts","../../src/servers/utils/link-base.ts","../../src/servers/auth/firebase-auth.ts","../../src/shared/actor-context.ts","../../src/history/types.ts","../../src/history/inject.ts","../../src/shared/path-template.ts","../../src/repositories/factory.ts","../../src/sync/serializer.ts","../../src/sync/triggers.ts","../../src/sync/constants.ts","../../src/shared/zod-compat.ts","../../src/sync/schema-mapper.ts","../../src/sync/adapters/bigquery-types.ts","../../src/sync/adapters/bigquery.ts","../../src/sync/queue.ts","../../src/sync/worker.ts","../../src/sync/create-sync.ts","../../src/sync/ddl-generator.ts","../../src/sync/migration.ts","../../src/sync/adapters/meilisearch.ts"],"names":["compilePath","path","paramNames","src","c","_match","name","extractPath","req","raw","idx","MiniRouter","_req","res","err","middleware","handler","method","pattern","matchedRoute","params","route","m","i","enrichedReq","finalHandler","index","next","mw","getLinkBase","staticBasePath","region","base","project","resolvedRegion","target","service","host","resolveRegion","first","isAuthExtension","value","DEFAULT_HISTORY_REASON_HEADER","DEFAULT_HISTORY_COMMENT_HEADER","ACTOR_RESOLVER_HEADERS_SYMBOL","ALS_SYMBOL","g","AsyncLocalStorage","readFieldPath","obj","cur","part","pickFirstString","paths","p","val","readHeader","headerFn","createActorResolver","config","contextKeys","userIdFields","userEmailFields","reasonHeader","commentHeader","displayReasonHeader","displayCommentHeader","extrasFn","resolver","user","getFn","key","candidate","reason","comment","extras","DEFAULT_HISTORY_SHADOW_KEY","resolveShadowConfig","shadowOpt","customFields","getHistoryShadowKey","getHistoryIdentityKeys","shadow","extractSegmentParam","segment","parsePathTemplate","rawPath","documentKey","isGroup","segments","s","seg","isEvenSegments","collectionSegments","collectionId","collectionPath","parentKeys","documentPathTemplate","extractParentKeys","refCb","match","buildRepoStaticMeta","parsedPath","systemKeys","k","historyConfig","makeLazyRepo","resolve","overlay","resolved","ensure","_t","prop","serializeValue","options","seen","depth","geo","mapped","item","serializeNestedObject","MAX_FLATTEN_DEPTH","MAX_FLATTEN_KEYS","flattenObject","prefix","result","flatKey","exclude","columnMap","mappedKey","unflattenDocument","doc","rawValue","trimmed","parts","current","serializeDocument","isFlat","sourceDoc","dropped","filtered","v","flat","topLevel","column","escapeHtml","page","title","linkBase","body","safeTitle","safeLinkBase","sendHtml","html","status","sendJson","data","isJsonRequest","isTruthyFlag","normalized","parseDryRun","rawUrl","qIdx","parsed","TRANSIENT_FIRESTORE_CODES","isTransientFirestoreError","code","getPageWithRetry","maxAttempts","baseDelayMs","attempt","delayMs","getActiveQueuesForRepo","info","queues","adapter","exactKey","q","fallback","createadminsyncServer","repoMapping","adapterOrAdapters","handleMessage","repoConfigs","pubsub","topicPrefix","basePath","features","adapters","rawMapping","repoInfos","configuredKeys","hasExplicitRepos","allKeys","repoNames","repoCfg","repo","hasTemplateTriggerPath","activeAdapters","a","historyShadowKey","router","activeForceSyncs","ext","mountPath","realm","expected","lb","safeLb","rows","r","safeName","encodedName","links","adapterBadges","configCheckLink","results","h","exists","e","allHealthy","renderAdapterCard","adapterName","health","statusBadge","extraContent","details","expectedCols","actualSet","extraCols","colRows","extraRows","safeAdapters","collRef","dryRun","scanned","enqueued","handlerErrors","errorSamples","batchSize","query","FieldPath","lastDoc","queueBaselines","collectQueueErrors","queue","stats","entry","computeTotals","statsEntries","minFlushed","totalFailed","deltaFlushed","deltaFailed","effectiveExclude","preExisting","paginatedQuery","pageReadStartedAt","snapshot","docId","serialized","msg","activeQueues","synced","errors","errMsg","errorBlock","summaryLine","consoleBase","tPrefix","checks","msgLower","isApiDisabled","isPermission","isProjectNotFound","isNotFound","conn","category","topicName","topic","allOk","statusIcon","grouped","renderSection","items","fixHtml","overallBadge","DEFAULT_TOPIC_PREFIX","buildDocumentPath","repoName","syncMetaFromConfig","cfg","syncMetaFromRepo","docTemplate","createSyncTriggers","onDocumentWritten","triggers","topicCache","getTopic","t","publish","syncEvent","entries","repoConfigsMap","meta","documentPath","resolvedGroupPath","effectiveTriggerOptions","hasTriggerOptions","triggerHandler","event","before","after","beforeExists","afterExists","SYNC_VERSION_COLUMN","TYPE_MAP","getTypeName","schema","v4Type","v3Type","getInnerType","getShape","WRAPPER_TYPES","unwrap","nullable","inner","LOGICAL_MAP","zodTypeToLogical","flattenSchema","shape","dialect","parentNullable","excludeSet","primaryKey","columns","field","fieldSchema","fullKey","typeName","isNullable","nestedShape","logical","isPK","colName","zodSchemaToColumns","normalizeBigQueryType","type","upper","isBigQueryTypeCompatible","existing","desired","b","BigQueryDialect","id","bigqueryDialect","storageNsCache","loadStorageNs","formatChangeSequenceNumber","version","n","isRetryableStorageError","withRetry","fn","maxRetries","baseMs","cap","delay","SchemaTypeMismatchError","tableName","existingType","desiredType","_BigQueryAdapter","targetName","ids","missing","col","repoConfig","actualCols","expectedSet","extra","matched","healthy","metadata","f","fields","table","qi","pk","cols","notNull","opts","optionsClause","ddl","stmt","sql","cached","writer","timestampColumns","cdc","row","esc","d","ms","out","ns","bqSchema","storageSchema","protoDescriptor","destinationTable","connection","BigQueryAdapter","_SyncQueue","interval","events","fullBatchesOnly","batch","upsertsById","deleteIds","evt","upserts","SyncQueue","migratedTargets","ensureMigratedTarget","migrationKey","sqlAdapter","newCols","createSyncWorker","deps","rawAdapter","rawAdaptersList","flushIntervalMs","autoMigrate","maxDlqAttempts","workerOptions","getAdaptersForRepo","allowed","getQueue","queueKey","dlTopicName","dlTopic","dlTopicEnsured","ensureDlTopic","onFlushError","error","attempts","payload","targetAdapters","createHandler","handlerFn","promises","visited","lazyProxy","factory","instance","_","createFirestoreSync","adminConfig","triggerOptions","worker","handlers","activeRepoNames","adminHandler","createTableDDL","addColumnsDDL","generateDDL","statements","tableDef","existingCols","loadMeilisearchClient","MeiliSearch","areMeiliSettingsEqual","curVal","MeilisearchAdapter","shouldUnflatten","docs","_primaryKey","rawSettings","retrievableAttributes","attributesToRetrieve","rest","settings","rawInfo","isHealthy","defineMeilisearchAdapter"],"mappings":"4GAsBA,IAAA,EAAA,CAAA,CAAA,CAAA,EAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,OAAA,KAAA,CAAA,GAAA,CAAA,IAAA,KAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,SAAA,CAAA,CAAA,CAAA,GAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,OAAA,CAAA,KAAA,CAAA,IAAA,CAAA,SAAA,CAAA,CAAA,MAAA,KAAA,CAAA,sBAAA,CAAA,CAAA,CAAA,oBAAA,CAAA,CAAA,CAAA,CC+FA,SAASA,EAAAA,CAAYC,CAAAA,CAAyD,CAC5E,IAAMC,CAAAA,CAAuB,EAAC,CACxBC,CAAAA,CAAMF,EACT,OAAA,CAAQ,qBAAA,CAAwBG,CAAAA,EAAOA,CAAAA,GAAM,GAAA,CAAMA,CAAAA,CAAI,CAAA,EAAA,EAAKA,CAAC,EAAG,CAAA,CAChE,OAAA,CAAQ,4BAAA,CAA8B,CAACC,CAAAA,CAAQC,CAAAA,IAC9CJ,CAAAA,CAAW,IAAA,CAAKI,CAAI,CAAA,CACb,SAAA,CACR,CAAA,CAEH,OAAO,CAAE,OAAA,CAAS,IAAI,MAAA,CAAO,CAAA,CAAA,EAAIH,CAAG,CAAA,CAAA,CAAG,CAAA,CAAG,UAAA,CAAAD,CAAW,CACvD,CAEA,SAASK,EAAAA,CAAYC,CAAAA,CAAqB,CACxC,IAAMC,CAAAA,CAAMD,CAAAA,CAAI,IAAA,EAAQA,CAAAA,CAAI,KAAO,GAAA,CAC7BE,CAAAA,CAAMD,C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AO,IAAA,CAAK,MAAA,CAAO,WAAc,UAAA,CAAY,CAC/C,IAAMtd,CAAAA,CAAM,MAAM,IAAA,CAAK,MAAA,CAAO,SAAA,EAAU,CACxCsd,EAAYtd,CAAAA,EAAK,MAAA,GAAW,WAAA,EAAeA,CAAAA,GAAQ,CAAA,EACrD,CAAA,KAAA,GAAW,OAAO,IAAA,CAAK,OAAO,MAAA,EAAW,UAAA,CAAY,CACnD,IAAMA,CAAAA,CAAM,MAAM,IAAA,CAAK,MAAA,CAAO,QAAO,CACrCsd,CAAAA,CAAYtd,CAAAA,EAAK,MAAA,GAAW,WAAA,EAAeA,CAAAA,GAAQ,CAAA,EACrD,CACA,IAAI0V,CAAAA,CACJ,OAAI,OAAO,IAAA,CAAK,MAAA,CAAO,UAAA,EAAe,UAAA,GAEpCA,CAAAA,CAAAA,CADU,MAAM,IAAA,CAAK,MAAA,CAAO,UAAA,EAAW,GAC1B,UAAA,CAAA,CAER,CAAE,OAAA,CAAS4H,CAAAA,CAAW,QAAA5H,CAAQ,CACvC,CAAA,MAAS,CAAA,CAAQ,CACf,OAAO,CAAE,OAAA,CAAS,MAAO,KAAA,CAAO,CAAA,EAAG,OAAA,EAAW,MAAA,CAAO,CAAC,CAAE,CAC1D,CACF,CACF,EAkBO,SAAS6H,EAAAA,CAEdlX,CAAAA,CAAoE,CACpE,OAAO,IAAM,IAAIuW,EAAAA,CAAsBvW,CAAO,CAChD","file":"index.js","sourcesContent":["/**\n * Sync Admin — optional HTTP endpoint for inspecting and managing the\n * Firestore → SQL sync pipeline.\n *\n * Features (gated by `featuresFlag`):\n * - **healthCheck** — compare expected Zod-derived columns vs actual SQL columns\n * - **manualSync** — force re-sync all documents in a Firestore collection\n *\n * @example\n * ```typescript\n * const sync = createFirestoreSync(repos, {\n * // …deps, adapter, etc.\n * admin: {\n * auth: { type: \"basic\", username: \"admin\", password: \"secret\" },\n * featuresFlag: { healthCheck: true, manualSync: true },\n * },\n * });\n *\n * export const adminsync = onRequest(sync.adminHandler!);\n * ```\n */\n\nimport { FieldPath } from \"firebase-admin/firestore\";\nimport { z } from \"zod\";\nimport type { AnyReq, AnyRes, RouteParams } from \"../servers/admin/router\";\nimport { MiniRouter } from \"../servers/admin/router\";\nimport { isAuthExtension } from \"../servers/auth\";\nimport { makeLazyRepo } from \"../repositories/factory\";\nimport { getLinkBase, resolveRegion } from \"../servers/utils/link-base\";\nimport type { SyncQueue } from \"./queue\";\nimport { getHistoryShadowKey } from \"../history/inject\";\nimport { serializeDocument } from \"./serializer\";\nimport type {\n adminsyncConfig,\n PubSubClientDep,\n RepoSyncConfig,\n SyncAdapter,\n SyncEvent,\n SyncHealthResult,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\ntype Req = AnyReq & { params: RouteParams };\n\ninterface RepoInfo {\n name: string;\n schema: z.ZodObject<any> | null;\n documentKey: string;\n tableName: string;\n isGroup: boolean;\n repoCfg: RepoSyncConfig<string> | undefined;\n repo: any;\n adapters: SyncAdapter[];\n historyShadowKey: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// HTML & request helpers\n// ---------------------------------------------------------------------------\n\nfunction escapeHtml(value: unknown): string {\n return String(value ?? \"\")\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\nfunction page(title: string, linkBase: string, body: string): string {\n const safeTitle = escapeHtml(title);\n const safeLinkBase = escapeHtml(linkBase);\n return `<!DOCTYPE html>\n<html lang=\"en\"><head>\n<meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<title>${safeTitle} — Sync Admin</title>\n<style>\n *{box-sizing:border-box;margin:0;padding:0}\n body{font-family:system-ui,-apple-system,sans-serif;background:#f5f5f5;color:#1a1a1a;padding:2rem}\n a{color:#0969da;text-decoration:none}a:hover{text-decoration:underline}\n h1{margin-bottom:1rem}h2{margin:1.5rem 0 .75rem}\n table{border-collapse:collapse;width:100%;margin-bottom:1rem}\n th,td{text-align:left;padding:.5rem .75rem;border:1px solid #d0d7de}\n th{background:#f6f8fa;font-weight:600}\n tr:nth-child(even){background:#fafbfc}\n .badge{display:inline-block;padding:.15rem .5rem;border-radius:1rem;font-size:.8rem;font-weight:600}\n .badge-ok{background:#dafbe1;color:#1a7f37}\n .badge-warn{background:#fff8c5;color:#9a6700}\n .badge-err{background:#ffebe9;color:#cf222e}\n .btn{display:inline-block;padding:.4rem 1rem;border:1px solid #d0d7de;border-radius:.375rem;\n background:#fff;cursor:pointer;font-size:.85rem;text-decoration:none;color:#1a1a1a}\n .btn:hover{background:#f3f4f6}.btn-primary{background:#0969da;color:#fff;border-color:#0969da}\n .btn-primary:hover{background:#0860ca}\n nav{margin-bottom:1.5rem}nav a{margin-right:1rem}\n .card{background:#fff;border:1px solid #d0d7de;border-radius:.5rem;padding:1.25rem;margin-bottom:1rem}\n pre{background:#f6f8fa;padding:1rem;border-radius:.375rem;overflow-x:auto;font-size:.85rem}\n .muted{color:#656d76;font-size:.85rem}\n</style>\n</head><body>\n<nav><a href=\"${safeLinkBase}/\">← Dashboard</a></nav>\n<h1>${safeTitle}</h1>\n${body}\n</body></html>`;\n}\n\nfunction sendHtml(res: AnyRes, html: string, status = 200): void {\n res.status(status).set(\"Content-Type\", \"text/html; charset=utf-8\").send(html);\n}\n\nfunction sendJson(res: AnyRes, data: unknown, status = 200): void {\n res\n .status(status)\n .set(\"Content-Type\", \"application/json\")\n .send(JSON.stringify(data, null, 2));\n}\n\nfunction isJsonRequest(req: AnyReq): boolean {\n const accept = (req.headers?.[\"accept\"] ?? \"\") as string;\n return accept.includes(\"application/json\");\n}\n\nfunction isTruthyFlag(value: unknown): boolean {\n if (value === true || value === 1) return true;\n if (Array.isArray(value)) return value.some(isTruthyFlag);\n if (typeof value === \"string\") {\n const normalized = value.trim().toLowerCase();\n return (\n normalized === \"true\" ||\n normalized === \"1\" ||\n normalized === \"yes\" ||\n normalized === \"on\"\n );\n }\n return false;\n}\n\nfunction parseDryRun(req: AnyReq): boolean {\n if (req.query && isTruthyFlag(req.query[\"dryRun\"])) {\n return true;\n }\n\n const rawUrl = req.url ?? req.originalUrl ?? \"\";\n const qIdx = rawUrl.indexOf(\"?\");\n if (qIdx !== -1) {\n const params = new URLSearchParams(rawUrl.slice(qIdx + 1));\n if (isTruthyFlag(params.get(\"dryRun\"))) {\n return true;\n }\n }\n\n const body = req.body;\n if (body && typeof body === \"object\") {\n if (isTruthyFlag((body as Record<string, unknown>)[\"dryRun\"])) {\n return true;\n }\n } else if (typeof body === \"string\" && body.trim().length > 0) {\n const trimmed = body.trim();\n if (trimmed.startsWith(\"{\")) {\n try {\n const parsed = JSON.parse(trimmed);\n if (\n parsed &&\n typeof parsed === \"object\" &&\n isTruthyFlag((parsed as Record<string, unknown>)[\"dryRun\"])\n ) {\n return true;\n }\n } catch {\n // Ignore malformed JSON bodies\n }\n } else {\n const params = new URLSearchParams(trimmed);\n if (isTruthyFlag(params.get(\"dryRun\"))) {\n return true;\n }\n }\n }\n\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Firestore read retry & queue helpers\n// ---------------------------------------------------------------------------\n\n/** gRPC status codes eligible for retry on Firestore page reads. */\nconst TRANSIENT_FIRESTORE_CODES = new Set<number | string>([\n 4, // DEADLINE_EXCEEDED\n 8, // RESOURCE_EXHAUSTED\n 10, // ABORTED\n 13, // INTERNAL\n 14, // UNAVAILABLE\n \"4\",\n \"8\",\n \"10\",\n \"13\",\n \"14\",\n \"DEADLINE_EXCEEDED\",\n \"RESOURCE_EXHAUSTED\",\n \"ABORTED\",\n \"INTERNAL\",\n \"UNAVAILABLE\",\n]);\n\nfunction isTransientFirestoreError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const code = (err as { code?: unknown }).code;\n return (\n (typeof code === \"number\" || typeof code === \"string\") &&\n TRANSIENT_FIRESTORE_CODES.has(code)\n );\n}\n\nasync function getPageWithRetry<T>(\n getFn: () => Promise<T>,\n maxAttempts = 3,\n baseDelayMs = 100,\n): Promise<T> {\n let attempt = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n attempt++;\n try {\n return await getFn();\n } catch (err) {\n if (attempt >= maxAttempts || !isTransientFirestoreError(err)) {\n throw err;\n }\n const delayMs = baseDelayMs * 2 ** (attempt - 1);\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n }\n}\n\nfunction getActiveQueuesForRepo(\n info: RepoInfo,\n queues: Map<string, SyncQueue>,\n): Array<{ adapterName: string; queue: SyncQueue }> {\n const seen = new Set<SyncQueue>();\n const result: Array<{ adapterName: string; queue: SyncQueue }> = [];\n\n for (const adapter of info.adapters) {\n const exactKey = `${info.name}:${adapter.name}`;\n const q = queues.get(exactKey);\n if (q && !seen.has(q)) {\n seen.add(q);\n result.push({ adapterName: adapter.name ?? \"default\", queue: q });\n }\n }\n\n if (result.length === 0) {\n const fallback = queues.get(info.name);\n if (fallback && !seen.has(fallback)) {\n seen.add(fallback);\n result.push({\n adapterName: info.adapters[0]?.name ?? \"default\",\n queue: fallback,\n });\n }\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create the sync admin HTTP handler.\n */\nexport function createadminsyncServer(\n repoMapping: Record<string, any>,\n adapterOrAdapters: SyncAdapter | SyncAdapter[],\n queues: Map<string, SyncQueue>,\n handleMessage: (event: SyncEvent) => Promise<void>,\n config: adminsyncConfig,\n repoConfigs: Record<string, RepoSyncConfig<string> | undefined>,\n pubsub?: PubSubClientDep,\n topicPrefix?: string,\n): (req: any, res: any) => Promise<void> {\n const basePath = (config.basePath ?? \"/\").replace(/\\/$/, \"\") || \"\";\n const features = config.featuresFlag ?? {};\n const region = resolveRegion(config.httpsOptions?.region);\n\n const adapters: SyncAdapter[] = Array.isArray(adapterOrAdapters)\n ? adapterOrAdapters\n : [adapterOrAdapters];\n\n const rawMapping: Record<string, any> | undefined = (repoMapping as any)\n ?.rawMapping;\n const repoInfos: RepoInfo[] = [];\n\n const configuredKeys = Object.keys(repoConfigs ?? {});\n const hasExplicitRepos = configuredKeys.length > 0;\n const allKeys = rawMapping ? Object.keys(rawMapping) : Object.keys(repoMapping);\n const repoNames = hasExplicitRepos\n ? configuredKeys.filter((name) => allKeys.includes(name) || name in repoMapping)\n : allKeys;\n\n for (const name of repoNames) {\n const repoCfg = repoConfigs[name];\n const repo = rawMapping\n ? makeLazyRepo(rawMapping[name], () => (repoMapping as Record<string, any>)[name])\n : (repoMapping as Record<string, any>)[name];\n\n const isGroup = !!(repo as any)._isGroup;\n const collectionPath = (repo as any)._collectionPath as string | undefined;\n const hasTemplateTriggerPath =\n typeof collectionPath === \"string\" && collectionPath.includes(\"/\");\n if (\n !hasExplicitRepos &&\n isGroup &&\n !repoCfg?.triggerPath &&\n !hasTemplateTriggerPath\n ) {\n continue;\n }\n\n const activeAdapters = repoCfg?.adapters && repoCfg.adapters.length > 0\n ? adapters.filter((a) => repoCfg.adapters!.includes(a.name))\n : adapters;\n\n const historyShadowKey =\n typeof (repo as any)._historyShadowKey === \"string\"\n ? ((repo as any)._historyShadowKey as string)\n : getHistoryShadowKey((repo as any)._historyConfig);\n\n repoInfos.push({\n name,\n schema: (repo as any).schema ?? null,\n documentKey:\n (repo as any)._systemKeys?.[0] ?? (repo as any).documentKey ?? \"docId\",\n tableName: repoCfg?.tableName ?? name,\n isGroup,\n repoCfg,\n repo,\n adapters: activeAdapters,\n historyShadowKey,\n });\n }\n\n const router = new MiniRouter();\n const activeForceSyncs = new Set<string>();\n\n // -- Auth middleware -----------------------------------------------------\n if (config.auth) {\n if (isAuthExtension(config.auth)) {\n const ext = config.auth;\n for (const route of ext.routes) {\n const mountPath = `${basePath}${route.path}`;\n if (route.method === \"GET\") router.get(mountPath, route.handler);\n else router.post(mountPath, route.handler);\n }\n router.use(ext.middleware);\n } else if (typeof config.auth === \"function\") {\n router.use(config.auth as any);\n } else {\n const realm = config.auth.realm ?? \"Sync Admin\";\n const expected =\n \"Basic \" +\n Buffer.from(`${config.auth.username}:${config.auth.password}`).toString(\n \"base64\",\n );\n router.use((req, res, next) => {\n const authorization = (req as any).headers?.[\"authorization\"] ?? \"\";\n if (authorization !== expected) {\n res\n .status(401)\n .set(\"WWW-Authenticate\", `Basic realm=\"${realm}\"`)\n .set(\"Content-Type\", \"text/plain\")\n .send(\"Unauthorized\");\n return;\n }\n next();\n });\n }\n }\n\n // -- Dashboard ----------------------------------------------------------\n router.get(`${basePath}/`, (req, res) => {\n const lb = getLinkBase(req, basePath, region);\n const safeLb = escapeHtml(lb);\n const rows = repoInfos\n .map((r) => {\n const safeName = escapeHtml(r.name);\n const encodedName = encodeURIComponent(r.name);\n const links: string[] = [];\n if (features.healthCheck)\n links.push(`<a class=\"btn\" href=\"${safeLb}/${encodedName}/health\">Health</a>`);\n if (features.manualSync)\n links.push(\n `<a class=\"btn btn-primary\" href=\"${safeLb}/${encodedName}/force-sync\">Force Sync</a>`,\n );\n const adapterBadges = r.adapters\n .map((a) => `<span class=\"badge badge-ok\">${escapeHtml(a.name)}</span>`)\n .join(\" \");\n\n return `<tr>\n <td><strong>${safeName}</strong></td>\n <td>${escapeHtml(r.tableName)}</td>\n <td>${adapterBadges || '<span class=\"badge badge-warn\">none</span>'}</td>\n <td>${r.isGroup ? '<span class=\"badge badge-warn\">group</span>' : '<span class=\"badge badge-ok\">collection</span>'}</td>\n <td>${r.schema ? \"✓\" : \"✗\"}</td>\n <td>${links.join(\" \")}</td>\n </tr>`;\n })\n .join(\"\\n\");\n\n const configCheckLink = features.configCheck\n ? `<p style=\"margin-top:.5rem\"><a class=\"btn\" href=\"${safeLb}/config-check\">⚙ Config Check</a></p>`\n : \"\";\n\n const html = page(\n \"Sync Dashboard\",\n lb,\n `<div class=\"card\">\n <table>\n <thead><tr><th>Repository</th><th>Target Name</th><th>Adapters</th><th>Type</th><th>Schema</th><th>Actions</th></tr></thead>\n <tbody>${rows}</tbody>\n </table>\n ${configCheckLink}\n </div>`,\n );\n sendHtml(res, html);\n });\n router.get(`${basePath}`, (req, res) => {\n const lb = getLinkBase(req, basePath, region);\n res.status(302).set(\"Location\", `${lb}/`).send(\"\");\n });\n\n // -- Health Check -------------------------------------------------------\n if (features.healthCheck) {\n router.get(`${basePath}/:repoName/health`, async (req: Req, res) => {\n const lb = getLinkBase(req, basePath, region);\n const info = repoInfos.find((r) => r.name === req.params.repoName);\n if (!info) {\n sendHtml(\n res,\n page(\"Not Found\", lb, `<p>Unknown repo: ${escapeHtml(req.params.repoName)}</p>`),\n 404,\n );\n return;\n }\n\n const results: Array<{\n adapterName: string;\n health: SyncHealthResult;\n }> = [];\n\n for (const adapter of info.adapters) {\n if (typeof adapter.healthCheck === \"function\") {\n const h = await adapter.healthCheck({\n targetName: info.tableName,\n primaryKey: info.documentKey,\n schema: info.schema ?? undefined,\n repoConfig: info.repoCfg,\n });\n results.push({ adapterName: adapter.name, health: h });\n } else {\n try {\n const exists = await adapter.targetExists(info.tableName);\n results.push({\n adapterName: adapter.name,\n health: {\n healthy: exists,\n targetName: info.tableName,\n targetExists: exists,\n error: exists ? null : `Target \"${info.tableName}\" does not exist`,\n },\n });\n } catch (e: any) {\n results.push({\n adapterName: adapter.name,\n health: {\n healthy: false,\n targetName: info.tableName,\n targetExists: false,\n error: e?.message ?? String(e),\n },\n });\n }\n }\n }\n\n const allHealthy =\n results.length > 0 && results.every((r) => r.health.healthy);\n\n if (isJsonRequest(req)) {\n sendJson(res, {\n repo: info.name,\n targetName: info.tableName,\n healthy: allHealthy,\n adapters: results.map((r) => ({\n name: r.adapterName,\n ...r.health,\n })),\n });\n return;\n }\n\n const renderAdapterCard = (r: {\n adapterName: string;\n health: SyncHealthResult;\n }) => {\n const { adapterName, health } = r;\n const statusBadge = health.healthy\n ? '<span class=\"badge badge-ok\">Healthy</span>'\n : '<span class=\"badge badge-err\">Unhealthy</span>';\n\n let extraContent = \"\";\n const details = health.details as any;\n if (details?.expected && Array.isArray(details.expected)) {\n const expectedCols = details.expected;\n const actualSet = new Set(details.actual ?? []);\n const extraCols = (details.extra ?? []) as string[];\n const colRows = expectedCols\n .map((c: any) => {\n const status = actualSet.has(c.name)\n ? '<span class=\"badge badge-ok\">OK</span>'\n : '<span class=\"badge badge-err\">MISSING</span>';\n return `<tr><td>${escapeHtml(c.name)}</td><td>${escapeHtml(c.type)}</td><td>${c.nullable ? \"Yes\" : \"No\"}</td><td>${c.isPrimaryKey ? \"✓\" : \"\"}</td><td>${status}</td></tr>`;\n })\n .join(\"\\n\");\n const extraRows = extraCols\n .map(\n (c: string) =>\n `<tr><td>${escapeHtml(c)}</td><td colspan=\"3\" class=\"muted\">not in schema</td><td><span class=\"badge badge-warn\">EXTRA</span></td></tr>`,\n )\n .join(\"\\n\");\n\n extraContent = `<h2>Columns</h2>\n <table>\n <thead><tr><th>Column</th><th>SQL Type</th><th>Nullable</th><th>PK</th><th>Status</th></tr></thead>\n <tbody>${colRows}${extraRows}</tbody>\n </table>`;\n } else if (details?.numberOfDocuments !== undefined) {\n extraContent = `<h2>Index Stats</h2>\n <table>\n <tr><th>Documents Count</th><td>${escapeHtml(details.numberOfDocuments)}</td></tr>\n <tr><th>Indexing in Progress</th><td>${details.isIndexing ? '<span class=\"badge badge-warn\">Yes</span>' : '<span class=\"badge badge-ok\">No</span>'}</td></tr>\n <tr><th>Primary Key</th><td><code>${escapeHtml(details.primaryKey ?? \"default\")}</code></td></tr>\n </table>`;\n }\n\n return `<div class=\"card\" style=\"margin-top:1rem\">\n <h2>Adapter: <code>${escapeHtml(adapterName)}</code> ${statusBadge}</h2>\n <p>Target: <code>${escapeHtml(health.targetName)}</code> ${!health.targetExists ? '<span class=\"badge badge-err\">NOT FOUND</span>' : \"\"}</p>\n ${health.error ? `<p class=\"badge badge-err\" style=\"margin-top:.5rem\">Error: ${escapeHtml(health.error)}</p>` : \"\"}\n ${extraContent}\n </div>`;\n };\n\n const html = page(\n `Health: ${info.name}`,\n lb,\n `<div class=\"card\">\n <p>Overall status for <strong>${escapeHtml(info.name)}</strong>: ${allHealthy ? '<span class=\"badge badge-ok\">Healthy</span>' : '<span class=\"badge badge-err\">Issues detected</span>'}</p>\n </div>\n ${results.map(renderAdapterCard).join(\"\\n\")}`,\n );\n sendHtml(res, html);\n });\n }\n\n // -- Force Sync ---------------------------------------------------------\n if (features.manualSync) {\n router.get(`${basePath}/:repoName/force-sync`, (req: Req, res) => {\n const lb = getLinkBase(req, basePath, region);\n const info = repoInfos.find((r) => r.name === req.params.repoName);\n if (!info) {\n sendHtml(\n res,\n page(\"Not Found\", lb, `<p>Unknown repo: ${escapeHtml(req.params.repoName)}</p>`),\n 404,\n );\n return;\n }\n\n const safeName = escapeHtml(info.name);\n const safeAdapters = info.adapters.map((a) => escapeHtml(a.name)).join(\", \");\n const html = page(\n `Force Sync: ${info.name}`,\n lb,\n `<div class=\"card\">\n <p>This will read <strong>all</strong> documents from the <code>${safeName}</code> Firestore collection\n and upsert them into all active target storage adapters (${safeAdapters}).</p>\n <p class=\"muted\" style=\"margin:.75rem 0\">This may take a while for large collections.</p>\n <form method=\"POST\" action=\"${escapeHtml(lb)}/${encodeURIComponent(info.name)}/force-sync\">\n <label style=\"display:block;margin-bottom:.75rem\">\n <input type=\"checkbox\" name=\"dryRun\" value=\"true\"> Dry run (scan &amp; validate serialization only, no writes)\n </label>\n <button type=\"submit\" class=\"btn btn-primary\">Start Force Sync</button>\n </form>\n </div>`,\n );\n sendHtml(res, html);\n });\n\n router.post(`${basePath}/:repoName/force-sync`, async (req: Req, res) => {\n const lb = getLinkBase(req, basePath, region);\n const info = repoInfos.find((r) => r.name === req.params.repoName);\n if (!info) {\n sendJson(res, { error: `Unknown repo: ${req.params.repoName}` }, 404);\n return;\n }\n\n const collRef = info.repo.ref;\n if (!collRef) {\n sendJson(\n res,\n { error: `No collection reference for \"${info.name}\"` },\n 400,\n );\n return;\n }\n\n if (activeForceSyncs.has(info.name)) {\n if (isJsonRequest(req)) {\n sendJson(\n res,\n {\n error: `Force sync is already running for \"${info.name}\"`,\n repo: info.name,\n },\n 409,\n );\n return;\n }\n sendHtml(\n res,\n page(\n `Force Sync: ${info.name}`,\n lb,\n `<div class=\"card\">\n <p class=\"badge badge-warn\">Already Running</p>\n <p>A force sync is already in progress for <strong>${escapeHtml(info.name)}</strong>. Please wait for it to finish before starting another.</p>\n </div>`,\n ),\n 409,\n );\n return;\n }\n\n activeForceSyncs.add(info.name);\n try {\n const dryRun = parseDryRun(req);\n let scanned = 0;\n let enqueued = 0;\n let handlerErrors = 0;\n const errorSamples: string[] = [];\n const batchSize = 500;\n const orderedRef =\n typeof collRef.orderBy === \"function\"\n ? collRef.orderBy(FieldPath.documentId())\n : collRef;\n const query = orderedRef.limit(batchSize);\n let lastDoc: any = null;\n\n const queueBaselines = new Map<\n SyncQueue,\n {\n adapterName: string;\n flushedEvents: number;\n failedEvents: number;\n lastErrorSeq: number;\n }\n >();\n\n const collectQueueErrors = (): void => {\n for (const [queue, base] of queueBaselines.entries()) {\n if (typeof (queue as any).getStats !== \"function\") continue;\n const stats = queue.getStats();\n for (const entry of stats.recentErrors) {\n if (entry.seq > base.lastErrorSeq) {\n if (errorSamples.length < 5) {\n errorSamples.push(\n `[${base.adapterName}] flush failed (${entry.count} event(s)): ${entry.message}`,\n );\n }\n }\n }\n base.lastErrorSeq = stats.errorSeq;\n }\n };\n\n const computeTotals = (): { synced: number; errors: number } => {\n if (dryRun) {\n return { synced: 0, errors: handlerErrors };\n }\n const statsEntries = Array.from(queueBaselines.entries()).filter(\n ([q]) => typeof (q as any).getStats === \"function\",\n );\n if (statsEntries.length === 0) {\n return { synced: enqueued, errors: handlerErrors };\n }\n let minFlushed = enqueued;\n let totalFailed = 0;\n for (const [queue, base] of statsEntries) {\n const stats = queue.getStats();\n const deltaFlushed = Math.max(\n 0,\n stats.flushedEvents - base.flushedEvents,\n );\n const deltaFailed = Math.max(\n 0,\n stats.failedEvents - base.failedEvents,\n );\n if (deltaFlushed < minFlushed) minFlushed = deltaFlushed;\n totalFailed += deltaFailed;\n }\n return {\n synced: minFlushed,\n errors: handlerErrors + totalFailed,\n };\n };\n\n const effectiveExclude = info.historyShadowKey\n ? Array.from(\n new Set([\n ...(info.repoCfg?.exclude ?? []),\n info.historyShadowKey,\n ]),\n )\n : info.repoCfg?.exclude;\n\n try {\n if (!dryRun) {\n // Drain any pre-existing buffered events before snapshotting baselines\n // so prior traffic is not attributed to this force-sync run.\n const preExisting = getActiveQueuesForRepo(info, queues);\n for (const { adapterName, queue } of preExisting) {\n await queue.flush();\n if (typeof (queue as any).getStats === \"function\") {\n const s = queue.getStats();\n queueBaselines.set(queue, {\n adapterName,\n flushedEvents: s.flushedEvents,\n failedEvents: s.failedEvents,\n lastErrorSeq: s.errorSeq,\n });\n } else {\n queueBaselines.set(queue, {\n adapterName,\n flushedEvents: 0,\n failedEvents: 0,\n lastErrorSeq: 0,\n });\n }\n }\n }\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const paginatedQuery = lastDoc ? query.startAfter(lastDoc) : query;\n let pageReadStartedAt = Date.now();\n const snapshot = await getPageWithRetry<{\n empty: boolean;\n docs: any[];\n }>(() => {\n pageReadStartedAt = Date.now();\n return paginatedQuery.get();\n });\n if (snapshot.empty || snapshot.docs.length === 0) break;\n\n for (const doc of snapshot.docs) {\n scanned++;\n let docId = String(doc.id ?? \"unknown\");\n try {\n const data = doc.data() as Record<string, unknown>;\n docId = String(data?.[info.documentKey] ?? doc.id);\n const serialized = serializeDocument(data, {\n exclude: effectiveExclude,\n columnMap: info.repoCfg?.columnMap,\n flat: info.repoCfg?.flat,\n transformDoc: info.repoCfg?.transformDoc,\n });\n\n if (!dryRun) {\n await handleMessage({\n operation: \"UPSERT\",\n repoName: info.name,\n docId,\n data: serialized,\n timestamp: new Date(pageReadStartedAt).toISOString(),\n version: pageReadStartedAt,\n });\n enqueued++;\n }\n } catch (e: any) {\n handlerErrors++;\n const msg = e?.message ?? String(e);\n console.error(\n `[ForceSync:${info.name}] doc=${docId} failed:`,\n e,\n );\n if (errorSamples.length < 5) {\n errorSamples.push(`${docId}: ${msg}`);\n }\n }\n }\n\n // Apply backpressure: flush all active adapter queues at the end of\n // each page before reading the next page from Firestore.\n if (!dryRun) {\n const activeQueues = getActiveQueuesForRepo(info, queues);\n for (const { adapterName, queue } of activeQueues) {\n if (!queueBaselines.has(queue)) {\n queueBaselines.set(queue, {\n adapterName,\n flushedEvents: 0,\n failedEvents: 0,\n lastErrorSeq: 0,\n });\n }\n await queue.flush();\n }\n collectQueueErrors();\n }\n\n lastDoc = snapshot.docs[snapshot.docs.length - 1];\n if (snapshot.docs.length < batchSize) break;\n }\n } catch (e: any) {\n if (!dryRun) {\n for (const { adapterName, queue } of getActiveQueuesForRepo(\n info,\n queues,\n )) {\n if (!queueBaselines.has(queue)) {\n queueBaselines.set(queue, {\n adapterName,\n flushedEvents: 0,\n failedEvents: 0,\n lastErrorSeq: 0,\n });\n }\n }\n collectQueueErrors();\n }\n const { synced, errors } = computeTotals();\n const errMsg = e?.message ?? String(e);\n if (isJsonRequest(req)) {\n sendJson(\n res,\n {\n error: errMsg,\n ...(dryRun && { dryRun: true }),\n scanned,\n synced,\n errors,\n ...(errorSamples.length > 0 && { errorSamples }),\n },\n 500,\n );\n return;\n }\n sendHtml(\n res,\n page(\n `Force Sync: ${info.name}`,\n lb,\n `<div class=\"card\">\n <p class=\"badge badge-err\">Error: ${escapeHtml(errMsg)}</p>\n <p>Scanned ${scanned} docs, synced ${synced} docs before failure (${errors} errors).</p>\n </div>`,\n ),\n 500,\n );\n return;\n }\n\n const { synced, errors } = computeTotals();\n\n if (isJsonRequest(req)) {\n sendJson(res, {\n ...(dryRun && { dryRun: true }),\n repo: info.name,\n table: info.tableName,\n scanned,\n synced,\n errors,\n ...(errorSamples.length > 0 && { errorSamples }),\n });\n return;\n }\n\n const errorBlock =\n errorSamples.length > 0\n ? `<details style=\"margin-top:1rem\"><summary>First ${errorSamples.length} error(s)</summary>\n <pre style=\"white-space:pre-wrap\">${errorSamples\n .map((s) => escapeHtml(s))\n .join(\"\\n\\n\")}</pre></details>`\n : \"\";\n\n const safeAdapters = info.adapters\n .map((a) => escapeHtml(a.name))\n .join(\", \");\n\n const statusBadge = dryRun\n ? `<p class=\"badge ${errors > 0 ? \"badge-warn\" : \"badge-ok\"}\">${errors > 0 ? \"Dry run completed with errors\" : \"Dry run complete\"}</p>`\n : `<p class=\"badge ${errors > 0 ? \"badge-warn\" : \"badge-ok\"}\">${errors > 0 ? \"Completed with errors\" : \"Complete\"}</p>`;\n\n const summaryLine = dryRun\n ? `<p>Dry run scanned <strong>${scanned}</strong> documents (0 synced, no writes performed).</p>`\n : `<p>Scanned <strong>${scanned}</strong> documents, synced <strong>${synced}</strong> documents to targets (${safeAdapters}).</p>`;\n\n const html = page(\n `Force Sync: ${info.name}`,\n lb,\n `<div class=\"card\">\n ${statusBadge}\n ${summaryLine}\n ${errors > 0 ? `<p class=\"badge badge-warn\">${errors} error(s)</p>` : \"\"}\n ${errorBlock}\n </div>`,\n );\n sendHtml(res, html);\n } finally {\n activeForceSyncs.delete(info.name);\n }\n });\n }\n\n // -- Config Check -------------------------------------------------------\n if (features.configCheck) {\n router.get(`${basePath}/config-check`, async (req, res) => {\n const lb = getLinkBase(req, basePath, region);\n const project =\n process.env[\"GCLOUD_PROJECT\"] ??\n process.env[\"GOOGLE_CLOUD_PROJECT\"] ??\n process.env[\"GCP_PROJECT\"] ??\n \"unknown\";\n const consoleBase = `https://console.cloud.google.com`;\n const tPrefix = topicPrefix ?? \"firestore-sync\";\n\n interface CheckResult {\n name: string;\n category: \"bigquery\" | \"meilisearch\" | \"pubsub\" | \"firestore\" | \"storage\";\n status: \"ok\" | \"error\" | \"warn\";\n message: string;\n fix?: { gcloud?: string; console?: string; hint?: string };\n }\n\n const checks: CheckResult[] = [];\n\n // Check each configured adapter\n for (const adapter of adapters) {\n if (adapter.name === \"bigquery\") {\n try {\n await adapter.targetExists(\"__nonexistent_health_check__\");\n checks.push({\n name: \"BigQuery API\",\n category: \"bigquery\",\n status: \"ok\",\n message: \"BigQuery API is reachable\",\n });\n } catch (e: any) {\n const msg = e?.message ?? String(e);\n const msgLower = msg.toLowerCase();\n const isApiDisabled =\n msgLower.includes(\"disabled\") ||\n msgLower.includes(\"has not been used\") ||\n msgLower.includes(\"accessnotconfigured\");\n const isPermission =\n msgLower.includes(\"permission\") ||\n msg.includes(\"403\") ||\n msgLower.includes(\"access denied\");\n const isProjectNotFound =\n msgLower.includes(\"project\") && msgLower.includes(\"not found\");\n const isNotFound =\n msgLower.includes(\"not found\") || msg.includes(\"404\");\n\n if (isApiDisabled) {\n checks.push({\n name: \"BigQuery API\",\n category: \"bigquery\",\n status: \"error\",\n message: \"BigQuery API is not enabled\",\n fix: {\n gcloud: `gcloud services enable bigquery.googleapis.com --project=${project}`,\n console: `${consoleBase}/apis/library/bigquery.googleapis.com?project=${project}`,\n },\n });\n } else if (isProjectNotFound) {\n checks.push({\n name: \"BigQuery Project\",\n category: \"bigquery\",\n status: \"error\",\n message: msg,\n fix: {\n hint:\n \"The GCP project does not exist or the credentials don't have access to it.\",\n console: `${consoleBase}/home/dashboard`,\n },\n });\n } else if (isPermission) {\n checks.push({\n name: \"BigQuery API\",\n category: \"bigquery\",\n status: \"error\",\n message: `Permission denied: ${msg}`,\n fix: {\n hint: \"Grant the service account BigQuery Data Editor + BigQuery Job User roles\",\n console: `${consoleBase}/iam-admin/iam?project=${project}`,\n },\n });\n } else if (isNotFound) {\n checks.push({\n name: \"BigQuery Dataset\",\n category: \"bigquery\",\n status: \"error\",\n message: `Dataset not found: ${msg}`,\n fix: {\n hint: \"Create the dataset first\",\n gcloud: `bq mk --dataset ${project}:YOUR_DATASET_ID`,\n console: `${consoleBase}/bigquery?project=${project}`,\n },\n });\n } else {\n checks.push({\n name: \"BigQuery API\",\n category: \"bigquery\",\n status: \"ok\",\n message:\n \"BigQuery API is reachable (table lookup returned expected error)\",\n });\n }\n }\n } else if (adapter.name === \"meilisearch\" || typeof (adapter as any).checkConnection === \"function\") {\n try {\n const conn = typeof (adapter as any).checkConnection === \"function\"\n ? await (adapter as any).checkConnection()\n : { healthy: await adapter.targetExists(\"__nonexistent__\") };\n checks.push({\n name: \"Meilisearch API\",\n category: \"meilisearch\",\n status: conn.healthy ? \"ok\" : \"error\",\n message: conn.healthy\n ? `Meilisearch is reachable${conn.version ? ` (v${conn.version})` : \"\"}`\n : `Meilisearch connection error: ${conn.error ?? \"unknown\"}`,\n ...(conn.error && {\n fix: {\n hint: \"Ensure Meilisearch is running and host/apiKey options are valid.\",\n },\n }),\n });\n } catch (e: any) {\n checks.push({\n name: \"Meilisearch API\",\n category: \"meilisearch\",\n status: \"error\",\n message: `Meilisearch error: ${e?.message ?? String(e)}`,\n });\n }\n }\n }\n\n // Per-repo target existence\n for (const info of repoInfos) {\n for (const adapter of info.adapters) {\n const category = adapter.name === \"bigquery\" ? \"bigquery\" : adapter.name === \"meilisearch\" ? \"meilisearch\" : \"storage\";\n try {\n const exists = await adapter.targetExists(info.tableName);\n checks.push({\n name: `[${adapter.name}] Target: ${info.tableName}`,\n category,\n status: exists ? \"ok\" : \"warn\",\n message: exists\n ? `Target \\`${info.tableName}\\` exists`\n : `Target \\`${info.tableName}\\` does not exist yet`,\n ...(!exists && {\n fix: {\n hint: `Target will be auto-created on first sync if autoMigrate is enabled.`,\n },\n }),\n });\n } catch (e: any) {\n checks.push({\n name: `[${adapter.name}] Target: ${info.tableName}`,\n category,\n status: \"error\",\n message: e?.message ?? String(e),\n });\n }\n }\n }\n\n // --- Pub/Sub checks ---\n if (pubsub) {\n for (const info of repoInfos) {\n const topicName = `${tPrefix}-${info.name}`;\n try {\n const topic = (pubsub as any).topic(topicName);\n if (typeof topic.exists === \"function\") {\n const [exists] = await topic.exists();\n checks.push({\n name: `Topic: ${topicName}`,\n category: \"pubsub\",\n status: exists ? \"ok\" : \"error\",\n message: exists\n ? `Topic \\`${topicName}\\` exists`\n : `Topic \\`${topicName}\\` does not exist`,\n ...(!exists && {\n fix: {\n gcloud: `gcloud pubsub topics create ${topicName} --project=${project}`,\n console: `${consoleBase}/cloudpubsub/topic/list?project=${project}`,\n },\n }),\n });\n } else {\n checks.push({\n name: `Topic: ${topicName}`,\n category: \"pubsub\",\n status: \"warn\",\n message:\n \"Cannot verify topic existence (PubSub client doesn't expose .exists())\",\n fix: {\n gcloud: `gcloud pubsub topics create ${topicName} --project=${project}`,\n console: `${consoleBase}/cloudpubsub/topic/list?project=${project}`,\n },\n });\n }\n } catch (e: any) {\n const msg = e?.message ?? String(e);\n const isApiDisabled =\n msg.includes(\"disabled\") || msg.includes(\"has not been used\");\n checks.push({\n name: isApiDisabled ? \"Pub/Sub API\" : `Topic: ${topicName}`,\n category: \"pubsub\",\n status: \"error\",\n message: isApiDisabled ? \"Pub/Sub API is not enabled\" : msg,\n fix: isApiDisabled\n ? {\n gcloud: `gcloud services enable pubsub.googleapis.com --project=${project}`,\n console: `${consoleBase}/apis/library/pubsub.googleapis.com?project=${project}`,\n }\n : {\n gcloud: `gcloud pubsub topics create ${topicName} --project=${project}`,\n console: `${consoleBase}/cloudpubsub/topic/list?project=${project}`,\n },\n });\n if (isApiDisabled) break;\n }\n }\n } else {\n checks.push({\n name: \"Pub/Sub Client\",\n category: \"pubsub\",\n status: \"warn\",\n message: \"PubSub client not available for config check\",\n });\n }\n\n // --- JSON response ---\n if (isJsonRequest(req)) {\n const allOk = checks.every((c) => c.status === \"ok\");\n sendJson(res, { project, healthy: allOk, checks });\n return;\n }\n\n // --- HTML response ---\n const statusIcon = (s: string) =>\n s === \"ok\"\n ? '<span class=\"badge badge-ok\">OK</span>'\n : s === \"warn\"\n ? '<span class=\"badge badge-warn\">WARN</span>'\n : '<span class=\"badge badge-err\">ERROR</span>';\n\n const grouped = {\n bigquery: checks.filter((c) => c.category === \"bigquery\"),\n meilisearch: checks.filter((c) => c.category === \"meilisearch\"),\n pubsub: checks.filter((c) => c.category === \"pubsub\"),\n firestore: checks.filter((c) => c.category === \"firestore\"),\n storage: checks.filter((c) => c.category === \"storage\"),\n };\n\n const renderSection = (title: string, items: CheckResult[]) => {\n if (items.length === 0) return \"\";\n const rows = items\n .map((c) => {\n let fixHtml = \"\";\n if (c.fix) {\n const parts: string[] = [];\n if (c.fix.hint) parts.push(`<p class=\"muted\">${escapeHtml(c.fix.hint)}</p>`);\n if (c.fix.gcloud) parts.push(`<pre>$ ${escapeHtml(c.fix.gcloud)}</pre>`);\n if (c.fix.console)\n parts.push(\n `<p><a href=\"${escapeHtml(c.fix.console)}\" target=\"_blank\">Open GCP Console →</a></p>`,\n );\n fixHtml = `<div style=\"margin-top:.5rem\">${parts.join(\"\")}</div>`;\n }\n return `<tr>\n <td>${statusIcon(c.status)}</td>\n <td><strong>${escapeHtml(c.name)}</strong><br><span class=\"muted\">${escapeHtml(c.message)}</span>${fixHtml}</td>\n </tr>`;\n })\n .join(\"\\n\");\n return `<h2>${escapeHtml(title)}</h2>\n <table><thead><tr><th style=\"width:80px\">Status</th><th>Check</th></tr></thead>\n <tbody>${rows}</tbody></table>`;\n };\n\n const allOk = checks.every((c) => c.status === \"ok\");\n const overallBadge = allOk\n ? '<span class=\"badge badge-ok\">All checks passed</span>'\n : '<span class=\"badge badge-warn\">Some issues found</span>';\n\n const html = page(\n \"Config Check\",\n lb,\n `<div class=\"card\">\n <p>Project: <code>${escapeHtml(project)}</code> ${overallBadge}</p>\n ${renderSection(\"BigQuery\", grouped.bigquery)}\n ${renderSection(\"Meilisearch\", grouped.meilisearch)}\n ${renderSection(\"Pub/Sub\", grouped.pubsub)}\n ${renderSection(\"Other Targets\", grouped.storage)}\n ${renderSection(\"Firestore\", grouped.firestore)}\n </div>`,\n );\n sendHtml(res, html);\n });\n }\n\n // -- Request handler ----------------------------------------------------\n return async (req: any, res: any): Promise<void> => {\n await router.handle(req, res);\n };\n}\n\n","/**\n * Minimal zero-dependency HTTP router for Firebase Functions.\n * Compatible with any Express-like (req, res) handler.\n *\n * Supports:\n * - Named path parameters (e.g. \"/repos/:name/:id\")\n * - GET, POST, DELETE methods\n * - Global middleware (before each route)\n * - 404 / error fallbacks\n *\n * @example\n * ```typescript\n * import { MiniRouter } from \"@lpdjs/firestore-repo-service/servers/admin\";\n *\n * // Create router\n * const router = new MiniRouter();\n *\n * // Add global middleware (executed before every route)\n * router.use(async (req, res, next) => {\n * console.log(`${req.method} ${req.url}`);\n * await next();\n * });\n *\n * // Auth middleware\n * router.use((req, res, next) => {\n * if (!req.headers?.authorization) {\n * res.status(401).send(\"Unauthorized\");\n * return;\n * }\n * next();\n * });\n *\n * // Define routes with path parameters\n * router.get(\"/users\", async (req, res) => {\n * res.json({ users: await getAllUsers() });\n * });\n *\n * router.get(\"/users/:id\", async (req, res) => {\n * const user = await getUser(req.params.id); // Access path params\n * if (!user) {\n * res.status(404).send(\"User not found\");\n * return;\n * }\n * res.json(user);\n * });\n *\n * router.post(\"/users\", async (req, res) => {\n * const user = await createUser(req.body);\n * res.status(201).json(user);\n * });\n *\n * router.delete(\"/users/:id\", async (req, res) => {\n * await deleteUser(req.params.id);\n * res.status(204).end();\n * });\n *\n * // Custom 404 handler\n * router.onNotFound((req, res) => {\n * res.status(404).json({ error: \"Route not found\", path: req.url });\n * });\n *\n * // Custom error handler\n * router.onError((err, req, res) => {\n * console.error(\"Error:\", err);\n * res.status(500).json({ error: \"Internal server error\" });\n * });\n *\n * // Use with Firebase Functions\n * export const api = onRequest(async (req, res) => {\n * await router.handle(req, res);\n * });\n * ```\n */\n\nexport type AnyReq = {\n method?: string;\n url?: string;\n /** Express originalUrl — preserved before any router stripping, contains the full path including the Firebase Functions prefix */\n originalUrl?: string;\n path?: string;\n headers?: Record<string, string | string[] | undefined>;\n body?: unknown;\n query?: Record<string, string | string[] | undefined>;\n};\n\nexport type AnyRes = {\n status: (code: number) => AnyRes;\n set: (key: string, value: string) => AnyRes;\n send: (body: string) => void;\n json: (body: unknown) => void;\n end: () => void;\n};\n\nexport type RouteParams = Record<string, string>;\n\nexport type RouteHandler = (\n req: AnyReq & { params: RouteParams },\n res: AnyRes,\n) => void | Promise<void>;\n\nexport type Middleware = (\n req: AnyReq & { params: RouteParams },\n res: AnyRes,\n next: () => void | Promise<void>,\n) => void | Promise<void>;\n\n// ---------------------------------------------------------------------------\n// Route matching\n// ---------------------------------------------------------------------------\n\ninterface CompiledRoute {\n method: string;\n pattern: RegExp;\n paramNames: string[];\n handler: RouteHandler;\n}\n\nfunction compilePath(path: string): { pattern: RegExp; paramNames: string[] } {\n const paramNames: string[] = [];\n const src = path\n .replace(/[.*+?^${}()|[\\]\\\\]/g, (c) => (c === \":\" ? c : `\\\\${c}`))\n .replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, (_match, name: string) => {\n paramNames.push(name);\n return \"([^/]+)\";\n });\n\n return { pattern: new RegExp(`^${src}$`), paramNames };\n}\n\nfunction extractPath(req: AnyReq): string {\n const raw = req.path ?? req.url ?? \"/\";\n const idx = raw.indexOf(\"?\");\n return idx === -1 ? raw : raw.slice(0, idx);\n}\n\n// ---------------------------------------------------------------------------\n// Router class\n// ---------------------------------------------------------------------------\n\nexport class MiniRouter {\n private routes: CompiledRoute[] = [];\n private middlewares: Middleware[] = [];\n private notFoundHandler: RouteHandler = (_req, res) => {\n res.status(404).send(\"Not Found\");\n };\n private errorHandler: (err: unknown, req: AnyReq, res: AnyRes) => void = (\n err,\n _req,\n res,\n ) => {\n console.error(\"[MiniRouter]\", err);\n res.status(500).send(\"Internal Server Error\");\n };\n\n // ── Route registration ────────────────────────────────────────────────────\n\n use(middleware: Middleware): this {\n this.middlewares.push(middleware);\n return this;\n }\n\n get(path: string, handler: RouteHandler): this {\n return this.addRoute(\"GET\", path, handler);\n }\n\n post(path: string, handler: RouteHandler): this {\n return this.addRoute(\"POST\", path, handler);\n }\n\n put(path: string, handler: RouteHandler): this {\n return this.addRoute(\"PUT\", path, handler);\n }\n\n patch(path: string, handler: RouteHandler): this {\n return this.addRoute(\"PATCH\", path, handler);\n }\n\n delete(path: string, handler: RouteHandler): this {\n return this.addRoute(\"DELETE\", path, handler);\n }\n\n onNotFound(handler: RouteHandler): this {\n this.notFoundHandler = handler;\n return this;\n }\n\n onError(handler: (err: unknown, req: AnyReq, res: AnyRes) => void): this {\n this.errorHandler = handler;\n return this;\n }\n\n private addRoute(method: string, path: string, handler: RouteHandler): this {\n const { pattern, paramNames } = compilePath(path);\n this.routes.push({\n method: method.toUpperCase(),\n pattern,\n paramNames,\n handler,\n });\n return this;\n }\n\n // ── Dispatch ──────────────────────────────────────────────────────────────\n\n async handle(req: AnyReq, res: AnyRes): Promise<void> {\n const method = (req.method ?? \"GET\").toUpperCase();\n const path = extractPath(req);\n\n // Find matching route\n let matchedRoute: CompiledRoute | null = null;\n let params: RouteParams = {};\n\n for (const route of this.routes) {\n if (route.method !== method) continue;\n const m = path.match(route.pattern);\n if (m) {\n matchedRoute = route;\n params = {};\n route.paramNames.forEach((name, i) => {\n params[name] = decodeURIComponent(m[i + 1] ?? \"\");\n });\n break;\n }\n }\n\n const enrichedReq = Object.assign(req, { params });\n\n // Run middleware chain → then handler\n const handler = matchedRoute ? matchedRoute.handler : this.notFoundHandler;\n\n try {\n await this.runMiddlewareChain(enrichedReq, res, handler);\n } catch (err) {\n this.errorHandler(err, req, res);\n }\n }\n\n private async runMiddlewareChain(\n req: AnyReq & { params: RouteParams },\n res: AnyRes,\n finalHandler: RouteHandler,\n ): Promise<void> {\n let index = 0;\n\n const next = async (): Promise<void> => {\n if (index < this.middlewares.length) {\n const mw = this.middlewares[index++]!;\n await mw(req, res, next);\n } else {\n await finalHandler(req, res);\n }\n };\n\n await next();\n }\n}\n","/**\n * Compute the URL prefix used to build absolute paths from inside a\n * Firebase HTTPS function. Handles three deployment shapes uniformly:\n *\n * 1. **Firebase emulator** (`FUNCTIONS_EMULATOR=true`) — exposes functions at\n * `http://localhost:5001/{project}/{region}/{functionTarget}/...`. The\n * handler receives `req.url` *without* this prefix, so we rebuild it from\n * `GCLOUD_PROJECT`, `FUNCTION_REGION`, `FUNCTION_TARGET`.\n *\n * 2. **Cloud Functions v2 default URL** (`*.cloudfunctions.net/{name}`) —\n * Cloud Run terminates routing at the service name, so links must include\n * the `K_SERVICE` prefix. Detected via the `host` header containing\n * `cloudfunctions.net`.\n *\n * 3. **Custom domain / Hosting rewrite** — the proxy strips the prefix\n * before reaching the handler, so links are relative to the configured\n * `staticBasePath`.\n *\n * @param req The incoming request (needs `headers.host` / `hostname`).\n * @param staticBasePath The user-configured base path (e.g. `\"/api\"`).\n * @param region Explicit deployment region (e.g. `\"europe-west1\"`).\n * Used **only** in the emulator branch to build the\n * `/{project}/{region}/{target}` prefix; when omitted it\n * falls back to `FUNCTION_REGION` then `\"us-central1\"`.\n * Pass it (e.g. from `httpsOptions.region`) whenever the\n * function is deployed outside `us-central1`, since the\n * emulator does not reliably expose the region via env.\n * @returns A path prefix (no trailing slash) suitable for prepending to\n * `req.url` to build a same-function absolute URL.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getLinkBase(\n req: any,\n staticBasePath: string,\n region?: string,\n): string {\n const base = staticBasePath === \"/\" ? \"\" : staticBasePath.replace(/\\/$/, \"\");\n\n if (process.env[\"FUNCTIONS_EMULATOR\"] === \"true\") {\n const project =\n process.env[\"GCLOUD_PROJECT\"] ??\n process.env[\"GOOGLE_CLOUD_PROJECT\"] ??\n \"demo-project\";\n const resolvedRegion =\n region ?? process.env[\"FUNCTION_REGION\"] ?? \"us-central1\";\n // FUNCTION_TARGET uses dots (e.g. \"sync.functions.adminsync\") but the\n // emulator URL uses hyphens (\"sync-functions-adminsync\").\n const target = (process.env[\"FUNCTION_TARGET\"] ?? \"\").replace(/\\./g, \"-\");\n return `/${project}/${resolvedRegion}/${target}${base}`;\n }\n\n // Cloud Functions v2: K_SERVICE = function name = URL path prefix.\n // Only add it when accessed via cloudfunctions.net (not custom domains).\n // Cloud Run (Gen 2) lowercases service names, but K_SERVICE may still\n // carry the original mixed-case export name — normalise to lowercase\n // so that generated links match the canonical URL.\n const service = process.env[\"K_SERVICE\"];\n const host: string =\n req?.hostname ?? req?.headers?.[\"host\"] ?? \"\";\n if (service && typeof host === \"string\" && host.includes(\"cloudfunctions.net\")) {\n return `/${service.toLowerCase()}${base}`;\n }\n\n return base;\n}\n\n/**\n * Normalise the `region` field of a Firebase `HttpsOptions` (which may be a\n * single region, an array, a CEL `Expression`, or a `ResetValue`) into a single\n * concrete region string for {@link getLinkBase}. Returns `undefined` for\n * anything that is not a plain string at config time.\n */\nexport function resolveRegion(region: unknown): string | undefined {\n if (typeof region === \"string\") return region;\n if (Array.isArray(region)) {\n const first = region[0];\n return typeof first === \"string\" ? first : undefined;\n }\n return undefined;\n}\n","/**\n * Firebase Auth helper for the admin & CRUD servers.\n *\n * Returns an {@link AuthExtension} ready to plug into `servers.admin()` or\n * `servers.crud()`. Supports two transport modes:\n *\n * - **`cookie`** — session cookie pattern (default for admin UIs). Mounts\n * `/__login`, `/__session`, `/__logout` routes; the page lets the user sign\n * in client-side with the Firebase JS SDK and exchanges the resulting ID\n * token for an HttpOnly session cookie via Firebase Admin SDK.\n * - **`bearer`** — verifies `Authorization: Bearer <idToken>` on every request\n * (default for REST APIs). No login routes mounted.\n * - **`both`** — accept either cookie or bearer.\n *\n * The helper is **agnostic** about authorization: pass an `allow` callback\n * returning whatever role/context shape you need. The result is exposed as\n * `req.user.context` to downstream middlewares and route handlers.\n *\n * @example Admin (cookie + role trio)\n * ```ts\n * import { firebaseAuth } from \"@lpdjs/firestore-repo-service/servers/auth\";\n * import { getAuth } from \"firebase-admin/auth\";\n *\n * servers.admin({\n * auth: firebaseAuth({\n * getAuth,\n * mode: \"cookie\",\n * apiKey: process.env.FIREBASE_WEB_API_KEY!,\n * authDomain: process.env.FIREBASE_AUTH_DOMAIN!,\n * allow: ({ email, claims }) => {\n * if (claims.superAdmin) return { role: \"superAdmin\" };\n * if (email?.endsWith(\"@solarpush.io\")) return { role: \"admin\" };\n * if (email) return { role: \"viewer\" };\n * return null;\n * },\n * }),\n * repos: { ... },\n * });\n * ```\n *\n * @example CRUD (bearer + business rules per repo)\n * ```ts\n * servers.crud({\n * auth: firebaseAuth({ getAuth, mode: \"bearer\", allow: (u) => u }),\n * repos: {\n * comments: {\n * repo: repos.comments,\n * rules: {\n * list: () => true,\n * get: ({ user, doc }) => doc.public || doc.authorId === user.uid,\n * create: ({ user }) => !!user.uid,\n * update: ({ user, doc }) => user.uid === doc.authorId,\n * delete: ({ user, doc }) => user.claims.role === \"moderator\",\n * },\n * },\n * },\n * });\n * ```\n */\n\nimport type { AnyReq, Middleware, RouteHandler } from \"../admin/router\";\nimport { getLinkBase } from \"../utils/link-base\";\nimport { renderLoginPage } from \"./login-page\";\nimport {\n createLogoutHandler,\n createSessionHandler,\n parseCookies,\n SESSION_COOKIE_DEFAULT,\n} from \"./session\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal Firebase Admin Auth surface needed by this helper.\n * Avoids a hard import of `firebase-admin/auth` so the package stays\n * decoupled from a specific firebase-admin version.\n */\nexport interface FirebaseAdminAuthLike {\n verifyIdToken(\n idToken: string,\n checkRevoked?: boolean,\n ): Promise<DecodedIdTokenLike>;\n verifySessionCookie(\n sessionCookie: string,\n checkRevoked?: boolean,\n ): Promise<DecodedIdTokenLike>;\n createSessionCookie(\n idToken: string,\n sessionCookieOptions: { expiresIn: number },\n ): Promise<string>;\n revokeRefreshTokens(uid: string): Promise<void>;\n}\n\nexport interface DecodedIdTokenLike {\n uid: string;\n email?: string;\n email_verified?: boolean;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [claim: string]: any;\n}\n\n/** Identity attached to every authenticated request as `req.user`. */\nexport interface AuthUser<TContext = unknown> {\n uid: string;\n email: string | null;\n emailVerified: boolean;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n claims: Record<string, any>;\n /** Result of the user-supplied `allow()` callback. */\n context: TContext;\n}\n\n/** A route descriptor mounted by `firebaseAuth` before the protected chain. */\nexport interface AuthRoute {\n method: \"GET\" | \"POST\";\n path: string;\n handler: RouteHandler;\n}\n\n/**\n * Returned by {@link firebaseAuth}. Servers detect this shape (vs.\n * `BasicAuthConfig` / raw `Middleware`) and mount the routes before pushing\n * the middleware onto the chain.\n */\nexport interface AuthExtension {\n readonly __authExtension: true;\n middleware: Middleware;\n /** Auxiliary routes (login page, session, logout). Empty in pure bearer mode. */\n routes: AuthRoute[];\n /** Path used to redirect unauthenticated browser requests. */\n loginPath: string;\n}\n\nexport type FirebaseAuthMode = \"cookie\" | \"bearer\" | \"both\";\n\n/** Provider configuration for the bundled login page. */\nexport interface FirebaseAuthLoginPageConfig {\n /** Page title. Default: \"Admin sign-in\". */\n title?: string;\n /**\n * Providers shown on the login page.\n * Default: `[\"password\", \"google\"]`.\n */\n providers?: (\"password\" | \"google\")[];\n}\n\nexport interface FirebaseAuthConfig<TContext = unknown> {\n /** Lazy getter for the Firebase Admin Auth instance. */\n getAuth: () => FirebaseAdminAuthLike;\n\n /** Transport mode. Default: `\"cookie\"`. */\n mode?: FirebaseAuthMode;\n\n /**\n * Authorization callback. Receives the verified token claims and returns:\n * - a context object → request is allowed, exposed as `req.user.context`,\n * - `null` → request is rejected (401 / redirect to login).\n *\n * If omitted, the default policy allows any authenticated user with\n * `context = null`.\n */\n allow?: (\n user: Omit<AuthUser, \"context\">,\n ) => TContext | null | Promise<TContext | null>;\n\n // ── Cookie mode options ────────────────────────────────────────────────\n /**\n * Whether to mount the bundled `/__login`, `/__session`, `/__logout`\n * routes. Default: `true` for `cookie`/`both`, `false` for `bearer`.\n */\n loginPage?: boolean | FirebaseAuthLoginPageConfig;\n\n /**\n * Firebase Web API key required by the JS SDK on the login page.\n * Mandatory when `loginPage` is enabled. Find it in your Firebase Console\n * under Project Settings → General → Web app config.\n */\n apiKey?: string;\n\n /**\n * Firebase Auth domain (e.g. `my-project.firebaseapp.com`).\n * Mandatory when `loginPage` is enabled.\n */\n authDomain?: string;\n\n /** Cookie name. Default: `__admin_session`. */\n cookieName?: string;\n\n /** Session cookie TTL in days. Default: `5` (Firebase max is 14). */\n sessionTtlDays?: number;\n\n /**\n * Cookie `Secure` flag. Default: `true`. Set to `false` only for local\n * development over HTTP.\n */\n secureCookie?: boolean;\n\n /** Cookie `SameSite`. Default: `\"Lax\"`. */\n sameSite?: \"Strict\" | \"Lax\" | \"None\";\n\n /**\n * Deployment region (e.g. `\"europe-west1\"`). Used to build the login page's\n * same-function URLs **under the Firebase emulator**, which does not reliably\n * expose the region via env — without it the emulator prefix falls back to\n * `us-central1`, so the session POST 404s when deployed elsewhere. Has no\n * effect in production (the prefix is derived from the request there). When\n * created via `servers.admin/crud()` this defaults to `httpsOptions.region`.\n */\n region?: string;\n\n /**\n * Firebase Auth emulator host (e.g. `127.0.0.1:9099`). When set, the login\n * page's client SDK is pointed at the emulator via `connectAuthEmulator`,\n * matching the Admin SDK (which already targets the emulator when\n * `FIREBASE_AUTH_EMULATOR_HOST` is set). Defaults to that env var, so local\n * `firebase emulators:start` runs work out of the box; pass `\"\"` to force it\n * off.\n */\n authEmulatorHost?: string;\n\n /**\n * Enable the built-in CSRF defense: state-changing requests\n * (`POST`/`PUT`/`PATCH`/`DELETE`) authenticated by **session cookie** must\n * carry an `Origin`/`Referer` header matching the request host. Bearer\n * requests are exempt (a browser never auto-attaches an `Authorization`\n * header, so they are not CSRF-able).\n *\n * **Defaults to `true` only when `sameSite: \"None\"`** (and not in `bearer`\n * mode). With the default `Lax`/`Strict` cookie the browser already blocks\n * the session cookie on cross-site mutations, so the check is unnecessary\n * and is left off to avoid false positives behind proxies whose `Host`\n * differs from the public origin (e.g. Cloud Functions v2 / Cloud Run).\n * Set to `true` to force the check on regardless of `sameSite`, or `false`\n * to disable it even with `sameSite: \"None\"` (only if you implement your\n * own CSRF protection upstream).\n */\n csrfProtection?: boolean;\n\n /**\n * Behaviour when authentication fails or `allow()` returns `null`.\n * - `\"redirect\"` (default in cookie mode) → 302 to the login page,\n * - `\"401\"` (default in bearer mode) → JSON 401 response.\n */\n onUnauthenticated?: \"redirect\" | \"401\";\n\n /**\n * Routes that should bypass the auth middleware (matched against the path\n * after the basePath stripping). The auxiliary login routes are always\n * public regardless of this option.\n */\n publicPaths?: (string | RegExp)[];\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction defaultLoginPage(mode: FirebaseAuthMode): boolean {\n return mode === \"cookie\" || mode === \"both\";\n}\n\nfunction defaultUnauth(mode: FirebaseAuthMode): \"redirect\" | \"401\" {\n return mode === \"bearer\" ? \"401\" : \"redirect\";\n}\n\nfunction pathOf(req: AnyReq): string {\n const raw = req.path ?? req.url ?? \"/\";\n const idx = raw.indexOf(\"?\");\n return idx === -1 ? raw : raw.slice(0, idx);\n}\n\nfunction queryAction(req: AnyReq): string | null {\n const q = (req as { query?: Record<string, unknown> }).query;\n if (q && typeof q.__action === \"string\") return q.__action;\n // Fallback: parse from URL when query parsing isn't done by the runtime.\n const url = req.url ?? \"\";\n const idx = url.indexOf(\"?\");\n if (idx === -1) return null;\n const params = new URLSearchParams(url.slice(idx + 1));\n return params.get(\"__action\");\n}\n\nfunction methodOf(req: AnyReq): string {\n return String(req.method ?? \"GET\").toUpperCase();\n}\n\n/**\n * Strip a redirect / `next` target down to a safe **same-origin path**.\n *\n * Rejects protocol-relative (`//evil.com`), backslash-escaped (`/\\evil.com`)\n * and absolute (`https://…`) targets that would let an attacker turn the\n * post-login redirect into an open redirect / phishing vector (issue #07).\n * Anything suspicious collapses to `\"/\"`.\n */\nfunction sanitizeNextPath(next: string): string {\n if (typeof next !== \"string\" || next.length === 0) return \"/\";\n if (!next.startsWith(\"/\")) return \"/\";\n if (next.startsWith(\"//\") || next.startsWith(\"/\\\\\")) return \"/\";\n if (next.includes(\"://\")) return \"/\";\n return next;\n}\n\nfunction headerOf(req: AnyReq, name: string): string | undefined {\n const raw = req.headers?.[name];\n if (Array.isArray(raw)) return raw[0];\n return typeof raw === \"string\" ? raw : undefined;\n}\n\nconst CSRF_SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/**\n * Same-origin check used as a CSRF defense for state-changing requests.\n * Compares the request `Origin` (or `Referer`) host against the request host.\n * Returns `true` only when they match. A missing/invalid Origin fails closed.\n */\nfunction isSameOriginRequest(req: AnyReq): boolean {\n const originHeader = headerOf(req, \"origin\") ?? headerOf(req, \"referer\");\n if (!originHeader) return false;\n const host = headerOf(req, \"x-forwarded-host\") ?? headerOf(req, \"host\");\n if (!host) return false;\n try {\n return new URL(originHeader).host === host;\n } catch {\n return false;\n }\n}\n\nfunction isPublic(\n path: string,\n patterns: (string | RegExp)[] | undefined,\n): boolean {\n if (!patterns || patterns.length === 0) return false;\n for (const p of patterns) {\n if (typeof p === \"string\") {\n if (path === p || path.startsWith(p + \"/\")) return true;\n } else if (p.test(path)) {\n return true;\n }\n }\n return false;\n}\n\nfunction wantsHtml(req: AnyReq): boolean {\n const accept = String(req.headers?.accept ?? \"\");\n // Strict: only real browser navigations advertise `text/html`. Treating\n // `*/*` or a missing Accept header as HTML caused curl, healthchecks and\n // server-to-server fetches to receive a 200 login page instead of a clear\n // 401 (issue #16).\n return accept.includes(\"text/html\");\n}\n\nfunction extractBearer(req: AnyReq): string | null {\n const raw = req.headers?.authorization;\n const header = Array.isArray(raw) ? raw[0] : raw;\n if (!header) return null;\n const m = /^Bearer\\s+(.+)$/i.exec(header);\n return m ? m[1]!.trim() : null;\n}\n\nfunction rejectUnauthenticated(\n req: AnyReq,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n res: any,\n policy: \"redirect\" | \"401\",\n loginPath: string,\n): void {\n if (policy === \"redirect\" && wantsHtml(req)) {\n const target = encodeURIComponent(req.url ?? \"/\");\n res\n .status(302)\n .set(\"Location\", `${loginPath}?next=${target}`)\n .set(\"Cache-Control\", \"no-store\")\n .end();\n return;\n }\n res\n .status(401)\n .set(\"Content-Type\", \"application/json; charset=utf-8\")\n .send(JSON.stringify({ success: false, error: \"Unauthorized\" }));\n}\n\n// ---------------------------------------------------------------------------\n// Public factory\n// ---------------------------------------------------------------------------\n\n/**\n * Build a Firebase Auth extension for use with `servers.admin()` or\n * `servers.crud()`. See module-level docs for the full design and examples.\n */\nexport function firebaseAuth<TContext = unknown>(\n config: FirebaseAuthConfig<TContext>,\n): AuthExtension {\n const mode: FirebaseAuthMode = config.mode ?? \"cookie\";\n const cookieName = config.cookieName ?? SESSION_COOKIE_DEFAULT;\n const ttlDays = config.sessionTtlDays ?? 5;\n const secure = config.secureCookie ?? true;\n const sameSite = config.sameSite ?? \"Lax\";\n // The Origin/Referer (CSRF) check is only needed when `SameSite=None`:\n // with the default `Lax` (or `Strict`) the browser already refuses to send\n // the session cookie on cross-site state-changing requests, so a cross-site\n // POST/PUT/DELETE is unauthenticated and harmless. Enforcing the Origin\n // check unconditionally also breaks legitimate same-origin requests on\n // platforms where the container's `Host` differs from the public origin\n // (e.g. Cloud Functions v2 / Cloud Run, where `Host` is the internal\n // `*.run.app` host while `Origin` is the `*.cloudfunctions.net` domain).\n // Can be forced on/off explicitly via `csrfProtection`.\n const csrfProtection =\n config.csrfProtection ?? (mode !== \"bearer\" && sameSite === \"None\");\n if (mode !== \"bearer\" && sameSite === \"None\") {\n console.warn(\n \"[firebaseAuth] `sameSite: \\\"None\\\"` disables the browser's built-in \" +\n \"SameSite CSRF protection. \" +\n (csrfProtection\n ? \"The same-origin (Origin/Referer) check is active as the primary \" +\n \"defense — ensure state-changing requests are sent same-origin or \" +\n \"carry a bearer token.\"\n : \"`csrfProtection` is disabled — your endpoints are CSRF-exposed.\"),\n );\n }\n const onUnauth = config.onUnauthenticated ?? defaultUnauth(mode);\n const loginEnabled =\n config.loginPage === undefined\n ? defaultLoginPage(mode)\n : config.loginPage !== false;\n\n const loginPath = \"/__login\";\n const sessionPath = \"/__session\";\n const logoutPath = \"/__logout\";\n\n // ── Auxiliary handlers (kept in `routes` for hosting deployments\n // where users can mount them at known paths, AND invoked in-band by the\n // middleware on `?__action=session|logout` so vanilla Cloud Functions\n // — where there is no separate URL prefix per route — work too). ──────\n const sessionHandler = createSessionHandler({\n getAuth: config.getAuth,\n cookieName,\n ttlDays,\n secure,\n sameSite,\n });\n const logoutHandler = createLogoutHandler({\n getAuth: config.getAuth,\n cookieName,\n secure,\n sameSite,\n });\n\n function renderInlineLogin(\n req: AnyReq,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n res: any,\n error: string | null = null,\n status = 200,\n ): void {\n // Validate lazily (at request time) so module loading during Firebase CLI\n // analysis doesn't throw before env vars are injected.\n if (!config.apiKey || !config.authDomain) {\n throw new Error(\n \"[firebaseAuth] `apiKey` and `authDomain` are required when `loginPage` is enabled. \" +\n \"Find both in the Firebase Console under Project Settings → General → Web app config.\",\n );\n }\n const pageCfg: FirebaseAuthLoginPageConfig =\n typeof config.loginPage === \"object\" ? config.loginPage : {};\n // Build a same-function absolute URL: the function's external prefix\n // (Cloud Functions name, emulator project/region/target, or \"\" for\n // custom domains) + the in-router request path. The browser otherwise\n // resolves form actions relative to the public URL, which doesn't\n // include the function name on Cloud Functions.\n const prefix = getLinkBase(req, \"/\", config.region);\n const inner = req.url ?? \"/\";\n // Sanitize to a same-origin path so a crafted request URL (e.g.\n // `//evil.com/...` on a custom domain where the prefix is empty) cannot\n // turn the post-login redirect or the form action into an open redirect\n // (issue #07).\n const fullPath = sanitizeNextPath(\n `${prefix}${inner.startsWith(\"/\") ? inner : `/${inner}`}`,\n );\n const sep = fullPath.includes(\"?\") ? \"&\" : \"?\";\n const sessionAction = `${fullPath}${sep}__action=session`;\n const html = renderLoginPage({\n title: pageCfg.title ?? \"Admin sign-in\",\n providers: pageCfg.providers ?? [\"password\", \"google\"],\n apiKey: config.apiKey!,\n authDomain: config.authDomain!,\n sessionPath: sessionAction,\n next: fullPath,\n error,\n authEmulatorHost:\n config.authEmulatorHost ?? process.env[\"FIREBASE_AUTH_EMULATOR_HOST\"],\n });\n res\n .status(status)\n .set(\"Content-Type\", \"text/html; charset=utf-8\")\n .set(\"Cache-Control\", \"no-store\")\n .send(html);\n }\n\n // ── Auxiliary routes ─────────────────────────────────────────────────────\n const routes: AuthRoute[] = [];\n if (loginEnabled) {\n routes.push({\n method: \"GET\",\n path: loginPath,\n handler: (req, res) => {\n const error = (req.query?.error as string | undefined) ?? null;\n renderInlineLogin(req, res, error);\n },\n });\n routes.push({\n method: \"POST\",\n path: sessionPath,\n handler: sessionHandler,\n });\n routes.push({\n method: \"POST\",\n path: logoutPath,\n handler: logoutHandler,\n });\n }\n\n const publicPaths: (string | RegExp)[] = [\n ...(config.publicPaths ?? []),\n loginPath,\n sessionPath,\n logoutPath,\n ];\n\n // ── Middleware ───────────────────────────────────────────────────────────\n const middleware: Middleware = async (req, res, next) => {\n const path = pathOf(req);\n const method = methodOf(req);\n\n // 0. CSRF defense for cookie sessions (only active when `SameSite=None`,\n // or when `csrfProtection` is explicitly forced on — see config). With\n // the default Lax/Strict cookie the browser already blocks the session\n // cookie on cross-site state-changing requests, so this is skipped to\n // avoid breaking legitimate same-origin requests behind proxies. When\n // active it runs FIRST so it also protects the in-band\n // `?__action=logout|session` shortcut below (issues #05, #06).\n if (\n csrfProtection &&\n mode !== \"bearer\" &&\n !CSRF_SAFE_METHODS.has(method) &&\n !extractBearer(req) &&\n !isSameOriginRequest(req)\n ) {\n res\n .status(403)\n .set(\"Content-Type\", \"application/json; charset=utf-8\")\n .send(\n JSON.stringify({\n success: false,\n error: \"Origin check failed (possible CSRF)\",\n }),\n );\n return;\n }\n\n // 1. In-band action endpoints. The bundled login page posts the session\n // exchange (and logout) to the CURRENT url with `?__action=session`\n // (resp. `logout`) rather than to the mounted `/__session` route,\n // because on vanilla Cloud Functions the helper cannot reliably know\n // the function's public URL prefix to address a separate route. These\n // actions are inherently public (login/logout need no prior auth) and\n // are protected against cross-site abuse by the same-origin guard\n // above (issue #06).\n if (loginEnabled && method === \"POST\") {\n const action = queryAction(req);\n if (action === \"session\") {\n await sessionHandler(req, res);\n return;\n }\n if (action === \"logout\") {\n await logoutHandler(req, res);\n return;\n }\n }\n\n // 2. Public paths (mounted login routes, user-supplied allowlist).\n if (isPublic(path, publicPaths)) {\n await next();\n return;\n }\n\n let decoded: DecodedIdTokenLike | null = null;\n try {\n const auth = config.getAuth();\n\n // Try bearer first when allowed (cheaper, no cookie parsing).\n if (mode === \"bearer\" || mode === \"both\") {\n const token = extractBearer(req);\n if (token) {\n decoded = await auth.verifyIdToken(token, true);\n }\n }\n\n // Fall back to cookie when allowed.\n if (!decoded && (mode === \"cookie\" || mode === \"both\")) {\n const cookieHeader = req.headers?.cookie;\n const raw = Array.isArray(cookieHeader)\n ? cookieHeader.join(\"; \")\n : cookieHeader;\n const cookies = parseCookies(typeof raw === \"string\" ? raw : \"\");\n const session = cookies[cookieName];\n if (session) {\n decoded = await auth.verifySessionCookie(session, true);\n }\n }\n } catch {\n decoded = null;\n }\n\n if (!decoded) {\n rejectUnauthenticated(req, res);\n return;\n }\n\n const baseUser: Omit<AuthUser, \"context\"> = {\n uid: decoded.uid,\n email: typeof decoded.email === \"string\" ? decoded.email : null,\n emailVerified: !!decoded.email_verified,\n claims: decoded as Record<string, unknown>,\n };\n\n let context: TContext | null;\n try {\n context = config.allow\n ? await config.allow(baseUser)\n : (null as TContext | null);\n } catch {\n context = null;\n }\n\n if (config.allow && context === null) {\n rejectUnauthenticated(req, res);\n return;\n }\n\n (req as AnyReq & { user?: AuthUser<TContext> }).user = {\n ...baseUser,\n context: context as TContext,\n };\n\n await next();\n };\n\n /**\n * Reject according to the configured policy:\n * - cookie/both + GET HTML browser request → render the login page inline\n * on the SAME URL with a `401` status (works on Cloud Functions where\n * there's no separate `/__login` route reachable from the public URL).\n * A 401 keeps the response HTTP-compliant for monitoring/healthchecks\n * while browsers still render the page (issue #16).\n * - bearer mode or non-HTML clients → JSON 401.\n */\n function rejectUnauthenticated(\n req: AnyReq,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n res: any,\n ): void {\n if (\n onUnauth === \"redirect\" &&\n loginEnabled &&\n methodOf(req) === \"GET\" &&\n wantsHtml(req)\n ) {\n renderInlineLogin(req, res, null, 401);\n return;\n }\n res\n .status(401)\n .set(\"Content-Type\", \"application/json; charset=utf-8\")\n .send(JSON.stringify({ success: false, error: \"Unauthorized\" }));\n }\n\n return {\n __authExtension: true,\n middleware,\n routes,\n loginPath,\n };\n}\n\n/**\n * Type guard: detect an {@link AuthExtension} (vs. legacy\n * `BasicAuthConfig` / `Middleware`).\n */\nexport function isAuthExtension(value: unknown): value is AuthExtension {\n return (\n !!value &&\n typeof value === \"object\" &&\n (value as { __authExtension?: unknown }).__authExtension === true\n );\n}\n\n/**\n * Helper for explicitly opening a CRUD operation when the server has\n * `auth` defined (bypasses the default-deny policy).\n *\n * @example\n * ```ts\n * rules: { list: allowAll, get: allowAll }\n * ```\n */\nexport const allowAll = (): true => true;\n","/**\n * Request-scoped & programmatic actor context backed by `AsyncLocalStorage`.\n *\n * Uses a `globalThis[Symbol.for(...)]` singleton so separate tsup bundles\n * (`dist/index`, `dist/servers/hono`, `dist/servers/crud`, `dist/history`,\n * `dist/servers/index`) always share the exact same `AsyncLocalStorage`\n * instance.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Context, MiddlewareHandler } from \"hono\";\n\n/** Actor & audit metadata captured for history writes. */\nexport interface HistoryActor {\n userId?: string | null;\n userEmail?: string | null;\n reason?: string | null;\n comment?: string | null;\n extras?: Record<string, unknown>;\n}\n\n/** Function resolving the current actor lazily from a Hono `Context`. */\nexport type ActorResolver = (c: Context) => HistoryActor | null | undefined;\n\n/**\n * Declarative configuration for {@link createActorResolver} so projects can\n * customize context keys, nested user property paths, and request headers\n * without writing a full resolver from scratch.\n */\nexport interface ActorResolverFieldConfig {\n /**\n * Hono context keys inspected in order via `c.get(key)`.\n * Default: `[\"user\", \"docsUser\"]`.\n */\n contextKeys?: string[];\n /**\n * Property paths on the user object checked in order for `userId`.\n * Supports dot-notation (e.g. `\"baseUser.id\"`).\n * Default: `[\"uid\", \"id\", \"sub\"]`.\n */\n userIdFields?: string[];\n /**\n * Property paths on the user object checked in order for `userEmail`.\n * Supports dot-notation (e.g. `\"baseUser.email\"`).\n * Default: `[\"email\"]`.\n */\n userEmailFields?: string[];\n /**\n * HTTP header name for change reason, or `false` to disable header lookup.\n * Default: `\"x-history-reason\"`.\n */\n reasonHeader?: string | false;\n /**\n * HTTP header name for change comment, or `false` to disable header lookup.\n * Default: `\"x-history-comment\"`.\n */\n commentHeader?: string | false;\n /**\n * Optional extractor to populate `actor.extras` from `(c, user)`.\n */\n extras?: (\n c: Context,\n user: Record<string, unknown> | null,\n ) => Record<string, unknown> | undefined;\n}\n\n/**\n * Accepted by `HonoServerOptions.actorResolver`, `ApiRegistryOptions.actorResolver`,\n * `CrudServerOptions.actorResolver`, and `CreateServersDeps.actorResolver`:\n * either a custom resolver function or a declarative field-mapping config.\n */\nexport type ActorResolverOption = ActorResolver | ActorResolverFieldConfig;\n\n/** Canonical default HTTP header name for change reason. */\nexport const DEFAULT_HISTORY_REASON_HEADER = \"X-History-Reason\";\n\n/** Canonical default HTTP header name for change comment. */\nexport const DEFAULT_HISTORY_COMMENT_HEADER = \"X-History-Comment\";\n\n/** Resolved history audit header names exposed by an `actorResolver`. */\nexport interface ResolvedHistoryHeaderNames {\n reasonHeader: string | false;\n commentHeader: string | false;\n}\n\nconst ACTOR_RESOLVER_HEADERS_SYMBOL = Symbol.for(\n \"@lpdjs/firestore-repo-service:actorResolverHeaders\",\n);\n\ninterface ActorStore {\n c?: Context;\n resolver?: ActorResolver;\n override?: Partial<HistoryActor>;\n}\n\nconst ALS_SYMBOL = Symbol.for(\"@lpdjs/firestore-repo-service:actorContext\");\nconst g = globalThis as Record<\n symbol,\n AsyncLocalStorage<ActorStore> | undefined\n>;\nconst actorStorage = (g[ALS_SYMBOL] ??= new AsyncLocalStorage<ActorStore>());\n\n/** Safely traverse a dot-notation path (e.g. `\"baseUser.email\"`) on an object. */\nfunction readFieldPath(\n obj: Record<string, unknown>,\n path: string,\n): unknown {\n if (!path.includes(\".\")) return obj[path];\n let cur: unknown = obj;\n for (const part of path.split(\".\")) {\n if (!cur || typeof cur !== \"object\") return undefined;\n cur = (cur as Record<string, unknown>)[part];\n }\n return cur;\n}\n\n/** Pick the first non-empty string/number value across candidate paths. */\nfunction pickFirstString(\n obj: Record<string, unknown>,\n paths: string[],\n): string | null {\n for (const p of paths) {\n const val = readFieldPath(obj, p);\n if (typeof val === \"string\" && val.length > 0) return val;\n if (typeof val === \"number\") return String(val);\n }\n return null;\n}\n\n/** Read an HTTP header safely from a Hono `Context` (tolerates minimal mocks). */\nfunction readHeader(c: Context, name: string | false): string | undefined {\n if (name === false) return undefined;\n const headerFn = (c as any)?.req?.header;\n if (typeof headerFn !== \"function\") return undefined;\n const val = headerFn.call((c as any).req, name);\n return typeof val === \"string\" && val.length > 0 ? val : undefined;\n}\n\n/**\n * Build an {@link ActorResolver} from a declarative field/header configuration.\n *\n * @example\n * ```ts\n * const actorResolver = createActorResolver({\n * contextKeys: [\"authUser\", \"user\"],\n * userIdFields: [\"docId\", \"uid\"],\n * userEmailFields: [\"baseUser.email\", \"email\"],\n * reasonHeader: \"x-audit-reason\",\n * });\n * ```\n */\nexport function createActorResolver(\n config: ActorResolverFieldConfig = {},\n): ActorResolver {\n const contextKeys = config.contextKeys ?? [\"user\", \"docsUser\"];\n const userIdFields = config.userIdFields ?? [\"uid\", \"id\", \"sub\"];\n const userEmailFields = config.userEmailFields ?? [\"email\"];\n const reasonHeader =\n config.reasonHeader === undefined ? \"x-history-reason\" : config.reasonHeader;\n const commentHeader =\n config.commentHeader === undefined\n ? \"x-history-comment\"\n : config.commentHeader;\n const displayReasonHeader: string | false =\n config.reasonHeader === undefined\n ? DEFAULT_HISTORY_REASON_HEADER\n : config.reasonHeader;\n const displayCommentHeader: string | false =\n config.commentHeader === undefined\n ? DEFAULT_HISTORY_COMMENT_HEADER\n : config.commentHeader;\n const extrasFn = config.extras;\n\n const resolver: ActorResolver = (c: Context): HistoryActor | null => {\n let user: Record<string, unknown> | null = null;\n const getFn = (c as any)?.get;\n if (typeof getFn === \"function\") {\n for (const key of contextKeys) {\n const candidate = getFn.call(c, key);\n if (candidate && typeof candidate === \"object\") {\n user = candidate as Record<string, unknown>;\n break;\n }\n }\n }\n\n const reason = readHeader(c, reasonHeader);\n const comment = readHeader(c, commentHeader);\n const extras = extrasFn ? extrasFn(c, user) : undefined;\n\n if (!user) {\n if (reason === undefined && comment === undefined && !extras) {\n return null;\n }\n return {\n ...(reason !== undefined ? { reason } : {}),\n ...(comment !== undefined ? { comment } : {}),\n ...(extras ? { extras } : {}),\n };\n }\n\n return {\n userId: pickFirstString(user, userIdFields),\n userEmail: pickFirstString(user, userEmailFields),\n ...(reason !== undefined ? { reason } : {}),\n ...(comment !== undefined ? { comment } : {}),\n ...(extras ? { extras } : {}),\n };\n };\n\n Object.defineProperty(resolver, ACTOR_RESOLVER_HEADERS_SYMBOL, {\n value: {\n reasonHeader: displayReasonHeader,\n commentHeader: displayCommentHeader,\n } satisfies ResolvedHistoryHeaderNames,\n enumerable: false,\n configurable: false,\n });\n\n return resolver;\n}\n\n/**\n * Inspect an {@link ActorResolverOption} (declarative config object, resolver\n * created via {@link createActorResolver}, custom function, or `undefined`)\n * and return the effective history audit header names for OpenAPI / CORS.\n */\nexport function getActorResolverHeaders(\n option?: ActorResolverOption,\n): ResolvedHistoryHeaderNames {\n if (!option) {\n return {\n reasonHeader: DEFAULT_HISTORY_REASON_HEADER,\n commentHeader: DEFAULT_HISTORY_COMMENT_HEADER,\n };\n }\n if (typeof option === \"function\") {\n const meta = (option as any)[ACTOR_RESOLVER_HEADERS_SYMBOL] as\n | ResolvedHistoryHeaderNames\n | undefined;\n if (meta) return { ...meta };\n return {\n reasonHeader: DEFAULT_HISTORY_REASON_HEADER,\n commentHeader: DEFAULT_HISTORY_COMMENT_HEADER,\n };\n }\n return {\n reasonHeader:\n option.reasonHeader === undefined\n ? DEFAULT_HISTORY_REASON_HEADER\n : option.reasonHeader,\n commentHeader:\n option.commentHeader === undefined\n ? DEFAULT_HISTORY_COMMENT_HEADER\n : option.commentHeader,\n };\n}\n\n/**\n * Default actor resolver compatible with Firebase JWT / `firebaseBearerAuth` /\n * custom auth middlewares setting `c.get(\"user\")` or `c.get(\"docsUser\")`.\n */\nexport const defaultActorResolver: ActorResolver = createActorResolver();\n\n/** Normalize either a function resolver or a declarative config object. */\nexport function normalizeActorResolver(\n option?: ActorResolverOption,\n): ActorResolver | undefined {\n if (!option) return undefined;\n return typeof option === \"function\" ? option : createActorResolver(option);\n}\n\n/**\n * Hono middleware mounted automatically at the top of `HonoServer`.\n * Stores `{ c, resolver }` in `AsyncLocalStorage` so downstream repository\n * writes resolve the authenticated user lazily after auth middlewares run.\n */\nexport function createActorContextMiddleware(\n resolver?: ActorResolverOption,\n): MiddlewareHandler {\n const normalized = normalizeActorResolver(resolver);\n return async (c, next) => {\n await actorStorage.run({ c, resolver: normalized }, async () => {\n await next();\n });\n };\n}\n\n/**\n * Resolve the active {@link HistoryActor} for the current async execution\n * context, or `null` when outside any scope or when no actor is available.\n */\nexport function getCurrentActor(): HistoryActor | null {\n const store = actorStorage.getStore();\n if (!store) return null;\n\n let fromReq: HistoryActor | null | undefined = null;\n if (store.c) {\n try {\n fromReq = (store.resolver ?? defaultActorResolver)(store.c);\n } catch {\n fromReq = null;\n }\n }\n\n if (!fromReq && !store.override) return null;\n\n const merged: HistoryActor = { ...(fromReq ?? {}) };\n if (store.override) {\n if (store.override.userId !== undefined) {\n merged.userId = store.override.userId;\n }\n if (store.override.userEmail !== undefined) {\n merged.userEmail = store.override.userEmail;\n }\n if (store.override.reason !== undefined) {\n merged.reason = store.override.reason;\n }\n if (store.override.comment !== undefined) {\n merged.comment = store.override.comment;\n }\n if (store.override.extras !== undefined) {\n merged.extras = {\n ...(fromReq?.extras ?? {}),\n ...store.override.extras,\n };\n }\n }\n\n return merged;\n}\n\n/**\n * Execute `fn` within an isolated actor scope — ideal for crons, Pub/Sub\n * workers, scripts, and unit tests.\n *\n * @example\n * ```ts\n * await withActor({ userId: \"cron:invoicing\", reason: \"monthly-run\" }, async () => {\n * await repos.invoices.create(payload);\n * });\n * ```\n */\nexport function withActor<T>(actor: HistoryActor, fn: () => T): T {\n return actorStorage.run({ override: { ...actor } }, fn);\n}\n\n/**\n * Enrich or override actor metadata (`reason`, `comment`, `extras`, …) for the\n * current active request / `withActor` scope without touching repository calls.\n *\n * Safe no-op returning `false` when called outside any active ALS scope.\n */\nexport function setRequestActorMeta(meta: Partial<HistoryActor>): boolean {\n const store = actorStorage.getStore();\n if (!store) return false;\n\n const prev = store.override ?? {};\n const nextOverride: Partial<HistoryActor> = { ...prev, ...meta };\n if (prev.extras || meta.extras) {\n nextOverride.extras = {\n ...(prev.extras ?? {}),\n ...(meta.extras ?? {}),\n };\n }\n store.override = nextOverride;\n return true;\n}\n","/**\n * Types and interfaces for the history (change-log) module.\n *\n * The package writes history entries in **schema v2** (1 Firestore document\n * per `update`/`create`/`delete` event, with a `changes` map keyed by field\n * name). It reads both v1 (legacy: 1 doc per modified field) and v2 by\n * normalising them into a unified {@link HistoryEntry} shape.\n */\n\nimport type { Timestamp } from \"firebase-admin/firestore\";\nimport type {\n DocumentOptions,\n onDocumentWritten,\n} from \"firebase-functions/v2/firestore\";\n\n/**\n * Cloud Functions v2 options forwarded to `onDocumentWritten()` for history triggers.\n * The `document` field is omitted because the library sets it itself from the collection path.\n */\nexport type TriggerOptions = Omit<DocumentOptions, \"document\">;\nexport type HistoryTriggerOptions = TriggerOptions;\n\n/* ------------------------------------------------------------------------- */\n/* Public unified shape */\n/* ------------------------------------------------------------------------- */\n\nexport type HistoryOperation = \"create\" | \"update\" | \"delete\" | \"custom\";\n\n/**\n * Structured payload attached to `operation: \"custom\"` history entries\n * (business actions independent of model fields, e.g. manual invoice creation,\n * PDF export, email sent, etc.).\n */\nexport interface HistoryCustomData {\n /** Human-readable title (e.g. `\"Création de la facture\"`). */\n title: string;\n /** Optional human-readable description (e.g. `\"Facture #F-2026-042 créée manuellement\"`). */\n description?: string;\n /** Optional business action key for filtering/grouping/icons (e.g. `\"invoice_create_manually\"`). */\n key?: string;\n /** Optional front-end visibility flag (default: `true`). */\n display?: boolean;\n /** Optional arbitrary structured business payload (e.g. `{ invoiceId, amount }`). */\n data?: Record<string, unknown>;\n}\n\n/** Input payload accepted by `repo.history.recordCustom(...)`. */\nexport interface HistoryCustomInput extends HistoryCustomData {\n /**\n * Optional metadata overrides (`reason`, `comment`, `extras`, `userId`,\n * `userEmail`). Automatically merged on top of the active ALS actor.\n */\n meta?: HistoryMeta;\n}\n\n/**\n * Detected JS/Firestore type of a value as stored in a history entry.\n * Matches the values returned by {@link valueType}.\n */\nexport type HistoryValueType =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"timestamp\"\n | \"date\"\n | \"array\"\n | \"object\"\n | \"null\"\n | \"undefined\";\n\n/** A single field change inside a history entry. */\nexport interface HistoryFieldChange {\n oldValue: unknown;\n newValue: unknown;\n type: { old: HistoryValueType; new: HistoryValueType };\n}\n\n/** Captured metadata for a history entry. */\nexport interface HistoryMeta {\n userId?: string | null;\n userEmail?: string | null;\n reason?: string | null;\n comment?: string | null;\n /** Free-form extra fields copied from the source document. */\n extras?: Record<string, unknown>;\n}\n\n/**\n * Unified history entry returned by `repo.history.list(...)`.\n * Both v1 and v2 documents are normalised into this shape.\n */\nexport interface HistoryEntry<T = Record<string, unknown>> {\n /** Stable id of the underlying Firestore history document (the v1+v2 storage doc). */\n historyDocId: string;\n /** Id of the entity this entry belongs to. */\n historyToObjectId: string;\n /** When the change was recorded. */\n historySetAt: Timestamp;\n /** Source schema version. v1 = legacy (1 doc/field), v2 = current (1 doc/update). */\n schemaVersion: 1 | 2;\n /** v2 only — v1 is always normalised to \"update\". */\n operation: HistoryOperation;\n /** Captured author / context information. */\n meta: HistoryMeta;\n /** Present on `operation: \"custom\"` entries (business actions independent of model fields). */\n custom?: HistoryCustomData;\n /** Per-field changes. Keys are field names of T. */\n changes: { [K in keyof T & string]?: HistoryFieldChange } & {\n [field: string]: HistoryFieldChange;\n };\n}\n\n/* ------------------------------------------------------------------------- */\n/* Storage-level shapes (what is actually written / read in Firestore) */\n/* ------------------------------------------------------------------------- */\n\n/** v2 document layout. */\nexport interface V2HistoryDoc {\n schemaVersion: 2;\n historyDocId: string;\n historyToObjectId: string;\n historySetAt: Timestamp;\n operation: HistoryOperation;\n meta: HistoryMeta;\n /** Present on `operation: \"custom\"` entries. */\n custom?: HistoryCustomData;\n changes: Record<string, HistoryFieldChange>;\n /** Optional TTL marker (Firestore deletes the doc after this date). */\n expiresAt?: Timestamp;\n /** Set when the doc had to be truncated to fit the 1 MiB limit. */\n _truncated?: boolean;\n}\n\n/** v1 document layout (legacy — read-only support). */\nexport interface V1HistoryDoc {\n // schemaVersion is absent in v1.\n schemaVersion?: undefined;\n historyDocId: string;\n historyToObjectId: string;\n historyUserId?: string;\n historyUserEmail?: string;\n historySetAt: Timestamp;\n field: string;\n changes: { oldValue: unknown; newValue: unknown };\n types?: { oldValue: string; newValue: string };\n // Extra freeform metadata seen in legacy code.\n historyDetails?: Record<string, unknown> | null;\n extraHistoryDetails?: {\n comment?: string;\n reason?: string;\n toKey?: string;\n force?: boolean;\n } | null;\n extraContentKeys?: Record<string, unknown> | null;\n objectType?: string;\n}\n\n/* ------------------------------------------------------------------------- */\n/* Configuration */\n/* ------------------------------------------------------------------------- */\n\n/** Default top-level shadow field name stored on Firestore documents for auto-injected history metadata. */\nexport const DEFAULT_HISTORY_SHADOW_KEY = \"_historyMeta\";\n\n/**\n * Customize (or disable via `false`) the sub-field names stored inside the\n * shadow metadata object on Firestore documents.\n */\nexport interface HistoryShadowFieldsConfig {\n /** Key inside the shadow object for author userId, or `false` to omit. Default: `\"userId\"`. */\n userId?: string | false;\n /** Key inside the shadow object for author userEmail, or `false` to omit. Default: `\"userEmail\"`. */\n userEmail?: string | false;\n /** Key inside the shadow object for change reason, or `false` to omit. Default: `\"reason\"`. */\n reason?: string | false;\n /** Key inside the shadow object for change comment, or `false` to omit. Default: `\"comment\"`. */\n comment?: string | false;\n /** Key inside the shadow object for extras map, or `false` to omit. Default: `\"extras\"`. */\n extras?: string | false;\n}\n\n/**\n * Configuration for the internal shadow field used to transport actor metadata\n * to Firestore `onDocumentWritten` triggers without modifying Zod schemas.\n */\nexport interface HistoryShadowConfig {\n /**\n * Top-level field name stored on the Firestore document (not required in the\n * Zod schema, automatically excluded from diffs and sync, and stripped on read).\n * Default: `\"_historyMeta\"`.\n */\n key?: string;\n /**\n * Customize or disable individual sub-field names inside the shadow object.\n * Default: `{ userId: \"userId\", userEmail: \"userEmail\", reason: \"reason\", comment: \"comment\", extras: \"extras\" }`.\n */\n fields?: HistoryShadowFieldsConfig;\n}\n\n/**\n * Fallback author values written when no actor is active in `AsyncLocalStorage`\n * (crons, scripts, admin UI, public routes).\n */\nexport interface HistoryFallbackActor {\n userId?: string | null;\n userEmail?: string | null;\n}\n\n/**\n * Per-repo history configuration. Attached on the repository config under\n * the `history` key. All meta sub-keys must reference fields that exist on\n * the model (compile-time enforced by {@link HistoryConfigForModel}).\n */\nexport interface HistoryConfigBase {\n /** Master switch — when false/absent, no triggers are generated and no `repo.history` API is exposed. */\n enabled: boolean;\n /** Subcollection name used to store history docs. Default: \"history\". */\n subcollection?: string;\n /**\n * Automatically inject actor metadata from `AsyncLocalStorage` into the\n * shadow field on repository writes (`create`, `set`, `update`, `batch`,\n * `transaction`, `bulk`). Default: `true` when `enabled: true`.\n */\n autoInjectMeta?: boolean;\n /**\n * Shadow field configuration (zero Zod schema changes).\n *\n * - Omitted or `true` (when `meta` is absent): uses `\"_historyMeta\"` with default sub-fields.\n * - `string`: shorthand for `{ key: \"<customKey>\" }`.\n * - `HistoryShadowConfig`: customize both `key` and nested `fields`.\n * - `false`: disable shadow metadata injection/reading.\n */\n shadow?: boolean | string | HistoryShadowConfig;\n /**\n * Fallback actor written when no actor is active in `AsyncLocalStorage` so\n * previous author metadata never leaks onto subsequent writes.\n * Default: `{ userId: null, userEmail: null }`.\n */\n fallbackActor?: HistoryFallbackActor;\n /**\n * Optional Firestore TTL configuration. When set, every written history doc\n * gets an `expiresAt` Timestamp at `now + days`. You still need to enable\n * the TTL policy on the `expiresAt` field via gcloud / console.\n */\n ttl?: { days: number };\n /**\n * Cloud Functions v2 options forwarded to `onDocumentWritten()` for this\n * repository's history trigger (e.g. `region`, `vpcConnector`, `memory`, etc.).\n */\n triggerOptions?: HistoryTriggerOptions;\n}\n\n/**\n * Strongly-typed history config bound to a model `T`.\n *\n * - `meta.*` keys must be keyof T (or string for `extras` entries).\n * - `include` / `exclude` accept keyof T.\n */\nexport interface HistoryConfigForModel<T> extends HistoryConfigBase {\n meta?: {\n /** Field on T that holds the author user id. */\n userId?: keyof T & string;\n /** Field on T that holds the author email. */\n userEmail?: keyof T & string;\n /** Field on T that holds an optional change reason. */\n reason?: keyof T & string;\n /** Field on T that holds an optional change comment. */\n comment?: keyof T & string;\n /** Free-form extra field names copied verbatim into `meta.extras`. */\n extras?: (keyof T & string)[];\n };\n /** When set, only these top-level fields are diffed. */\n include?: (keyof T & string)[];\n /** Always excluded from the diff (in addition to meta + system keys). */\n exclude?: (keyof T & string)[];\n /**\n * Optional async hook to enrich/mutate an entry before it's written.\n * Return `null` to drop the entry entirely.\n */\n onBeforeWrite?: (\n entry: V2HistoryDoc,\n ctx: { repoName: string; docId: string; before: T | null; after: T | null },\n ) => V2HistoryDoc | null | Promise<V2HistoryDoc | null>;\n}\n\n/* ------------------------------------------------------------------------- */\n/* Read API options */\n/* ------------------------------------------------------------------------- */\n\nexport interface HistoryListOptions<T = unknown> {\n /** Max number of normalised entries to return. Default: 50. */\n limit?: number;\n /** Cursor for pagination (use `historySetAt` of the last received entry). */\n cursor?: Timestamp;\n /** Sort direction on `historySetAt`. Default: \"desc\". */\n direction?: \"asc\" | \"desc\";\n /** Restrict to entries that touch any of these fields (post-filter). */\n fields?: (keyof T & string)[];\n /** Restrict to entries with these operations (v2 only — v1 is always \"update\"). */\n operations?: HistoryOperation[];\n}\n\nexport interface HistoryRawListOptions {\n limit?: number;\n cursor?: Timestamp;\n direction?: \"asc\" | \"desc\";\n}\n\n/* ------------------------------------------------------------------------- */\n/* Trigger factory configuration */\n/* ------------------------------------------------------------------------- */\n\n/**\n * Firestore trigger constructors injected by the consumer.\n * Mirrors the DI pattern used by `createSyncTriggers`.\n */\nexport interface HistoryFirestoreTriggersDep {\n // Either onDocumentWritten alone is enough; we keep the more granular ones\n // available so the worker can stay efficient.\n onDocumentWritten: typeof onDocumentWritten;\n}\n\n/** Per-repo override at the `createHistoryTriggers` call site. */\nexport interface HistoryTriggerRepoOverride {\n /**\n * Explicit Firestore document path pattern. Required for collection-group\n * repositories whose path cannot be auto-detected.\n * @example \"residences/{residenceId}/workshops/{docId}\"\n */\n triggerPath?: string;\n /**\n * Cloud Functions v2 options forwarded to `onDocumentWritten()` for this\n * repository's history trigger. Overrides global `triggerOptions`.\n */\n triggerOptions?: HistoryTriggerOptions;\n}\n\nexport interface HistoryTriggersConfig<M = Record<string, any>> {\n deps: HistoryFirestoreTriggersDep;\n /** Defaults applied to every repo unless overridden. */\n defaults?: { ttl?: { days: number } };\n /**\n * Cloud Functions v2 options forwarded to `onDocumentWritten()` for every\n * history trigger handler. Use to configure `region`, `vpcConnector`,\n * `memory`, `cpu`, `timeoutSeconds`, `maxInstances`, `secrets`, etc.\n */\n triggerOptions?: HistoryTriggerOptions;\n /** Per-repo overrides keyed by repo name in the mapping. */\n repos?: Partial<Record<keyof M & string, HistoryTriggerRepoOverride>>;\n}\n","/**\n * Shadow metadata injection, resolution, and read-stripping helpers for the\n * history module.\n *\n * Writes actor metadata from the cross-bundle `AsyncLocalStorage` context into\n * a configurable shadow object (default `_historyMeta`) on Firestore documents\n * without requiring any changes to model Zod schemas.\n */\n\nimport { getCurrentActor } from \"../shared/actor-context\";\nimport {\n DEFAULT_HISTORY_SHADOW_KEY,\n type HistoryConfigForModel,\n} from \"./types\";\n\nexport interface ResolvedShadowFields {\n userId: string | false;\n userEmail: string | false;\n reason: string | false;\n comment: string | false;\n extras: string | false;\n}\n\nexport interface ResolvedShadowConfig {\n key: string;\n fields: ResolvedShadowFields;\n}\n\n/**\n * Resolve the effective shadow storage configuration for a repository's\n * `history` config, or `null` when shadow storage is inactive.\n *\n * Shadow storage is active whenever `history.enabled` is `true`, `shadow` is\n * not `false`, and either `meta` is omitted or `shadow` is explicitly provided.\n */\nexport function resolveShadowConfig(\n config: HistoryConfigForModel<any> | undefined | null,\n): ResolvedShadowConfig | null {\n if (!config?.enabled) return null;\n if (config.shadow === false) return null;\n if (config.meta && config.shadow === undefined) return null;\n\n const shadowOpt = config.shadow;\n const key =\n typeof shadowOpt === \"string\" && shadowOpt.trim().length > 0\n ? shadowOpt.trim()\n : typeof shadowOpt === \"object\" &&\n shadowOpt !== null &&\n typeof shadowOpt.key === \"string\" &&\n shadowOpt.key.trim().length > 0\n ? shadowOpt.key.trim()\n : DEFAULT_HISTORY_SHADOW_KEY;\n\n const customFields =\n typeof shadowOpt === \"object\" && shadowOpt !== null\n ? shadowOpt.fields\n : undefined;\n\n return {\n key,\n fields: {\n userId: customFields?.userId ?? \"userId\",\n userEmail: customFields?.userEmail ?? \"userEmail\",\n reason: customFields?.reason ?? \"reason\",\n comment: customFields?.comment ?? \"comment\",\n extras: customFields?.extras ?? \"extras\",\n },\n };\n}\n\n/**\n * Return the active shadow key for a repository's history config, or `null`\n * when shadow storage is inactive.\n */\nexport function getHistoryShadowKey(\n config: HistoryConfigForModel<any> | undefined | null,\n): string | null {\n return resolveShadowConfig(config)?.key ?? null;\n}\n\n/**\n * Return the reserved identity/shadow keys that must be stripped from incoming\n * CRUD payloads (anti-spoofing) and omitted from Create/Update OpenAPI schemas.\n */\nexport function getHistoryIdentityKeys(\n config: HistoryConfigForModel<any> | undefined | null,\n): string[] {\n const shadow = resolveShadowConfig(config);\n return shadow ? [shadow.key] : [];\n}\n\n/**\n * Strip the internal shadow field from a document returned by repository\n * read/write methods (`get`, `query`, `paginate`, `create`, `set`, `update`,\n * `transaction.get`). Zero-overhead no-op when `shadowKey` is `null` or absent.\n */\nexport function stripHistoryShadowField<T>(\n value: T,\n shadowKey: string | null | undefined,\n): T {\n if (!shadowKey || !value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n const rec = value as Record<string, unknown>;\n if (!(shadowKey in rec)) return value;\n\n const { [shadowKey]: _dropped, ...rest } = rec;\n return rest as T;\n}\n\n/**\n * Inject the current ALS actor metadata into the configurable shadow field on\n * a Firestore write payload (`create`, `set`, `update`, `batch`, `transaction`,\n * `bulk`).\n *\n * Always writes explicit `null` for absent `reason`, `comment`, `extras`, and\n * applies `fallbackActor` when no actor is active so previous write metadata\n * never leaks — including across Firestore `set(..., { merge: true })`.\n */\nexport function injectHistoryMeta(\n payload: Record<string, unknown>,\n historyConfig: HistoryConfigForModel<any> | undefined,\n): void {\n if (!historyConfig?.enabled || historyConfig.autoInjectMeta === false) return;\n\n const shadow = resolveShadowConfig(historyConfig);\n if (!shadow) return;\n\n const actor = getCurrentActor();\n const fallback = historyConfig.fallbackActor ?? {};\n const userId =\n actor?.userId !== undefined ? actor.userId : (fallback.userId ?? null);\n const userEmail =\n actor?.userEmail !== undefined\n ? actor.userEmail\n : (fallback.userEmail ?? null);\n const reason = actor?.reason ?? null;\n const comment = actor?.comment ?? null;\n const extras =\n actor?.extras && Object.keys(actor.extras).length > 0 ? actor.extras : null;\n\n const shadowObj: Record<string, unknown> = {};\n const { fields } = shadow;\n if (fields.userId !== false) shadowObj[fields.userId] = userId;\n if (fields.userEmail !== false) shadowObj[fields.userEmail] = userEmail;\n if (fields.reason !== false) shadowObj[fields.reason] = reason;\n if (fields.comment !== false) shadowObj[fields.comment] = comment;\n if (fields.extras !== false) shadowObj[fields.extras] = extras;\n\n payload[shadow.key] = shadowObj;\n}\n","import { randomBytes } from \"node:crypto\";\nimport type { DocumentReference, Firestore } from \"firebase-admin/firestore\";\n\nconst ID_CHARS =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n/**\n * Generate a random 20-char alphanumeric ID matching Firestore's native format.\n *\n * Uses a CSPRNG (`crypto.randomBytes`) with rejection sampling (dropping the\n * biased tail `>= 62*4`) to keep the distribution uniform across the 62-char\n * alphabet.\n */\nexport function generateFirestoreId(): string {\n let id = \"\";\n while (id.length < 20) {\n const bytes = randomBytes(20);\n for (let i = 0; i < bytes.length && id.length < 20; i++) {\n const byte = bytes[i]!;\n if (byte >= ID_CHARS.length * 4) continue; // drop biased tail (248..255)\n id += ID_CHARS.charAt(byte % ID_CHARS.length);\n }\n }\n return id;\n}\n\n/** Extract parameter name from a `{param}` segment, or `null` if static. */\nfunction extractSegmentParam(segment: string): string | null {\n const match = segment.match(/^\\{([^}]+)\\}$/);\n return match?.[1]?.trim() || null;\n}\n\n/**\n * Parsed metadata from a repository `path` configuration string.\n */\nexport interface ParsedPathTemplate {\n /** Raw path string as configured on the repository */\n rawPath: string;\n /**\n * Target Firestore collection ID (last collection segment, e.g. `\"prev_events\"`\n * from `\"prevention/prev_rules/prev_workshops/{workshopId}/prev_events\"`).\n * Used for `db.collectionGroup(collectionId)`.\n */\n collectionId: string;\n /**\n * Collection path (without trailing document segment). Used for `db.collection(...)`\n * on non-group repositories (`isGroup: false`).\n */\n collectionPath: string;\n /**\n * Ordered list of dynamic `{param}` parent keys extracted from the path\n * (excluding fixed transit segments like `\"prev_rules\"` and the trailing\n * `documentKey`).\n */\n parentKeys: string[];\n /**\n * Full Firestore document path pattern including trailing `/{documentKey}`\n * (e.g. `\"prevention/prev_rules/prev_workshops/{workshopId}/prev_events/{docId}\"`),\n * or `null` when `isGroup: true` and `rawPath` is a bare single-segment\n * collection name without a path template.\n */\n documentPathTemplate: string | null;\n /** `true` when `rawPath` contains `/` or `{...}` template placeholders */\n hasTemplate: boolean;\n}\n\n/**\n * Parse a repository `path` into collection ID, ordered dynamic parent keys,\n * and full document path template.\n *\n * Supports:\n * - Bare collection names: `\"users\"`, `\"res_events\"`\n * - Odd-segment collection templates: `\"residences/{residenceId}/res_events\"`,\n * `\"prevention/prev_rules/prev_workshops/{workshopId}/prev_events\"`\n * - Even-segment document templates: `\"residences/{residenceId}/res_events/{docId}\"`\n */\nexport function parsePathTemplate(\n rawPath: string,\n documentKey = \"docId\",\n isGroup = false,\n): ParsedPathTemplate {\n if (typeof rawPath !== \"string\" || !rawPath.trim()) {\n return {\n rawPath: rawPath ?? \"\",\n collectionId: \"\",\n collectionPath: \"\",\n parentKeys: [],\n documentPathTemplate: null,\n hasTemplate: false,\n };\n }\n\n const segments = rawPath\n .split(\"/\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n if (segments.length === 0) {\n return {\n rawPath,\n collectionId: rawPath,\n collectionPath: rawPath,\n parentKeys: [],\n documentPathTemplate: null,\n hasTemplate: false,\n };\n }\n\n if (segments.length === 1) {\n const seg = segments[0]!;\n return {\n rawPath,\n collectionId: seg,\n collectionPath: seg,\n parentKeys: [],\n documentPathTemplate: isGroup ? null : `${seg}/{${documentKey}}`,\n hasTemplate: rawPath.includes(\"{\") && rawPath.includes(\"}\"),\n };\n }\n\n // Multi-segment path:\n // - Even number of segments (col/doc/col/{docId}) -> last segment is the document ID placeholder\n // - Odd number of segments (col/doc/col) -> last segment is the target collection\n const isEvenSegments = segments.length % 2 === 0;\n const collectionSegments = isEvenSegments ? segments.slice(0, -1) : segments;\n const collectionId = collectionSegments[collectionSegments.length - 1]!;\n const collectionPath = collectionSegments.join(\"/\");\n\n // Parent segments are all segments before the target collection segment\n const parentSegments = collectionSegments.slice(0, -1);\n const parentKeys = parentSegments\n .map(extractSegmentParam)\n .filter((p): p is string => p !== null);\n\n const documentPathTemplate = isEvenSegments\n ? segments.join(\"/\")\n : `${collectionPath}/{${documentKey}}`;\n\n return {\n rawPath,\n collectionId,\n collectionPath,\n parentKeys,\n documentPathTemplate,\n hasTemplate: true,\n };\n}\n\n/**\n * Build a Firestore `DocumentReference` from a `documentPathTemplate`\n * (e.g. `\"prevention/prev_rules/prev_workshops/{workshopId}/prev_events/{docId}\"`)\n * and positional dynamic arguments (`[workshopId, docId]`).\n *\n * Static transit segments (like `\"prev_rules\"`) are preserved automatically.\n */\nexport function buildDocumentRefFromTemplate(\n db: Firestore,\n documentPathTemplate: string,\n args: unknown[],\n): DocumentReference {\n const segments = documentPathTemplate\n .split(\"/\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n let argIndex = 0;\n const resolvedSegments: string[] = [];\n\n for (const seg of segments) {\n const paramName = extractSegmentParam(seg);\n if (paramName !== null) {\n const val = args[argIndex++];\n if (typeof val !== \"string\" || val.trim() === \"\") {\n throw new Error(\n `Missing or empty path parameter \"${paramName}\" when resolving document reference for \"${documentPathTemplate}\".`,\n );\n }\n resolvedSegments.push(val);\n } else {\n resolvedSegments.push(seg);\n }\n }\n\n const anyDb = db as any;\n\n // Try walking db.collection(seg0).doc(seg1).collection(seg2).doc(seg3)...\n // so mocks that spy on .collection().doc() work identically to hand-written refCb.\n if (typeof anyDb?.collection === \"function\" && resolvedSegments.length >= 2) {\n let cur: any = anyDb;\n let walked = true;\n for (let i = 0; i < resolvedSegments.length; i += 2) {\n const colName = resolvedSegments[i]!;\n const docId = resolvedSegments[i + 1]!;\n if (typeof cur?.collection !== \"function\") {\n walked = false;\n break;\n }\n const colRef = cur.collection(colName);\n if (typeof colRef?.doc !== \"function\") {\n walked = false;\n break;\n }\n cur = colRef.doc(docId);\n }\n if (walked && cur && cur !== anyDb) {\n return cur as DocumentReference;\n }\n }\n\n // Fallback: db.doc(fullPath)\n const fullPath = resolvedSegments.join(\"/\");\n if (typeof anyDb?.doc === \"function\") {\n return anyDb.doc(fullPath) as DocumentReference;\n }\n\n // Last-resort fallback for minimal single-collection test mocks\n if (typeof anyDb?.collection === \"function\" && resolvedSegments.length >= 2) {\n const colPath = resolvedSegments.slice(0, -1).join(\"/\");\n const docId = resolvedSegments[resolvedSegments.length - 1]!;\n const colRef = anyDb.collection(colPath);\n if (typeof colRef?.doc === \"function\") {\n return colRef.doc(docId) as DocumentReference;\n }\n return colRef as DocumentReference;\n }\n\n throw new Error(\n `Cannot resolve DocumentReference for \"${fullPath}\": Firestore instance does not expose .collection() or .doc().`,\n );\n}\n\nexport interface ExtractPathArgsOptions {\n pathKey?: string | null;\n documentKey?: string | null;\n parentKeys?: string[];\n documentPathTemplate?: string | null;\n isGroup?: boolean;\n}\n\n/**\n * Extract the dynamic document reference arguments from a stored document.\n *\n * Unlike naive odd-segment splitting, this helper skips fixed transit document\n * segments (such as `\"prev_rules\"` in `\"prevention/prev_rules/prev_workshops/w1/prev_events/e1\"`)\n * by matching against `documentPathTemplate` or `parentKeys`.\n */\nexport function extractPathArgsFromDoc(\n doc: Record<string, unknown> | null | undefined,\n options: ExtractPathArgsOptions = {},\n): string[] | undefined {\n if (!doc || typeof doc !== \"object\") return undefined;\n\n const {\n pathKey,\n documentKey = \"docId\",\n parentKeys,\n documentPathTemplate,\n isGroup,\n } = options;\n\n const fullPath =\n pathKey && typeof doc[pathKey] === \"string\" && doc[pathKey]\n ? (doc[pathKey] as string)\n : undefined;\n\n // 1. If we have both fullPath and a matching documentPathTemplate, extract only `{param}` positions\n if (fullPath && documentPathTemplate) {\n const pathSegments = fullPath.split(\"/\").filter(Boolean);\n const tplSegments = documentPathTemplate.split(\"/\").filter(Boolean);\n if (pathSegments.length === tplSegments.length) {\n const extracted: string[] = [];\n for (let i = 0; i < tplSegments.length; i++) {\n if (extractSegmentParam(tplSegments[i]!) !== null) {\n extracted.push(pathSegments[i]!);\n }\n }\n if (extracted.length > 0) {\n return extracted;\n }\n }\n }\n\n // 2. If parentKeys are known and non-empty\n if (parentKeys && parentKeys.length > 0) {\n const expectedCount = parentKeys.length + 1;\n\n if (fullPath) {\n const segments = fullPath.split(\"/\").filter(Boolean);\n const oddSegments: string[] = [];\n for (let i = 1; i < segments.length; i += 2) {\n oddSegments.push(segments[i]!);\n }\n if (oddSegments.length >= expectedCount) {\n return oddSegments.slice(oddSegments.length - expectedCount);\n }\n }\n\n // Fallback: extract parentKeys + documentKey directly from document fields\n const docIdVal = documentKey ? doc[documentKey] : undefined;\n if (typeof docIdVal === \"string\" && docIdVal.trim() !== \"\") {\n const parentVals: string[] = [];\n let allPresent = true;\n for (const pk of parentKeys) {\n const v = doc[pk];\n if (typeof v === \"string\" && v.trim() !== \"\") {\n parentVals.push(v);\n } else {\n allPresent = false;\n break;\n }\n }\n if (allPresent) {\n return [...parentVals, docIdVal];\n }\n }\n }\n\n // 3. Fallback when fullPath is present\n if (fullPath) {\n const segments = fullPath.split(\"/\").filter(Boolean);\n const oddSegments: string[] = [];\n for (let i = 1; i < segments.length; i += 2) {\n oddSegments.push(segments[i]!);\n }\n if (oddSegments.length > 0) {\n // For non-group repos without parentKeys (e.g. under a fixed transit doc), only the last docId is dynamic\n if (!isGroup && (!parentKeys || parentKeys.length === 0)) {\n return [oddSegments[oddSegments.length - 1]!];\n }\n return oddSegments;\n }\n }\n\n return undefined;\n}\n","import type {\n CollectionReference,\n Firestore,\n Query,\n} from \"firebase-admin/firestore\";\nimport {\n getHistoryIdentityKeys,\n getHistoryShadowKey,\n} from \"../history/inject\";\nimport { createHistoryMethods, type HistoryMethods } from \"../history/read\";\nimport { createAggregateMethods } from \"../methods/aggregate\";\nimport { createBatchMethods } from \"../methods/batch\";\nimport { createBulkMethods } from \"../methods/bulk\";\nimport { createCrudMethods } from \"../methods/crud\";\nimport { createGetMethods } from \"../methods/get\";\nimport { createQueryMethods } from \"../methods/query\";\nimport { createPopulateMethods } from \"../methods/relations\";\nimport { createSystemMethods } from \"../methods/system\";\nimport { createTransactionMethods } from \"../methods/transaction\";\nimport {\n buildDocumentRefFromTemplate,\n parsePathTemplate,\n} from \"../shared/path-template\";\nimport type { RepositoryConfig } from \"../shared/types\";\nimport type { ConfiguredRepository } from \"./types\";\n\n/**\n * Extract parent-key parameter names from a refCb function.\n * For `(db, postId, docId) => …` this returns `[\"postId\"]` (everything\n * between the first param – the Firestore `db` – and the last param – the\n * document's own ID).\n * Returns an empty array when the function has ≤ 2 params (db + docId).\n * @internal\n */\nfunction extractParentKeys(refCb: unknown): string[] {\n if (typeof refCb !== \"function\") return [];\n const src = refCb.toString();\n const match = src.match(/^\\s*(?:function\\s*\\w*\\s*)?\\(([^)]*)\\)/);\n if (!match?.[1]) return [];\n const params = match[1]\n .split(\",\")\n .map((p) => p.trim().replace(/\\s*[:=].*$/, \"\").trim())\n .filter(Boolean);\n // (db, docId) → 0 parents; (db, parentId, docId) → 1 parent; etc.\n if (params.length <= 2) return [];\n return params.slice(1, -1);\n}\n\n/**\n * Build the **static** repository metadata that server/trigger builders read at\n * definition time (schema, system keys, path/group flags, history settings,\n * relational keys) directly from a raw repository **config** — i.e. without\n * resolving Firestore. Mirrors the same fields exposed by the resolved\n * repository, so it can back a {@link makeLazyRepo} overlay.\n */\nexport function buildRepoStaticMeta(config: any): Record<string, unknown> {\n const documentKey = (config?.documentKey as string | undefined) ?? \"docId\";\n const isGroup = !!config?.isGroup;\n const parsedPath = parsePathTemplate(\n typeof config?.path === \"string\" ? config.path : \"\",\n documentKey,\n isGroup,\n );\n const parentKeys =\n parsedPath.parentKeys.length > 0\n ? parsedPath.parentKeys\n : isGroup\n ? extractParentKeys(config?.refCb)\n : [];\n\n const systemKeys = [\n config?.documentKey,\n config?.pathKey,\n config?.createdKey,\n config?.updatedKey,\n ].filter((k): k is string => typeof k === \"string\");\n const historyConfig =\n config?.history && typeof config.history === \"object\"\n ? config.history\n : undefined;\n return {\n schema: config?.schema,\n _systemKeys: systemKeys,\n _pathKey: (config?.pathKey as string | undefined) ?? null,\n _isGroup: isGroup,\n _createdKey: (config?.createdKey as string | undefined) ?? null,\n _parentKeys: parentKeys,\n _documentPathTemplate: parsedPath.documentPathTemplate,\n _collectionId:\n typeof config?.path === \"string\" ? parsedPath.collectionId : null,\n relationalKeys: config?.relationalKeys,\n _historyConfig: historyConfig,\n _historyShadowKey: getHistoryShadowKey(historyConfig),\n _historyIdentityKeys: getHistoryIdentityKeys(historyConfig),\n _historySubcollection: historyConfig?.enabled\n ? (historyConfig.subcollection ?? \"history\")\n : undefined,\n // Collection path of a non-group repo (== resolved `ref.path`). Lets\n // trigger builders derive the document path without resolving the db.\n _collectionPath:\n typeof config?.path === \"string\" ? parsedPath.collectionPath : null,\n };\n}\n\n/**\n * Wrap a repository behind a lazy Proxy: **static** metadata (see\n * {@link buildRepoStaticMeta}) is served from `config` without resolving\n * Firestore, while every dynamic access (`ref`, `get`, `query`, `history.*`, …)\n * resolves the real repository on first use via `resolve()` and memoizes it.\n *\n * Lets server builders read static config at module-load time without forcing\n * `getFirestore()` — the db is only touched when a request handler actually\n * uses a repository method.\n */\nexport function makeLazyRepo<R>(config: any, resolve: () => R): R {\n const overlay = buildRepoStaticMeta(config);\n let resolved: R | undefined;\n const ensure = (): R => {\n const res = resolved ??= resolve();\n if (!res) {\n const path = (overlay as any)._collectionPath || \"unknown\";\n throw new Error(`[makeLazyRepo] Failed to resolve repository for path \"${path}\". The repository mapping resolved to undefined. This almost always indicates a circular import where the repository was exported as undefined.`);\n }\n return res;\n };\n return new Proxy(overlay as any, {\n get(_t, prop) {\n if (typeof prop === \"string\" && prop in overlay) {\n return (overlay as any)[prop];\n }\n return (ensure() as any)[prop];\n },\n has(_t, prop) {\n if (typeof prop === \"string\" && prop in overlay) return true;\n return prop in (ensure() as any);\n },\n }) as R;\n}\n\n/**\n * Creates a configured repository instance with all methods\n */\nexport function createRepository<\n T extends RepositoryConfig<any, any, any, any, any, any, any, any, any, any, any>,\n>(\n db: Firestore,\n config: T,\n allRepositories: Record<string, any> = {},\n): ConfiguredRepository<T> {\n const documentKey = config.documentKey as string;\n const parsedPath = parsePathTemplate(\n config.path,\n documentKey,\n !!config.isGroup,\n );\n const parentKeys =\n parsedPath.parentKeys.length > 0\n ? parsedPath.parentKeys\n : config.isGroup\n ? extractParentKeys(config.refCb)\n : [];\n\n // Create collection reference\n const collectionRef: CollectionReference | Query = config.isGroup\n ? db.collectionGroup(parsedPath.collectionId)\n : db.collection(parsedPath.collectionPath);\n\n // Keep actual collection for create operations\n const actualCollection = config.isGroup\n ? null\n : db.collection(parsedPath.collectionPath);\n\n // Create document reference function (auto-generated from path template when refCb is omitted)\n const documentRef =\n typeof config.refCb === \"function\"\n ? (...args: any[]) => (config.refCb as any)(db, ...args)\n : (...args: any[]) =>\n buildDocumentRefFromTemplate(\n db,\n parsedPath.documentPathTemplate ??\n `${parsedPath.collectionPath}/{${documentKey}}`,\n args,\n );\n\n // History config & shadow metadata resolution\n const historyConfig = (config as any).history as\n | { enabled: boolean; [k: string]: any }\n | undefined;\n const historyShadowKey = getHistoryShadowKey(historyConfig as any);\n const historyIdentityKeys = getHistoryIdentityKeys(historyConfig as any);\n\n // Create all method groups\n const getMethods = createGetMethods(\n collectionRef as Query,\n config.foreignKeys,\n actualCollection,\n documentRef,\n documentKey,\n historyShadowKey,\n );\n const queryMethods = createQueryMethods(\n collectionRef as Query,\n config.queryKeys,\n config.relationalKeys as Record<string, any> | undefined,\n allRepositories,\n historyShadowKey,\n );\n const aggregateMethods = createAggregateMethods(collectionRef as Query);\n const crudMethods = createCrudMethods(\n actualCollection,\n documentRef,\n documentKey,\n config.pathKey as string | undefined,\n config.createdKey as string | undefined,\n config.updatedKey as string | undefined,\n parentKeys,\n parsedPath.documentPathTemplate,\n historyConfig as any,\n );\n const batchMethods = createBatchMethods(\n db,\n documentRef,\n config.documentKey as string,\n config.pathKey as string | undefined,\n config.createdKey as string | undefined,\n config.updatedKey as string | undefined,\n historyConfig as any,\n );\n const transactionMethods = createTransactionMethods(\n db,\n documentRef,\n config.documentKey as string,\n config.pathKey as string | undefined,\n config.createdKey as string | undefined,\n config.updatedKey as string | undefined,\n historyConfig as any,\n );\n const bulkMethods = createBulkMethods(\n db,\n config.createdKey as string | undefined,\n config.updatedKey as string | undefined,\n historyConfig as any,\n );\n const systemMethods = createSystemMethods(\n db,\n collectionRef,\n config.documentKey as string,\n config.pathKey as string | undefined,\n config.createdKey as string | undefined,\n config.updatedKey as string | undefined,\n );\n const populateMethods = createPopulateMethods(config, allRepositories);\n\n // History namespace (opt-in via config.history.enabled)\n const history: HistoryMethods<any> | null =\n historyConfig?.enabled\n ? (createHistoryMethods(\n documentRef,\n [\n config.documentKey as string,\n config.pathKey as string | undefined,\n config.createdKey as string | undefined,\n config.updatedKey as string | undefined,\n ].filter((k): k is string => typeof k === \"string\"),\n (config as any).path ?? \"(unknown)\",\n historyConfig as any,\n ) as HistoryMethods<any>)\n : null;\n\n return {\n ref: collectionRef,\n documentRef,\n get: getMethods,\n query: queryMethods,\n aggregate: aggregateMethods,\n ...crudMethods,\n batch: batchMethods,\n transaction: transactionMethods,\n bulk: bulkMethods,\n system: systemMethods,\n ...populateMethods,\n ...(history ? { history } : {}),\n // Expose the configured history subcollection name (when history is enabled)\n // so external consumers (admin UI, etc.) can display / link it correctly.\n _historySubcollection: history\n ? (historyConfig?.subcollection ?? \"history\")\n : undefined,\n // Expose the raw history config so trigger builders (createHistoryTriggers)\n // can introspect `enabled`, `meta`, `include`, `exclude`, `ttl`, `subcollection`.\n // The public `history` key is intentionally the methods namespace, not the\n // config — this private field bridges the two without breaking that API.\n _historyConfig: historyConfig,\n _historyShadowKey: historyShadowKey,\n _historyIdentityKeys: historyIdentityKeys,\n // Pass through the Zod schema if one was attached via createRepositoryConfig(schema)\n schema: (config as any).schema,\n // Pass through relational keys built by buildRepositoryRelations\n relationalKeys: (config as any).relationalKeys,\n // Auto-managed keys that should never be accepted in user-provided payloads\n _systemKeys: [\n config.documentKey as string,\n config.pathKey as string | undefined,\n config.createdKey as string | undefined,\n config.updatedKey as string | undefined,\n ].filter((k): k is string => typeof k === \"string\"),\n // Expose pathKey name so server handlers can extract path args from documents\n _pathKey: (config.pathKey as string | undefined) ?? null,\n // Whether this is a collectionGroup repository\n _isGroup: !!config.isGroup,\n // Parent key field names auto-detected from path template or refCb signature\n _parentKeys: parentKeys,\n // Full document path template (e.g. \"prevention/prev_rules/prev_workshops/{workshopId}/prev_events/{docId}\")\n _documentPathTemplate: parsedPath.documentPathTemplate,\n // Resolved collection ID and collection path\n _collectionId: parsedPath.collectionId,\n _collectionPath: parsedPath.collectionPath,\n // Expose createdKey so server handlers can inject it when using set() for creates\n _createdKey: (config.createdKey as string | undefined) ?? null,\n } as unknown as ConfiguredRepository<T>;\n}\n","import type { RepoSyncConfig } from \"./types\";\n\n/**\n * Convert a single Firestore value into a SQL-safe primitive or JSON-serializable value.\n *\n * Complex types (arrays, GeoPoints, binary) become JSON strings in flat mode.\n * In non-flat mode (`stringifyArrays: false`), arrays and nested objects stay structured.\n * Primitives pass through unchanged.\n */\nexport function serializeValue(\n value: unknown,\n options?: { stringifyArrays?: boolean },\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): unknown {\n if (value === null || value === undefined) return null;\n\n // Firestore Timestamp (duck-typed: has .toDate())\n if (\n typeof value === \"object\" &&\n typeof (value as Record<string, unknown>).toDate === \"function\"\n ) {\n return ((value as { toDate(): Date }).toDate()).toISOString();\n }\n\n if (value instanceof Date) return value.toISOString();\n\n if (Buffer.isBuffer(value)) return value.toString(\"base64\");\n\n if (value instanceof Uint8Array) {\n return Buffer.from(value).toString(\"base64\");\n }\n\n // Firestore GeoPoint (duck-typed: has latitude & longitude)\n if (\n typeof value === \"object\" &&\n \"latitude\" in (value as object) &&\n \"longitude\" in (value as object)\n ) {\n const geo = value as { latitude: number; longitude: number };\n if (options?.stringifyArrays === false) {\n return { lat: geo.latitude, lng: geo.longitude };\n }\n return JSON.stringify({ lat: geo.latitude, lng: geo.longitude });\n }\n\n // Arrays\n if (Array.isArray(value)) {\n const mapped = value.map((item) =>\n serializeValue(item, options, seen, depth + 1),\n );\n return options?.stringifyArrays === false ? mapped : JSON.stringify(mapped);\n }\n\n // Plain objects (when inside nested serialization)\n if (\n typeof value === \"object\" &&\n value !== null &&\n options?.stringifyArrays === false\n ) {\n return serializeNestedObject(\n value as Record<string, unknown>,\n new Set(),\n {},\n seen,\n depth + 1,\n );\n }\n\n // string | number | boolean — pass through\n // Plain objects in flat mode are handled by flattenObject in serializeDocument\n return value;\n}\n\n/**\n * Recursively flatten a nested object into a flat key-value map\n * using underscore-separated keys: `{ address: { street: \"x\" } }` → `{ address_street: \"x\" }`.\n * Arrays and non-plain-object values are serialized as leaves.\n *\n * Guards against pathological inputs that would otherwise crash the worker\n * (and trigger an infinite PubSub redelivery loop, see issue #11):\n * - **Cycles** (`obj.self = obj`) → emitted once as a `{ __cycle: true }` marker.\n * - **Excessive depth** → truncated past {@link MAX_FLATTEN_DEPTH}.\n * - **Excessive width** → stops emitting past {@link MAX_FLATTEN_KEYS}\n * (BigQuery caps tables at 10k columns).\n */\nconst MAX_FLATTEN_DEPTH = 32;\nconst MAX_FLATTEN_KEYS = 5000;\n\nfunction flattenObject(\n obj: Record<string, unknown>,\n prefix: string,\n result: Record<string, unknown>,\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): void {\n if (depth > MAX_FLATTEN_DEPTH) {\n result[prefix || \"_truncated\"] = JSON.stringify({ __truncated: true });\n return;\n }\n if (seen.has(obj)) {\n result[prefix || \"_cycle\"] = JSON.stringify({ __cycle: true });\n return;\n }\n seen.add(obj);\n\n for (const [key, value] of Object.entries(obj)) {\n if (Object.keys(result).length >= MAX_FLATTEN_KEYS) break;\n const flatKey = prefix ? `${prefix}__${key}` : key;\n\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !Buffer.isBuffer(value) &&\n !(value instanceof Uint8Array) &&\n // Not a Firestore Timestamp\n typeof (value as Record<string, unknown>).toDate !== \"function\" &&\n // Not a GeoPoint\n !(\"latitude\" in (value as object) && \"longitude\" in (value as object))\n ) {\n // Plain object → recurse\n flattenObject(\n value as Record<string, unknown>,\n flatKey,\n result,\n seen,\n depth + 1,\n );\n } else {\n result[flatKey] = serializeValue(value);\n }\n }\n\n // Allow the same object to appear in sibling branches (only direct\n // ancestors form a cycle), so drop it from the path on the way out.\n seen.delete(obj);\n}\n\n/**\n * Recursively serialize a nested object preserving object and array structures,\n * while serializing leaf values (Timestamps, Dates, Buffers, GeoPoints).\n */\nfunction serializeNestedObject(\n obj: Record<string, unknown>,\n exclude: Set<string>,\n columnMap: Record<string, string>,\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): Record<string, unknown> {\n if (depth > MAX_FLATTEN_DEPTH) {\n return { __truncated: true };\n }\n if (seen.has(obj)) {\n return { __cycle: true };\n }\n seen.add(obj);\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (exclude.has(key)) continue;\n const mappedKey = columnMap[key] ?? key;\n\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !Buffer.isBuffer(value) &&\n !(value instanceof Uint8Array) &&\n typeof (value as Record<string, unknown>).toDate !== \"function\" &&\n !(\"latitude\" in (value as object) && \"longitude\" in (value as object))\n ) {\n result[mappedKey] = serializeNestedObject(\n value as Record<string, unknown>,\n new Set(),\n {},\n seen,\n depth + 1,\n );\n } else {\n result[mappedKey] = serializeValue(\n value,\n { stringifyArrays: false },\n seen,\n depth + 1,\n );\n }\n }\n\n seen.delete(obj);\n return result;\n}\n\n/**\n * Reconstructs nested objects from flat double-underscore keys (`address__city` → `address.city`)\n * and parses JSON-stringified arrays back into native arrays.\n */\nexport function unflattenDocument(\n doc: Record<string, unknown>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, rawValue] of Object.entries(doc)) {\n let value = rawValue;\n\n // If array or object was stringified into JSON (e.g. from a flat SQL sync worker event)\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (\n (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) ||\n (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\"))\n ) {\n try {\n value = JSON.parse(trimmed);\n } catch {\n // Keep as string if not valid JSON\n }\n }\n }\n\n if (key.startsWith(\"__\") || !key.includes(\"__\")) {\n result[key] = value;\n continue;\n }\n\n const parts = key.split(\"__\").filter(Boolean);\n let current: any = result;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (\n !current[part] ||\n typeof current[part] !== \"object\" ||\n Array.isArray(current[part])\n ) {\n current[part] = {};\n }\n current = current[part];\n }\n current[parts[parts.length - 1]!] = value;\n }\n\n return result;\n}\n\n/**\n * Serialize a full Firestore document.\n *\n * When `flat` is `true` (default):\n * Nested objects are flattened into underscore-separated column names\n * (e.g. `address.street` → `address_street`). Arrays become JSON strings.\n *\n * When `flat` is `false`:\n * Nested objects and native arrays are preserved with leaf types normalized\n * (ideal for Meilisearch and document search engines).\n *\n * Applies optional field exclusions, column renames, and custom `transformDoc`.\n */\nexport function serializeDocument(\n doc: Record<string, unknown>,\n options?: Pick<\n RepoSyncConfig,\n \"exclude\" | \"columnMap\" | \"flat\" | \"transformDoc\"\n >,\n): Record<string, unknown> {\n const isFlat = options?.flat !== false;\n let result: Record<string, unknown>;\n\n if (isFlat) {\n const exclude = new Set(options?.exclude);\n const columnMap = options?.columnMap ?? {};\n\n // Drop excluded top-level keys before flattening so keys starting with\n // \"__\" (e.g. \"__audit\") are reliably excluded without splitting issues.\n let sourceDoc = doc;\n if (exclude.size > 0) {\n let dropped = false;\n const filtered: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(doc)) {\n if (exclude.has(k)) {\n dropped = true;\n continue;\n }\n filtered[k] = v;\n }\n if (dropped) sourceDoc = filtered;\n }\n\n // First flatten the document\n const flat: Record<string, unknown> = {};\n flattenObject(sourceDoc, \"\", flat);\n\n // Then apply excludes and column renames\n result = {};\n for (const [flatKey, value] of Object.entries(flat)) {\n if (exclude.has(flatKey)) continue;\n // Also check top-level prefix for excludes (e.g. exclude \"address\" removes all address_* cols)\n const topLevel = flatKey.split(\"__\")[0]!;\n if (topLevel !== flatKey && exclude.has(topLevel)) continue;\n const column =\n columnMap[flatKey] ??\n (flatKey.includes(\"__\")\n ? columnMap[flatKey.split(\"__\").pop()!]\n : undefined) ??\n flatKey;\n result[column] = value;\n }\n } else {\n const exclude = new Set(options?.exclude);\n const columnMap = (options?.columnMap ?? {}) as Record<string, string>;\n result = serializeNestedObject(doc, exclude, columnMap);\n }\n\n if (typeof options?.transformDoc === \"function\") {\n result = options.transformDoc(result);\n }\n\n return result;\n}\n","/**\n * Firestore Cloud Function triggers that publish {@link SyncEvent}s to\n * Google Cloud PubSub.\n *\n * Dependencies (`firebase-functions`, `@google-cloud/pubsub`) are injected\n * via the `deps` config property — no lazy loading or module resolution issues.\n *\n * Out-of-order delivery is handled at the application level: every event\n * carries a `version` (publish-time `Date.now()` in ms) which is propagated\n * to SQL as the `__sync_version` column. The worker's MERGE only updates a\n * row when the incoming `version` is strictly greater than the stored one —\n * so a stale event delivered after a newer one is silently skipped.\n *\n * @example\n * ```typescript\n * import { createSyncTriggers } from \"@lpdjs/firestore-repo-service/sync\";\n * import * as firestoreTriggers from \"firebase-functions/v2/firestore\";\n * import { PubSub } from \"@google-cloud/pubsub\";\n *\n * const triggers = createSyncTriggers(repos, {\n * deps: { firestoreTriggers, pubsub: new PubSub() },\n * topicPrefix: \"my-sync\",\n * repos: { users: { exclude: [\"password\"] } },\n * });\n *\n * export const { users_onCreate, users_onUpdate, users_onDelete } = triggers;\n * ```\n */\n\nimport { getHistoryShadowKey } from \"../history/inject\";\nimport { parsePathTemplate } from \"../shared/path-template\";\nimport { serializeDocument } from \"./serializer\";\nimport type { RepoSyncConfig, SyncEvent, SyncTriggersConfig } from \"./types\";\n\nconst DEFAULT_TOPIC_PREFIX = \"firestore-sync\";\n\n/**\n * Derive the Firestore document path pattern for a trigger.\n * Returns `null` when the collection path cannot be determined.\n */\nfunction buildDocumentPath(\n repoName: string,\n collectionPath: string | null,\n): string | null {\n if (!collectionPath) {\n console.warn(\n `[SyncTriggers] Cannot determine collection path for \"${repoName}\". Skipping.`,\n );\n return null;\n }\n\n return `${collectionPath}/{docId}`;\n}\n\n/** Static, db-free metadata needed to register a sync trigger. */\ninterface SyncRepoMeta {\n isGroup: boolean;\n documentKey: string;\n /** Collection path of a non-group repo. */\n collectionPath: string | null;\n /** Auto-derived document trigger path template when path is a full template. */\n documentPathTemplate: string | null;\n /** Shadow history field key to exclude automatically from synced payloads. */\n historyShadowKey: string | null;\n}\n\nfunction syncMetaFromConfig(cfg: any): SyncRepoMeta {\n const systemKeys = [\n cfg?.documentKey,\n cfg?.pathKey,\n cfg?.createdKey,\n cfg?.updatedKey,\n ].filter((k): k is string => typeof k === \"string\");\n const rawPath = typeof cfg?.path === \"string\" ? cfg.path : null;\n const parsed = rawPath\n ? parsePathTemplate(rawPath, cfg?.documentKey ?? \"docId\")\n : null;\n return {\n isGroup: !!cfg?.isGroup,\n documentKey: systemKeys[0] ?? \"docId\",\n collectionPath: parsed ? parsed.collectionPath : null,\n documentPathTemplate:\n parsed && (!cfg?.isGroup || parsed.collectionPath.includes(\"/\"))\n ? parsed.documentPathTemplate\n : null,\n historyShadowKey: getHistoryShadowKey(cfg?.history),\n };\n}\n\nfunction syncMetaFromRepo(repo: any): SyncRepoMeta {\n const collectionPath = repo?._collectionPath ?? repo?.ref?.path ?? null;\n const docTemplate =\n typeof repo?._documentPathTemplate === \"string\"\n ? repo._documentPathTemplate\n : null;\n return {\n isGroup: !!repo?._isGroup,\n documentKey: repo?._systemKeys?.[0] ?? \"docId\",\n collectionPath,\n documentPathTemplate:\n docTemplate && (!repo?._isGroup || (collectionPath && collectionPath.includes(\"/\")))\n ? docTemplate\n : null,\n historyShadowKey:\n typeof repo?._historyShadowKey === \"string\"\n ? repo._historyShadowKey\n : getHistoryShadowKey(repo?._historyConfig),\n };\n}\n\n/**\n * Create Firestore Cloud Functions (v2) triggers that publish\n * {@link SyncEvent}s to PubSub for each repository in `repoMapping`.\n *\n * For each non-group repository, three triggers are created:\n * - `{repoName}_onCreate` → publishes an `INSERT` event\n * - `{repoName}_onUpdate` → publishes an `UPSERT` event\n * - `{repoName}_onDelete` → publishes a `DELETE` event\n *\n * Each event carries a monotonic `version` (`Date.now()` in ms) used by\n * the worker to discard out-of-order PubSub deliveries.\n */\nexport function createSyncTriggers<M extends Record<string, any>>(\n repoMapping: M,\n config: SyncTriggersConfig<NoInfer<M>>,\n): Record<string, any> {\n const { onDocumentWritten } = config.deps.firestoreTriggers;\n const pubsub = config.deps.pubsub;\n\n const topicPrefix = config?.topicPrefix ?? DEFAULT_TOPIC_PREFIX;\n const triggers: Record<string, any> = {};\n\n // Cache topic clients so the publisher reuses the same batching state\n // for a given topic across invocations.\n const topicCache = new Map<string, any>();\n function getTopic(topicName: string): any {\n let t = topicCache.get(topicName);\n if (t) return t;\n t = (pubsub as any).topic(topicName);\n topicCache.set(topicName, t);\n return t;\n }\n\n async function publish(\n topicName: string,\n syncEvent: SyncEvent,\n ): Promise<void> {\n const topic = getTopic(topicName);\n await topic.publishMessage({ json: syncEvent });\n }\n\n // Prefer the raw mapping config (exposed by `createRepositoryMapping`) so\n // triggers register WITHOUT resolving Firestore. Falls back to introspecting\n // resolved repositories when a plain repo object is passed.\n const rawMapping: Record<string, any> | undefined = (repoMapping as any)\n ?.rawMapping;\n const entries: [string, SyncRepoMeta][] = rawMapping\n ? Object.entries(rawMapping).map(([name, cfg]) => [\n name,\n syncMetaFromConfig(cfg),\n ])\n : (Object.entries(repoMapping) as [string, any][]).map(([name, repo]) => [\n name,\n syncMetaFromRepo(repo),\n ]);\n\n const repoConfigsMap = config?.repos as\n | Record<string, RepoSyncConfig<string> | undefined>\n | undefined;\n const configuredKeys = Object.keys(repoConfigsMap ?? {});\n const hasExplicitRepos = configuredKeys.length > 0;\n\n for (const [repoName, meta] of entries) {\n if (hasExplicitRepos && (!repoConfigsMap || !(repoName in repoConfigsMap))) {\n continue;\n }\n\n const repoCfg = repoConfigsMap?.[repoName];\n\n let documentPath: string | null;\n\n if (meta.isGroup) {\n const resolvedGroupPath =\n repoCfg?.triggerPath ?? meta.documentPathTemplate;\n if (!resolvedGroupPath) {\n console.warn(\n `[SyncTriggers] Skipping collection-group repo \"${repoName}\". ` +\n \"Provide a triggerPath in the sync repos config for group collections or use a full path template.\",\n );\n continue;\n }\n documentPath = resolvedGroupPath;\n } else {\n documentPath =\n repoCfg?.triggerPath ??\n meta.documentPathTemplate ??\n buildDocumentPath(repoName, meta.collectionPath);\n }\n if (!documentPath) continue;\n\n const documentKey: string = meta.documentKey;\n const effectiveExclude = meta.historyShadowKey\n ? Array.from(new Set([...(repoCfg?.exclude ?? []), meta.historyShadowKey]))\n : repoCfg?.exclude;\n const topicName = `${topicPrefix}-${repoName}`;\n\n const effectiveTriggerOptions = {\n ...config?.triggerOptions,\n ...repoCfg?.triggerOptions,\n };\n const hasTriggerOptions = Object.keys(effectiveTriggerOptions).length > 0;\n\n const triggerHandler = async (event: any) => {\n const before = event.data?.before;\n const after = event.data?.after;\n\n if (!before && !after) return;\n\n const beforeExists = !!before?.exists;\n const afterExists = !!after?.exists;\n\n if (!beforeExists && afterExists) {\n // CREATE -> INSERT\n const data = after.data() as Record<string, unknown> | undefined;\n if (!data) return;\n\n const docId = String(data[documentKey] ?? after.id);\n const serialized = serializeDocument(data, {\n exclude: effectiveExclude,\n columnMap: repoCfg?.columnMap,\n flat: repoCfg?.flat,\n transformDoc: repoCfg?.transformDoc,\n });\n\n const syncEvent: SyncEvent = {\n operation: \"INSERT\",\n repoName,\n docId,\n data: serialized,\n timestamp: new Date().toISOString(),\n version: Date.now(),\n };\n\n await publish(topicName, syncEvent);\n } else if (beforeExists && afterExists) {\n // UPDATE -> UPSERT\n const data = after.data() as Record<string, unknown> | undefined;\n if (!data) return;\n\n const docId = String(data[documentKey] ?? after.id);\n const serialized = serializeDocument(data, {\n exclude: effectiveExclude,\n columnMap: repoCfg?.columnMap,\n flat: repoCfg?.flat,\n transformDoc: repoCfg?.transformDoc,\n });\n\n const syncEvent: SyncEvent = {\n operation: \"UPSERT\",\n repoName,\n docId,\n data: serialized,\n timestamp: new Date().toISOString(),\n version: Date.now(),\n };\n\n await publish(topicName, syncEvent);\n } else if (beforeExists && !afterExists) {\n // DELETE\n const data = before.data() as Record<string, unknown> | undefined;\n const docId = String(data?.[documentKey] ?? before.id);\n\n const syncEvent: SyncEvent = {\n operation: \"DELETE\",\n repoName,\n docId,\n data: null,\n timestamp: new Date().toISOString(),\n version: Date.now(),\n };\n\n await publish(topicName, syncEvent);\n }\n };\n\n triggers[`${repoName}_onSync`] = hasTriggerOptions\n ? onDocumentWritten(\n { document: documentPath, ...effectiveTriggerOptions } as any,\n triggerHandler,\n )\n : onDocumentWritten(documentPath, triggerHandler);\n }\n\n return triggers;\n}\n","/**\n * Internal constants shared between the worker, queue, schema mapper and\n * SQL adapters.\n */\n\n/**\n * Name of the SQL column that stores the publish-time `version` of each\n * sync event. Used by the worker to discard out-of-order PubSub deliveries\n * (the MERGE only updates rows when the incoming version is strictly\n * greater than the stored one).\n *\n * Two underscores prefix avoids collisions with user-defined fields.\n */\nexport const SYNC_VERSION_COLUMN = \"__sync_version\";\n","/**\n * Zod introspection utilities — compatible with Zod 4.\n *\n * Centralizes all internal `_zod.def` accesses so the rest of the codebase\n * never touches Zod internals directly. If a future Zod version changes\n * the internal layout, only this file needs updating.\n */\n\nimport type { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Type-name resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Canonical Zod type names used in the codebase.\n * These match the **Zod 3** naming convention (e.g. \"ZodString\") that the\n * form-gen / admin handlers already rely on, so we don't need to rewrite\n * every `case \"ZodString\":` branch.\n */\ntype ZodTypeName =\n | \"ZodString\"\n | \"ZodNumber\"\n | \"ZodBigInt\"\n | \"ZodBoolean\"\n | \"ZodDate\"\n | \"ZodEnum\"\n | \"ZodNativeEnum\"\n | \"ZodLiteral\"\n | \"ZodObject\"\n | \"ZodArray\"\n | \"ZodOptional\"\n | \"ZodNullable\"\n | \"ZodDefault\"\n | \"ZodCoerce\"\n | \"ZodUnion\"\n | \"ZodUndefined\"\n | \"ZodUnknown\"\n | \"ZodAny\"\n | \"ZodRecord\"\n | string;\n\n/**\n * Map from Zod 4 `_zod.def.type` (lowercase) → Zod 3 `_def.typeName` format.\n * Any key not in this map is capitalised as `Zod${Capitalised}`.\n */\nconst TYPE_MAP: Record<string, ZodTypeName> = {\n string: \"ZodString\",\n number: \"ZodNumber\",\n bigint: \"ZodBigInt\",\n boolean: \"ZodBoolean\",\n date: \"ZodDate\",\n enum: \"ZodEnum\",\n nativeEnum: \"ZodNativeEnum\",\n literal: \"ZodLiteral\",\n object: \"ZodObject\",\n array: \"ZodArray\",\n optional: \"ZodOptional\",\n nullable: \"ZodNullable\",\n default: \"ZodDefault\",\n coerce: \"ZodCoerce\",\n union: \"ZodUnion\",\n undefined: \"ZodUndefined\",\n unknown: \"ZodUnknown\",\n any: \"ZodAny\",\n record: \"ZodRecord\",\n};\n\n/**\n * Get the canonical type name of a Zod schema.\n *\n * Works with both Zod 3 (`_def.typeName`) and Zod 4 (`_zod.def.type`).\n * Returns names in Zod-3 style (\"ZodString\", \"ZodObject\" …) for\n * backward-compatible switch/case usage.\n */\nexport function getTypeName(schema: z.ZodType): ZodTypeName {\n const s = schema as any;\n\n // Zod 4 path\n const v4Type: string | undefined = s._zod?.def?.type;\n if (v4Type)\n return (\n TYPE_MAP[v4Type] ??\n `Zod${v4Type.charAt(0).toUpperCase()}${v4Type.slice(1)}`\n );\n\n // Zod 3 fallback\n const v3Type: string | undefined = s._def?.typeName;\n if (v3Type) return v3Type;\n\n return \"\";\n}\n\n// ---------------------------------------------------------------------------\n// Unwrapping wrappers (Optional / Nullable / Default)\n// ---------------------------------------------------------------------------\n\n/**\n * Get the inner schema from a wrapper type (Optional / Nullable / Default).\n */\nexport function getInnerType(schema: z.ZodType): z.ZodType | undefined {\n const s = schema as any;\n\n // Zod 4: _zod.def.innerType\n if (s._zod?.def?.innerType) return s._zod.def.innerType;\n\n // Zod 3 compat: _def.innerType\n if (s._def?.innerType) return s._def.innerType;\n\n return undefined;\n}\n\n/**\n * Get the **source** schema of an effect / transform / pipe wrapper, i.e. the\n * schema describing what the user actually provides:\n * - Zod 3 `ZodEffects` (`.transform()` / `.refine()` / `.preprocess()`) →\n * `_def.schema`;\n * - Zod 4 `ZodPipe` (the shape `.transform()` compiles to) → the `in` side.\n *\n * Lets form/field introspection see through `z.string().transform(...)` (which\n * should still render as a text input) instead of falling back to a JSON\n * textarea. Returns `undefined` when the schema is not an effect/pipe.\n */\nexport function getEffectInnerType(schema: z.ZodType): z.ZodType | undefined {\n const s = schema as any;\n\n // Zod 4: pipe — prefer the input side (what the user types).\n const pipeIn = s._zod?.def?.in;\n if (pipeIn) return pipeIn as z.ZodType;\n\n // Zod 3: ZodEffects wraps the base schema under `_def.schema`.\n if (s._def?.schema) return s._def.schema as z.ZodType;\n\n return undefined;\n}\n\n/**\n * Get the **element schema** from a `ZodArray`.\n * Returns `undefined` for non-array schemas.\n */\nexport function getArrayElementType(\n schema: z.ZodType,\n): z.ZodType | undefined {\n const s = schema as any;\n\n // Zod 4: _zod.def.element\n if (s._zod?.def?.element) return s._zod.def.element;\n\n // Zod 3: _def.type (ZodArray stores element schema in _def.type)\n if (s._def?.type) return s._def.type;\n\n return undefined;\n}\n\n/**\n * Returns the list of **required** (non-optional) top-level keys of a ZodObject.\n * A key is required when its schema is NOT wrapped in ZodOptional.\n * ZodNullable / ZodDefault fields are still considered required — they must be present.\n */\nexport function getRequiredSchemaKeys(schema: z.ZodObject<any>): string[] {\n const required: string[] = [];\n for (const [key, fieldSchema] of Object.entries(schema.shape)) {\n const typeName = getTypeName(fieldSchema as z.ZodType);\n if (typeName !== \"ZodOptional\") {\n required.push(key);\n }\n }\n return required;\n}\n\n/**\n * Get the default value for a ZodDefault schema.\n * In Zod 3 this was `_def.defaultValue()` (function). In Zod 4 it's a direct value.\n */\nexport function getDefaultValue(schema: z.ZodType): unknown {\n const s = schema as any;\n\n // Zod 4\n if (s._zod?.def?.defaultValue !== undefined) return s._zod.def.defaultValue;\n\n // Zod 3 compat\n const v = s._def?.defaultValue;\n if (typeof v === \"function\") return v();\n return v;\n}\n\n// ---------------------------------------------------------------------------\n// Object shape\n// ---------------------------------------------------------------------------\n\n/**\n * Get the shape of a ZodObject schema (Record<string, ZodType>).\n * Handles both Zod 3 (`_def.shape()` function) and Zod 4 (`.shape` property).\n */\nexport function getShape(schema: z.ZodType): Record<string, z.ZodType> {\n const s = schema as any;\n\n // Direct `.shape` property (Zod 3 & 4 for ZodObject instances)\n if (s.shape && typeof s.shape === \"object\") return s.shape;\n\n // Zod 4: _zod.def.shape\n if (s._zod?.def?.shape && typeof s._zod.def.shape === \"object\")\n return s._zod.def.shape;\n\n // Zod 3 fallback: _def.shape() or _def.shape\n if (s._def?.shape) {\n return typeof s._def.shape === \"function\" ? s._def.shape() : s._def.shape;\n }\n\n return {};\n}\n\n// ---------------------------------------------------------------------------\n// Enum / Literal values\n// ---------------------------------------------------------------------------\n\n/**\n * Get the values of a ZodEnum schema as a string[].\n */\nexport function getEnumValues(schema: z.ZodType): string[] {\n const s = schema as any;\n\n // Zod 4: `.options` or `_zod.def.entries`\n if (Array.isArray(s.options)) return s.options;\n if (s._zod?.def?.entries)\n return Object.values(s._zod.def.entries) as string[];\n\n // Zod 3: `_def.values`\n if (Array.isArray(s._def?.values)) return s._def.values;\n\n return [];\n}\n\n/**\n * Get the value object of a ZodNativeEnum schema.\n */\nexport function getNativeEnumValues(\n schema: z.ZodType,\n): Record<string, unknown> {\n const s = schema as any;\n\n // Zod 4: `_zod.def.entries` or `.enum`\n if (s._zod?.def?.entries) return s._zod.def.entries;\n if (s.enum && typeof s.enum === \"object\") return s.enum;\n\n // Zod 3: `_def.values`\n if (s._def?.values && typeof s._def.values === \"object\") return s._def.values;\n\n return {};\n}\n\n/**\n * Get the value of a ZodLiteral schema.\n */\nexport function getLiteralValue(schema: z.ZodType): unknown {\n const s = schema as any;\n\n // Zod 4: `_zod.def.values[0]`\n if (Array.isArray(s._zod?.def?.values)) return s._zod.def.values[0];\n\n // Zod 3: `_def.value`\n return s._def?.value;\n}\n\n/**\n * Get the member schemas of a ZodUnion (or ZodDiscriminatedUnion).\n * Works with both Zod 3 (`_def.options`) and Zod 4 (`.options` /\n * `_zod.def.options`). Returns an empty array when none can be resolved.\n */\nexport function getUnionOptions(schema: z.ZodType): z.ZodType[] {\n const s = schema as any;\n\n // Zod 4\n if (Array.isArray(s.options)) return s.options as z.ZodType[];\n if (Array.isArray(s._zod?.def?.options))\n return s._zod.def.options as z.ZodType[];\n\n // Zod 3\n if (Array.isArray(s._def?.options)) return s._def.options as z.ZodType[];\n\n return [];\n}\n\n// ---------------------------------------------------------------------------\n// String checks\n// ---------------------------------------------------------------------------\n\n/**\n * Get relevant \"check kinds\" from a ZodString schema.\n * Returns an array of kind strings: \"email\", \"url\", etc.\n */\nexport function getStringChecks(schema: z.ZodType): string[] {\n const s = schema as any;\n const kinds: string[] = [];\n\n // Zod 4: checks with `.format` field\n const v4Checks: any[] | undefined = s._zod?.def?.checks;\n if (Array.isArray(v4Checks)) {\n for (const c of v4Checks) {\n if (c.format) kinds.push(c.format);\n }\n if (kinds.length > 0) return kinds;\n }\n\n // Zod 3: _def.checks with `.kind` field\n const v3Checks: any[] | undefined = s._def?.checks;\n if (Array.isArray(v3Checks)) {\n for (const c of v3Checks) {\n if (c.kind) kinds.push(c.kind);\n }\n }\n\n return kinds;\n}\n","import { z } from \"zod\";\nimport {\n getTypeName,\n getInnerType,\n getShape,\n} from \"../shared/zod-compat\";\nimport { SYNC_VERSION_COLUMN } from \"./constants\";\nimport type { SqlColumn, SqlDialect, LogicalType } from \"./types\";\n\nconst WRAPPER_TYPES = new Set([\"ZodOptional\", \"ZodNullable\", \"ZodDefault\"]);\n\nfunction unwrap(schema: z.ZodType): { inner: z.ZodType; nullable: boolean } {\n let current = schema;\n let nullable = false;\n\n for (;;) {\n const name = getTypeName(current);\n if (!WRAPPER_TYPES.has(name)) break;\n if (name === \"ZodOptional\" || name === \"ZodNullable\") nullable = true;\n const inner = getInnerType(current);\n if (!inner) break;\n current = inner;\n }\n\n return { inner: current, nullable };\n}\n\nconst LOGICAL_MAP: Record<string, LogicalType> = {\n ZodString: \"string\",\n ZodNumber: \"number\",\n ZodBigInt: \"bigint\",\n ZodBoolean: \"boolean\",\n ZodDate: \"timestamp\",\n ZodEnum: \"string\",\n ZodNativeEnum: \"string\",\n ZodLiteral: \"string\",\n};\n\nexport function zodTypeToLogical(schema: z.ZodType): LogicalType {\n const { inner } = unwrap(schema);\n return LOGICAL_MAP[getTypeName(inner)] ?? \"json\";\n}\n\nexport interface ZodSchemaToColumnsOptions {\n primaryKey?: string;\n exclude?: string[];\n columnMap?: Record<string, string>;\n}\n\n/**\n * Recursively flatten a Zod object schema into flat SQL columns.\n * Nested objects produce `parent_child` column names.\n * Arrays and non-object complex types become JSON columns.\n */\nfunction flattenSchema(\n shape: Record<string, z.ZodType>,\n dialect: SqlDialect,\n prefix: string,\n parentNullable: boolean,\n excludeSet: Set<string>,\n columnMap: Record<string, string>,\n primaryKey: string | undefined,\n columns: SqlColumn[],\n): void {\n for (const [field, fieldSchema] of Object.entries(shape)) {\n const fullKey = prefix ? `${prefix}__${field}` : field;\n\n // Exclude check on the original (dotless) path and the flattened key\n if (excludeSet.has(field) || excludeSet.has(fullKey)) continue;\n\n const { inner, nullable } = unwrap(fieldSchema);\n const typeName = getTypeName(inner);\n const isNullable = parentNullable || nullable;\n\n // Nested object → recurse to flatten\n if (typeName === \"ZodObject\") {\n const nestedShape = getShape(inner as z.ZodObject<any>);\n flattenSchema(\n nestedShape,\n dialect,\n fullKey,\n isNullable,\n excludeSet,\n columnMap,\n primaryKey,\n columns,\n );\n continue;\n }\n\n // Arrays and other complex types → JSON\n const logical = LOGICAL_MAP[typeName] ?? \"json\";\n const isPK = fullKey === primaryKey || field === primaryKey;\n const colName = columnMap[fullKey] ?? columnMap[field] ?? fullKey;\n\n columns.push({\n name: colName,\n sqlType: dialect.mapType(logical),\n nullable: isPK ? false : isNullable,\n isPrimaryKey: isPK,\n });\n }\n}\n\n/**\n * Convert a Zod object schema into an array of {@link SqlColumn} definitions\n * suitable for SQL table creation.\n *\n * Nested ZodObject fields are recursively flattened into separate columns\n * with underscore-separated names (e.g. `address.street` → `address_street`).\n * Arrays become JSON columns.\n */\nexport function zodSchemaToColumns(\n schema: z.ZodObject<any>,\n dialect: SqlDialect,\n options: ZodSchemaToColumnsOptions = {},\n): SqlColumn[] {\n const { primaryKey, exclude = [], columnMap = {} } = options;\n const excludeSet = new Set(exclude);\n const shape = getShape(schema);\n const columns: SqlColumn[] = [];\n\n flattenSchema(shape, dialect, \"\", false, excludeSet, columnMap, primaryKey, columns);\n\n // Internal version column used by the worker to discard out-of-order\n // PubSub deliveries (added unconditionally — never excluded).\n if (!columns.some((c) => c.name === SYNC_VERSION_COLUMN)) {\n columns.push({\n name: SYNC_VERSION_COLUMN,\n sqlType: dialect.mapType(\"bigint\"),\n nullable: true,\n isPrimaryKey: false,\n description: \"Monotonic publish version (Date.now() ms). Internal.\",\n });\n }\n\n return columns;\n}\n","/**\n * BigQuery type-name utilities used by the {@link BigQueryAdapter}.\n *\n * - {@link normalizeBigQueryType} canonicalises BigQuery type strings so that\n * `INTEGER`/`INT64`, `FLOAT`/`FLOAT64`, `BOOLEAN`/`BOOL`, etc. compare\n * equal during schema-drift detection.\n * - {@link isBigQueryTypeCompatible} returns whether a desired type can\n * safely keep an existing column of another type — only widenings that\n * BigQuery accepts via `ALTER COLUMN SET DATA TYPE` are allowed.\n */\n\n/**\n * Canonicalise a BigQuery type name returned by `getMetadata().schema`\n * (which may use legacy aliases like `INTEGER` or `FLOAT`) so that it can\n * be compared against the type produced by `BigQueryDialect.mapType()`.\n */\nexport function normalizeBigQueryType(type: string): string {\n const upper = type.toUpperCase();\n switch (upper) {\n case \"INTEGER\":\n return \"INT64\";\n case \"FLOAT\":\n return \"FLOAT64\";\n case \"BOOLEAN\":\n return \"BOOL\";\n default:\n return upper;\n }\n}\n\n/**\n * Whether `desired` is the same as, or a safe widening of, `existing`.\n * The widenings mirror what BigQuery allows via\n * `ALTER COLUMN x SET DATA TYPE …` — see\n * https://cloud.google.com/bigquery/docs/managing-table-schemas#change_column_types\n */\nexport function isBigQueryTypeCompatible(\n existing: string,\n desired: string,\n): boolean {\n const a = normalizeBigQueryType(existing);\n const b = normalizeBigQueryType(desired);\n if (a === b) return true;\n\n const widenings: Record<string, string[]> = {\n INT64: [\"NUMERIC\", \"BIGNUMERIC\", \"FLOAT64\"],\n NUMERIC: [\"BIGNUMERIC\", \"FLOAT64\"],\n DATE: [\"DATETIME\", \"TIMESTAMP\"],\n DATETIME: [\"TIMESTAMP\"],\n };\n return widenings[a]?.includes(b) ?? false;\n}\n","/**\n * BigQuery adapter — streams Firestore changes to BigQuery via the\n * **Storage Write API** in CDC (Change Data Capture) mode.\n *\n * Why CDC over the legacy MERGE approach:\n *\n * - **No DML concurrency limit.** MERGE/DELETE DML is bounded by ≈ 2\n * concurrent statements per table; busy collections triggered\n * `Could not serialize access … due to concurrent update` errors.\n * The Storage Write API has no such bound, so multiple Cloud Function\n * instances can flush in parallel without conflicts.\n * - **Cheaper at scale.** Storage Write is roughly ~50% cheaper than\n * legacy streaming inserts, and free for the first 2 TiB / month.\n * - **Same idempotency model.** Each row carries `_CHANGE_SEQUENCE_NUMBER`\n * built from the existing `__sync_version` column, so out-of-order\n * PubSub deliveries are merged correctly by BigQuery.\n *\n * Requirements:\n *\n * - Destination tables **must** declare a `PRIMARY KEY (...) NOT ENFORCED`\n * constraint and be clustered on that key. {@link BigQueryAdapter.createTable}\n * handles both for tables managed by this library.\n * - Tables should be created with `OPTIONS(max_staleness = INTERVAL …)`\n * so the CDC merge runs in the background instead of on every read\n * — see {@link BigQueryAdapterOptions.maxStaleness}.\n * - Service account needs `bigquery.tables.updateData` (e.g. via the\n * `roles/bigquery.dataEditor` role).\n *\n * @example\n * ```ts\n * import { BigQuery } from \"@google-cloud/bigquery\";\n * import { BigQueryAdapter } from \"@lpdjs/firestore-repo-service/sync/bigquery\";\n *\n * const adapter = new BigQueryAdapter({\n * projectId: \"my-project\",\n * datasetId: \"firestore_sync\",\n * bigquery: new BigQuery({ projectId: \"my-project\" }),\n * maxStaleness: \"INTERVAL 15 MINUTE\",\n * });\n * ```\n */\n\nimport type { BigQuery } from \"@google-cloud/bigquery\";\nimport type { z } from \"zod\";\nimport { SYNC_VERSION_COLUMN } from \"../constants\";\nimport { zodSchemaToColumns } from \"../schema-mapper\";\nimport type {\n LogicalType,\n RepoSyncConfig,\n SqlAdapter,\n SqlColumn,\n SqlDialect,\n SqlTableDef,\n SyncHealthResult,\n} from \"../types\";\nimport {\n isBigQueryTypeCompatible,\n normalizeBigQueryType,\n} from \"./bigquery-types\";\n\n// ---------------------------------------------------------------------------\n// Dialect\n// ---------------------------------------------------------------------------\n\n/** BigQuery SQL dialect mapping. */\nclass BigQueryDialect implements SqlDialect {\n readonly name = \"bigquery\";\n\n mapType(logical: LogicalType): string {\n switch (logical) {\n case \"string\":\n return \"STRING\";\n case \"number\":\n return \"FLOAT64\";\n case \"bigint\":\n return \"INT64\";\n case \"boolean\":\n return \"BOOL\";\n case \"timestamp\":\n return \"TIMESTAMP\";\n case \"json\":\n return \"JSON\";\n case \"text\":\n return \"STRING\";\n }\n }\n\n quoteIdentifier(id: string): string {\n // BigQuery escapes identifiers with backticks; a literal backtick inside\n // an identifier must be doubled. Without this, an identifier containing a\n // backtick (e.g. a column name propagated from a Firestore document key)\n // would break out of the quoting and enable DDL injection.\n return \"`\" + id.replace(/`/g, \"``\") + \"`\";\n }\n}\n\n/** Shared BigQuery dialect singleton. */\nexport const bigqueryDialect: SqlDialect = new BigQueryDialect();\n\n// ---------------------------------------------------------------------------\n// Storage Write API loader (kept loose so `@google-cloud/bigquery-storage`\n// stays an OPTIONAL peer dep)\n// ---------------------------------------------------------------------------\n\ntype StorageNs = {\n managedwriter: {\n WriterClient: new (opts?: any) => any;\n JSONWriter: new (params: { connection: any; protoDescriptor: any }) => any;\n DefaultStream: any;\n };\n adapt: {\n convertBigQuerySchemaToStorageTableSchema(schema: any): any;\n convertStorageSchemaToProto2Descriptor(\n schema: any,\n scope: string,\n ...opts: any[]\n ): any;\n withChangeType(): any;\n withChangeSequenceNumber(): any;\n };\n};\n\nlet storageNsCache: StorageNs | null = null;\nfunction loadStorageNs(): StorageNs {\n if (storageNsCache) return storageNsCache;\n // Lazy require so the library does not pull `@google-cloud/bigquery-storage`\n // unless this adapter is actually instantiated.\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = require(\"@google-cloud/bigquery-storage\");\n storageNsCache = mod as StorageNs;\n return storageNsCache;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Format `__sync_version` (Firestore commit timestamp in microseconds since\n * epoch) as the 16-character hex string required by `_CHANGE_SEQUENCE_NUMBER`.\n *\n * BigQuery compares sequence numbers lexicographically, so a fixed-width hex\n * representation is mandatory for correct ordering.\n */\nfunction formatChangeSequenceNumber(version: unknown): string {\n let n: bigint;\n if (typeof version === \"bigint\") n = version;\n else if (typeof version === \"number\") n = BigInt(version);\n else if (typeof version === \"string\") n = BigInt(version);\n else n = 0n;\n if (n < 0n) n = 0n;\n return n.toString(16).padStart(16, \"0\");\n}\n\n/**\n * Returns true when the Storage Write append failed with a transient gRPC\n * status (UNAVAILABLE, DEADLINE_EXCEEDED, INTERNAL, ABORTED). Caller can\n * safely retry these.\n */\nfunction isRetryableStorageError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const e = err as { code?: number };\n // gRPC codes: 4=DEADLINE_EXCEEDED, 10=ABORTED, 13=INTERNAL, 14=UNAVAILABLE\n return e.code === 4 || e.code === 10 || e.code === 13 || e.code === 14;\n}\n\nasync function withRetry<T>(\n fn: () => Promise<T>,\n maxRetries = 6,\n baseMs = 200,\n): Promise<T> {\n let attempt = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n return await fn();\n } catch (err) {\n attempt++;\n if (!isRetryableStorageError(err) || attempt > maxRetries) throw err;\n const cap = baseMs * Math.pow(2, attempt);\n const delay = Math.random() * cap;\n await new Promise((res) => setTimeout(res, delay));\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal structural shape of `@google-cloud/bigquery`'s `BigQuery` client\n * actually used by the adapter (`.dataset(...)` and `.query(...)`).\n *\n * Why structural and not just `BigQuery`: TypeScript treats classes with\n * private fields nominally. When a consumer's `node_modules` ends up with\n * a *second* copy of `@google-cloud/bigquery` (very common in workspace\n * setups, peer-dep dedup misses, monorepo nesting), the `BigQuery` they\n * import is *technically* a different type than the one this library's\n * `BigQuery` references — even though they are runtime-identical — and\n * assignment fails with `Types have separate declarations of a private\n * property '_universeDomain'`.\n *\n * Accepting a structural superset sidesteps the duplicate-install issue\n * without giving up type safety on the methods we actually call.\n */\nexport interface BigQueryLike {\n dataset(datasetId: string): {\n table(tableName: string): any;\n [key: string]: any;\n };\n query(options: { query: string; params?: unknown[] } | string): Promise<any>;\n}\n\nexport interface BigQueryAdapterOptions {\n /** GCP project id that owns the dataset. */\n projectId: string;\n /** BigQuery dataset id. */\n datasetId: string;\n /**\n * BigQuery client used for DDL operations (createTable, addColumns,\n * getMetadata, executeRaw). Storage Write only handles inserts.\n *\n * Typed as the structural {@link BigQueryLike} (a superset satisfied by\n * `BigQuery` from `@google-cloud/bigquery`) to avoid TypeScript nominal\n * mismatches when the consumer's project ends up with two copies of\n * `@google-cloud/bigquery` in different `node_modules`. Pass\n * `new BigQuery({...})` from your own install — it satisfies this shape\n * structurally.\n */\n bigquery: BigQueryLike | BigQuery;\n /**\n * Optional pre-built Storage Write `WriterClient`. When omitted a new\n * one is created lazily on first use.\n */\n writerClient?: any;\n /**\n * Value passed to `OPTIONS(max_staleness = ...)` on `createTable`.\n *\n * **Why this matters**: in BigQuery CDC mode, Storage Write API rows\n * land in a delta buffer. They become visible to queries only after a\n * MERGE applies them to the base table. Two paths exist:\n *\n * - **Background MERGE** — runs periodically in the background, paid\n * for as part of CDC pricing, and never blocks your readers.\n * - **Read-time MERGE** — every `SELECT` query merges the delta on the\n * fly before returning. Always-fresh reads but every query pays for\n * the merge work.\n *\n * `max_staleness` is the tolerated lag between a write and what reads\n * see. Setting it tells BigQuery: \"background MERGE is fine if reads\n * are at most this stale\". When the threshold is exceeded, the next\n * read triggers a one-shot merge.\n *\n * **The default `INTERVAL 0` means \"always read-time merge\"** — every\n * query forces a full merge of pending CDC writes. That makes reads\n * dramatically slower and more expensive on busy tables, so this\n * library defaults to a 15 minute window in production.\n *\n * Recommended:\n * - `INTERVAL 15 MINUTE` in production (good cost/freshness trade-off).\n * - `INTERVAL 1 MINUTE` in dev for quick visibility.\n * - Set to `null` to omit the option entirely (only do this when you\n * know what you are doing — you'll likely hit slow & expensive reads).\n *\n * @default \"INTERVAL 15 MINUTE\"\n */\n maxStaleness?: string | null;\n}\n\nexport class SchemaTypeMismatchError extends Error {\n constructor(\n readonly tableName: string,\n readonly column: string,\n readonly existingType: string,\n readonly desiredType: string,\n ) {\n super(\n `Schema drift detected on \\`${tableName}\\`: column \\`${column}\\` has ` +\n `type ${existingType} in BigQuery but the current Zod schema maps ` +\n `it to ${desiredType}. BigQuery cannot safely convert between these ` +\n `types — to resolve, either (a) keep the BigQuery type and add a ` +\n `transform in your repo to coerce values, (b) rename the field in ` +\n `your Zod schema (creates a new column), or (c) drop & recreate ` +\n `the table.`,\n );\n this.name = \"SchemaTypeMismatchError\";\n }\n}\n\n/**\n * BigQuery implementation of {@link SqlAdapter} using the Storage Write API\n * in CDC mode. See module-level docstring for the rationale.\n */\nexport class BigQueryAdapter implements SqlAdapter {\n readonly name = \"bigquery\";\n private readonly bigquery: BigQueryLike;\n private readonly projectId: string;\n private readonly datasetId: string;\n private readonly maxStaleness: string | null;\n private writerClient: any;\n /** Cache of `{ writer, primaryKey }` per table name. */\n private readonly writers = new Map<\n string,\n { writer: any; primaryKey: string; timestampColumns?: Set<string> }\n >();\n\n constructor(options: BigQueryAdapterOptions) {\n this.bigquery = options.bigquery;\n this.projectId = options.projectId;\n this.datasetId = options.datasetId;\n this.maxStaleness =\n options.maxStaleness === undefined\n ? \"INTERVAL 15 MINUTE\"\n : options.maxStaleness;\n this.writerClient = options.writerClient;\n }\n\n get dialect(): SqlDialect {\n return bigqueryDialect;\n }\n\n // -------- SyncAdapter implementation ------------------------------------\n\n async targetExists(targetName: string): Promise<boolean> {\n return this.tableExists(targetName);\n }\n\n async upsert(\n targetName: string,\n items: Record<string, unknown>[],\n primaryKey: string,\n ): Promise<void> {\n return this.upsertRows(targetName, items, primaryKey);\n }\n\n async delete(\n targetName: string,\n primaryKey: string,\n ids: string[],\n ): Promise<void> {\n return this.deleteRows(targetName, primaryKey, ids);\n }\n\n async ensureTarget(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n exclude?: string[];\n columnMap?: Record<string, string>;\n }): Promise<void> {\n if (!options.schema) return;\n const { targetName, primaryKey, schema, exclude, columnMap } = options;\n const columns = zodSchemaToColumns(schema, this.dialect, {\n primaryKey,\n exclude,\n columnMap,\n });\n const exists = await this.tableExists(targetName);\n if (!exists) {\n await this.createTable({ tableName: targetName, columns });\n } else {\n const existing = await this.getTableColumnsWithTypes(targetName);\n const missing: typeof columns = [];\n for (const col of columns) {\n const existingType = existing.get(col.name);\n if (existingType === undefined) {\n missing.push(col);\n continue;\n }\n if (!isBigQueryTypeCompatible(existingType, col.sqlType)) {\n throw new SchemaTypeMismatchError(\n targetName,\n col.name,\n existingType,\n col.sqlType,\n );\n }\n }\n if (missing.length > 0) {\n await this.addColumns(targetName, missing);\n await this.onSchemaChange?.(targetName);\n }\n }\n }\n\n async healthCheck(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n repoConfig?: RepoSyncConfig<string>;\n }): Promise<SyncHealthResult> {\n const { targetName, primaryKey, schema, repoConfig } = options;\n if (!schema) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: \"No Zod schema attached to repository\",\n };\n }\n try {\n const exists = await this.tableExists(targetName);\n if (!exists) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: `Table \\`${targetName}\\` does not exist`,\n };\n }\n const actualCols = await this.getTableColumns(targetName);\n const expectedCols = zodSchemaToColumns(schema, this.dialect, {\n primaryKey,\n exclude: repoConfig?.exclude,\n columnMap: repoConfig?.columnMap as Record<string, string> | undefined,\n });\n const actualSet = new Set(actualCols);\n const expectedSet = new Set(expectedCols.map((c) => c.name));\n const missing = expectedCols.filter((c) => !actualSet.has(c.name));\n const extra = actualCols.filter((c) => !expectedSet.has(c));\n const matched = expectedCols.filter((c) => actualSet.has(c.name));\n const healthy = missing.length === 0;\n\n return {\n healthy,\n targetName,\n targetExists: true,\n error: healthy\n ? null\n : `Missing columns: ${missing.map((c) => c.name).join(\", \")}`,\n details: {\n expected: expectedCols.map((c) => ({\n name: c.name,\n type: c.sqlType,\n nullable: c.nullable,\n isPrimaryKey: c.isPrimaryKey,\n })),\n actual: actualCols,\n matched: matched.map((c) => c.name),\n missing: missing.map((c) => ({ name: c.name, type: c.sqlType })),\n extra,\n },\n };\n } catch (e: any) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: e?.message ?? String(e),\n };\n }\n }\n\n // -------- DDL (delegated to @google-cloud/bigquery) ----------------------\n\n async tableExists(tableName: string): Promise<boolean> {\n const [exists] = await this.dataset.table(tableName).exists();\n return exists;\n }\n\n async getTableColumns(tableName: string): Promise<string[]> {\n const [metadata] = await this.dataset.table(tableName).getMetadata();\n const fields: Array<{ name: string }> = metadata.schema?.fields ?? [];\n return fields.map((f) => f.name);\n }\n\n async getTableColumnsWithTypes(\n tableName: string,\n ): Promise<Map<string, string>> {\n const [metadata] = await this.dataset.table(tableName).getMetadata();\n const fields: Array<{ name: string; type: string }> =\n metadata.schema?.fields ?? [];\n const result = new Map<string, string>();\n for (const f of fields) {\n result.set(f.name, normalizeBigQueryType(f.type));\n }\n return result;\n }\n\n async createTable(table: SqlTableDef): Promise<void> {\n const qi = (id: string) => this.dialect.quoteIdentifier(id);\n const pk = table.columns.find((c) => c.isPrimaryKey)?.name;\n if (!pk) {\n throw new Error(\n `BigQueryAdapter requires a primary key on table \\`${table.tableName}\\` ` +\n `(Storage Write CDC mode needs PRIMARY KEY NOT ENFORCED).`,\n );\n }\n const cols = table.columns\n .map((c) => {\n const notNull = c.isPrimaryKey ? \" NOT NULL\" : \"\";\n return ` ${qi(c.name)} ${c.sqlType}${notNull}`;\n })\n .join(\",\\n\");\n\n const opts: string[] = [];\n if (this.maxStaleness !== null) {\n opts.push(`max_staleness = ${this.maxStaleness}`);\n }\n const optionsClause =\n opts.length > 0 ? `\\nOPTIONS(${opts.join(\", \")})` : \"\";\n\n const ddl =\n `CREATE TABLE IF NOT EXISTS ${this.fqn(table.tableName)} (\\n${cols},\\n` +\n ` PRIMARY KEY (${qi(pk)}) NOT ENFORCED\\n)` +\n `\\nCLUSTER BY ${qi(pk)}` +\n `${optionsClause};`;\n\n await this.bigquery.query({ query: ddl });\n }\n\n async addColumns(tableName: string, columns: SqlColumn[]): Promise<void> {\n const qi = (id: string) => this.dialect.quoteIdentifier(id);\n for (const c of columns) {\n const stmt = `ALTER TABLE ${this.fqn(tableName)} ADD COLUMN ${qi(c.name)} ${c.sqlType};`;\n await this.bigquery.query({ query: stmt });\n }\n }\n\n async executeRaw(sql: string): Promise<void> {\n await this.bigquery.query({ query: sql });\n }\n\n /**\n * Invalidate the cached writer for a table. Called by the worker after\n * `addColumns` so the next append rebuilds the proto descriptor against\n * the new schema.\n */\n onSchemaChange(tableName: string): void {\n const cached = this.writers.get(tableName);\n if (cached) {\n try {\n cached.writer.close();\n } catch {\n // ignore — connection may already be torn down\n }\n this.writers.delete(tableName);\n }\n }\n\n // -------- Inserts (Storage Write API) -----------------------------------\n\n async insertRows(\n tableName: string,\n rows: Record<string, unknown>[],\n ): Promise<void> {\n if (rows.length === 0) return;\n // Plain inserts have no PK matching, but in CDC mode every row needs a\n // _CHANGE_TYPE. We treat them as UPSERT.\n const writer = await this.getOrCreateWriter(tableName);\n const timestampColumns = this.writers.get(tableName)?.timestampColumns;\n const cdc = rows.map((row) => ({\n ...this.normalizeRow(row, timestampColumns),\n _CHANGE_TYPE: \"UPSERT\",\n _CHANGE_SEQUENCE_NUMBER: formatChangeSequenceNumber(\n row[SYNC_VERSION_COLUMN],\n ),\n }));\n await this.appendWithRetry(tableName, writer, cdc);\n }\n\n async upsertRows(\n tableName: string,\n rows: Record<string, unknown>[],\n primaryKey: string,\n ): Promise<void> {\n if (rows.length === 0) return;\n const writer = await this.getOrCreateWriter(tableName, primaryKey);\n const timestampColumns = this.writers.get(tableName)?.timestampColumns;\n const cdc = rows.map((row) => ({\n ...this.normalizeRow(row, timestampColumns),\n _CHANGE_TYPE: \"UPSERT\",\n _CHANGE_SEQUENCE_NUMBER: formatChangeSequenceNumber(\n row[SYNC_VERSION_COLUMN],\n ),\n }));\n await this.appendWithRetry(tableName, writer, cdc);\n }\n\n async deleteRows(\n tableName: string,\n primaryKey: string,\n ids: string[],\n ): Promise<void> {\n if (ids.length === 0) return;\n const writer = await this.getOrCreateWriter(tableName, primaryKey);\n // Storage Write CDC requires a value for every NOT-NULL column (the PK)\n // and a `_CHANGE_TYPE`. Other columns may be omitted; missing values are\n // interpreted as NULL. We pass the maximum sequence number so the DELETE\n // wins over any concurrent UPSERT for the same key — tombstones from the\n // queue carry no `__sync_version` of their own.\n const cdc = ids.map((id) => ({\n [primaryKey]: id,\n _CHANGE_TYPE: \"DELETE\",\n _CHANGE_SEQUENCE_NUMBER: \"ffffffffffffffff\",\n }));\n await this.appendWithRetry(tableName, writer, cdc);\n }\n\n // -------- Internal helpers ----------------------------------------------\n\n private get dataset() {\n return this.bigquery.dataset(this.datasetId);\n }\n\n private fqn(tableName: string): string {\n // Escape backticks in both identifier parts to prevent DDL/DML injection\n // (BigQuery doubles backticks to embed a literal one).\n const esc = (s: string) => s.replace(/`/g, \"``\");\n return `\\`${esc(this.datasetId)}.${esc(tableName)}\\``;\n }\n\n /** ISO 8601 timestamp pattern (e.g. 2026-03-29T20:59:27.394Z) */\n private static readonly ISO_TIMESTAMP_RE =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/;\n\n /**\n * Convert a Date or epoch-millis number into the epoch-microseconds string\n * required by the Storage Write API for TIMESTAMP columns.\n *\n * The JSONWriter encodes through protobuf and a TIMESTAMP field is an\n * `int64`. Passing an ISO string would make `Long.fromString` throw\n * `interior hyphen` on the `-` characters.\n */\n private static toEpochMicros(d: Date): string {\n const ms = d.getTime();\n return (BigInt(ms) * 1000n).toString();\n }\n\n /** Convert JS values into shapes accepted by JSONWriter. */\n private normalizeRow(\n row: Record<string, unknown>,\n timestampColumns?: Set<string>,\n ): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(row)) {\n if (v === undefined) continue;\n if (v instanceof Date) {\n // TIMESTAMP column → int64 epoch micros (as string to preserve precision)\n out[k] = BigQueryAdapter.toEpochMicros(v);\n } else if (\n typeof v === \"string\" &&\n this.shouldCoerceTimestamp(k, v, timestampColumns)\n ) {\n // ISO timestamp produced upstream by `serializeDocument` (Firestore\n // Timestamp → ISO string) — convert to epoch micros for protobuf.\n const d = new Date(v);\n if (!Number.isNaN(d.getTime())) {\n out[k] = BigQueryAdapter.toEpochMicros(d);\n } else {\n out[k] = v;\n }\n } else if (typeof v === \"object\" && v !== null) {\n // JSON columns: serialise nested objects/arrays\n out[k] = JSON.stringify(v);\n } else if (typeof v === \"bigint\") {\n out[k] = v.toString();\n } else {\n out[k] = v;\n }\n }\n return out;\n }\n\n /**\n * Decide whether a string value should be coerced to an epoch-micros\n * timestamp.\n *\n * When the destination table's column types are known (writer already\n * built from table metadata), coerce **only** when the column is actually\n * TIMESTAMP/DATETIME/DATE. This prevents a business string that merely\n * looks like an ISO date (a log line, a slug, a formatted id) from being\n * silently rewritten — and avoids type-mismatch write errors on STRING\n * columns (issue #15).\n *\n * When column types are unavailable (e.g. a writer injected directly, or\n * metadata not yet fetched), fall back to the ISO-shape heuristic so\n * behaviour is unchanged.\n */\n private shouldCoerceTimestamp(\n column: string,\n value: string,\n timestampColumns?: Set<string>,\n ): boolean {\n if (timestampColumns) return timestampColumns.has(column);\n return BigQueryAdapter.ISO_TIMESTAMP_RE.test(value);\n }\n\n private async appendWithRetry(\n tableName: string,\n writer: any,\n rows: Record<string, unknown>[],\n ): Promise<void> {\n await withRetry(async () => {\n try {\n const pending = writer.appendRows(rows);\n await pending.getResult();\n } catch (err) {\n // On certain errors (schema drift, broken connection) drop the\n // cached writer so the next call rebuilds it.\n this.onSchemaChange(tableName);\n throw err;\n }\n });\n }\n\n private async getOrCreateWriter(\n tableName: string,\n primaryKey?: string,\n ): Promise<any> {\n const cached = this.writers.get(tableName);\n if (cached) {\n if (primaryKey && cached.primaryKey !== primaryKey) {\n // PK changed — invalidate and rebuild\n this.onSchemaChange(tableName);\n } else {\n return cached.writer;\n }\n }\n\n const ns = loadStorageNs();\n if (!this.writerClient) {\n this.writerClient = new ns.managedwriter.WriterClient({\n projectId: this.projectId,\n });\n }\n\n const [metadata] = await this.dataset.table(tableName).getMetadata();\n const bqSchema = { fields: metadata.schema?.fields ?? [] };\n if (!primaryKey) {\n // Try to recover PK from table constraints if available\n const tableConstraintsPK =\n metadata.tableConstraints?.primaryKey?.columns?.[0];\n primaryKey = tableConstraintsPK ?? bqSchema.fields[0]?.name;\n }\n\n const storageSchema =\n ns.adapt.convertBigQuerySchemaToStorageTableSchema(bqSchema);\n const protoDescriptor = ns.adapt.convertStorageSchemaToProto2Descriptor(\n storageSchema,\n \"Row\",\n ns.adapt.withChangeType(),\n ns.adapt.withChangeSequenceNumber(),\n );\n\n // Track which columns are actually TIMESTAMP-like so `normalizeRow` only\n // coerces ISO-looking strings when the destination column expects a\n // timestamp — a business string that merely *looks* like an ISO date must\n // not be silently converted to epoch micros (see issue #15).\n const timestampColumns = new Set<string>(\n (bqSchema.fields as Array<{ name: string; type?: string }>)\n .filter((f) =>\n [\"TIMESTAMP\", \"DATETIME\", \"DATE\"].includes(\n String(f.type ?? \"\").toUpperCase(),\n ),\n )\n .map((f) => f.name),\n );\n\n const destinationTable = `projects/${this.projectId}/datasets/${this.datasetId}/tables/${tableName}`;\n // Pass `DefaultStream` as `streamId` (not `streamType`): the `_default`\n // stream is implicit on every table, so the client must short-circuit to\n // `${destinationTable}/streams/_default` instead of calling\n // `createWriteStream({ type: DEFAULT })` which BigQuery rejects with\n // `Unable to create a stream with type TYPE_UNSPECIFIED`.\n const connection = await this.writerClient.createStreamConnection({\n streamId: ns.managedwriter.DefaultStream,\n destinationTable,\n });\n\n const writer = new ns.managedwriter.JSONWriter({\n connection,\n protoDescriptor,\n });\n\n this.writers.set(tableName, {\n writer,\n primaryKey: primaryKey ?? \"\",\n timestampColumns,\n });\n return writer;\n }\n\n /** Close all open writer connections. Useful for graceful shutdown. */\n async close(): Promise<void> {\n for (const { writer } of this.writers.values()) {\n try {\n writer.close();\n } catch {\n /* ignore */\n }\n }\n this.writers.clear();\n if (this.writerClient && typeof this.writerClient.close === \"function\") {\n try {\n this.writerClient.close();\n } catch {\n /* ignore */\n }\n }\n }\n}\n","/**\n * Per-repo in-memory batch buffer.\n *\n * Accumulates {@link SyncEvent}s and flushes them in batches to a\n * {@link SqlAdapter}. On flush failure the events are re-published\n * to PubSub for retry (if a PubSub re-publisher is provided).\n */\n\nimport { SYNC_VERSION_COLUMN } from \"./constants\";\nimport type { SyncAdapter, SyncEvent } from \"./types\";\n\nexport interface SyncQueueOptions {\n /** Target adapter to flush data to */\n adapter: SyncAdapter;\n /** SQL table name or Search index UID */\n tableName: string;\n /** Primary key column/field name */\n primaryKey: string;\n /** Max rows per flush (default: 100) */\n batchSize?: number;\n /** Auto-flush interval in ms (default: 5_000). 0 = manual only. */\n flushIntervalMs?: number;\n /** Called on flush failure with the failed events. Typically re-publishes to PubSub. */\n onFlushError?: (events: SyncEvent[], error: unknown) => Promise<void>;\n}\n\nexport interface SyncQueueErrorEntry {\n /** Monotonic error sequence number for this queue instance */\n seq: number;\n /** Error message string */\n message: string;\n /** Number of events in the failed batch */\n count: number;\n /** Epoch millis when the failure occurred */\n timestamp: number;\n}\n\nexport interface SyncQueueStats {\n /** Total events successfully flushed to the adapter */\n flushedEvents: number;\n /** Total events whose flush failed */\n failedEvents: number;\n /** Total batches successfully flushed */\n flushedBatches: number;\n /** Total batches whose flush failed */\n failedBatches: number;\n /** Monotonic sequence counter of recorded flush errors */\n errorSeq: number;\n /** Recent flush error entries (capped ring buffer) */\n recentErrors: SyncQueueErrorEntry[];\n}\n\nexport interface SyncQueueFlushReport {\n /** Events successfully flushed during this flush call */\n flushed: number;\n /** Events that failed during this flush call */\n failed: number;\n /** Error messages recorded during this flush call */\n errors: string[];\n}\n\n/**\n * In-memory buffer that batches sync events per-repo and flushes them\n * to a target adapter.\n */\nexport class SyncQueue {\n private static readonly MAX_RECENT_ERRORS = 50;\n\n private buffer: SyncEvent[] = [];\n private flushing = false;\n private lastFlushFailed = false;\n private flushPromise: Promise<void> | null = null;\n private timer: ReturnType<typeof setInterval> | null = null;\n\n private flushedEvents = 0;\n private failedEvents = 0;\n private flushedBatches = 0;\n private failedBatches = 0;\n private errorSeq = 0;\n private recentErrors: SyncQueueErrorEntry[] = [];\n\n private readonly adapter: SyncAdapter;\n private readonly tableName: string;\n private readonly primaryKey: string;\n private readonly batchSize: number;\n private readonly onFlushError?: SyncQueueOptions[\"onFlushError\"];\n\n constructor(opts: SyncQueueOptions) {\n this.adapter = opts.adapter;\n this.tableName = opts.tableName;\n this.primaryKey = opts.primaryKey;\n this.batchSize = opts.batchSize ?? 100;\n this.onFlushError = opts.onFlushError;\n\n const interval = opts.flushIntervalMs ?? 5_000;\n if (interval > 0) {\n this.timer = setInterval(() => {\n void this.flush().catch((err) => {\n console.error(\n `[SyncQueue] Scheduled flush failed for ${this.tableName}:`,\n err,\n );\n });\n }, interval);\n // Allow the Node process to exit even if the timer is running\n if (typeof this.timer === \"object\" && \"unref\" in this.timer) {\n this.timer.unref();\n }\n }\n }\n\n /** Number of events waiting in the buffer. */\n get size(): number {\n return this.buffer.length;\n }\n\n /** Snapshot cumulative flush statistics for this queue. */\n getStats(): SyncQueueStats {\n return {\n flushedEvents: this.flushedEvents,\n failedEvents: this.failedEvents,\n flushedBatches: this.flushedBatches,\n failedBatches: this.failedBatches,\n errorSeq: this.errorSeq,\n recentErrors: this.recentErrors.map((e) => ({ ...e })),\n };\n }\n\n /** Push one or more events into the buffer. Triggers auto-flush if batchSize reached. */\n enqueue(...events: SyncEvent[]): void {\n this.buffer.push(...events);\n if (\n this.buffer.length >= this.batchSize &&\n !this.flushing &&\n !this.lastFlushFailed\n ) {\n void this._autoFlush().catch((err) => {\n console.error(\n `[SyncQueue] Auto-flush failed for ${this.tableName}:`,\n err,\n );\n });\n }\n }\n\n /**\n * Auto-flush full batches triggered by `enqueue()`.\n * Only drains complete batches of `batchSize` so events trickling in during\n * an async flush are not sent as tiny 1-2 row micro-batches.\n */\n private async _autoFlush(): Promise<void> {\n while (this.flushPromise) {\n await this.flushPromise;\n }\n if (this.buffer.length < this.batchSize || this.lastFlushFailed) return;\n\n this.flushing = true;\n this.flushPromise = this._drain(true).finally(() => {\n this.flushing = false;\n this.flushPromise = null;\n });\n await this.flushPromise;\n }\n\n /**\n * Flush all buffered events to the target adapter.\n * Upserts and deletes are batched separately.\n */\n async flush(): Promise<void> {\n while (this.flushPromise) {\n await this.flushPromise;\n }\n if (this.buffer.length === 0) return;\n\n this.flushing = true;\n this.flushPromise = this._drain(false).finally(() => {\n this.flushing = false;\n this.flushPromise = null;\n });\n await this.flushPromise;\n }\n\n /**\n * Flush all buffered events and return the delta of flushed/failed counts\n * and error messages recorded while draining.\n */\n async flushWithReport(): Promise<SyncQueueFlushReport> {\n const before = this.getStats();\n await this.flush();\n const after = this.getStats();\n return {\n flushed: after.flushedEvents - before.flushedEvents,\n failed: after.failedEvents - before.failedEvents,\n errors: after.recentErrors\n .filter((e) => e.seq > before.errorSeq)\n .map((e) => e.message),\n };\n }\n\n /**\n * Drain the buffer. When `fullBatchesOnly` is true, stops once fewer than\n * `batchSize` events remain so partial batches wait for explicit `flush()`\n * or the periodic timer.\n */\n private async _drain(fullBatchesOnly: boolean): Promise<void> {\n try {\n while (\n fullBatchesOnly\n ? this.buffer.length >= this.batchSize\n : this.buffer.length > 0\n ) {\n const progressed = await this._doFlush();\n if (!progressed) break;\n }\n } finally {\n this.flushing = false;\n }\n }\n\n /**\n * Flush a single batch (up to `batchSize` events) to the adapter.\n */\n private async _doFlush(): Promise<boolean> {\n // Drain the buffer atomically\n const batch = this.buffer.splice(0, this.batchSize);\n if (batch.length === 0) return false;\n\n try {\n const upsertsById = new Map<string, Record<string, unknown>>();\n const deleteIds: string[] = [];\n\n for (const evt of batch) {\n if (evt.operation === \"DELETE\") {\n deleteIds.push(evt.docId);\n // A delete supersedes any pending upsert in the same batch.\n upsertsById.delete(evt.docId);\n } else if (evt.data) {\n // Multiple updates to the same doc within a single batch:\n // Keep only the row with the highest __sync_version per docId.\n const existing = upsertsById.get(evt.docId);\n if (!existing) {\n upsertsById.set(evt.docId, evt.data);\n } else {\n const a = Number(existing[SYNC_VERSION_COLUMN] ?? 0);\n const b = Number(evt.data[SYNC_VERSION_COLUMN] ?? 0);\n if (b >= a) upsertsById.set(evt.docId, evt.data);\n }\n }\n }\n\n const upserts = Array.from(upsertsById.values());\n\n if (upserts.length > 0) {\n if (typeof this.adapter.upsert === \"function\") {\n await this.adapter.upsert(this.tableName, upserts, this.primaryKey);\n } else if (typeof (this.adapter as any).upsertRows === \"function\") {\n await (this.adapter as any).upsertRows(this.tableName, upserts, this.primaryKey);\n }\n }\n if (deleteIds.length > 0) {\n if (typeof this.adapter.delete === \"function\") {\n await this.adapter.delete(\n this.tableName,\n this.primaryKey,\n deleteIds,\n );\n } else if (typeof (this.adapter as any).deleteRows === \"function\") {\n await (this.adapter as any).deleteRows(\n this.tableName,\n this.primaryKey,\n deleteIds,\n );\n }\n }\n\n this.flushedEvents += batch.length;\n this.flushedBatches++;\n this.lastFlushFailed = false;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.failedEvents += batch.length;\n this.failedBatches++;\n this.errorSeq++;\n this.recentErrors.push({\n seq: this.errorSeq,\n message: msg,\n count: batch.length,\n timestamp: Date.now(),\n });\n if (this.recentErrors.length > SyncQueue.MAX_RECENT_ERRORS) {\n this.recentErrors.shift();\n }\n\n if (this.onFlushError) {\n await this.onFlushError(batch, err);\n } else {\n // Re-insert at the front so we retry next flush\n this.buffer.unshift(...batch);\n this.lastFlushFailed = true;\n console.error(`[SyncQueue] Flush failed for ${this.tableName}:`, err);\n return false;\n }\n }\n return true;\n }\n\n /** Stop the auto-flush timer and flush remaining events. */\n async shutdown(): Promise<void> {\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n await this.flush();\n }\n}\n","/**\n * PubSub worker — creates a Cloud Function that receives {@link SyncEvent}\n * messages from PubSub, routes them to per-repo / per-adapter {@link SyncQueue}s, and\n * flushes batches to the configured {@link SyncAdapter}s.\n *\n * Dependencies (`firebase-functions`, `@google-cloud/pubsub`) are injected\n * via the `deps` config property.\n */\n\nimport { z } from \"zod\";\nimport { SchemaTypeMismatchError } from \"./adapters/bigquery\";\nimport { SYNC_VERSION_COLUMN } from \"./constants\";\nimport { SyncQueue } from \"./queue\";\nimport { zodSchemaToColumns } from \"./schema-mapper\";\nimport type {\n RepoSyncConfig,\n SyncAdapter,\n SyncEvent,\n SyncWorkerConfig,\n} from \"./types\";\n\nexport { SchemaTypeMismatchError };\n\n// ---------------------------------------------------------------------------\n// Migration tracking\n// ---------------------------------------------------------------------------\n\n/** Set of `${repoName}:${adapter.name}` pairs that have already been migrated. */\nconst migratedTargets = new Set<string>();\n\nasync function ensureMigratedTarget(\n repoName: string,\n adapter: SyncAdapter,\n schema: z.ZodObject<any>,\n tableName: string,\n primaryKey: string,\n exclude?: string[],\n columnMap?: Record<string, string>,\n): Promise<void> {\n const migrationKey = `${repoName}:${adapter.name}`;\n if (migratedTargets.has(migrationKey)) return;\n\n if (typeof adapter.ensureTarget === \"function\") {\n await adapter.ensureTarget({\n targetName: tableName,\n primaryKey,\n schema,\n exclude,\n columnMap,\n });\n } else if (\"dialect\" in adapter && typeof (adapter as any).createTable === \"function\") {\n const sqlAdapter = adapter as any;\n const columns = zodSchemaToColumns(schema, sqlAdapter.dialect, {\n primaryKey,\n exclude,\n columnMap,\n });\n const exists = await sqlAdapter.tableExists(tableName);\n if (!exists) {\n await sqlAdapter.createTable({ tableName, columns });\n } else {\n const existing = new Set(await sqlAdapter.getTableColumns(tableName));\n const newCols = columns.filter((c: any) => !existing.has(c.name));\n if (newCols.length > 0) {\n await sqlAdapter.addColumns(tableName, newCols);\n await sqlAdapter.onSchemaChange?.(tableName);\n }\n }\n }\n\n migratedTargets.add(migrationKey);\n}\n\n// ---------------------------------------------------------------------------\n// Worker factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a PubSub-triggered Cloud Function that syncs Firestore changes\n * to target storage adapters.\n *\n * Returns an object with:\n * - `createHandler` — creates a Cloud Function for a PubSub topic\n * - `handleMessage` — process a SyncEvent directly (for testing)\n * - `queues` — internal SyncQueue map (for testing / manual flush)\n * - `shutdown()` — flush all queues and stop timers\n */\nexport function createSyncWorker<M extends Record<string, any>>(\n repoMapping: M,\n config: SyncWorkerConfig<NoInfer<M>>,\n) {\n const {\n deps,\n adapter: rawAdapter,\n adapters: rawAdaptersList,\n batchSize = 100,\n flushIntervalMs = 5_000,\n autoMigrate = false,\n topicPrefix = \"firestore-sync\",\n maxDlqAttempts = 5,\n workerOptions,\n repos: repoConfigs = {} as Record<\n string,\n RepoSyncConfig<string> | undefined\n >,\n } = config;\n\n // Normalize adapters list\n const normalizedRawAdapters: any[] = rawAdaptersList\n ? rawAdaptersList\n : Array.isArray(rawAdapter)\n ? rawAdapter\n : rawAdapter\n ? [rawAdapter]\n : [];\n\n const adapters: SyncAdapter[] = normalizedRawAdapters.map((a) =>\n typeof a === \"function\" ? a() : a,\n );\n\n function getAdaptersForRepo(repoName: string): SyncAdapter[] {\n const repoCfg = repoConfigs[repoName];\n if (repoCfg?.adapters && repoCfg.adapters.length > 0) {\n const allowed = new Set(repoCfg.adapters);\n return adapters.filter((a) => allowed.has(a.name));\n }\n return adapters;\n }\n\n // Build per-repo/per-adapter queues lazily\n const queues = new Map<string, SyncQueue>();\n\n function getQueue(\n repoName: string,\n adapter: SyncAdapter,\n primaryKey: string,\n ): SyncQueue {\n const queueKey = `${repoName}:${adapter.name}`;\n let q = queues.get(queueKey);\n if (q) return q;\n\n const repoCfg = repoConfigs[repoName];\n const tableName = repoCfg?.tableName ?? repoName;\n\n // Per-adapter DLQ topic for isolated failure recovery\n const dlTopicName = `${topicPrefix}-${repoName}-${adapter.name}-dlq`;\n const dlTopic = deps.pubsub.topic(dlTopicName);\n let dlTopicEnsured = false;\n\n const ensureDlTopic = async (): Promise<void> => {\n if (dlTopicEnsured) return;\n try {\n await dlTopic.create();\n console.info(\n `[SyncWorker:${adapter.name}] Created DLQ topic \"${dlTopicName}\"`,\n );\n } catch (e: unknown) {\n if ((e as { code?: number })?.code !== 6) throw e; // 6 = ALREADY_EXISTS\n }\n dlTopicEnsured = true;\n };\n\n const onFlushError = async (\n events: SyncEvent[],\n error: unknown,\n ): Promise<void> => {\n console.error(\n `[SyncWorker:${adapter.name}] Flush failed for \"${repoName}\" (${events.length} events):`,\n error,\n );\n await ensureDlTopic();\n\n await Promise.all(\n events.map((evt) => {\n const attempts = (evt.attempts ?? 0) + 1;\n if (maxDlqAttempts > 0 && attempts > maxDlqAttempts) {\n console.error(\n `[SyncWorker:${adapter.name}] Dropping event for \"${repoName}\" after ${attempts - 1} DLQ attempts:`,\n { docId: evt.docId, operation: evt.operation },\n );\n return Promise.resolve();\n }\n const payload: SyncEvent = {\n ...evt,\n attempts,\n firstFailedAt: evt.firstFailedAt ?? Date.now(),\n };\n return dlTopic.publishMessage({ json: payload });\n }),\n );\n };\n\n q = new SyncQueue({\n adapter,\n tableName,\n primaryKey,\n batchSize,\n flushIntervalMs,\n onFlushError,\n });\n queues.set(queueKey, q);\n // Also alias by repoName for single-adapter convenience\n if (!queues.has(repoName)) {\n queues.set(repoName, q);\n }\n return q;\n }\n\n // Message handler (works with or without Cloud Functions wrapper)\n async function handleMessage(syncEvent: SyncEvent): Promise<void> {\n const { repoName } = syncEvent;\n const repo = (repoMapping as Record<string, any>)[repoName];\n if (!repo) {\n console.warn(`[SyncWorker] Unknown repo \"${repoName}\", skipping event`);\n return;\n }\n\n const documentKey: string =\n (repo as any)._systemKeys?.[0] ?? (repo as any).documentKey ?? \"docId\";\n\n const repoCfg = repoConfigs[repoName];\n const columnMap = repoCfg?.columnMap as Record<string, string> | undefined;\n const primaryKey = columnMap?.[documentKey] ?? documentKey;\n\n if (syncEvent.data) {\n syncEvent.data[SYNC_VERSION_COLUMN] = syncEvent.version ?? Date.now();\n }\n\n const targetAdapters = getAdaptersForRepo(repoName);\n for (const adapter of targetAdapters) {\n if (autoMigrate) {\n const schema: z.ZodObject<any> | undefined =\n (repo as any).schema ?? undefined;\n if (schema) {\n const tableName = repoCfg?.tableName ?? repoName;\n await ensureMigratedTarget(\n repoName,\n adapter,\n schema,\n tableName,\n primaryKey,\n repoCfg?.exclude,\n columnMap,\n );\n }\n }\n\n const queue = getQueue(repoName, adapter, primaryKey);\n queue.enqueue(syncEvent);\n }\n }\n\n // Cloud Function v2 PubSub handler\n function createHandler(topicName: string) {\n const handlerFn = async (event: any) => {\n const data: SyncEvent = event.data?.message?.json ?? event.data?.json;\n if (!data) {\n console.warn(\"[SyncWorker] Received empty PubSub message\");\n return;\n }\n await handleMessage(data);\n\n // Flush all queues associated with this repo\n const targetAdapters = getAdaptersForRepo(data.repoName);\n for (const adapter of targetAdapters) {\n const queueKey = `${data.repoName}:${adapter.name}`;\n const q = queues.get(queueKey);\n if (q) await q.flush();\n }\n };\n\n if (workerOptions) {\n return deps.pubsubHandler.onMessagePublished(\n { topic: topicName, ...workerOptions },\n handlerFn,\n );\n }\n return deps.pubsubHandler.onMessagePublished(topicName, handlerFn);\n }\n\n return {\n /** Process a SyncEvent directly (for testing or custom PubSub integration). */\n handleMessage,\n /** Create a Cloud Function handler for a specific PubSub topic. */\n createHandler,\n /** Internal queue map (for testing). */\n queues,\n /** Flush all queues and stop timers. */\n async shutdown(): Promise<void> {\n const promises: Promise<void>[] = [];\n const visited = new Set<SyncQueue>();\n for (const q of queues.values()) {\n if (!visited.has(q)) {\n visited.add(q);\n promises.push(q.shutdown());\n }\n }\n await Promise.all(promises);\n },\n };\n}\n","/**\n * Unified wrapper — combines triggers + worker + admin into a single call.\n *\n * @example\n * ```typescript\n * import { onDocumentWritten } from \"firebase-functions/v2/firestore\";\n * import * as pubsubHandler from \"firebase-functions/v2/pubsub\";\n * import { PubSub } from \"@google-cloud/pubsub\";\n *\n * const sync = createFirestoreSync(repos, {\n * deps: { firestoreTriggers: { onDocumentWritten }, pubsubHandler, pubsub: new PubSub() },\n * adapters: [bigqueryAdapter, meilisearchAdapter],\n * topicPrefix: \"firestore-sync\",\n * autoMigrate: true,\n * admin: {\n * auth: { type: \"basic\", username: \"admin\", password: \"secret\" },\n * featuresFlag: { healthCheck: true, manualSync: true },\n * },\n * repos: {\n * users: { exclude: [\"documentPath\"], columnMap: { docId: \"user_id\" } },\n * posts: { columnMap: { docId: \"post_id\" } },\n * },\n * });\n *\n * // Triggers + PubSub handlers\n * export const { users_onSync, posts_onSync, sync_users, sync_posts } = sync.functions;\n *\n * // Admin endpoint — wrap with onRequest yourself or pass onRequest in config\n * export const adminsync = onRequest(sync.adminHandler!);\n * ```\n */\n\nimport { createadminsyncServer } from \"./admin\";\nimport type { SyncQueue } from \"./queue\";\nimport { createSyncTriggers } from \"./triggers\";\nimport type {\n FirestoreSyncConfig,\n OrFactory,\n RepoSyncConfig,\n SyncAdapter,\n SyncEvent,\n} from \"./types\";\nimport { createSyncWorker } from \"./worker\";\n\nconst DEFAULT_TOPIC_PREFIX = \"firestore-sync\";\n\n/**\n * Wraps a value-or-factory into a lazy proxy that only instantiates\n * when a property is first accessed. If the value is already an instance,\n * returns it as-is (zero overhead).\n */\nfunction lazyProxy<T extends object>(v: OrFactory<T>): T {\n if (typeof v !== \"function\") return v;\n const factory = v as () => T;\n let instance: T | undefined;\n return new Proxy({} as T, {\n get(_, prop) {\n if (!instance) instance = factory();\n return (instance as any)[prop];\n },\n has(_, prop) {\n if (!instance) instance = factory();\n return prop in (instance as object);\n },\n });\n}\n\nexport function createFirestoreSync<M extends Record<string, any>>(\n repoMapping: M,\n config: FirestoreSyncConfig<NoInfer<M>>,\n) {\n const {\n deps,\n adapter: rawAdapter,\n adapters: rawAdaptersList,\n topicPrefix = DEFAULT_TOPIC_PREFIX,\n batchSize,\n flushIntervalMs,\n autoMigrate,\n admin: adminConfig,\n workerOptions,\n triggerOptions,\n repos: repoConfigs,\n } = config;\n\n // Resolve lazy deps\n const pubsub = lazyProxy(deps.pubsub);\n\n const rawAdapters = rawAdaptersList\n ? rawAdaptersList\n : Array.isArray(rawAdapter)\n ? rawAdapter\n : rawAdapter\n ? [rawAdapter]\n : [];\n\n const adapters: SyncAdapter[] = rawAdapters.map((a) => lazyProxy(a as any));\n\n // Create triggers (Firestore → PubSub)\n const triggers = createSyncTriggers(repoMapping, {\n deps: { firestoreTriggers: deps.firestoreTriggers, pubsub },\n topicPrefix,\n triggerOptions,\n repos: repoConfigs,\n });\n\n // Create worker (PubSub → Target Adapters)\n const worker = createSyncWorker(repoMapping, {\n deps: { pubsubHandler: deps.pubsubHandler, pubsub },\n adapters,\n batchSize,\n flushIntervalMs,\n autoMigrate,\n topicPrefix,\n workerOptions,\n repos: repoConfigs,\n });\n\n // Auto-create a PubSub handler per active repo\n const handlers: Record<string, any> = {};\n const repoConfigsMap = repoConfigs as\n | Record<string, RepoSyncConfig<string> | undefined>\n | undefined;\n const rawMapping = (repoMapping as any)?.rawMapping;\n const configuredKeys = Object.keys(repoConfigsMap ?? {});\n const hasExplicitRepos = configuredKeys.length > 0;\n const allKeys = rawMapping ? Object.keys(rawMapping) : Object.keys(repoMapping);\n const activeRepoNames = hasExplicitRepos\n ? configuredKeys.filter((name) => allKeys.includes(name) || name in repoMapping)\n : allKeys;\n\n for (const repoName of activeRepoNames) {\n const rawMapping = (repoMapping as any)?.rawMapping;\n const isGroup = rawMapping\n ? !!rawMapping[repoName]?.isGroup\n : !!(repoMapping[repoName] as any)?._isGroup;\n const rawPath: string | undefined = rawMapping\n ? rawMapping[repoName]?.path\n : (repoMapping[repoName] as any)?._collectionPath;\n const hasTemplateTriggerPath =\n typeof rawPath === \"string\" && rawPath.includes(\"/\");\n if (\n !hasExplicitRepos &&\n isGroup &&\n !repoConfigsMap?.[repoName]?.triggerPath &&\n !hasTemplateTriggerPath\n ) {\n continue;\n }\n\n handlers[`sync_${repoName}`] = worker.createHandler(\n `${topicPrefix}-${repoName}`,\n );\n }\n\n // Optional admin endpoint\n let adminHandler: ((req: any, res: any) => Promise<void>) | null = null;\n if (adminConfig) {\n adminHandler = createadminsyncServer(\n repoMapping,\n adapters,\n worker.queues as Map<string, SyncQueue>,\n worker.handleMessage as (event: SyncEvent) => Promise<void>,\n adminConfig,\n (repoConfigs ?? {}) as Record<string, RepoSyncConfig<string> | undefined>,\n pubsub,\n topicPrefix,\n );\n // If onRequest is provided, wrap it as a Cloud Function automatically.\n // Otherwise expose the raw handler so the user can wrap it.\n handlers[\"adminsync\"] = adminConfig.onRequest\n ? adminConfig.httpsOptions\n ? adminConfig.onRequest(adminConfig.httpsOptions, adminHandler)\n : adminConfig.onRequest(adminHandler)\n : adminHandler;\n }\n\n const result = {\n /** All Cloud Functions (triggers + handlers + optional admin) — spread into exports */\n functions: { ...triggers, ...handlers } as Record<string, any>,\n /**\n * Raw admin HTTP handler — wrap with `onRequest()` yourself if you\n * didn't pass `onRequest` in the admin config.\n * @example\n * ```ts\n * export const adminsync = onRequest(sync.adminHandler!);\n * ```\n */\n adminHandler: adminHandler as\n | ((req: any, res: any) => Promise<void>)\n | null,\n /** Process a SyncEvent directly (for testing) */\n handleMessage: worker.handleMessage as (event: SyncEvent) => Promise<void>,\n /** Internal queue map (for testing) */\n queues: worker.queues as Map<string, SyncQueue>,\n /** Flush all queues and stop timers */\n shutdown: worker.shutdown as () => Promise<void>,\n };\n\n // Hide non-function properties from Firebase's recursive discovery.\n // Only `functions` is enumerable — the rest is accessible but invisible to Object.keys().\n for (const key of [\n \"adminHandler\",\n \"handleMessage\",\n \"queues\",\n \"shutdown\",\n ] as const) {\n Object.defineProperty(result, key, { enumerable: false });\n }\n\n return result;\n}\n","/**\n * DDL generator — produces CREATE TABLE / ALTER TABLE statements from\n * SqlColumn definitions and a SqlDialect.\n *\n * `generateDDL()` is the public entry point: it walks a repository mapping,\n * converts each repo's Zod schema to columns, and returns the full DDL\n * as a single string.\n */\n\nimport { z } from \"zod\";\nimport { zodSchemaToColumns } from \"./schema-mapper\";\nimport type {\n GenerateDDLConfig,\n RepoSyncConfig,\n SqlColumn,\n SqlDialect,\n SqlTableDef,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Low-level DDL helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Generate a CREATE TABLE statement from a table definition.\n * Uses the dialect for identifier quoting and type mapping.\n *\n * NOTE: This produces preview/export DDL with unqualified table names.\n * For actual execution, use `adapter.createTable()` which handles\n * dataset/schema qualification internally.\n */\nexport function createTableDDL(\n dialect: SqlDialect,\n table: SqlTableDef,\n): string {\n const cols = table.columns\n .map((c) => {\n const notNull = c.isPrimaryKey ? \" NOT NULL\" : \"\";\n return ` ${dialect.quoteIdentifier(c.name)} ${c.sqlType}${notNull}`;\n })\n .join(\",\\n\");\n\n return `CREATE TABLE IF NOT EXISTS ${dialect.quoteIdentifier(table.tableName)} (\\n${cols}\\n);`;\n}\n\n/**\n * Generate ALTER TABLE ADD COLUMN statements for columns missing from an\n * existing table.\n *\n * NOTE: This produces preview/export DDL with unqualified table names.\n * For actual execution, use `adapter.addColumns()` which handles\n * dataset/schema qualification internally.\n */\nexport function addColumnsDDL(\n dialect: SqlDialect,\n tableName: string,\n columns: SqlColumn[],\n): string {\n return columns\n .map(\n (c) =>\n `ALTER TABLE ${dialect.quoteIdentifier(tableName)} ADD COLUMN ${dialect.quoteIdentifier(c.name)} ${c.sqlType};`,\n )\n .join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// High-level DDL generation\n// ---------------------------------------------------------------------------\n\n/**\n * Walk a full repository mapping and produce DDL for every repo that has a\n * Zod schema attached.\n *\n * @param repoMapping - Object whose values expose `.schema` (ZodObject)\n * @param dialect - Target SQL dialect\n * @param config - Optional per-repo overrides (table name, exclusions…)\n * @returns Complete DDL string (one CREATE TABLE per repo, separated by newlines)\n */\nexport function generateDDL<M extends Record<string, any>>(\n repoMapping: M,\n dialect: SqlDialect,\n config?: GenerateDDLConfig<NoInfer<M>>,\n): string {\n const statements: string[] = [];\n\n for (const [repoName, repo] of Object.entries(repoMapping) as [\n string,\n any,\n ][]) {\n const schema: z.ZodObject<any> | undefined =\n repo.schema ?? (repo as any)._schema ?? undefined;\n if (!schema) continue;\n\n const repoCfg = (\n config?.repos as Record<string, RepoSyncConfig<string>> | undefined\n )?.[repoName];\n const tableName = repoCfg?.tableName ?? repoName;\n\n // Detect documentKey from repo metadata\n const documentKey: string =\n (repo as any)._systemKeys?.[0] ?? (repo as any).documentKey ?? \"docId\";\n\n const columns = zodSchemaToColumns(schema, dialect, {\n primaryKey: documentKey,\n exclude: repoCfg?.exclude,\n columnMap: repoCfg?.columnMap as Record<string, string> | undefined,\n });\n\n const tableDef: SqlTableDef = { tableName, columns };\n statements.push(createTableDDL(dialect, tableDef));\n }\n\n return statements.join(\"\\n\\n\");\n}\n","/**\n * Migration manager — generates DDL and optionally auto-migrates SQL tables\n * to match the Zod schemas defined in a repository mapping.\n *\n * Migrations are **additive only**: new columns are added, existing columns\n * are never dropped or modified.\n */\n\nimport { z } from \"zod\";\nimport { zodSchemaToColumns } from \"./schema-mapper\";\nimport type {\n GenerateDDLConfig,\n RepoSyncConfig,\n SqlAdapter,\n SqlColumn,\n SqlTableDef,\n} from \"./types\";\n\nexport interface MigrateResult {\n /** Tables that were created from scratch */\n created: string[];\n /** Tables that had columns added */\n altered: string[];\n /** Tables that were already up-to-date */\n upToDate: string[];\n /** Tables skipped (no schema available) */\n skipped: string[];\n}\n\n/**\n * Auto-migrate all repos: create missing tables, add missing columns.\n *\n * @returns Summary of what was done per table.\n */\nexport async function autoMigrate<M extends Record<string, any>>(\n repoMapping: M,\n adapter: SqlAdapter,\n config?: GenerateDDLConfig<NoInfer<M>>,\n): Promise<MigrateResult> {\n const result: MigrateResult = {\n created: [],\n altered: [],\n upToDate: [],\n skipped: [],\n };\n\n for (const [repoName, repo] of Object.entries(repoMapping) as [\n string,\n any,\n ][]) {\n const schema: z.ZodObject<any> | undefined =\n (repo as any).schema ?? undefined;\n if (!schema) {\n result.skipped.push(repoName);\n continue;\n }\n\n const repoCfg = (\n config?.repos as Record<string, RepoSyncConfig<string>> | undefined\n )?.[repoName];\n const tableName = repoCfg?.tableName ?? repoName;\n const documentKey: string =\n (repo as any)._systemKeys?.[0] ?? (repo as any).documentKey ?? \"docId\";\n\n const columns = zodSchemaToColumns(schema, adapter.dialect, {\n primaryKey: documentKey,\n exclude: repoCfg?.exclude,\n columnMap: repoCfg?.columnMap as Record<string, string> | undefined,\n });\n\n const tableDef: SqlTableDef = { tableName, columns };\n const exists = await adapter.tableExists(tableName);\n\n if (!exists) {\n await adapter.createTable(tableDef);\n result.created.push(tableName);\n } else {\n const existingCols = new Set(await adapter.getTableColumns(tableName));\n const newCols: SqlColumn[] = columns.filter(\n (c) => !existingCols.has(c.name),\n );\n\n if (newCols.length > 0) {\n await adapter.addColumns(tableName, newCols);\n result.altered.push(tableName);\n } else {\n result.upToDate.push(tableName);\n }\n }\n }\n\n return result;\n}\n","/**\n * Meilisearch adapter — streams Firestore changes to Meilisearch indexes.\n *\n * @example\n * ```ts\n * import { MeilisearchAdapter } from \"@lpdjs/firestore-repo-service/sync/meilisearch\";\n *\n * const adapter = new MeilisearchAdapter({\n * host: \"http://localhost:7700\",\n * apiKey: \"masterKey\",\n * indexesSettings: {\n * users: {\n * filterableAttributes: [\"role\", \"status\", \"createdAt\"],\n * sortableAttributes: [\"createdAt\", \"name\"],\n * searchableAttributes: [\"name\", \"email\"],\n * },\n * },\n * });\n * ```\n */\n\nimport type { z } from \"zod\";\nimport { unflattenDocument } from \"../serializer\";\nimport type {\n ExtractRepoFieldPaths,\n RepoSyncConfig,\n SyncAdapter,\n SyncHealthResult,\n} from \"../types\";\n\n/**\n * Minimal structural shape of a Meilisearch client.\n */\nexport interface MeilisearchLike {\n index(indexUid: string): {\n addDocuments(documents: any[], options?: { primaryKey?: string }): Promise<any>;\n deleteDocuments(documentIds: string[] | number[]): Promise<any>;\n getStats(): Promise<any>;\n getRawInfo(): Promise<any>;\n updateSettings(settings: any): Promise<any>;\n [key: string]: any;\n };\n getIndex(indexUid: string): Promise<any>;\n createIndex(indexUid: string, options?: { primaryKey?: string }): Promise<any>;\n isHealthy?(): Promise<any>;\n health?(): Promise<any>;\n getVersion?(): Promise<any>;\n}\n\nexport interface MeilisearchIndexSettings<Fields extends string = string> {\n /**\n * Fields displayed in the returned documents. Defaults to `[\"*\"]`.\n */\n displayedAttributes?: (Fields | \"*\")[];\n /**\n * Alias for `displayedAttributes` (Algolia-style naming).\n */\n retrievableAttributes?: (Fields | \"*\")[];\n /**\n * Alias for `displayedAttributes`.\n */\n attributesToRetrieve?: (Fields | \"*\")[];\n /**\n * Fields that are searched for query words. Defaults to `[\"*\"]`.\n */\n searchableAttributes?: (Fields | \"*\")[];\n /**\n * Fields that can be filtered using the `filter` search parameter.\n */\n filterableAttributes?: Fields[];\n /**\n * Fields that can be sorted using the `sort` search parameter.\n */\n sortableAttributes?: Fields[];\n /**\n * Custom ranking rules for search result scoring.\n */\n rankingRules?: string[];\n /**\n * List of words ignored during search queries.\n */\n stopWords?: string[];\n /**\n * Custom synonyms map.\n */\n synonyms?: Record<string, string[]>;\n /**\n * Field used to deduplicate search results.\n */\n distinctAttribute?: Fields | null;\n /**\n * Typo tolerance settings.\n */\n typoTolerance?: Record<string, any>;\n /**\n * Faceting settings.\n */\n faceting?: Record<string, any>;\n /**\n * Pagination limits (e.g. `maxTotalHits`).\n */\n pagination?: { maxTotalHits?: number; [key: string]: any };\n /**\n * Custom separator tokens.\n */\n separatorTokens?: string[];\n /**\n * Custom non-separator tokens.\n */\n nonSeparatorTokens?: string[];\n /**\n * Custom dictionary words.\n */\n dictionary?: string[];\n /**\n * Proximity precision mode (\"byWord\" or \"byAttribute\").\n */\n proximityPrecision?: \"byWord\" | \"byAttribute\";\n /**\n * Maximum search duration before timeout in ms.\n */\n searchCutoffMs?: number;\n [key: string]: any;\n}\n\n/**\n * Typed index settings map constrained to the repos in repository mapping `M`.\n * Field attributes autocomplete and check dot-notation nested paths.\n */\nexport type TypedMeilisearchIndexesSettings<M> = {\n [K in string & keyof M]?: MeilisearchIndexSettings<ExtractRepoFieldPaths<M[K]>>;\n};\n\nexport interface MeilisearchAdapterOptions<\n M extends Record<string, any> = Record<string, any>,\n> {\n /**\n * Host URL of the Meilisearch instance (e.g. `http://localhost:7700` or `https://ms-xxxx.meilisearch.io`).\n * Required if `client` is not provided.\n */\n host?: string;\n /**\n * API Key (e.g. master key or admin key) with permissions to read/write indexes.\n */\n apiKey?: string;\n /**\n * Existing pre-built Meilisearch client instance.\n */\n client?: MeilisearchLike | any;\n /**\n * Custom index settings per target index name (e.g. filterableAttributes, sortableAttributes).\n * When typed with repository mapping `M`, keys are constrained to repo names and attributes\n * are typed with dot-notation field paths.\n */\n indexesSettings?: string extends keyof M\n ? Record<string, MeilisearchIndexSettings>\n : TypedMeilisearchIndexesSettings<M>;\n /**\n * Whether to automatically unflatten double-underscore keys (`address__city` → `address.city`)\n * and parse stringified JSON arrays back into native arrays.\n * Default: `true`.\n */\n unflatten?: boolean;\n /**\n * Optional custom document transformation before indexing in Meilisearch.\n */\n transformDoc?: (doc: Record<string, unknown>) => Record<string, unknown>;\n}\n\n/** Lazy-loader for the optional `meilisearch` peer dependency. */\nfunction loadMeilisearchClient(options: MeilisearchAdapterOptions<any>): MeilisearchLike {\n if (options.client) return options.client;\n if (!options.host) {\n throw new Error(\n \"MeilisearchAdapter requires either a `client` instance or a `host` option.\",\n );\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { MeiliSearch } = require(\"meilisearch\");\n return new MeiliSearch({\n host: options.host,\n apiKey: options.apiKey,\n });\n } catch (err: any) {\n throw new Error(\n `Failed to load the \"meilisearch\" package. Please install it with:\\n` +\n ` bun add meilisearch # or npm install meilisearch\\n` +\n `Original error: ${err?.message ?? String(err)}`,\n );\n }\n}\n\nfunction areMeiliSettingsEqual(current: any, desired: any): boolean {\n if (!current || !desired) return false;\n for (const [key, value] of Object.entries(desired)) {\n if (value === undefined) continue;\n const curVal = current[key];\n if (Array.isArray(value)) {\n if (!Array.isArray(curVal)) return false;\n if (value.length !== curVal.length) return false;\n for (let i = 0; i < value.length; i++) {\n if (value[i] !== curVal[i]) return false;\n }\n } else if (typeof value === \"object\" && value !== null) {\n if (JSON.stringify(value) !== JSON.stringify(curVal)) return false;\n } else {\n if (value !== curVal) return false;\n }\n }\n return true;\n}\n\n/**\n * SyncAdapter implementation for Meilisearch.\n */\nexport class MeilisearchAdapter<\n M extends Record<string, any> = Record<string, any>,\n> implements SyncAdapter {\n readonly name = \"meilisearch\";\n private _client: MeilisearchLike | null = null;\n private readonly options: MeilisearchAdapterOptions<M>;\n\n constructor(options: MeilisearchAdapterOptions<M>) {\n this.options = options;\n if (options.client) {\n this._client = options.client;\n }\n }\n\n /** Configured index settings */\n get indexesSettings(): MeilisearchAdapterOptions<M>[\"indexesSettings\"] {\n return this.options.indexesSettings;\n }\n\n /** Resolved Meilisearch client instance. */\n get client(): MeilisearchLike {\n if (!this._client) {\n this._client = loadMeilisearchClient(this.options);\n }\n return this._client;\n }\n\n // ---------------------------------------------------------------------------\n // SyncAdapter Methods\n // ---------------------------------------------------------------------------\n\n async targetExists(targetName: string): Promise<boolean> {\n try {\n await this.client.getIndex(targetName);\n return true;\n } catch (err: any) {\n if (\n err?.code === \"index_not_found\" ||\n err?.cause?.code === \"index_not_found\" ||\n err?.statusCode === 404 ||\n err?.status === 404 ||\n err?.response?.status === 404 ||\n err?.cause?.status === 404 ||\n err?.cause?.statusCode === 404 ||\n err?.cause?.response?.status === 404\n ) {\n return false;\n }\n throw err;\n }\n }\n\n async upsert(\n targetName: string,\n items: Record<string, unknown>[],\n primaryKey: string,\n ): Promise<void> {\n if (items.length === 0) return;\n const shouldUnflatten = this.options.unflatten !== false;\n const docs = items.map((item) => {\n let doc = shouldUnflatten ? unflattenDocument(item) : item;\n if (typeof this.options.transformDoc === \"function\") {\n doc = this.options.transformDoc(doc);\n }\n return doc;\n });\n const index = this.client.index(targetName);\n await index.addDocuments(docs, { primaryKey });\n }\n\n async delete(\n targetName: string,\n _primaryKey: string,\n ids: string[],\n ): Promise<void> {\n if (ids.length === 0) return;\n const index = this.client.index(targetName);\n await index.deleteDocuments(ids);\n }\n\n async ensureTarget(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n exclude?: string[];\n columnMap?: Record<string, string>;\n }): Promise<void> {\n const { targetName, primaryKey } = options;\n const exists = await this.targetExists(targetName);\n if (!exists) {\n await this.client.createIndex(targetName, { primaryKey });\n }\n\n const rawSettings = this.options.indexesSettings?.[targetName];\n if (rawSettings) {\n const { retrievableAttributes, attributesToRetrieve, ...rest } = rawSettings;\n const settings = {\n ...rest,\n displayedAttributes:\n rest.displayedAttributes ?? retrievableAttributes ?? attributesToRetrieve,\n };\n if (settings.displayedAttributes === undefined) {\n delete (settings as any).displayedAttributes;\n }\n\n const index = this.client.index(targetName);\n if (typeof index.getSettings === \"function\") {\n try {\n const current = await index.getSettings();\n if (areMeiliSettingsEqual(current, settings)) {\n return;\n }\n } catch {\n // If reading current settings fails, fallback to updating\n }\n }\n\n await index.updateSettings(settings);\n }\n }\n\n async healthCheck(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n repoConfig?: RepoSyncConfig<string>;\n }): Promise<SyncHealthResult> {\n const { targetName } = options;\n try {\n const exists = await this.targetExists(targetName);\n if (!exists) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: `Meilisearch index \"${targetName}\" does not exist`,\n };\n }\n const index = this.client.index(targetName);\n const stats = await index.getStats();\n const rawInfo = typeof index.getRawInfo === \"function\" ? await index.getRawInfo() : {};\n\n return {\n healthy: true,\n targetName,\n targetExists: true,\n error: null,\n details: {\n numberOfDocuments: stats?.numberOfDocuments ?? 0,\n isIndexing: stats?.isIndexing ?? false,\n fieldDistribution: stats?.fieldDistribution ?? {},\n primaryKey: rawInfo?.primaryKey ?? options.primaryKey,\n },\n };\n } catch (err: any) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: err?.message ?? String(err),\n };\n }\n }\n\n /** Verify overall connection and connectivity to the Meilisearch instance. */\n async checkConnection(): Promise<{\n healthy: boolean;\n version?: string;\n error?: string;\n }> {\n try {\n let isHealthy = true;\n if (typeof this.client.isHealthy === \"function\") {\n const res = await this.client.isHealthy();\n isHealthy = res?.status === \"available\" || res === true;\n } else if (typeof this.client.health === \"function\") {\n const res = await this.client.health();\n isHealthy = res?.status === \"available\" || res === true;\n }\n let version: string | undefined;\n if (typeof this.client.getVersion === \"function\") {\n const v = await this.client.getVersion();\n version = v?.pkgVersion;\n }\n return { healthy: isHealthy, version };\n } catch (e: any) {\n return { healthy: false, error: e?.message ?? String(e) };\n }\n }\n}\n\n/**\n * Type-safe factory helper for creating a Meilisearch adapter bound to a repository mapping `M`.\n * Provides full autocompletion and strict type checking on repository names and nested field paths.\n *\n * @example\n * ```ts\n * const adapter = defineMeilisearchAdapter<typeof repos>({\n * client: createMeilisearchClient(),\n * indexesSettings: {\n * adminUsers: {\n * searchableAttributes: [\"docId\", \"baseUser.email\"],\n * },\n * },\n * });\n * ```\n */\nexport function defineMeilisearchAdapter<\n M extends Record<string, any> = Record<string, any>,\n>(options: MeilisearchAdapterOptions<M>): () => MeilisearchAdapter<M> {\n return () => new MeilisearchAdapter<M>(options);\n}\n"]}