@gusto/baerly-storage 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/dist/API.md +59 -7
- package/dist/{app-config-Dj_nGBfj.d.ts → app-config-C0Bbw_Z6.d.ts} +9 -9
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/baerly.js +10 -10
- package/dist/baerly.js.map +1 -1
- package/dist/bytes-BXdamO3L.js +11 -0
- package/dist/bytes-BXdamO3L.js.map +1 -0
- package/dist/{client-CC5yVs1S.d.ts → client-DYZfoZb9.d.ts} +3 -3
- package/dist/client-react.d.ts +3 -3
- package/dist/client.d.ts +3 -3
- package/dist/cloudflare.d.ts +31 -4
- package/dist/cloudflare.js +72 -6
- package/dist/cloudflare.js.map +1 -1
- package/dist/{config-Bsg8wgwo.js → config-DVfDGyw1.js} +82 -2
- package/dist/config-DVfDGyw1.js.map +1 -0
- package/dist/{context-Oj7ffwD-.js → context-DRZ3tZ5l.js} +3 -2
- package/dist/{context-Oj7ffwD-.js.map → context-DRZ3tZ5l.js.map} +1 -1
- package/dist/{cost-B1WiZxlf.js → cost-CQt1YRkA.js} +3 -4
- package/dist/{cost-B1WiZxlf.js.map → cost-CQt1YRkA.js.map} +1 -1
- package/dist/{current-json-BkatBzF7.js → current-json-C-EyJqs0.js} +107 -5
- package/dist/current-json-C-EyJqs0.js.map +1 -0
- package/dist/{db-aRMK_0R0.d.ts → db-BM3y2JQw.d.ts} +3 -3
- package/dist/{deploy-BB-wqbhf.js → deploy-CrAbfgCq.js} +2 -2
- package/dist/{deploy-BB-wqbhf.js.map → deploy-CrAbfgCq.js.map} +1 -1
- package/dist/dev-vite.d.ts +3 -3
- package/dist/dev-vite.js +3 -3
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-B8h9GCN9.js → doctor-Db-hzPmE.js} +144 -7
- package/dist/doctor-Db-hzPmE.js.map +1 -0
- package/dist/{dump-BHo_sIMZ.js → dump-BYA55NLP.js} +3 -4
- package/dist/{dump-BHo_sIMZ.js.map → dump-BYA55NLP.js.map} +1 -1
- package/dist/errors-DOdL95kK.js.map +1 -1
- package/dist/{export-Dz2PZKSR.js → export-Bhbz90-z.js} +4 -5
- package/dist/{export-Dz2PZKSR.js.map → export-Bhbz90-z.js.map} +1 -1
- package/dist/{fsck-DEz9lyCy.js → fsck-CPPZWt9p.js} +5 -8
- package/dist/fsck-CPPZWt9p.js.map +1 -0
- package/dist/{http-DeJEeUcO.js → http-Cw8p6y5b.js} +5 -5
- package/dist/{http-DeJEeUcO.js.map → http-Cw8p6y5b.js.map} +1 -1
- package/dist/http.d.ts +3 -3
- package/dist/http.js +1 -1
- package/dist/{index-m6pY8iRU.d.ts → index-C3JAH1Yo.d.ts} +14 -2
- package/dist/{index-5lX_5NxZ.d.ts → index-DSvwEUeF.d.ts} +63 -54
- package/dist/{index-DPaQhAro.d.ts → index-DwDTWPSU.d.ts} +2 -2
- package/dist/{index-spCBsIwm.d.ts → index-cUY-36AN.d.ts} +3 -3
- package/dist/index.d.ts +5 -5
- package/dist/index.js +3 -3
- package/dist/{indexes-BIH73Uv4.d.ts → indexes-DAu2AkTW.d.ts} +2 -2
- package/dist/{inspect-x02aFWnh.js → inspect-Bdbzvi-_.js} +5 -6
- package/dist/{inspect-x02aFWnh.js.map → inspect-Bdbzvi-_.js.map} +1 -1
- package/dist/maintenance-BRrThz8V.d.ts +449 -0
- package/dist/maintenance-BvOv6BMM.js +1295 -0
- package/dist/maintenance-BvOv6BMM.js.map +1 -0
- package/dist/maintenance-ClzBC1Vv.js +1895 -0
- package/dist/maintenance-ClzBC1Vv.js.map +1 -0
- package/dist/maintenance.d.ts +2 -323
- package/dist/maintenance.js +2 -2
- package/dist/node.d.ts +20 -79
- package/dist/node.js +2 -2
- package/dist/{observability-2IDYRuZK.js → observability-CpOiEN0k.js} +2 -2
- package/dist/{observability-2IDYRuZK.js.map → observability-CpOiEN0k.js.map} +1 -1
- package/dist/observability.d.ts +2 -2
- package/dist/observability.js +2 -2
- package/dist/{plan-Cs17VqjU.js → plan-DOTl21vq.js} +3 -4
- package/dist/{plan-Cs17VqjU.js.map → plan-DOTl21vq.js.map} +1 -1
- package/dist/{query-DcSbFLJt.js → query-BmiQy328.js} +58 -26
- package/dist/query-BmiQy328.js.map +1 -0
- package/dist/{rebuild-index-DwXM0WfA.js → rebuild-index-DC_nR6wP.js} +4 -5
- package/dist/{rebuild-index-DwXM0WfA.js.map → rebuild-index-DC_nR6wP.js.map} +1 -1
- package/dist/{restore-CbKVMMpm.js → restore-C6IcmLeA.js} +44 -120
- package/dist/restore-C6IcmLeA.js.map +1 -0
- package/dist/{log-walk-DIru96UT.js → snapshot-SS8USDUF.js} +187 -20
- package/dist/snapshot-SS8USDUF.js.map +1 -0
- package/dist/{src-Cr9C7_tT.js → src-DU1sCMlr.js} +315 -278
- package/dist/src-DU1sCMlr.js.map +1 -0
- package/dist/{src-n0Te1r98.js → src-QQ7jDeL2.js} +25 -6
- package/dist/src-QQ7jDeL2.js.map +1 -0
- package/dist/{src-Chafbw8r.js → src-zhEAmmF7.js} +35 -4
- package/dist/src-zhEAmmF7.js.map +1 -0
- package/dist/{bucket-uri-BrDEYvzy.js → subcommand-DZcHcsYp.js} +222 -22
- package/dist/subcommand-DZcHcsYp.js.map +1 -0
- package/dist/{usage-RVUQMLop.js → usage-CLjirdD-.js} +4 -4
- package/dist/{usage-RVUQMLop.js.map → usage-CLjirdD-.js.map} +1 -1
- package/dist/{validate-DhH1lO8I.js → validate-DCq_0DIn.js} +2 -2
- package/dist/validate-DCq_0DIn.js.map +1 -0
- package/package.json +13 -6
- package/dist/bucket-uri-BrDEYvzy.js.map +0 -1
- package/dist/config-Bsg8wgwo.js.map +0 -1
- package/dist/current-json-BkatBzF7.js.map +0 -1
- package/dist/doctor-B8h9GCN9.js.map +0 -1
- package/dist/fsck-DEz9lyCy.js.map +0 -1
- package/dist/indexes-BXn7a06a.js +0 -297
- package/dist/indexes-BXn7a06a.js.map +0 -1
- package/dist/log-walk-DIru96UT.js.map +0 -1
- package/dist/maintenance-Bn6ul9aV.js +0 -758
- package/dist/maintenance-Bn6ul9aV.js.map +0 -1
- package/dist/query-DcSbFLJt.js.map +0 -1
- package/dist/rebuild-index-C5gTXryd.js +0 -119
- package/dist/rebuild-index-C5gTXryd.js.map +0 -1
- package/dist/restore-CbKVMMpm.js.map +0 -1
- package/dist/snapshot-D7C4_FSl.js +0 -71
- package/dist/snapshot-D7C4_FSl.js.map +0 -1
- package/dist/snapshot-z_N9hpTe.js +0 -917
- package/dist/snapshot-z_N9hpTe.js.map +0 -1
- package/dist/src-Chafbw8r.js.map +0 -1
- package/dist/src-Cr9C7_tT.js.map +0 -1
- package/dist/src-n0Te1r98.js.map +0 -1
- package/dist/subcommand-BWs6K7zb.js +0 -110
- package/dist/subcommand-BWs6K7zb.js.map +0 -1
- package/dist/validate-DhH1lO8I.js.map +0 -1
package/dist/src-n0Te1r98.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"src-n0Te1r98.js","names":["#root","#pathFor"],"sources":["../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.browser.js","../packages/dev/src/dev-banner.ts","../packages/dev/src/dev-landing.ts","../packages/dev/src/ensure-table.ts","../packages/dev/src/local-fs.ts"],"sourcesContent":["var x=String;\nvar create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x,blackBright:x,redBright:x,greenBright:x,yellowBright:x,blueBright:x,magentaBright:x,cyanBright:x,whiteBright:x,bgBlackBright:x,bgRedBright:x,bgGreenBright:x,bgYellowBright:x,bgBlueBright:x,bgMagentaBright:x,bgCyanBright:x,bgWhiteBright:x}};\nmodule.exports=create();\nmodule.exports.createColors = create;\n","import { createColors } from \"picocolors\";\n\nexport interface DevBannerHint {\n readonly key: string;\n readonly value: string;\n}\n\nexport interface DevBannerOpts {\n readonly name: string;\n readonly primaryUrl?: { readonly label: string; readonly url: string };\n readonly apiUrl?: { readonly label: string; readonly url: string; readonly note?: string };\n readonly hints?: ReadonlyArray<DevBannerHint>;\n /** Force plain-text output (no color, no `←`). Defaults to !isTTY || CI. */\n readonly plain?: boolean;\n /** Sink. Defaults to process.stderr. */\n readonly write?: (chunk: string) => void;\n}\n\nexport function printDevBanner(opts: DevBannerOpts): void {\n const isPlain =\n opts.plain !== undefined\n ? opts.plain\n : process.env[\"CI\"] !== undefined || !process.stderr.isTTY;\n const write = opts.write ?? ((chunk) => process.stderr.write(chunk));\n const pc = createColors(!isPlain);\n const hints = opts.hints ?? [];\n\n const lines: string[] = [];\n\n if (isPlain) {\n lines.push(`baerly · ${opts.name}`);\n\n if (opts.primaryUrl) {\n lines.push(`${opts.primaryUrl.label}: ${opts.primaryUrl.url}`);\n }\n if (opts.apiUrl) {\n const note = opts.apiUrl.note ? ` (${opts.apiUrl.note})` : \"\";\n lines.push(`${opts.apiUrl.label}: ${opts.apiUrl.url}${note}`);\n }\n for (const hint of hints) {\n lines.push(`${hint.key}: ${hint.value}`);\n }\n write(lines.join(\"\\n\") + \"\\n\");\n } else {\n lines.push(pc.bold(pc.cyan(`▎ baerly · ${opts.name}`)));\n lines.push(\"\");\n\n if (opts.primaryUrl) {\n const marker = ` ${pc.green(\"← open this\")}`;\n lines.push(` ${pc.dim(opts.primaryUrl.label)} → ${opts.primaryUrl.url}${marker}`);\n }\n if (opts.apiUrl) {\n const note = opts.apiUrl.note ? ` ${pc.dim(`(${opts.apiUrl.note})`)}` : \"\";\n lines.push(` ${pc.dim(opts.apiUrl.label)} → ${opts.apiUrl.url}${note}`);\n }\n if ((opts.primaryUrl || opts.apiUrl) && hints.length > 0) {\n lines.push(\"\");\n }\n if (hints.length > 0) {\n const maxKeyLen = Math.max(...hints.map((h) => h.key.length));\n for (const hint of hints) {\n lines.push(` ${pc.dim(hint.key.padEnd(maxKeyLen))} ${hint.value}`);\n }\n }\n lines.push(\"\");\n write(lines.join(\"\\n\"));\n }\n}\n","/**\n * Dev landing page for the API root (`GET /`).\n *\n * The HTTP surface is API-only: every path outside `/v1/*`\n * returns the {@link HttpErrorEnvelope} 404 shape. That's correct for\n * production but confusing in local dev — a user who clicks the\n * `http://localhost:3000` link in their terminal sees a JSON 404 and\n * assumes the server is broken.\n *\n * Adapters that wire the {@link DevLandingOptions} opt-in surface a\n * small HTML page on `GET /` instead: app label, a clickable link to\n * the UI, a `/v1/healthz` probe link, and a note that `/v1/c/*` is\n * auth-gated. `GET /favicon.ico` answers 204 so browsers don't pin a\n * second JSON 404 next to the landing page.\n *\n * Production deployments leave the option unset; the 404 falls\n * through to the existing envelope.\n */\n\n/** Options for {@link renderDevLanding}. */\nexport interface DevLandingOptions {\n /** Bucket-prefix / app name (typically passed through from the adapter's `app` option). */\n readonly app: string;\n /** URL of the human-facing UI (e.g., `\"http://localhost:5173\"`). */\n readonly uiUrl: string;\n}\n\n/**\n * Render the dev landing page HTML. Dependency-free; system fonts\n * only; no JS. All substitutions are HTML-escaped to keep the page\n * inert even when `app` / `uiUrl` come from env vars.\n */\nexport const renderDevLanding = (opts: DevLandingOptions): string => {\n const label = escapeHtml(opts.app);\n const app = escapeHtml(opts.app);\n const uiUrl = escapeHtml(opts.uiUrl);\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>${label} — baerly api</title>\n<style>\n body { font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; max-width: 40rem; margin: 3rem auto; padding: 0 1.5rem; color: #222; line-height: 1.5; }\n h1 { font-size: 1.25rem; margin: 0 0 0.25rem; }\n p.tag { color: #666; margin: 0 0 1.5rem; font-size: 0.9rem; }\n a { color: #06c; }\n ul { padding-left: 1.25rem; }\n li { margin: 0.25rem 0; }\n code { background: #f3f3f3; padding: 0.1em 0.35em; border-radius: 3px; font-size: 0.9em; }\n</style>\n</head>\n<body>\n<h1>${label}</h1>\n<p class=\"tag\">baerly api server · app <code>${app}</code></p>\n<p>This is the API server. The UI lives at <a href=\"${uiUrl}\">${uiUrl}</a>.</p>\n<ul>\n <li>Open the UI: <a href=\"${uiUrl}\">${uiUrl}</a></li>\n <li>Health probe: <a href=\"/v1/healthz\">/v1/healthz</a></li>\n <li>CRUD routes under <code>/v1/c/*</code> require an auth header and aren't clickable from here.</li>\n</ul>\n</body>\n</html>\n`;\n};\n\nconst escapeHtml = (s: string): string =>\n s.replace(/[&<>\"']/g, (c) => {\n switch (c) {\n case \"&\": {\n return \"&\";\n }\n case \"<\": {\n return \"<\";\n }\n case \">\": {\n return \">\";\n }\n case '\"': {\n return \""\";\n }\n default: {\n return \"'\";\n }\n }\n });\n","import {\n BaerlyError,\n CURRENT_JSON_SCHEMA_VERSION,\n createCurrentJson,\n type Storage,\n} from \"@baerly/protocol\";\n\n/**\n * Optional pre-warm: idempotently create the `current.json` manifest\n * for a single `(app, tenant, table)` triple. The kernel auto-creates\n * this manifest on the first commit anyway (see `Db.create` and\n * `Writer.commit`), so calling `ensureTable` is **not required** for\n * correctness — it's a one-Class-A-PUT optimization for callers that\n * want the manifest in place before the first request lands (seed\n * scripts, deploy-time provisioning, CI fixtures that snapshot the\n * bucket between phases, etc.).\n *\n * Wraps {@link createCurrentJson} with the canonical key shape\n * (`app/<app>/tenant/<tenant>/manifests/<table>/current.json`) and\n * swallows `BaerlyError{code:\"Conflict\"}` so re-runs are safe. An\n * existing manifest is preserved verbatim — this function never\n * overwrites a populated manifest. The seed shape matches the\n * kernel's auto-create exactly, so a pre-warm and an\n * auto-provisioned bucket are byte-identical.\n *\n * @example\n * ```ts\n * import { LocalFsStorage, ensureTable } from \"@gusto/baerly-storage/dev\";\n *\n * const storage = new LocalFsStorage({ root: \"./.baerly-data\" });\n * // Pre-warm so the first request doesn't pay the bootstrap PUT.\n * await ensureTable(storage, { app: \"helpdesk\", tenant: \"demo\", table: \"tickets\" });\n * // …then `baerlyNode({ config, storage, verifier })`.\n * ```\n */\nexport const ensureTable = async (\n storage: Storage,\n args: { app: string; tenant: string; table: string },\n): Promise<void> => {\n const key = `app/${args.app}/tenant/${args.tenant}/manifests/${args.table}/current.json`;\n try {\n await createCurrentJson(storage, key, {\n schema_version: CURRENT_JSON_SCHEMA_VERSION,\n snapshot: null,\n next_seq: 0,\n log_seq_start: 0,\n writer_fence: { epoch: 0, owner: \"\", claimed_at: \"\" },\n });\n } catch (error) {\n if (error instanceof BaerlyError && error.code === \"Conflict\") {\n return;\n }\n throw error;\n }\n};\n","import { createHash } from \"node:crypto\";\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, posix, relative, resolve, sep } from \"node:path\";\nimport {\n BaerlyError,\n type Storage,\n type StorageGetOptions,\n type StorageGetResult,\n type StorageListEntry,\n type StoragePutOptions,\n type StoragePutResult,\n} from \"@baerly/protocol\";\n\nexport interface LocalFsStorageOptions {\n /** Root directory; treated as \"the bucket\". */\n root: string;\n}\n\n/**\n * `Storage` backed by a directory tree. Keys may contain `/` and map\n * to nested directories on disk so `ls`/`cat` work as expected.\n *\n * ETags are content-addressed: `\"<sha-256-hex>\"` (the surrounding\n * double-quotes match S3's wire format for non-multipart objects).\n * Identical bodies share an ETag across runs — the property that\n * makes this adapter useful for fixture-based tests.\n *\n * Writes are atomic via `writeFile(temp) + rename(final)`; readers\n * never see a partially-written file. The adapter does NOT coordinate\n * cross-process `ifMatch`/`ifNoneMatch` checks (a TOCTOU race is\n * possible if two processes write the same key concurrently).\n * Single-process `baerlyDev()` is the design center; multi-process\n * scenarios use the S3 / Minio path.\n *\n * Node-only — imports `node:fs`, `node:path`, `node:crypto`. Lives in\n * `@baerly/dev` because the protocol kernel is pure-modules / no I/O\n * and must remain Worker-bundleable.\n */\nexport class LocalFsStorage implements Storage {\n readonly #root: string;\n\n constructor(opts: LocalFsStorageOptions) {\n this.#root = resolve(opts.root);\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n let body: Buffer;\n try {\n body = await readFile(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return null;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.get(${key}): ${(error as Error).message}`,\n error,\n );\n }\n const etag = etagOf(body);\n if (opts?.ifNoneMatch !== undefined && opts.ifNoneMatch === etag) {\n // 304 Not Modified — caller's cached copy is current.\n return null;\n }\n return { body: toUint8Array(body), etag };\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n const newEtag = etagOf(body);\n\n if (opts?.ifMatch !== undefined || opts?.ifNoneMatch === \"*\") {\n // TOCTOU within a process — fine. Cross-process callers should\n // not rely on these guards (see class JSDoc).\n const existing = await readExisting(path);\n if (opts?.ifNoneMatch === \"*\" && existing !== null) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifNoneMatch=\"*\" but key exists)`,\n );\n }\n if (opts?.ifMatch !== undefined) {\n if (existing === null) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`,\n );\n }\n const currentEtag = etagOf(existing);\n if (currentEtag !== opts.ifMatch) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${currentEtag})`,\n );\n }\n }\n }\n\n await mkdir(dirname(path), { recursive: true });\n // Write to a unique temp path then rename for atomicity. Temp lives\n // in `os.tmpdir()` so a half-written file never appears under the\n // bucket root where `list` might see it. PID + timestamp + random\n // tail makes the name unique across concurrent writers in the same\n // process.\n const tmp = join(\n tmpdir(),\n `baerly-localfs-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,\n );\n await writeFile(tmp, body);\n try {\n await rename(tmp, path);\n } catch (error) {\n // Best-effort cleanup of the temp file; swallow any error there\n // so the original failure surfaces unchanged.\n await rm(tmp, { force: true }).catch(() => {});\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.put(${key}): ${(error as Error).message}`,\n error,\n );\n }\n return { etag: newEtag, serverDate: new Date() };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n try {\n await rm(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return;\n } // idempotent\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.delete(${key}): ${(error as Error).message}`,\n error,\n );\n }\n }\n\n async *list(\n prefix: string,\n opts?: {\n startAfter?: string;\n maxKeys?: number;\n signal?: AbortSignal;\n },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n const startAfter = opts?.startAfter ?? \"\";\n const maxKeys = opts?.maxKeys ?? Infinity;\n const keys: string[] = [];\n await walk(this.#root, keys);\n keys.sort();\n let yielded = 0;\n for (const key of keys) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n if (key <= startAfter) {\n continue;\n }\n if (yielded >= maxKeys) {\n return;\n }\n opts?.signal?.throwIfAborted();\n const buf = await readFile(this.#pathFor(key));\n yield { key, etag: etagOf(buf) };\n yielded += 1;\n }\n }\n\n /**\n * Map an S3-style key to a filesystem path under `#root`, rejecting\n * anything that could escape the root (path traversal, absolute\n * paths, empty segments, backslashes). All rejections throw\n * `BaerlyError(\"InvalidConfig\", …)`.\n */\n #pathFor(key: string): string {\n if (key.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", \"LocalFsStorage: empty key\");\n }\n if (key.startsWith(\"/\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: leading \"/\" in key: ${key}`);\n }\n if (key.includes(\"\\\\\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: backslash in key: ${key}`);\n }\n const segments = key.split(\"/\");\n if (segments.some((s) => s === \"\" || s === \".\" || s === \"..\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: illegal segment in key: ${key}`);\n }\n const path = join(this.#root, ...segments);\n if (path !== this.#root && !path.startsWith(this.#root + sep)) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: resolved path escapes root: ${key}`);\n }\n return path;\n }\n}\n\nconst etagOf = (body: Uint8Array): string => {\n const h = createHash(\"sha256\").update(body).digest(\"hex\");\n return `\"${h}\"`;\n};\n\nconst toUint8Array = (buf: Buffer): Uint8Array =>\n new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n\nconst isErrnoException = (e: unknown): e is NodeJS.ErrnoException =>\n typeof e === \"object\" && e !== null && \"code\" in e;\n\nconst readExisting = async (path: string): Promise<Buffer | null> => {\n try {\n return await readFile(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n};\n\n/**\n * Recursive directory walk. Yields filesystem-relative paths in\n * forward-slash form so callers can use them as S3-style keys\n * regardless of the host's path separator.\n */\nconst walk = async (root: string, out: string[]): Promise<void> => {\n const stack: string[] = [root];\n while (stack.length > 0) {\n const dir = stack.pop()!;\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n continue;\n }\n throw error;\n }\n for (const entry of entries) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n stack.push(full);\n } else if (entry.isFile()) {\n out.push(relative(root, full).split(sep).join(posix.sep));\n }\n }\n }\n};\n"],"x_google_ignoreList":[0],"mappings":";;;;;;;;;CAAA,IAAI,IAAE;CACN,IAAI,SAAO,WAAW;EAAC,OAAO;GAAC,kBAAiB;GAAM,OAAM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,IAAI,UAAU;AAE3D,MAAM,oBAAoB,MACxB,OAAO,MAAM,YAAY,MAAM,QAAQ,UAAU;AAEnD,MAAM,eAAe,OAAO,SAAyC;CACnE,IAAI;EACF,OAAO,MAAM,SAAS,IAAI;CAC5B,SAAS,OAAO;EACd,IAAI,iBAAiB,KAAK,KAAK,MAAM,SAAS,UAC5C,OAAO;EAET,MAAM;CACR;AACF;;;;;;AAOA,MAAM,OAAO,OAAO,MAAc,QAAiC;CACjE,MAAM,QAAkB,CAAC,IAAI;CAC7B,OAAO,MAAM,SAAS,GAAG;EACvB,MAAM,MAAM,MAAM,IAAI;EACtB,IAAI;EACJ,IAAI;GACF,UAAU,MAAM,QAAQ,KAAK,EAAE,eAAe,KAAK,CAAC;EACtD,SAAS,OAAO;GACd,IAAI,iBAAiB,KAAK,KAAK,MAAM,SAAS,UAC5C;GAEF,MAAM;EACR;EACA,KAAK,MAAM,SAAS,SAAS;GAC3B,MAAM,OAAO,KAAK,KAAK,MAAM,IAAI;GACjC,IAAI,MAAM,YAAY,GACpB,MAAM,KAAK,IAAI;QACV,IAAI,MAAM,OAAO,GACtB,IAAI,KAAK,SAAS,MAAM,IAAI,EAAE,MAAM,GAAG,EAAE,KAAK,MAAM,GAAG,CAAC;EAE5D;CACF;AACF"}
|
|
@@ -1,110 +0,0 @@
|
|
|
1
|
-
import { t as loadAppConfig } from "./config-Bsg8wgwo.js";
|
|
2
|
-
import { a as setJsonMode, c as parseArgs, n as emitError, o as BaerlyError, s as defineCommand } from "./baerly.js";
|
|
3
|
-
import "node:stream";
|
|
4
|
-
//#region src/subcommand.ts
|
|
5
|
-
/** Shared exit-code mapping for caught `BaerlyError`s. */
|
|
6
|
-
const errorToExitCode = (code) => {
|
|
7
|
-
if (code === "InvalidConfig") return 1;
|
|
8
|
-
if (code === "Conflict" || code === "Internal" || code === "InvalidResponse") return 3;
|
|
9
|
-
return 2;
|
|
10
|
-
};
|
|
11
|
-
/**
|
|
12
|
-
* Build the app/tenant resolver. Captures `name` to surface the
|
|
13
|
-
* calling subcommand in the InvalidConfig hint.
|
|
14
|
-
*/
|
|
15
|
-
const makeResolveAppTenant = (name) => {
|
|
16
|
-
return async (args) => {
|
|
17
|
-
const flagApp = typeof args.app === "string" && args.app.length > 0 ? args.app : void 0;
|
|
18
|
-
const flagTenant = typeof args.tenant === "string" && args.tenant.length > 0 ? args.tenant : void 0;
|
|
19
|
-
if (flagApp !== void 0 && flagTenant !== void 0) return {
|
|
20
|
-
app: flagApp,
|
|
21
|
-
tenant: flagTenant
|
|
22
|
-
};
|
|
23
|
-
try {
|
|
24
|
-
const cfg = await loadAppConfig();
|
|
25
|
-
return {
|
|
26
|
-
app: flagApp ?? cfg.app,
|
|
27
|
-
tenant: flagTenant ?? cfg.tenant
|
|
28
|
-
};
|
|
29
|
-
} catch (error) {
|
|
30
|
-
throw new BaerlyError("InvalidConfig", `baerly ${name}: --app / --tenant not supplied and no baerly.config.{ts,js,mjs,json} in cwd (${error instanceof BaerlyError ? error.message : error.message})`, error);
|
|
31
|
-
}
|
|
32
|
-
};
|
|
33
|
-
};
|
|
34
|
-
/**
|
|
35
|
-
* Wrap `def.handler` with the standard JSON-mode toggle, unknown-key
|
|
36
|
-
* rejection, and error-to-exit-code mapping. Shared by both the citty
|
|
37
|
-
* `run({ args })` path and the test `run(argv)` path. The caller
|
|
38
|
-
* supplies the {@link SubcommandContext}; this lets each `run(argv)`
|
|
39
|
-
* invocation attach its own `streams` override without leaking across
|
|
40
|
-
* invocations.
|
|
41
|
-
*/
|
|
42
|
-
const kebabToCamel = (s) => s.replace(/-(\w)/g, (_, c) => c.toUpperCase());
|
|
43
|
-
const wrapHandler = (def) => {
|
|
44
|
-
const allowedKeys = new Set(Object.keys(def.args).flatMap((k) => k.includes("-") ? [k, kebabToCamel(k)] : [k]).concat(["_"]));
|
|
45
|
-
return async (args, ctx) => {
|
|
46
|
-
if ("json" in def.args) setJsonMode(args.json === true);
|
|
47
|
-
try {
|
|
48
|
-
for (const k of Object.keys(args)) if (!allowedKeys.has(k)) throw new BaerlyError("InvalidConfig", `baerly ${def.name}: unknown flag --${k}`);
|
|
49
|
-
return await def.handler(args, ctx);
|
|
50
|
-
} catch (error) {
|
|
51
|
-
if (error instanceof BaerlyError) {
|
|
52
|
-
emitError(def.name, error.code, error.message);
|
|
53
|
-
return errorToExitCode(error.code);
|
|
54
|
-
}
|
|
55
|
-
emitError(def.name, "Unknown", error.message);
|
|
56
|
-
return 2;
|
|
57
|
-
}
|
|
58
|
-
};
|
|
59
|
-
};
|
|
60
|
-
/**
|
|
61
|
-
* Wrap a baerly subcommand. Returns `{ cmd, run }` —
|
|
62
|
-
* - `cmd` is a citty `defineCommand` block; mount it in
|
|
63
|
-
* `baerly.ts`'s `subCommands`. It calls `process.exit(code)` on a
|
|
64
|
-
* non-zero exit so the parent process surfaces the failure.
|
|
65
|
-
* - `run(argv)` is the in-process test entry. It parses `argv` with
|
|
66
|
-
* citty's `parseArgs`, dispatches through the same wrapped
|
|
67
|
-
* handler, and returns the integer exit code (does NOT call
|
|
68
|
-
* `process.exit`).
|
|
69
|
-
*
|
|
70
|
-
* The two paths share `wrapHandler` so JSON-mode toggling,
|
|
71
|
-
* unknown-flag rejection, and error-to-exit-code mapping behave
|
|
72
|
-
* identically.
|
|
73
|
-
*/
|
|
74
|
-
const defineBaerlySubcommand = (def) => {
|
|
75
|
-
const resolveAppTenant = makeResolveAppTenant(def.name);
|
|
76
|
-
const wrapped = wrapHandler(def);
|
|
77
|
-
const cmd = defineCommand({
|
|
78
|
-
meta: {
|
|
79
|
-
name: def.name,
|
|
80
|
-
description: def.meta.description
|
|
81
|
-
},
|
|
82
|
-
args: def.args,
|
|
83
|
-
run: async ({ args }) => {
|
|
84
|
-
const code = await wrapped(args, { resolveAppTenant });
|
|
85
|
-
if (code !== 0) process.exit(code);
|
|
86
|
-
}
|
|
87
|
-
});
|
|
88
|
-
const run = async (argv, options) => {
|
|
89
|
-
let parsed;
|
|
90
|
-
try {
|
|
91
|
-
parsed = parseArgs(argv, def.args);
|
|
92
|
-
} catch (error) {
|
|
93
|
-
setJsonMode(argv.includes("--json"));
|
|
94
|
-
emitError(def.name, "InvalidConfig", error.message);
|
|
95
|
-
return 1;
|
|
96
|
-
}
|
|
97
|
-
return wrapped(parsed, {
|
|
98
|
-
resolveAppTenant,
|
|
99
|
-
streams: options?.streams
|
|
100
|
-
});
|
|
101
|
-
};
|
|
102
|
-
return {
|
|
103
|
-
cmd,
|
|
104
|
-
run
|
|
105
|
-
};
|
|
106
|
-
};
|
|
107
|
-
//#endregion
|
|
108
|
-
export { defineBaerlySubcommand as t };
|
|
109
|
-
|
|
110
|
-
//# sourceMappingURL=subcommand-BWs6K7zb.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"subcommand-BWs6K7zb.js","names":[],"sources":["../packages/cli/src/subcommand.ts"],"sourcesContent":["/**\n * Shared subcommand scaffolding for `baerly`.\n *\n * Every operator-facing subcommand (`inspect`, `export`, `doctor`, and\n * every `admin/*` command) was independently re-implementing the same\n * five pieces of boilerplate:\n *\n * 1. `setJsonMode(args.json === true)` before any emission.\n * 2. A `KNOWN_KEYS` whitelist asserting unknown `--flag` rejection.\n * 3. An `errorToExitCode(code)` mapping —\n * `InvalidConfig → 1`, `Conflict|Internal|InvalidResponse → 3`,\n * else `2`.\n * 4. `resolveAppTenant(args)` falling back through `baerly.config.*`\n * to either real values or hard-coded `\"app\"` / `\"tenant\"`\n * literals.\n * 5. Two parallel entry points: a citty `defineCommand` block that\n * calls `process.exit(code)` on failure, and a `runXxx(argv)`\n * function for in-process tests that returns the exit code.\n *\n * The five copies drifted: some commands suppressed protocol-level\n * errors (no `Conflict|Internal|InvalidResponse → 3` arm), and the\n * config-fallback silently produced `\"app\"` / `\"tenant\"` literals\n * (confidently-wrong output when no config is present).\n *\n * {@link defineBaerlySubcommand} centralizes the five pieces:\n * - Computes the known-keys set from `Object.keys(args)` itself, so\n * a new flag is picked up automatically.\n * - Applies the full 3-bucket exit-code mapping uniformly.\n * - {@link SubcommandContext.resolveAppTenant} throws\n * `BaerlyError(\"InvalidConfig\", …)` with a `--app` / `--tenant`\n * hint when neither flags nor a loadable `baerly.config.*` supply\n * the values.\n * - Returns a bundle of {@link SubcommandBundle.cmd} (citty wiring)\n * and {@link SubcommandBundle.run} (test entry) sharing one\n * wrapped handler.\n */\n\nimport { type Readable, type Writable } from \"node:stream\";\nimport {\n defineCommand,\n parseArgs,\n type ArgsDef,\n type ParsedArgs,\n type CommandDef,\n} from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { emitError, setJsonMode } from \"./output.ts\";\n\n/**\n * Optional stdin / stdout streams that a programmatic caller (today:\n * `runDump` / `runRestore` tests, and the export round-trip\n * integration test) can divert in place of `process.stdin` /\n * `process.stdout`. The citty entry point always uses the process\n * streams; only {@link SubcommandBundle.run} accepts these overrides.\n */\nexport interface SubcommandStreams {\n readonly stdin?: Readable;\n readonly stdout?: Writable;\n}\n\n/**\n * Capabilities the subcommand handler receives. Today: app/tenant\n * resolution. Kept narrow so the handler signature stays load-bearing\n * (the helper isn't a god object).\n */\nexport interface SubcommandContext {\n /**\n * Returns `{ app, tenant }` resolved from explicit flags or\n * `baerly.config.{ts,js,mjs,json}` in the cwd.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — neither flag was\n * supplied AND no loadable config was found. The error message\n * includes a hint mentioning `--app` / `--tenant`.\n */\n readonly resolveAppTenant: (args: {\n readonly app?: string;\n readonly tenant?: string;\n }) => Promise<{ app: string; tenant: string }>;\n /**\n * Programmatic stdin / stdout overrides. `undefined` (or any\n * missing field) means \"use the process stream\". Only\n * `admin dump` / `admin restore` consume this; other commands\n * ignore the field.\n */\n readonly streams?: SubcommandStreams;\n}\n\n/**\n * Definition fed to {@link defineBaerlySubcommand}. `name` is the JSON\n * envelope tag (`\"inspect\"`, `\"admin.compact\"`, etc.); `args` is the\n * citty ArgsDef; `handler` returns the integer exit code.\n */\nexport interface SubcommandDef<TArgs extends ArgsDef> {\n /** JSON envelope `command` tag and the prefix of every emitted error. */\n readonly name: string;\n readonly meta: { readonly description: string };\n readonly args: TArgs;\n readonly handler: (args: ParsedArgs<TArgs>, ctx: SubcommandContext) => Promise<number>;\n}\n\n/**\n * Output of {@link defineBaerlySubcommand}. `cmd` plugs into\n * `subCommands` in `baerly.ts`; `run` is the in-process entry for\n * unit tests.\n */\nexport interface SubcommandBundle<TArgs extends ArgsDef> {\n readonly cmd: CommandDef<TArgs>;\n readonly run: (\n argv: readonly string[],\n options?: { readonly streams?: SubcommandStreams },\n ) => Promise<number>;\n}\n\n/** Shared exit-code mapping for caught `BaerlyError`s. */\nconst errorToExitCode = (code: string): number => {\n if (code === \"InvalidConfig\") {\n return 1;\n }\n if (code === \"Conflict\" || code === \"Internal\" || code === \"InvalidResponse\") {\n return 3;\n }\n return 2;\n};\n\n/**\n * Build the app/tenant resolver. Captures `name` to surface the\n * calling subcommand in the InvalidConfig hint.\n */\nconst makeResolveAppTenant = (name: string): SubcommandContext[\"resolveAppTenant\"] => {\n return async (args) => {\n const flagApp = typeof args.app === \"string\" && args.app.length > 0 ? args.app : undefined;\n const flagTenant =\n typeof args.tenant === \"string\" && args.tenant.length > 0 ? args.tenant : undefined;\n if (flagApp !== undefined && flagTenant !== undefined) {\n return { app: flagApp, tenant: flagTenant };\n }\n try {\n const cfg = await loadAppConfig();\n return {\n app: flagApp ?? cfg.app,\n tenant: flagTenant ?? cfg.tenant,\n };\n } catch (error) {\n // Re-throw with our own wording so the operator sees the\n // calling-command name and the hint to pass --app / --tenant\n // explicitly. The underlying loadAppConfig error is preserved\n // as the cause.\n const inner = error instanceof BaerlyError ? error.message : (error as Error).message;\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly ${name}: --app / --tenant not supplied and no baerly.config.{ts,js,mjs,json} in cwd (${inner})`,\n error,\n );\n }\n };\n};\n\n/**\n * Wrap `def.handler` with the standard JSON-mode toggle, unknown-key\n * rejection, and error-to-exit-code mapping. Shared by both the citty\n * `run({ args })` path and the test `run(argv)` path. The caller\n * supplies the {@link SubcommandContext}; this lets each `run(argv)`\n * invocation attach its own `streams` override without leaking across\n * invocations.\n */\nconst kebabToCamel = (s: string): string =>\n s.replace(/-(\\w)/g, (_, c: string) => c.toUpperCase());\n\nconst wrapHandler = <TArgs extends ArgsDef>(\n def: SubcommandDef<TArgs>,\n): ((args: ParsedArgs<TArgs>, ctx: SubcommandContext) => Promise<number>) => {\n // Compute the allow-list once from the ArgsDef. citty injects `_`\n // for positional captures, so it must stay allowed. citty 0.2.2\n // also auto-injects a camelCase alias for every kebab-case flag\n // (e.g. `--where-comment` produces both `whereComment` and\n // `where-comment` on the parsed args), so each kebab key is\n // expanded to its camelCase variant in the allow-list too.\n const allowedKeys: ReadonlySet<string> = new Set(\n Object.keys(def.args)\n .flatMap((k) => (k.includes(\"-\") ? [k, kebabToCamel(k)] : [k]))\n .concat([\"_\"]),\n );\n return async (args, ctx) => {\n // `json` is conventional but not required — only toggle when it's\n // both declared in the ArgsDef and truthy on the parsed args.\n if (\"json\" in def.args) {\n setJsonMode((args as ParsedArgs<TArgs> & { json?: boolean }).json === true);\n }\n try {\n for (const k of Object.keys(args)) {\n if (!allowedKeys.has(k)) {\n throw new BaerlyError(\"InvalidConfig\", `baerly ${def.name}: unknown flag --${k}`);\n }\n }\n return await def.handler(args, ctx);\n } catch (error) {\n if (error instanceof BaerlyError) {\n emitError(def.name, error.code, error.message);\n return errorToExitCode(error.code);\n }\n emitError(def.name, \"Unknown\", (error as Error).message);\n return 2;\n }\n };\n};\n\n/**\n * Wrap a baerly subcommand. Returns `{ cmd, run }` —\n * - `cmd` is a citty `defineCommand` block; mount it in\n * `baerly.ts`'s `subCommands`. It calls `process.exit(code)` on a\n * non-zero exit so the parent process surfaces the failure.\n * - `run(argv)` is the in-process test entry. It parses `argv` with\n * citty's `parseArgs`, dispatches through the same wrapped\n * handler, and returns the integer exit code (does NOT call\n * `process.exit`).\n *\n * The two paths share `wrapHandler` so JSON-mode toggling,\n * unknown-flag rejection, and error-to-exit-code mapping behave\n * identically.\n */\nexport const defineBaerlySubcommand = <TArgs extends ArgsDef>(\n def: SubcommandDef<TArgs>,\n): SubcommandBundle<TArgs> => {\n const resolveAppTenant = makeResolveAppTenant(def.name);\n const wrapped = wrapHandler(def);\n\n const cmd = defineCommand({\n meta: { name: def.name, description: def.meta.description },\n args: def.args,\n run: async ({ args }) => {\n const code = await wrapped(args as ParsedArgs<TArgs>, { resolveAppTenant });\n if (code !== 0) {\n process.exit(code);\n }\n },\n });\n\n const run = async (\n argv: readonly string[],\n options?: { readonly streams?: SubcommandStreams },\n ): Promise<number> => {\n let parsed: ParsedArgs<TArgs>;\n try {\n parsed = parseArgs<TArgs>(argv as string[], def.args);\n } catch (error) {\n // Parse-time error from citty (missing required flag,\n // malformed value). Toggle JSON mode by sniffing argv since\n // we never reached the handler.\n setJsonMode(argv.includes(\"--json\"));\n emitError(def.name, \"InvalidConfig\", (error as Error).message);\n return 1;\n }\n return wrapped(parsed, { resolveAppTenant, streams: options?.streams });\n };\n\n return { cmd, run };\n};\n"],"mappings":";;;;;AAmHA,MAAM,mBAAmB,SAAyB;CAChD,IAAI,SAAS,iBACX,OAAO;CAET,IAAI,SAAS,cAAc,SAAS,cAAc,SAAS,mBACzD,OAAO;CAET,OAAO;AACT;;;;;AAMA,MAAM,wBAAwB,SAAwD;CACpF,OAAO,OAAO,SAAS;EACrB,MAAM,UAAU,OAAO,KAAK,QAAQ,YAAY,KAAK,IAAI,SAAS,IAAI,KAAK,MAAM,KAAA;EACjF,MAAM,aACJ,OAAO,KAAK,WAAW,YAAY,KAAK,OAAO,SAAS,IAAI,KAAK,SAAS,KAAA;EAC5E,IAAI,YAAY,KAAA,KAAa,eAAe,KAAA,GAC1C,OAAO;GAAE,KAAK;GAAS,QAAQ;EAAW;EAE5C,IAAI;GACF,MAAM,MAAM,MAAM,cAAc;GAChC,OAAO;IACL,KAAK,WAA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AM,QAAQ,MAA2B,EAAE,iBAAiB,CAAC;GAC1E,IAAI,SAAS,GACX,QAAQ,KAAK,IAAI;EAErB;CACF,CAAC;CAED,MAAM,MAAM,OACV,MACA,YACoB;EACpB,IAAI;EACJ,IAAI;GACF,SAAS,UAAiB,MAAkB,IAAI,IAAI;EACtD,SAAS,OAAO;GAId,YAAY,KAAK,SAAS,QAAQ,CAAC;GACnC,UAAU,IAAI,MAAM,iBAAkB,MAAgB,OAAO;GAC7D,OAAO;EACT;EACA,OAAO,QAAQ,QAAQ;GAAE;GAAkB,SAAS,SAAS;EAAQ,CAAC;CACxE;CAEA,OAAO;EAAE;EAAK;CAAI;AACpB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"validate-DhH1lO8I.js","names":[],"sources":["../packages/protocol/src/query/_internals.ts","../packages/protocol/src/query/matches.ts","../packages/protocol/src/query/satisfiable.ts","../packages/protocol/src/query/validate.ts"],"sourcesContent":["/**\n * Shared helpers for the predicate algebras in `./validate.ts`,\n * `./matches.ts`, and `./merge.ts`. These exist as a single module\n * because more than one of those files uses them and duplicating\n * the implementations would drift over time.\n *\n * Only {@link deepEqualDocumentValue} is part of the public surface;\n * the comparator primitives (`compareScalar`, `sameComparableType`,\n * `formatPath`) are internal to the protocol package and imported\n * by `./validate.ts` / `./merge.ts` / `./normalize.ts` directly.\n */\n\nimport type { DocumentValue } from \"../json.ts\";\n\n/** @internal Same primitive type for comparison purposes. */\nexport const sameComparableType = (a: DocumentValue, b: DocumentValue): boolean =>\n (typeof a === \"string\" && typeof b === \"string\") ||\n (typeof a === \"number\" && typeof b === \"number\");\n\n/**\n * @internal Returns negative / zero / positive for a<b / a==b / a>b.\n */\nexport const compareScalar = (a: DocumentValue, b: DocumentValue): number => {\n if (typeof a === \"number\" && typeof b === \"number\") {\n return a - b;\n }\n if (typeof a === \"string\" && typeof b === \"string\") {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n }\n return 0;\n};\n\n/** @internal Render a predicate path for use in error messages. */\nexport const formatPath = (path: ReadonlyArray<string>): string =>\n path.length === 0 ? \"<root>\" : path.map((p) => JSON.stringify(p)).join(\".\");\n\n/**\n * Recursive structural equality for `DocumentValue` values. Lifted to\n * `export` so the filtered-index implication checker (in\n * `@baerly/server`'s query planner) and other callers can reuse the\n * same comparison rule the validator + merger already trust. Two\n * values `a` and `b` are equal iff:\n *\n * - they are reference-equal (covers primitives and object identity);\n * - or they are both non-`null` objects with the same key set, and\n * every value pair is recursively equal.\n *\n * Arrays are out-of-band for `DocumentValue`; this function rejects\n * them implicitly via the same key-set walk (an array reads as an\n * object with numeric-string keys plus a `length` exposure that\n * `Object.keys` happens to skip — defensive callers should still gate\n * with `Array.isArray` first).\n */\nexport const deepEqualDocumentValue = (a: DocumentValue, b: DocumentValue): boolean => {\n if (a === b) {\n return true;\n } // primitives + object identity\n if (typeof a !== \"object\" || typeof b !== \"object\") {\n return false;\n }\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) {\n return false;\n }\n for (const key of aKeys) {\n if (!(key in b)) {\n return false;\n }\n const aSub = (a as Record<string, DocumentValue>)[key];\n const bSub = (b as Record<string, DocumentValue>)[key];\n if (aSub === undefined || bSub === undefined) {\n return false;\n }\n if (!deepEqualDocumentValue(aSub, bSub)) {\n return false;\n }\n }\n return true;\n};\n","/**\n * Wire predicate evaluator. Walks a validated {@link PredicateWire}\n * against a `JSONObject` document and returns `true` iff every\n * clause holds. Multiple clauses across all fields AND together.\n *\n * Pre-condition: `wire` must have been returned by\n * {@link validateWire} (see `./validate.ts`). Passing an\n * un-validated wire is a caller bug; behaviour is undefined.\n *\n * Companion modules: `./validate.ts` (construction-time check),\n * `./merge.ts` (AND-merge), `./wire.ts` (types).\n */\n\nimport type { DocumentValue, JSONObject, JSONValue } from \"../json.ts\";\n\nimport type { PredicateClause, PredicateWire } from \"./wire.ts\";\n\n/**\n * Evaluate a validated wire-form predicate against a `JSONObject`\n * document. Returns `true` iff every clause holds.\n *\n * @example\n * ```ts\n * matchesWire(\n * { clauses: [{ op: \"eq\", field: \"status\", value: \"open\" }] },\n * { status: \"open\", priority: \"p1\" },\n * ); // true\n *\n * matchesWire(\n * { clauses: [{ op: \"in\", field: \"priority\", value: [\"p1\", \"p2\"] }] },\n * { priority: \"p3\" },\n * ); // false\n *\n * matchesWire(\n * {\n * clauses: [\n * { op: \"gte\", field: \"count\", value: 1 },\n * { op: \"lt\", field: \"count\", value: 10 },\n * ],\n * },\n * { count: 5 },\n * ); // true\n * ```\n */\nexport const matchesWire = (wire: PredicateWire, doc: JSONObject): boolean => {\n for (const clause of wire.clauses) {\n const actual = lookupPath(doc, clause.field);\n if (!matchesClause(clause, actual)) {\n return false;\n }\n }\n return true;\n};\n\nconst lookupPath = (doc: JSONObject, field: string): JSONValue | undefined => {\n // Fast path: no dot → top-level lookup. Avoids allocating a split\n // array for the common case.\n if (!field.includes(\".\")) {\n return doc[field];\n }\n const segments = field.split(\".\");\n let cursor: JSONValue | undefined = doc;\n for (const segment of segments) {\n if (\n cursor === undefined ||\n cursor === null ||\n typeof cursor !== \"object\" ||\n Array.isArray(cursor)\n ) {\n // Traversal hit a primitive, null, missing key, or array\n // before consuming the path. Predicate cannot match.\n return undefined;\n }\n cursor = (cursor as JSONObject)[segment];\n }\n return cursor;\n};\n\nconst matchesClause = (clause: PredicateClause, actual: JSONValue | undefined): boolean => {\n switch (clause.op) {\n case \"eq\": {\n return matchesEq(clause.value as DocumentValue, actual);\n }\n case \"in\": {\n return matchesIn(clause.value as ReadonlyArray<DocumentValue>, actual);\n }\n case \"gt\": {\n return compareGT(actual, clause.value as DocumentValue, false);\n }\n case \"gte\": {\n return compareGT(actual, clause.value as DocumentValue, true);\n }\n case \"lt\": {\n return compareLT(actual, clause.value as DocumentValue, false);\n }\n case \"lte\": {\n return compareLT(actual, clause.value as DocumentValue, true);\n }\n }\n};\n\nconst matchesEq = (expected: DocumentValue, actual: JSONValue | undefined): boolean => {\n if (typeof expected === \"object\") {\n // Nested object equality is a sub-predicate match — open-world:\n // doc may carry extra keys. The object-form normaliser flattens\n // nested sub-predicates to dotted-path clauses on the way in, so\n // the only callers reaching this branch are callback-form\n // `q.eq(\"nested\", { ... })`.\n if (\n actual === undefined ||\n actual === null ||\n typeof actual !== \"object\" ||\n Array.isArray(actual)\n ) {\n return false;\n }\n for (const subKey of Object.keys(expected)) {\n const subExpected = (expected as Record<string, DocumentValue>)[subKey];\n if (subExpected === undefined) {\n continue;\n }\n const subActual = (actual as JSONObject)[subKey];\n if (!matchesEq(subExpected, subActual)) {\n return false;\n }\n }\n return true;\n }\n return expected === actual;\n};\n\nconst matchesIn = (\n members: ReadonlyArray<DocumentValue>,\n actual: JSONValue | undefined,\n): boolean => {\n for (const m of members) {\n if (typeof m === \"object\") {\n if (matchesEq(m, actual)) {\n return true;\n }\n } else if (m === actual) {\n return true;\n }\n }\n return false;\n};\n\nconst compareGT = (\n actual: JSONValue | undefined,\n bound: DocumentValue,\n inclusive: boolean,\n): boolean => {\n if (typeof bound === \"string\") {\n return typeof actual === \"string\" && (inclusive ? actual >= bound : actual > bound);\n }\n if (typeof bound === \"number\") {\n return typeof actual === \"number\" && (inclusive ? actual >= bound : actual > bound);\n }\n // Validator forbids boolean / null / object range bounds; defensive miss.\n return false;\n};\n\nconst compareLT = (\n actual: JSONValue | undefined,\n bound: DocumentValue,\n inclusive: boolean,\n): boolean => {\n if (typeof bound === \"string\") {\n return typeof actual === \"string\" && (inclusive ? actual <= bound : actual < bound);\n }\n if (typeof bound === \"number\") {\n return typeof actual === \"number\" && (inclusive ? actual <= bound : actual < bound);\n }\n return false;\n};\n","/**\n * Per-field satisfiability check for a {@link PredicateWire}. Groups\n * clauses by field, then runs the same logic the pre-redesign\n * `assertOpObjectSatisfiable` ran on a single op-object — but\n * generalised across N clauses on the same field (the wire merger\n * concatenates lists without coalescing).\n *\n * Triggers:\n * - Two `eq` clauses on the same field with different values →\n * `InvalidConfig` (the same conflict that pre-redesign\n * `mergePredicates` threw on shared primitive keys).\n * - Range bounds with `lo > hi` (or `lo == hi` with strict on\n * either side) → `UnsatisfiablePredicate`.\n * - `eq` value outside the residual range interval or absent from\n * every `in` set on the same field → `UnsatisfiablePredicate`.\n * - `in` sets that intersect to empty across multiple clauses →\n * `UnsatisfiablePredicate`.\n *\n * Used by both `./validate.ts` (wire-arrival check) and\n * `./merge.ts` (post-merge re-check, kept in lockstep).\n */\n\nimport { BaerlyError } from \"../errors.ts\";\nimport type { DocumentValue } from \"../json.ts\";\n\nimport {\n compareScalar,\n deepEqualDocumentValue,\n formatPath,\n sameComparableType,\n} from \"./_internals.ts\";\nimport type { PredicateClause, PredicateWire } from \"./wire.ts\";\n\ninterface FieldGroup {\n readonly eqs: DocumentValue[];\n readonly ins: ReadonlyArray<DocumentValue>[];\n lo?: { value: DocumentValue; inclusive: boolean };\n hi?: { value: DocumentValue; inclusive: boolean };\n}\n\nconst groupByField = (wire: PredicateWire): Map<string, FieldGroup> => {\n const out = new Map<string, FieldGroup>();\n for (const clause of wire.clauses) {\n let group = out.get(clause.field);\n if (group === undefined) {\n group = { eqs: [], ins: [] };\n out.set(clause.field, group);\n }\n applyClause(group, clause.field, clause);\n }\n return out;\n};\n\nconst applyClause = (group: FieldGroup, field: string, clause: PredicateClause): void => {\n switch (clause.op) {\n case \"eq\": {\n group.eqs.push(clause.value as DocumentValue);\n return;\n }\n case \"in\": {\n group.ins.push(clause.value as ReadonlyArray<DocumentValue>);\n return;\n }\n case \"gt\": {\n tightenLower(group, field, clause.value as DocumentValue, false);\n return;\n }\n case \"gte\": {\n tightenLower(group, field, clause.value as DocumentValue, true);\n return;\n }\n case \"lt\": {\n tightenUpper(group, field, clause.value as DocumentValue, false);\n return;\n }\n case \"lte\": {\n tightenUpper(group, field, clause.value as DocumentValue, true);\n return;\n }\n }\n};\n\nconst tightenLower = (\n group: FieldGroup,\n field: string,\n value: DocumentValue,\n inclusive: boolean,\n): void => {\n if (group.lo === undefined) {\n group.lo = { value, inclusive };\n return;\n }\n if (!sameComparableType(group.lo.value, value)) {\n // Type-incompatible bounds on the same field — the user wrote\n // (say) `q.gt(\"x\", 1).gt(\"x\", \"a\")`. Range matching is type-\n // strict at evaluation time so this is always-miss; surface\n // eagerly as `UnsatisfiablePredicate`.\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has type-incompatible lower bounds (${JSON.stringify(group.lo.value)} vs ${JSON.stringify(value)}).`,\n );\n }\n const c = compareScalar(group.lo.value, value);\n if (c < 0 || (c === 0 && inclusive === false && group.lo.inclusive === true)) {\n group.lo = { value, inclusive };\n }\n};\n\nconst tightenUpper = (\n group: FieldGroup,\n field: string,\n value: DocumentValue,\n inclusive: boolean,\n): void => {\n if (group.hi === undefined) {\n group.hi = { value, inclusive };\n return;\n }\n if (!sameComparableType(group.hi.value, value)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has type-incompatible upper bounds (${JSON.stringify(group.hi.value)} vs ${JSON.stringify(value)}).`,\n );\n }\n const c = compareScalar(group.hi.value, value);\n if (c > 0 || (c === 0 && inclusive === false && group.hi.inclusive === true)) {\n group.hi = { value, inclusive };\n }\n};\n\nconst intersectInSets = (\n sets: ReadonlyArray<ReadonlyArray<DocumentValue>>,\n): ReadonlyArray<DocumentValue> => {\n if (sets.length === 0) {\n return [];\n }\n let acc: ReadonlyArray<DocumentValue> = sets[0]!;\n for (let i = 1; i < sets.length; i++) {\n const next: DocumentValue[] = [];\n for (const a of acc) {\n for (const b of sets[i]!) {\n if (deepEqualDocumentValue(a, b)) {\n next.push(a);\n break;\n }\n }\n }\n acc = next;\n }\n return acc;\n};\n\n/**\n * Check that every per-field clause group on `wire` is jointly\n * satisfiable. Throws `BaerlyError{code:\"UnsatisfiablePredicate\"}`\n * (or `\"InvalidConfig\"` for conflicting `eq` clauses) on the\n * first contradiction. Returns `void` on success.\n */\nexport const assertWireSatisfiable = (wire: PredicateWire): void => {\n const groups = groupByField(wire);\n for (const [field, group] of groups) {\n // Multiple `eq` clauses on the same field must agree.\n if (group.eqs.length > 1) {\n for (let i = 1; i < group.eqs.length; i++) {\n if (!deepEqualDocumentValue(group.eqs[0]!, group.eqs[i]!)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Conflicting equality clauses on field ${formatPath([field])} (${JSON.stringify(group.eqs[0]!)} vs ${JSON.stringify(group.eqs[i]!)}). Predicate chains must agree on shared equality.`,\n );\n }\n }\n }\n const eq = group.eqs[0];\n // Range interval must be non-empty.\n if (\n group.lo !== undefined &&\n group.hi !== undefined &&\n sameComparableType(group.lo.value, group.hi.value)\n ) {\n const c = compareScalar(group.lo.value, group.hi.value);\n if (c > 0 || (c === 0 && (!group.lo.inclusive || !group.hi.inclusive))) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has empty interval (lo=${JSON.stringify(group.lo.value)} ${group.lo.inclusive ? \"gte\" : \"gt\"}, hi=${JSON.stringify(group.hi.value)} ${group.hi.inclusive ? \"lte\" : \"lt\"}).`,\n );\n }\n }\n // `eq` outside the residual interval / membership set.\n if (eq !== undefined) {\n if (group.lo !== undefined) {\n if (!sameComparableType(eq, group.lo.value)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} (${typeof eq}) is type-incompatible with lower bound ${JSON.stringify(group.lo.value)} (${typeof group.lo.value}); range ops require matching primitive types.`,\n );\n }\n const c = compareScalar(eq, group.lo.value);\n if (c < 0 || (c === 0 && !group.lo.inclusive)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} excluded by lower bound ${JSON.stringify(group.lo.value)} (${group.lo.inclusive ? \"gte\" : \"gt\"}).`,\n );\n }\n }\n if (group.hi !== undefined) {\n if (!sameComparableType(eq, group.hi.value)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} (${typeof eq}) is type-incompatible with upper bound ${JSON.stringify(group.hi.value)} (${typeof group.hi.value}); range ops require matching primitive types.`,\n );\n }\n const c = compareScalar(eq, group.hi.value);\n if (c > 0 || (c === 0 && !group.hi.inclusive)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} excluded by upper bound ${JSON.stringify(group.hi.value)} (${group.hi.inclusive ? \"lte\" : \"lt\"}).`,\n );\n }\n }\n if (group.ins.length > 0) {\n for (const set of group.ins) {\n let found = false;\n for (const m of set) {\n if (deepEqualDocumentValue(eq, m)) {\n found = true;\n break;\n }\n }\n if (!found) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} not present in in() set.`,\n );\n }\n }\n }\n }\n // Multiple `in` sets must intersect non-empty.\n if (group.ins.length > 1) {\n const isect = intersectInSets(group.ins);\n if (isect.length === 0) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has empty in() intersection across multiple clauses.`,\n );\n }\n }\n }\n};\n","/**\n * Wire predicate validator. Walks a {@link PredicateWire} and throws\n * on a structurally bad clause (`BaerlyError{code:\"InvalidConfig\"}`)\n * or a per-field clause group that contradicts itself\n * (`BaerlyError{code:\"UnsatisfiablePredicate\"}`).\n *\n * The object-form normaliser at `./normalize.ts` enforces shape on\n * the way in (rejecting `$`-keys / non-scalars / null / undefined);\n * the callback builder at `./builder.ts` enforces shape via the\n * type system. This validator is the wire-arrival check: it runs\n * over already-normalised clauses, defending against raw-`fetch`\n * callers who bypass the typed seam and submit arbitrary JSON.\n *\n * Companion modules: `./matches.ts` (evaluator), `./merge.ts`\n * (AND-merge). Shared helpers live in `./_internals.ts`.\n */\n\nimport { BaerlyError } from \"../errors.ts\";\n\nimport { assertWireSatisfiable } from \"./satisfiable.ts\";\nimport type { PredicateClause, PredicateOpName, PredicateWire } from \"./wire.ts\";\n\nconst OP_NAMES: ReadonlyArray<PredicateOpName> = [\"eq\", \"gt\", \"gte\", \"lt\", \"lte\", \"in\"];\nconst RANGE_OPS: ReadonlyArray<PredicateOpName> = [\"gt\", \"gte\", \"lt\", \"lte\"];\n\n/**\n * Validate a normalised predicate wire. Throws\n * `BaerlyError{code:\"InvalidConfig\"}` on a structurally bad clause,\n * or `BaerlyError{code:\"UnsatisfiablePredicate\"}` when a clause\n * group on one field contradicts itself.\n *\n * Returns the wire unchanged on success — callers can thread the\n * validated wire forward.\n *\n * @example\n * ```ts\n * validateWire({ clauses: [{ op: \"eq\", field: \"status\", value: \"open\" }] }); // ok\n * validateWire({ clauses: [{ op: \"in\", field: \"priority\", value: [] }] }); // throws UnsatisfiablePredicate\n * validateWire({ clauses: [{ op: \"eq\", field: \"_id\", value: \"x\" }] }); // throws InvalidConfig (top-level _id)\n * ```\n */\nexport const validateWire = (wire: PredicateWire): PredicateWire => {\n if (\n wire === null ||\n typeof wire !== \"object\" ||\n !Array.isArray((wire as { clauses?: unknown }).clauses)\n ) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate wire must be an object with a \"clauses\" array.`,\n );\n }\n for (let i = 0; i < wire.clauses.length; i++) {\n validateClause(wire.clauses[i]!, i);\n }\n assertWireSatisfiable(wire);\n return wire;\n};\n\nconst validateClause = (clause: PredicateClause, index: number): void => {\n if (clause === null || typeof clause !== \"object\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} must be an object — got ${JSON.stringify(clause)}.`,\n );\n }\n const { op, field, value } = clause;\n if (typeof op !== \"string\" || !(OP_NAMES as ReadonlyArray<string>).includes(op)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} has unsupported op ${JSON.stringify(op)} — supported: ${OP_NAMES.join(\" / \")}.`,\n );\n }\n if (typeof field !== \"string\" || field.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} has empty / non-string field.`,\n );\n }\n if (field === \"_id\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n 'Predicates may not key on \"_id\"; use .get(id) / .update(id, patch) / .replace(id, doc) / .delete(id) instead.',\n );\n }\n if (op === \"in\") {\n if (!Array.isArray(value)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} (op=\"in\", field=${JSON.stringify(field)}) must carry an array value.`,\n );\n }\n if (value.length === 0) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate clause at index ${index} (op=\"in\", field=${JSON.stringify(field)}) has empty value array — no document can match.`,\n );\n }\n for (let i = 0; i < value.length; i++) {\n validateMemberValue(value[i], field, index, i);\n }\n return;\n }\n if (Array.isArray(value)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} (op=${JSON.stringify(op)}, field=${JSON.stringify(field)}) must carry a primitive value, got an array — only op=\"in\" accepts arrays.`,\n );\n }\n if ((RANGE_OPS as ReadonlyArray<string>).includes(op)) {\n validateRangeBound(value, field, index);\n return;\n }\n validateScalar(value, field, index);\n};\n\nconst validateMemberValue = (\n value: unknown,\n field: string,\n clauseIndex: number,\n memberIndex: number,\n): void => {\n if (value === null || value === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} is ${value === null ? \"null\" : \"undefined\"} — members must be string / number / boolean / nested object.`,\n );\n }\n if (Array.isArray(value)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} is an array — members must be string / number / boolean / nested object.`,\n );\n }\n const t = typeof value;\n if (t === \"object\") {\n return;\n }\n if (t !== \"string\" && t !== \"number\" && t !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} has unsupported type ${JSON.stringify(t)} — must be string / number / boolean / nested object.`,\n );\n }\n if (t === \"number\" && !Number.isFinite(value as number)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`,\n );\n }\n};\n\nconst validateScalar = (value: unknown, field: string, clauseIndex: number): void => {\n if (value === null || value === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value is ${value === null ? \"null\" : \"undefined\"} — terminal values must be string / number / boolean / nested object.`,\n );\n }\n const t = typeof value;\n if (t === \"object\") {\n // Equality clauses against nested objects survive only via callback\n // form (the normaliser flattens object-form sub-predicates to\n // dotted-path eq clauses). Keep the structural recursion light —\n // values are sealed from the typed seam.\n return;\n }\n if (t !== \"string\" && t !== \"number\" && t !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value has unsupported type ${JSON.stringify(t)} — must be string / number / boolean / nested object.`,\n );\n }\n if (t === \"number\" && !Number.isFinite(value as number)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`,\n );\n }\n};\n\nconst validateRangeBound = (value: unknown, field: string, clauseIndex: number): void => {\n if (value === null || value === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is ${value === null ? \"null\" : \"undefined\"} — range bounds must be string or finite number.`,\n );\n }\n const t = typeof value;\n if (t === \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is a boolean — range bounds must be string or finite number (booleans are not ordered).`,\n );\n }\n if (t === \"object\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is a nested object — range bounds must be string or finite number.`,\n );\n }\n if (t !== \"string\" && t !== \"number\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) has unsupported type ${JSON.stringify(t)} — must be string or finite number.`,\n );\n }\n if (t === \"number\" && !Number.isFinite(value as number)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`,\n );\n }\n};\n"],"mappings":";;;AAeA,MAAa,sBAAsB,GAAkB,MAClD,OAAO,MAAM,YAAY,OAAO,MAAM,YACtC,OAAO,MAAM,YAAY,OAAO,MAAM;;;;AAKzC,MAAa,iBAAiB,GAAkB,MAA6B;CAC3E,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UACxC,OAAO,IAAI;CAEb,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UAAU;EAClD,IAAI,IAAI,GACN,OAAO;EAET,IAAI,IAAI,GACN,OAAO;EAET,OAAO;CACT;CACA,OAAO;AACT;;AAGA,MAAa,cAAc,SACzB,KAAK,WAAW,IAAI,WAAW,KAAK,KAAK,MAAM,KAAK,UAAU,CAAC,CAAC,EAAE,KAAK,GAAG;;;;;;;;;;;;;;;;;;AAmB5E,MAAa,0BAA0B,GAAkB,MAA8B;CACrF,IAAI,MAAM,GACR,OAAO;CAET,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UACxC,OAAO;CAET,MAAM,QAAQ,OAAO,KAAK,CAAC;CAC3B,MAAM,QAAQ,OAAO,KAAK,CAAC;CAC3B,IAAI,MAAM,WAAW,MAAM,QACzB,OAAO;CAET,KAAK,MAAM,OAAO,OAAO;EACvB,IAAI,EAAE,OAAO,IACX,O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