@gusto/baerly-storage 0.4.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/API.md +3 -2
- package/dist/CHANGELOG.md +125 -0
- package/dist/THIRD-PARTY-LICENSES.txt +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/aws4fetch.esm-CXE5ZbAa.js +460 -0
- package/dist/aws4fetch.esm-CXE5ZbAa.js.map +1 -0
- package/dist/baerly.js +10 -10
- package/dist/baerly.spec.json +1 -1
- package/dist/client-react.d.ts +2 -2
- package/dist/{client-Fe8CwB73.d.ts → client-ypCm3zjt.d.ts} +2 -2
- package/dist/client.d.ts +2 -2
- package/dist/{cloudflare-DzKBrUlg.js → cloudflare-wrVYf4bb.js} +457 -56
- package/dist/cloudflare-wrVYf4bb.js.map +1 -0
- package/dist/cloudflare.d.ts +13 -10
- package/dist/cloudflare.js +6 -6
- package/dist/cloudflare.js.map +1 -1
- package/dist/{config-1tv0-Yzm.js → config-B6nTy8e2.js} +435 -33
- package/dist/config-B6nTy8e2.js.map +1 -0
- package/dist/constants-CfeMWQWk.js.map +1 -1
- package/dist/{cost-DSMIVqzL.js → cost-_SE_SVgZ.js} +4 -4
- package/dist/{cost-DSMIVqzL.js.map → cost-_SE_SVgZ.js.map} +1 -1
- package/dist/{db-DsPkOVEH.d.ts → db-DjjthkTi.d.ts} +2 -2
- package/dist/{deploy-DonTr-CV.js → deploy-Di_Q01qx.js} +5 -5
- package/dist/deploy-Di_Q01qx.js.map +1 -0
- package/dist/dev-vite.d.ts +31 -27
- package/dist/dev-vite.js +60 -30
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/doctor-RWVRpvat.js +102 -0
- package/dist/doctor-RWVRpvat.js.map +1 -0
- package/dist/{dump-Bh5k26VQ.js → dump-m2vEYDNY.js} +4 -4
- package/dist/{dump-Bh5k26VQ.js.map → dump-m2vEYDNY.js.map} +1 -1
- package/dist/{export-DtF5tDIM.js → export-DenKwEQu.js} +4 -4
- package/dist/{export-DtF5tDIM.js.map → export-DenKwEQu.js.map} +1 -1
- package/dist/{fsck-D_djMO5D.js → fsck-2Vq-7-e2.js} +5 -5
- package/dist/{fsck-D_djMO5D.js.map → fsck-2Vq-7-e2.js.map} +1 -1
- package/dist/gcs-admin-Bx6xSNJj.d.ts +123 -0
- package/dist/gcs.d.ts +18 -0
- package/dist/gcs.js +2 -0
- package/dist/goog4-signer-Z7KnJ1su.js +321 -0
- package/dist/goog4-signer-Z7KnJ1su.js.map +1 -0
- package/dist/{http-DxM9MflO.js → http-7zT29K3P.js} +4 -4
- package/dist/{http-DxM9MflO.js.map → http-7zT29K3P.js.map} +1 -1
- package/dist/{aws4fetch.esm-p7eEzLCs.js → http-transport-BTgVCY5r.js} +24 -476
- package/dist/http-transport-BTgVCY5r.js.map +1 -0
- package/dist/http.d.ts +2 -2
- package/dist/http.js +2 -2
- package/dist/{index-BNRh23K9.d.ts → index-BHz92Acj.d.ts} +2 -2
- package/dist/{index-BYk9oCNf.d.ts → index-CEZKQsKt.d.ts} +3 -2
- package/dist/{index-B6oexfOB.d.ts → index-DP3ClvcA.d.ts} +12 -10
- package/dist/{index-0rZcMBwy.d.ts → index-uE-w2dgj.d.ts} +2 -2
- package/dist/index.d.ts +3 -3
- package/dist/index.js +3 -3
- package/dist/{inspect-6WZ-pC7-.js → inspect-BpYbH1DM.js} +5 -5
- package/dist/{inspect-6WZ-pC7-.js.map → inspect-BpYbH1DM.js.map} +1 -1
- package/dist/{log-tail-D98U1JBo.js → log-tail-QWU4wlu-.js} +3 -11
- package/dist/log-tail-QWU4wlu-.js.map +1 -0
- package/dist/{maintenance-B_e0T99L.d.ts → maintenance-BGHGt2Yg.d.ts} +2 -2
- package/dist/{maintenance-B4Dki6Ig.js → maintenance-DULFcpd1.js} +4 -17
- package/dist/maintenance-DULFcpd1.js.map +1 -0
- package/dist/{maintenance-C7coQp4c.js → maintenance-fEi-UZ2o.js} +5 -11
- package/dist/maintenance-fEi-UZ2o.js.map +1 -0
- package/dist/maintenance.d.ts +1 -1
- package/dist/maintenance.js +1 -1
- package/dist/node.d.ts +22 -61
- package/dist/node.js +4 -3
- package/dist/{observability-wzs3-BL_.js → observability-Ch-VQJyE.js} +85 -27
- package/dist/{observability-wzs3-BL_.js.map → observability-Ch-VQJyE.js.map} +1 -1
- package/dist/observability.d.ts +2 -2
- package/dist/observability.js +1 -1
- package/dist/{plan-a7PJHBCy.js → plan-C4qgiXSg.js} +2 -2
- package/dist/{plan-a7PJHBCy.js.map → plan-C4qgiXSg.js.map} +1 -1
- package/dist/{query-rAtXNQQB.js → query-C43r-6ib.js} +2 -2
- package/dist/{query-rAtXNQQB.js.map → query-C43r-6ib.js.map} +1 -1
- package/dist/{rebuild-index-BVzQSZlm.js → rebuild-index-BH1dc1p6.js} +4 -4
- package/dist/{rebuild-index-BVzQSZlm.js.map → rebuild-index-BH1dc1p6.js.map} +1 -1
- package/dist/{restore-R-4rbciV.js → restore-D0VYWzfP.js} +5 -5
- package/dist/{restore-R-4rbciV.js.map → restore-D0VYWzfP.js.map} +1 -1
- package/dist/{runtime-spec-_GTdeSMo.js → runtime-spec--LykAdl1.js} +2 -2
- package/dist/{runtime-spec-_GTdeSMo.js.map → runtime-spec--LykAdl1.js.map} +1 -1
- package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DD5gDc7t.d.ts} +6 -4
- package/dist/s3.d.ts +1 -1
- package/dist/s3.js +1 -1
- package/dist/sha256-CqcKTjw9.js +22 -0
- package/dist/sha256-CqcKTjw9.js.map +1 -0
- package/dist/{src-D__mHQmQ.js → src-BMFfDUI2.js} +69 -29
- package/dist/src-BMFfDUI2.js.map +1 -0
- package/dist/{src-CYHFDrKz.js → src-DvbTEya2.js} +3 -3
- package/dist/{src-CYHFDrKz.js.map → src-DvbTEya2.js.map} +1 -1
- package/dist/{subcommand-DoDA-K7d.js → subcommand-BV68pqwJ.js} +2 -2
- package/dist/{subcommand-DoDA-K7d.js.map → subcommand-BV68pqwJ.js.map} +1 -1
- package/dist/{usage-DBV1eQHC.js → usage-BMZR8o6U.js} +3 -3
- package/dist/{usage-DBV1eQHC.js.map → usage-BMZR8o6U.js.map} +1 -1
- package/package.json +12 -6
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
- package/dist/cloudflare-DzKBrUlg.js.map +0 -1
- package/dist/config-1tv0-Yzm.js.map +0 -1
- package/dist/deploy-DonTr-CV.js.map +0 -1
- package/dist/doctor-DSIyCDg_.js +0 -346
- package/dist/doctor-DSIyCDg_.js.map +0 -1
- package/dist/log-tail-D98U1JBo.js.map +0 -1
- package/dist/maintenance-B4Dki6Ig.js.map +0 -1
- package/dist/maintenance-C7coQp4c.js.map +0 -1
- package/dist/src-D__mHQmQ.js.map +0 -1
package/dist/dev-vite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev-vite.js","names":[],"sources":["../packages/dev/src/vite-plugin.ts"],"sourcesContent":["import type { AddressInfo } from \"node:net\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport type { Plugin } from \"vite\";\nimport { baerlyNode } from \"@baerly/adapter-node\";\nimport type { BaerlyAppConfig, Verifier } from \"@baerly/protocol\";\nimport { Db, resolveVerifier } from \"@baerly/server\";\nimport { type DevBannerHint, printDevBanner } from \"./dev-banner.ts\";\nimport { ensureTable } from \"./ensure-table.ts\";\nimport { LocalFsStorage } from \"./local-fs.ts\";\n\nexport interface BaerlyDevOptions {\n /**\n * The project's `baerly.config.ts`. `app`, `tenant`, `auth`, and the\n * table set (`Object.keys(config.collections)`) are derived from it.\n * Per-collection schemas/indexes flow through to the in-process\n * listener the same way `baerlyNode` / `baerlyWorker` pipe them.\n */\n readonly config: BaerlyAppConfig;\n /**\n * Shared-secret token. **Optional.** Required only when\n * `config.auth === \"shared-secret\"` and `verifier` is unset — in\n * that branch, clients must send `Authorization: Bearer <secret>`\n * AND the middleware injects the same bearer server-side before\n * forwarding to the in-process listener.\n *\n * Ignored when `config.auth === \"none\"` (no bearer to inject) or\n * when `verifier` is supplied (the operator owns the auth seam).\n *\n * Throwing the symmetric `InvalidConfig` on a misconfig matches\n * production behaviour: forgetting `SHARED_SECRET` in dev fails\n * fast at `vite dev` startup with the same locked wording the\n * adapter would emit.\n */\n readonly secret?: string;\n /**\n * Per-request `Verifier`. **Optional.** When set, overrides both\n * `config.auth` and `secret` (same precedence as the production\n * adapter factories). Use for dev-mode JWT validation against a\n * staging IdP, or any custom auth shape.\n */\n readonly verifier?: Verifier;\n /**\n * Absolute path to the data directory for LocalFsStorage.\n * **Optional** — defaults to `<vite root>/.baerly-data`, so the dev\n * server runs zero-config.\n */\n readonly dataDir?: string;\n /** Optional async seed callback, invoked after ensureTable, before mount. */\n readonly seed?: (db: Db) => Promise<void>;\n /** Extra hints appended to the dev banner. */\n readonly hints?: readonly DevBannerHint[];\n /** Set to false to suppress the dev banner. Default: true. */\n readonly banner?: boolean;\n}\n\nconst isV1Path = (url: string): boolean =>\n url === \"/v1\" || url.startsWith(\"/v1/\") || url.startsWith(\"/v1?\");\n\n/**\n * Inject `Authorization: ${value}` into a Node `IncomingMessage` such\n * that BOTH the parsed (`req.headers`) and the wire-form (`req.rawHeaders`)\n * views agree.\n *\n * Why both: `req.headers` is the parsed-and-lowercased JS map most\n * connect-style middleware reads, but Node→Fetch bridges typically\n * rebuild the Fetch `Headers` from `req.rawHeaders` (the original\n * `[name, value, name, value, …]` wire array) to preserve case and\n * multi-value semantics. `@cloudflare/vite-plugin`'s `createHeaders()`\n * does exactly that — so mutating `req.headers` alone silently drops\n * the bearer token when the in-process Worker receives the request.\n * Treat any new injection in this file as obligated to touch both.\n */\nconst injectAuthorizationHeader = (\n req: {\n headers: Record<string, string | string[] | undefined>;\n rawHeaders?: string[];\n },\n value: string,\n): void => {\n req.headers[\"authorization\"] = value;\n const raw = req.rawHeaders;\n if (raw === undefined) {\n return;\n }\n for (let i = 0; i < raw.length; i += 2) {\n if (raw[i]!.toLowerCase() === \"authorization\") {\n raw[i + 1] = value;\n return;\n }\n }\n raw.push(\"Authorization\", value);\n};\n\nexport interface BaerlyDevAuthOptions {\n /** Bearer token to inject on matched paths. */\n readonly secret: string;\n /**\n * Pathname prefixes to match. Default `[\"/v1\", \"/api\"]` — the\n * baerly cascade lives at `/v1/*`, and `/api/*` is the canonical\n * namespace for custom Worker routes (the \"wrap `baerly.fetch!`\"\n * recipe in the scaffold's AGENTS.md). Covering both by default\n * closes a recurring \"added a custom route, browser silently 401s\"\n * trap: agents typically edit `src/server/index.ts` without touching\n * `vite.config.ts`, so a `\"/v1\"`-only default leaves their new route\n * unauthenticated in `vite dev` and `pnpm verify` is silent on it.\n *\n * Override when you mount under a different namespace, or pass\n * `prefix: \"/v1\"` to opt out of `/api/*` injection entirely (rare —\n * the bearer is a harmless extra header on unmatched routes).\n */\n readonly prefix?: string | readonly string[];\n}\n\nconst normalisePrefixes = (prefix: string | readonly string[] | undefined): readonly string[] => {\n if (prefix === undefined) {\n return [\"/v1\", \"/api\"];\n }\n if (typeof prefix === \"string\") {\n return [prefix];\n }\n return prefix;\n};\n\nconst matchesAnyPrefix = (url: string, prefixes: readonly string[]): boolean => {\n for (const prefix of prefixes) {\n if (url === prefix || url.startsWith(`${prefix}/`) || url.startsWith(`${prefix}?`)) {\n return true;\n }\n }\n return false;\n};\n\n/**\n * Vite dev plugin: inject `Authorization: Bearer ${secret}` on every\n * request whose URL starts with one of `prefix` (default\n * `[\"/v1\", \"/api\"]`). Use this to keep the bearer token out of the\n * SPA bundle — the browser sends the request, Vite's middleware adds\n * the header, and the upstream handler (in-process worker or proxied\n * Node server) sees an authenticated request.\n *\n * **Custom Worker routes.** `baerlyWorker` only sees `/v1/*`; the\n * default `prefix` also covers `/api/*` because that's the canonical\n * namespace for the \"wrap `baerly.fetch!`\" recipe (a server-side\n * endpoint the SPA client can't run on its own, e.g. an endpoint\n * that fans a write across several documents server-side). If you\n * mount under a different namespace, override:\n *\n * ```ts\n * baerlyDevAuth({ secret, prefix: [\"/v1\", \"/internal\"] });\n * ```\n *\n * The bearer is dev-only convenience — production deploys put the\n * SPA, the baerly cascade, AND your custom routes behind the same\n * tenant boundary (CF Access, an upstream JWT, …), so this matters\n * exclusively while `vite dev` is the front door.\n *\n * @example\n * ```ts\n * import { baerlyDevAuth, loadDevVars } from \"@gusto/baerly-storage/dev/vite\";\n *\n * const { SHARED_SECRET } = loadDevVars(\".dev.vars\", \"SHARED_SECRET\");\n * export default defineConfig({\n * plugins: [\n * cloudflare(),\n * baerlyDevAuth({ secret: SHARED_SECRET ?? \"\" }),\n * ],\n * });\n * ```\n */\nexport function baerlyDevAuth(opts: BaerlyDevAuthOptions): Plugin {\n if (opts.secret === \"\") {\n throw new Error(\n \"baerlyDevAuth: secret must be non-empty. Set SHARED_SECRET in .dev.vars / .env.\",\n );\n }\n const prefixes: readonly string[] = normalisePrefixes(opts.prefix);\n return {\n name: \"baerly-dev-auth\",\n apply: \"serve\",\n configureServer(server) {\n server.middlewares.use((req, _res, next) => {\n const url = req.url ?? \"\";\n if (matchesAnyPrefix(url, prefixes)) {\n injectAuthorizationHeader(req, `Bearer ${opts.secret}`);\n }\n next();\n });\n },\n };\n}\n\n/**\n * Parse a `.dev.vars` / `.env` file and return the values for the\n * requested `keys`. Supports `KEY=value`, `# comments`, blank lines,\n * and single- or double-quoted values. Keys missing from the file\n * (or the whole file when it does not exist) come back as\n * `undefined` — fall back with `??` at the call site.\n *\n * The return type is `Record<K, string | undefined>` where `K` is\n * the union of literal key names you pass in, so property access\n * works under strict `noPropertyAccessFromIndexSignature`:\n *\n * ```ts\n * const { SHARED_SECRET } = loadDevVars(\".dev.vars\", \"SHARED_SECRET\");\n * // ^? string | undefined\n * ```\n */\nexport function loadDevVars<K extends string>(\n path: string,\n ...keys: readonly K[]\n): Record<K, string | undefined> {\n const out = {} as Record<K, string | undefined>;\n for (const key of keys) {\n out[key] = undefined;\n }\n if (!existsSync(path)) {\n return out;\n }\n const wanted = new Set<string>(keys);\n for (const rawLine of readFileSync(path, \"utf8\").split(\"\\n\")) {\n const line = rawLine.trim();\n if (line === \"\" || line.startsWith(\"#\")) {\n continue;\n }\n const eq = line.indexOf(\"=\");\n if (eq === -1) {\n continue;\n }\n const key = line.slice(0, eq).trim();\n if (!wanted.has(key)) {\n continue;\n }\n let value = line.slice(eq + 1).trim();\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n out[key as K] = value;\n }\n return out;\n}\n\n/**\n * Resolution order for the in-process verifier (mirrors\n * `baerlyNode` / `baerlyWorker`):\n *\n * 1. `opts.verifier` set → use as-is.\n * 2. else `opts.config.auth === \"shared-secret\"` → require\n * `opts.secret`; build `sharedSecret({ secret, tenantPrefix:\n * config.tenant })`. Throws `BaerlyError(\"InvalidConfig\", ...)`\n * at Vite startup when `opts.secret` is empty/unset — same\n * locked wording the production adapter would emit.\n * 3. else `opts.config.auth === \"none\"` → pin every request to\n * `config.tenant`; no header check.\n *\n * Bearer injection on `/v1/*` only fires in branch 2 (and only when\n * branch 1 didn't win) — the dev convenience that lets the SPA call\n * the listener without putting the secret in the browser bundle.\n * Branch 3 leaves the `Authorization` header alone.\n *\n * Verifier resolution happens eagerly at factory time so a misconfig\n * fails Vite startup, not the first `/v1/*` round-trip.\n */\nexport function baerlyDev(opts: BaerlyDevOptions): Plugin {\n // Resolution order: opts.verifier → config.auth.shared-secret →\n // config.auth.none → throw. Mirrors `baerlyWorker` / `baerlyNode`.\n // The synthetic `readEnv` hoists `opts.secret` to `SHARED_SECRET`\n // so the same resolver works — `baerlyDev` takes the secret as a\n // typed option rather than reading `process.env` directly.\n const verifier = resolveVerifier({\n factoryVerifier: opts.verifier,\n config: opts.config,\n readEnv: (k) => (k === \"SHARED_SECRET\" ? opts.secret : process.env[k]),\n });\n\n // Bearer injection only matters in the shared-secret branch (and\n // only when no override owns auth). For \"none\" or any custom\n // verifier, the `Authorization` header reaches the listener\n // unchanged.\n const bearerForInjection: string | undefined =\n opts.verifier === undefined && opts.config.auth === \"shared-secret\" ? opts.secret : undefined;\n\n return {\n name: \"baerly-dev\",\n apply: \"serve\",\n configureServer(server) {\n // Mount in the configureServer body (not a post-hook) so the\n // middleware runs BEFORE Vite's internal SPA history fallback.\n // Otherwise /v1/* requests get caught by the SPA fallback and\n // served the index.html shell.\n const app = opts.config.app;\n const tenant = opts.config.tenant;\n const tables = Object.keys(opts.config.collections);\n const ready = (async () => {\n const storage = new LocalFsStorage({\n root: opts.dataDir ?? resolve(server.config.root, \".baerly-data\"),\n });\n for (const table of tables) {\n await ensureTable(storage, { app, tenant, table });\n }\n if (opts.seed !== undefined) {\n const db = Db.create({ storage, app, tenant, config: opts.config });\n await opts.seed(db);\n }\n const requestHandler = baerlyNode({\n config: opts.config,\n storage,\n verifier,\n }).fetch;\n return getRequestListener(requestHandler);\n })();\n\n // Surface setup failures eagerly; without this an unhandled\n // rejection would silently kill the dev server.\n ready.catch((error: unknown) => {\n console.error(\"[baerly-dev] setup failed:\", error);\n });\n\n server.middlewares.use((req, res, next) => {\n const url = req.url;\n if (url === undefined || !isV1Path(url)) {\n next();\n return;\n }\n // Inject the bearer token server-side so the SPA never sees\n // the secret. Only runs for `config.auth === \"shared-secret\"`\n // without a `verifier:` override — otherwise the header\n // reaches the listener unchanged. Mutates both `req.headers`\n // and `req.rawHeaders` — see `injectAuthorizationHeader`'s\n // JSDoc.\n if (bearerForInjection !== undefined) {\n injectAuthorizationHeader(req, `Bearer ${bearerForInjection}`);\n }\n ready.then(\n (listener) => {\n listener(req as never, res as never);\n },\n (error: unknown) => {\n res.statusCode = 503;\n res.setHeader(\"content-type\", \"application/json\");\n res.end(JSON.stringify({ error: \"baerly-dev setup failed\", message: String(error) }));\n },\n );\n });\n\n if (opts.banner !== false) {\n server.httpServer?.once(\"listening\", () => {\n const address = server.httpServer?.address();\n const port =\n typeof address === \"object\" && address !== null\n ? (address as AddressInfo).port\n : undefined;\n const url = port !== undefined ? `http://localhost:${port}/` : \"http://localhost/\";\n printDevBanner({\n name: opts.config.app,\n primaryUrl: { label: \"App\", url },\n ...(opts.hints !== undefined && { hints: opts.hints }),\n });\n });\n }\n },\n };\n}\n"],"mappings":";;;;;;AAyDA,MAAM,YAAY,QAChB,QAAQ,SAAS,IAAI,WAAW,MAAM,KAAK,IAAI,WAAW,MAAM;;;;;;;;;;;;;;;AAgBlE,MAAM,6BACJ,KAIA,UACS;CACT,IAAI,QAAQ,mBAAmB;CAC/B,MAAM,MAAM,IAAI;CAChB,IAAI,QAAQ,KAAA,GACV;CAEF,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,GACnC,IAAI,IAAI,EAAE,CAAE,YAAY,MAAM,iBAAiB;EAC7C,IAAI,IAAI,KAAK;EACb;CACF;CAEF,IAAI,KAAK,iBAAiB,KAAK;AACjC;AAsBA,MAAM,qBAAqB,WAAsE;CAC/F,IAAI,WAAW,KAAA,GACb,OAAO,CAAC,OAAO,MAAM;CAEvB,IAAI,OAAO,WAAW,UACpB,OAAO,CAAC,MAAM;CAEhB,OAAO;AACT;AAEA,MAAM,oBAAoB,KAAa,aAAyC;CAC9E,KAAK,MAAM,UAAU,UACnB,IAAI,QAAQ,UAAU,IAAI,WAAW,GAAG,OAAO,EAAE,KAAK,IAAI,WAAW,GAAG,OAAO,EAAE,GAC/E,OAAO;CAGX,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,cAAc,MAAoC;CAChE,IAAI,KAAK,WAAW,IAClB,MAAM,IAAI,MACR,iFACF;CAEF,MAAM,WAA8B,kBAAkB,KAAK,MAAM;CACjE,OAAO;EACL,MAAM;EACN,OAAO;EACP,gBAAgB,QAAQ;GACtB,OAAO,YAAY,KAAK,KAAK,MAAM,SAAS;IAE1C,IAAI,iBADQ,I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M,SAAS,KAAA,IAAY,oBAAoB,KAAK,KAAK;IAC/D,eAAe;KACb,MAAM,KAAK,OAAO;KAClB,YAAY;MAAE,OAAO;MAAO;KAAI;KAChC,GAAI,KAAK,UAAU,KAAA,KAAa,EAAE,OAAO,KAAK,MAAM;IACtD,CAAC;GACH,CAAC;EAEL;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"dev-vite.js","names":[],"sources":["../packages/dev/src/vite-plugin.ts"],"sourcesContent":["import type { AddressInfo } from \"node:net\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport type { Plugin } from \"vite\";\nimport { baerlyNode } from \"@baerly/adapter-node\";\nimport { BaerlyError, type BaerlyAppConfig, type Verifier } from \"@baerly/protocol\";\nimport { Db, resolveVerifier } from \"@baerly/server\";\nimport { type DevBannerHint, printDevBanner } from \"./dev-banner.ts\";\nimport { ensureTable } from \"./ensure-table.ts\";\nimport { LocalFsStorage } from \"./local-fs.ts\";\n\nexport interface BaerlyDevOptions {\n /**\n * The project's `baerly.config.ts`. `app`, `tenant`, `auth`, and the\n * table set (`Object.keys(config.collections)`) are derived from it.\n * Per-collection schemas/indexes flow through to the in-process\n * listener the same way `baerlyNode` / `baerlyWorker` pipe them.\n *\n * **Optional.** If omitted, the config is loaded at dev-server startup\n * from `configPath`, or — if that's also omitted — by convention from\n * `<viteRoot>/src/baerly.config.ts`.\n *\n * Prefer omitting it (convention or `configPath`). Passing the object\n * means the caller's `vite.config` must `import` the config module,\n * which forces Nx's `@nx/vite` / `@nx/vitest` inference plugins to\n * bundle that module — and its transitive imports — while creating the\n * project graph. That pulls unresolved imports into the config bundle\n * and forces the app into the root `nx.json` inference-exclusion lists.\n * Letting `baerlyDev` load the config itself (below) keeps the caller's\n * `vite.config` import-free, the same way `reactRouter()` loads\n * `react-router.config.ts` by convention.\n */\n readonly config?: BaerlyAppConfig;\n /**\n * Absolute path to the `baerly.config` module (its default export is\n * the `BaerlyAppConfig`). Loaded lazily via Vite's `ssrLoadModule` at\n * dev-server startup. Overrides the `<viteRoot>/src/baerly.config.ts`\n * convention. Ignored when `config` is provided.\n */\n readonly configPath?: string;\n /**\n * Shared-secret token. **Optional.** Required only when\n * `config.auth === \"shared-secret\"` and `verifier` is unset — in\n * that branch, clients must send `Authorization: Bearer <secret>`\n * AND the middleware injects the same bearer server-side before\n * forwarding to the in-process listener.\n *\n * Ignored when `config.auth === \"none\"` (no bearer to inject) or\n * when `verifier` is supplied (the operator owns the auth seam).\n *\n * Throwing the symmetric `InvalidConfig` on a misconfig matches\n * production behaviour: forgetting `SHARED_SECRET` in dev throws\n * with the same locked wording the adapter would emit. With an\n * explicit `config` object this fails fast at `vite dev` startup\n * (factory-time resolution); when the config is loaded lazily\n * (`configPath` / convention) the throw is deferred to dev-server\n * startup and surfaces as a per-request 503 rather than aborting\n * the Vite process.\n */\n readonly secret?: string;\n /**\n * Per-request `Verifier`. **Optional.** When set, overrides both\n * `config.auth` and `secret` (same precedence as the production\n * adapter factories). Use for dev-mode JWT validation against a\n * staging IdP, or any custom auth shape.\n */\n readonly verifier?: Verifier;\n /**\n * Absolute path to the data directory for LocalFsStorage.\n * **Optional** — defaults to `<vite root>/.baerly-data`, so the dev\n * server runs zero-config.\n */\n readonly dataDir?: string;\n /** Optional async seed callback, invoked after ensureTable, before mount. */\n readonly seed?: (db: Db) => Promise<void>;\n /** Extra hints appended to the dev banner. */\n readonly hints?: readonly DevBannerHint[];\n /** Set to false to suppress the dev banner. Default: true. */\n readonly banner?: boolean;\n}\n\nconst isV1Path = (url: string): boolean =>\n url === \"/v1\" || url.startsWith(\"/v1/\") || url.startsWith(\"/v1?\");\n\n/**\n * Inject `Authorization: ${value}` into a Node `IncomingMessage` such\n * that BOTH the parsed (`req.headers`) and the wire-form (`req.rawHeaders`)\n * views agree.\n *\n * Why both: `req.headers` is the parsed-and-lowercased JS map most\n * connect-style middleware reads, but Node→Fetch bridges typically\n * rebuild the Fetch `Headers` from `req.rawHeaders` (the original\n * `[name, value, name, value, …]` wire array) to preserve case and\n * multi-value semantics. `@cloudflare/vite-plugin`'s `createHeaders()`\n * does exactly that — so mutating `req.headers` alone silently drops\n * the bearer token when the in-process Worker receives the request.\n * Treat any new injection in this file as obligated to touch both.\n */\nconst injectAuthorizationHeader = (\n req: {\n headers: Record<string, string | string[] | undefined>;\n rawHeaders?: string[];\n },\n value: string,\n): void => {\n req.headers[\"authorization\"] = value;\n const raw = req.rawHeaders;\n if (raw === undefined) {\n return;\n }\n for (let i = 0; i < raw.length; i += 2) {\n if (raw[i]!.toLowerCase() === \"authorization\") {\n raw[i + 1] = value;\n return;\n }\n }\n raw.push(\"Authorization\", value);\n};\n\nexport interface BaerlyDevAuthOptions {\n /** Bearer token to inject on matched paths. */\n readonly secret: string;\n /**\n * Pathname prefixes to match. Default `[\"/v1\", \"/api\"]` — the\n * baerly cascade lives at `/v1/*`, and `/api/*` is the canonical\n * namespace for custom Worker routes (the \"wrap `baerly.fetch!`\"\n * recipe in the scaffold's AGENTS.md). Covering both by default\n * closes a recurring \"added a custom route, browser silently 401s\"\n * trap: agents typically edit `src/server/index.ts` without touching\n * `vite.config.ts`, so a `\"/v1\"`-only default leaves their new route\n * unauthenticated in `vite dev` and `pnpm verify` is silent on it.\n *\n * Override when you mount under a different namespace, or pass\n * `prefix: \"/v1\"` to opt out of `/api/*` injection entirely (rare —\n * the bearer is a harmless extra header on unmatched routes).\n */\n readonly prefix?: string | readonly string[];\n}\n\nconst normalisePrefixes = (prefix: string | readonly string[] | undefined): readonly string[] => {\n if (prefix === undefined) {\n return [\"/v1\", \"/api\"];\n }\n if (typeof prefix === \"string\") {\n return [prefix];\n }\n return prefix;\n};\n\nconst matchesAnyPrefix = (url: string, prefixes: readonly string[]): boolean => {\n for (const prefix of prefixes) {\n if (url === prefix || url.startsWith(`${prefix}/`) || url.startsWith(`${prefix}?`)) {\n return true;\n }\n }\n return false;\n};\n\n/**\n * Vite dev plugin: inject `Authorization: Bearer ${secret}` on every\n * request whose URL starts with one of `prefix` (default\n * `[\"/v1\", \"/api\"]`). Use this to keep the bearer token out of the\n * SPA bundle — the browser sends the request, Vite's middleware adds\n * the header, and the upstream handler (in-process worker or proxied\n * Node server) sees an authenticated request.\n *\n * **Custom Worker routes.** `baerlyWorker` only sees `/v1/*`; the\n * default `prefix` also covers `/api/*` because that's the canonical\n * namespace for the \"wrap `baerly.fetch!`\" recipe (a server-side\n * endpoint the SPA client can't run on its own, e.g. an endpoint\n * that fans a write across several documents server-side). If you\n * mount under a different namespace, override:\n *\n * ```ts\n * baerlyDevAuth({ secret, prefix: [\"/v1\", \"/internal\"] });\n * ```\n *\n * The bearer is dev-only convenience — production deploys put the\n * SPA, the baerly cascade, AND your custom routes behind the same\n * tenant boundary (CF Access, an upstream JWT, …), so this matters\n * exclusively while `vite dev` is the front door.\n *\n * @example\n * ```ts\n * import { baerlyDevAuth, loadDevVars } from \"@gusto/baerly-storage/dev/vite\";\n *\n * const { SHARED_SECRET } = loadDevVars(\".dev.vars\", \"SHARED_SECRET\");\n * export default defineConfig({\n * plugins: [\n * cloudflare(),\n * baerlyDevAuth({ secret: SHARED_SECRET ?? \"\" }),\n * ],\n * });\n * ```\n */\nexport function baerlyDevAuth(opts: BaerlyDevAuthOptions): Plugin {\n if (opts.secret === \"\") {\n throw new Error(\n \"baerlyDevAuth: secret must be non-empty. Set SHARED_SECRET in .dev.vars / .env.\",\n );\n }\n const prefixes: readonly string[] = normalisePrefixes(opts.prefix);\n return {\n name: \"baerly-dev-auth\",\n apply: \"serve\",\n configureServer(server) {\n server.middlewares.use((req, _res, next) => {\n const url = req.url ?? \"\";\n if (matchesAnyPrefix(url, prefixes)) {\n injectAuthorizationHeader(req, `Bearer ${opts.secret}`);\n }\n next();\n });\n },\n };\n}\n\n/**\n * Parse a `.dev.vars` / `.env` file and return the values for the\n * requested `keys`. Supports `KEY=value`, `# comments`, blank lines,\n * and single- or double-quoted values. Keys missing from the file\n * (or the whole file when it does not exist) come back as\n * `undefined` — fall back with `??` at the call site.\n *\n * The return type is `Record<K, string | undefined>` where `K` is\n * the union of literal key names you pass in, so property access\n * works under strict `noPropertyAccessFromIndexSignature`:\n *\n * ```ts\n * const { SHARED_SECRET } = loadDevVars(\".dev.vars\", \"SHARED_SECRET\");\n * // ^? string | undefined\n * ```\n */\nexport function loadDevVars<K extends string>(\n path: string,\n ...keys: readonly K[]\n): Record<K, string | undefined> {\n const out = {} as Record<K, string | undefined>;\n for (const key of keys) {\n out[key] = undefined;\n }\n if (!existsSync(path)) {\n return out;\n }\n const wanted = new Set<string>(keys);\n for (const rawLine of readFileSync(path, \"utf8\").split(\"\\n\")) {\n const line = rawLine.trim();\n if (line === \"\" || line.startsWith(\"#\")) {\n continue;\n }\n const eq = line.indexOf(\"=\");\n if (eq === -1) {\n continue;\n }\n const key = line.slice(0, eq).trim();\n if (!wanted.has(key)) {\n continue;\n }\n let value = line.slice(eq + 1).trim();\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n out[key as K] = value;\n }\n return out;\n}\n\n/**\n * Resolution order for the in-process verifier (mirrors\n * `baerlyNode` / `baerlyWorker`):\n *\n * 1. `opts.verifier` set → use as-is.\n * 2. else `config.auth === \"shared-secret\"` → require\n * `opts.secret`; build `sharedSecret({ secret, tenantPrefix:\n * config.tenant })`. Throws `BaerlyError(\"InvalidConfig\", ...)`\n * when `opts.secret` is empty/unset — same locked wording the\n * production adapter would emit.\n * 3. else `config.auth === \"none\"` → pin every request to\n * `config.tenant`; no header check.\n *\n * Bearer injection on `/v1/*` only fires in branch 2 (and only when\n * branch 1 didn't win) — the dev convenience that lets the SPA call\n * the listener without putting the secret in the browser bundle.\n * Branch 3 leaves the `Authorization` header alone.\n *\n * When an explicit `config` object is passed, verifier resolution happens\n * eagerly at factory time so a misconfig fails Vite startup, not the first\n * `/v1/*` round-trip. When the config is loaded lazily (`configPath` or the\n * `<viteRoot>/src/baerly.config.ts` convention), that resolution is deferred\n * to dev-server startup, once the config is available.\n */\nfunction resolveAuth(opts: BaerlyDevOptions, config: BaerlyAppConfig) {\n // Resolution order: opts.verifier → config.auth.shared-secret →\n // config.auth.none → throw. Mirrors `baerlyWorker` / `baerlyNode`. The\n // synthetic `readEnv` hoists `opts.secret` to `SHARED_SECRET` so the same\n // resolver works — `baerlyDev` takes the secret as a typed option rather\n // than reading `process.env` directly.\n const verifier = resolveVerifier({\n factoryVerifier: opts.verifier,\n config,\n readEnv: (k) => (k === \"SHARED_SECRET\" ? opts.secret : process.env[k]),\n });\n // Bearer injection only matters in the shared-secret branch (and only when\n // no override owns auth). For \"none\" or any custom verifier, the\n // `Authorization` header reaches the listener unchanged.\n const bearerForInjection: string | undefined =\n opts.verifier === undefined && config.auth === \"shared-secret\" ? opts.secret : undefined;\n return { verifier, bearerForInjection };\n}\n\nexport function baerlyDev(opts: BaerlyDevOptions): Plugin {\n // Eager, factory-time auth resolution when a `config` object is passed —\n // preserves fail-fast startup on misconfig. When `config` is omitted it's\n // loaded lazily in `configureServer` (see below) and auth resolves there.\n const eagerAuth = opts.config !== undefined ? resolveAuth(opts, opts.config) : undefined;\n // Readiness handle: resolves once configureServer's async setup settles\n // (success OR failure). The setup runs un-awaited in the background (Vite\n // doesn't await configureServer's internal promises), so without this\n // there is no way to know it has finished touching the data dir. Exposed\n // via Vite's `api` field so a caller — or a test that provisions a\n // throwaway data dir — can await settle before tearing that dir down,\n // rather than racing the in-flight `ensureTable`/`storage.put`.\n let markSettled!: () => void;\n const whenSettled = new Promise<void>((settle) => {\n markSettled = settle;\n });\n return {\n name: \"baerly-dev\",\n apply: \"serve\",\n api: { whenSettled },\n configureServer(server) {\n // Everything below runs at dev-server startup, NOT at plugin-factory\n // time. That lets callers omit `config` and instead have us load\n // `baerly.config` here (via `configPath`, or by convention) — so their\n // `vite.config` never imports the config module. Resolving it here\n // rather than in the factory is what keeps baerly apps out of Nx's\n // inference-plugin exclusion lists (see `BaerlyDevOptions.config`).\n //\n // Mount the middleware in the configureServer body (not a post-hook) so\n // it runs BEFORE Vite's internal SPA history fallback; otherwise /v1/*\n // requests get caught by the fallback and served the index.html shell.\n const ready = (async () => {\n // Resolution order for the config source: explicit `config` object →\n // explicit `configPath` → convention `<viteRoot>/src/baerly.config.ts`.\n let config: BaerlyAppConfig;\n if (opts.config !== undefined) {\n config = opts.config;\n } else {\n const configPath = opts.configPath ?? resolve(server.config.root, \"src/baerly.config.ts\");\n const mod = (await server.ssrLoadModule(configPath)) as { default?: unknown };\n // Mirrors packages/cli/src/config.ts's loadAppConfig: a module with no\n // (or a misnamed) default export would otherwise silently become\n // `undefined` here, surfacing later as a bare `TypeError` on the first\n // `config.app` read with no hint that the real problem is the export.\n if (typeof mod.default !== \"object\" || mod.default === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly-dev: ${configPath} must default-export a BaerlyAppConfig object`,\n );\n }\n config = mod.default as BaerlyAppConfig;\n }\n\n // Reuse the eager (factory-time) auth resolution when a `config` object\n // was passed; otherwise resolve now that the loaded config is available.\n const { verifier, bearerForInjection } = eagerAuth ?? resolveAuth(opts, config);\n\n const app = config.app;\n const tenant = config.tenant;\n const tables = Object.keys(config.collections);\n const storage = new LocalFsStorage({\n root: opts.dataDir ?? resolve(server.config.root, \".baerly-data\"),\n });\n for (const table of tables) {\n await ensureTable(storage, { app, tenant, table });\n }\n if (opts.seed !== undefined) {\n const db = Db.create({ storage, app, tenant, config });\n await opts.seed(db);\n }\n const requestHandler = baerlyNode({ config, storage, verifier }).fetch;\n return {\n listener: getRequestListener(requestHandler),\n bearerForInjection,\n appName: config.app,\n };\n })();\n\n // Surface setup failures eagerly; without this an unhandled\n // rejection would silently kill the dev server.\n ready.catch((error: unknown) => {\n console.error(\"[baerly-dev] setup failed:\", error);\n });\n // Settle the exposed readiness handle regardless of outcome — a\n // failed setup is still \"done\", and awaiters (see `api.whenSettled`)\n // only need to know the background work has stopped touching storage.\n void ready.then(markSettled, markSettled);\n\n server.middlewares.use((req, res, next) => {\n const url = req.url;\n if (url === undefined || !isV1Path(url)) {\n next();\n return;\n }\n // Inject the bearer token server-side so the SPA never sees the secret.\n // Only for `config.auth === \"shared-secret\"` without a `verifier:`\n // override — otherwise the header reaches the listener unchanged.\n // Mutates both `req.headers` and `req.rawHeaders` (see\n // `injectAuthorizationHeader`'s JSDoc). When auth resolved eagerly\n // (explicit `config`), inject synchronously here — before the async\n // listener resolves — preserving the pre-lazy-load timing. When the\n // config is loaded lazily, the bearer isn't known yet, so injection\n // happens in the `ready.then` below (still before the listener runs).\n if (eagerAuth?.bearerForInjection !== undefined) {\n injectAuthorizationHeader(req, `Bearer ${eagerAuth.bearerForInjection}`);\n }\n ready.then(\n ({ listener, bearerForInjection }) => {\n if (eagerAuth === undefined && bearerForInjection !== undefined) {\n injectAuthorizationHeader(req, `Bearer ${bearerForInjection}`);\n }\n listener(req as never, res as never);\n },\n (error: unknown) => {\n res.statusCode = 503;\n res.setHeader(\"content-type\", \"application/json\");\n res.end(JSON.stringify({ error: \"baerly-dev setup failed\", message: String(error) }));\n },\n );\n });\n\n if (opts.banner !== false) {\n server.httpServer?.once(\"listening\", () => {\n const address = server.httpServer?.address();\n const port =\n typeof address === \"object\" && address !== null\n ? (address as AddressInfo).port\n : undefined;\n const url = port !== undefined ? `http://localhost:${port}/` : \"http://localhost/\";\n ready\n .then(({ appName }) => {\n printDevBanner({\n name: appName,\n primaryUrl: { label: \"App\", url },\n ...(opts.hints !== undefined && { hints: opts.hints }),\n });\n })\n // A rejected `ready` is already logged by the `ready.catch` above.\n // Each `.then()`/`.catch()` call creates its own derived promise,\n // so without this, a config-load failure here would be a SECOND,\n // unguarded rejection — the exact \"unhandled rejection kills the\n // dev server\" failure that catch was added to prevent.\n .catch(() => {});\n });\n }\n },\n };\n}\n"],"mappings":";;;;;;;AAkFA,MAAM,YAAY,QAChB,QAAQ,SAAS,IAAI,WAAW,MAAM,KAAK,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K,UAAU,oBAAoB;KAE/D,SAAS,KAAc,GAAY;IACrC,IACC,UAAmB;KAClB,IAAI,aAAa;KACjB,IAAI,UAAU,gBAAgB,kBAAkB;KAChD,IAAI,IAAI,KAAK,UAAU;MAAE,OAAO;MAA2B,SAAS,OAAO,KAAK;KAAE,CAAC,CAAC;IACtF,CACF;GACF,CAAC;GAED,IAAI,KAAK,WAAW,OAClB,OAAO,YAAY,KAAK,mBAAmB;IACzC,MAAM,UAAU,OAAO,YAAY,QAAQ;IAC3C,MAAM,OACJ,OAAO,YAAY,YAAY,YAAY,OACtC,QAAwB,OACzB,KAAA;IACN,MAAM,MAAM,SAAS,KAAA,IAAY,oBAAoB,KAAK,KAAK;IAC/D,MACG,MAAM,EAAE,cAAc;KACrB,eAAe;MACb,MAAM;MACN,YAAY;OAAE,OAAO;OAAO;MAAI;MAChC,GAAI,KAAK,UAAU,KAAA,KAAa,EAAE,OAAO,KAAK,MAAM;KACtD,CAAC;IACH,CAAC,CAAC,CAMD,YAAY,CAAC,CAAC;GACnB,CAAC;EAEL;CACF;AACF"}
|
package/dist/dev.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { n as DevBannerOpts, r as printDevBanner, t as DevBannerHint } from "./dev-banner-CWHIk8tH.js";
|
|
2
|
-
import { a as renderDevLanding, i as DevLandingOptions, n as LocalFsStorageOptions, r as ensureTable, t as LocalFsStorage } from "./index-
|
|
2
|
+
import { a as renderDevLanding, i as DevLandingOptions, n as LocalFsStorageOptions, r as ensureTable, t as LocalFsStorage } from "./index-uE-w2dgj.js";
|
|
3
3
|
export { type DevBannerHint, type DevBannerOpts, type DevLandingOptions, LocalFsStorage, LocalFsStorageOptions, ensureTable, printDevBanner, renderDevLanding };
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { r as parseBucketUri, t as loadAppConfig } from "./config-B6nTy8e2.js";
|
|
2
|
+
import { a as mergeReports, i as doctorCloudflare, n as defaultRunner, o as doctorCas, r as doctorGcsConfig } from "./cloudflare-wrVYf4bb.js";
|
|
3
|
+
import { i as isJsonMode, o as BaerlyError, t as color } from "./baerly.js";
|
|
4
|
+
import { i as JSON_ARG, s as defineBaerlySubcommand } from "./subcommand-BV68pqwJ.js";
|
|
5
|
+
//#region src/doctor.ts
|
|
6
|
+
const DOCTOR_ARGS = {
|
|
7
|
+
target: {
|
|
8
|
+
type: "string",
|
|
9
|
+
description: "Override `baerly.config.ts:target`. Only \"cloudflare\" supported (Node variants self-validate at scaffold time).",
|
|
10
|
+
valueHint: "cloudflare"
|
|
11
|
+
},
|
|
12
|
+
bucket: {
|
|
13
|
+
type: "string",
|
|
14
|
+
description: "Live-probe a bucket's CAS support (writes + deletes one sentinel; verifies If-Match / If-None-Match are honoured). s3://, gcs://, file:///, or memory:// URI. For gcs://, also runs GCS-specific bucket-config checks (Object Versioning probe + soft-delete advisory). Independent of --target.",
|
|
15
|
+
valueHint: "s3://bucket/prefix | gcs://bucket"
|
|
16
|
+
},
|
|
17
|
+
fix: {
|
|
18
|
+
type: "boolean",
|
|
19
|
+
description: "Remediate auto-fixable findings (R2 bucket creation; secret prompts stay manual)."
|
|
20
|
+
},
|
|
21
|
+
json: JSON_ARG
|
|
22
|
+
};
|
|
23
|
+
const SEVERITY_GLYPH = {
|
|
24
|
+
ok: "✓",
|
|
25
|
+
info: "•",
|
|
26
|
+
warning: "⚠",
|
|
27
|
+
error: "✗"
|
|
28
|
+
};
|
|
29
|
+
const colorize = (severity, glyph) => {
|
|
30
|
+
if (severity === "error") return color.red(glyph);
|
|
31
|
+
if (severity === "warning") return color.yellow(glyph);
|
|
32
|
+
if (severity === "info") return color.dim(glyph);
|
|
33
|
+
return glyph;
|
|
34
|
+
};
|
|
35
|
+
const renderReport = (label, report) => {
|
|
36
|
+
if (isJsonMode()) {
|
|
37
|
+
process.stdout.write(`${JSON.stringify({ result: {
|
|
38
|
+
command: "doctor",
|
|
39
|
+
[label.kind]: label.value,
|
|
40
|
+
...report
|
|
41
|
+
} })}\n`);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
process.stdout.write(`baerly doctor --${label.kind}=${label.value}\n\n`);
|
|
45
|
+
let okCount = 0;
|
|
46
|
+
let warningCount = 0;
|
|
47
|
+
let errorCount = 0;
|
|
48
|
+
for (const f of report.findings) {
|
|
49
|
+
const glyph = SEVERITY_GLYPH[f.severity] ?? "•";
|
|
50
|
+
process.stdout.write(` ${colorize(f.severity, glyph)} ${f.message}\n`);
|
|
51
|
+
if (f.fix !== void 0) process.stdout.write(` fix: ${f.fix}\n`);
|
|
52
|
+
if (f.severity === "ok") okCount += 1;
|
|
53
|
+
else if (f.severity === "warning") warningCount += 1;
|
|
54
|
+
else if (f.severity === "error") errorCount += 1;
|
|
55
|
+
}
|
|
56
|
+
process.stdout.write(`\nStatus: ${errorCount} error${errorCount === 1 ? "" : "s"}, ${warningCount} warning${warningCount === 1 ? "" : "s"}, ${okCount} ok.\n`);
|
|
57
|
+
};
|
|
58
|
+
const bundle = defineBaerlySubcommand({
|
|
59
|
+
name: "doctor",
|
|
60
|
+
meta: { description: "Walk the deploy invariants and report findings. Dispatches by baerly.config.ts:target." },
|
|
61
|
+
args: DOCTOR_ARGS,
|
|
62
|
+
handler: async (args) => {
|
|
63
|
+
if (args.bucket !== void 0) {
|
|
64
|
+
const { storage, keyPrefix, gcs } = await parseBucketUri(args.bucket);
|
|
65
|
+
if (gcs !== void 0) {
|
|
66
|
+
const merged = mergeReports([await doctorCas(storage, keyPrefix, { staleEtag: "1" }), await doctorGcsConfig(gcs)]);
|
|
67
|
+
renderReport({
|
|
68
|
+
kind: "bucket",
|
|
69
|
+
value: args.bucket
|
|
70
|
+
}, merged);
|
|
71
|
+
return merged.status === "error" ? 2 : 0;
|
|
72
|
+
}
|
|
73
|
+
const report = await doctorCas(storage, keyPrefix);
|
|
74
|
+
renderReport({
|
|
75
|
+
kind: "bucket",
|
|
76
|
+
value: args.bucket
|
|
77
|
+
}, report);
|
|
78
|
+
return report.status === "error" ? 2 : 0;
|
|
79
|
+
}
|
|
80
|
+
const config = await loadAppConfig();
|
|
81
|
+
const target = args.target ?? config.target;
|
|
82
|
+
if (target === "cloudflare") {
|
|
83
|
+
const report = await doctorCloudflare(config, {
|
|
84
|
+
runner: defaultRunner(),
|
|
85
|
+
...args.fix === true && { fix: true }
|
|
86
|
+
});
|
|
87
|
+
renderReport({
|
|
88
|
+
kind: "target",
|
|
89
|
+
value: target
|
|
90
|
+
}, report);
|
|
91
|
+
return report.status === "error" ? 2 : 0;
|
|
92
|
+
}
|
|
93
|
+
throw new BaerlyError("InvalidConfig", `baerly doctor: target ${JSON.stringify(target)} has no doctor backend. (Node variants self-validate at scaffold time; the example IS the contract.)`);
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
/** citty `defineCommand` block for `baerly doctor`. */
|
|
97
|
+
const doctor = bundle.cmd;
|
|
98
|
+
bundle.run;
|
|
99
|
+
//#endregion
|
|
100
|
+
export { doctor };
|
|
101
|
+
|
|
102
|
+
//# sourceMappingURL=doctor-RWVRpvat.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"doctor-RWVRpvat.js","names":[],"sources":["../packages/cli/src/doctor.ts"],"sourcesContent":["/**\n * `baerly doctor` — citty dispatcher for deploy-invariant checks.\n *\n * Two modes:\n * - `--bucket <uri>` — connect to a live bucket and probe its CAS\n * support (the protocol's load-bearing backend prerequisite). This\n * mode WRITES + deletes one throwaway sentinel; see\n * {@link doctorCas}. Independent of `baerly.config.ts` / `--target`.\n * For `gcs://` URIs, also runs the GCS-specific bucket-config checks\n * in {@link doctorGcsConfig} (an active Object Versioning probe plus\n * a static soft-delete advisory) and merges their findings into the\n * same report.\n * - otherwise — reads `baerly.config.ts:target` and routes to\n * {@link doctorCloudflare} (read-only deploy-invariant checks). The\n * Node target self-validates at scaffold time — the example IS the\n * contract — so it has no doctor backend.\n *\n * Drift detection, index rebuilds, and writes/min health are separate\n * verbs:\n * - `baerly admin fsck --indexes [--fix]` — index drift.\n * - `baerly admin usage` — writes/min M-size graduation.\n * - `baerly admin rebuild-index` — single-index reconciliation.\n *\n * Renders the returned {@link DoctorReport} into either a\n * stdout checklist (text mode) or a JSON envelope (`--json`\n * mode).\n *\n * Exit-code contract (mirrors `baerly deploy`):\n * - 0 success — report status is `ok` or `warning`.\n * - 1 user error (InvalidConfig, unknown target, missing config).\n * - 2 storage / external error.\n * - 3 protocol invariant.\n *\n * A `warning` status returns exit 0 (the user can deploy; we just\n * flagged a maintenance / coherence issue). An `error` status\n * returns exit 2 unless the underlying cause was an InvalidConfig\n * (which already returned 1 via a thrown BaerlyError).\n */\n\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { parseBucketUri } from \"./bucket-uri.ts\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { doctorCas } from \"./doctor/cas.ts\";\nimport { doctorCloudflare, mergeReports, type DoctorReport } from \"./doctor/cloudflare.ts\";\nimport { doctorGcsConfig, GCS_STALE_GENERATION_PROBE_VALUE } from \"./doctor/gcs.ts\";\nimport { defaultRunner } from \"./runner.ts\";\nimport { color, isJsonMode } from \"./output.ts\";\nimport { defineBaerlySubcommand, JSON_ARG } from \"./subcommand.ts\";\n\nconst DOCTOR_ARGS = {\n target: {\n type: \"string\",\n description:\n 'Override `baerly.config.ts:target`. Only \"cloudflare\" supported (Node variants self-validate at scaffold time).',\n valueHint: \"cloudflare\",\n },\n bucket: {\n type: \"string\",\n description:\n \"Live-probe a bucket's CAS support (writes + deletes one sentinel; verifies If-Match / If-None-Match are honoured). s3://, gcs://, file:///, or memory:// URI. For gcs://, also runs GCS-specific bucket-config checks (Object Versioning probe + soft-delete advisory). Independent of --target.\",\n valueHint: \"s3://bucket/prefix | gcs://bucket\",\n },\n fix: {\n type: \"boolean\",\n description:\n \"Remediate auto-fixable findings (R2 bucket creation; secret prompts stay manual).\",\n },\n json: JSON_ARG,\n} as const satisfies ArgsDef;\n\nconst SEVERITY_GLYPH: Record<string, string> = {\n ok: \"✓\",\n info: \"•\",\n warning: \"⚠\",\n error: \"✗\",\n};\n\nconst colorize = (severity: string, glyph: string): string => {\n if (severity === \"error\") {\n return color.red(glyph);\n }\n if (severity === \"warning\") {\n return color.yellow(glyph);\n }\n if (severity === \"info\") {\n return color.dim(glyph);\n }\n return glyph;\n};\n\nconst renderReport = (\n label: { kind: \"target\" | \"bucket\"; value: string },\n report: DoctorReport,\n): void => {\n if (isJsonMode()) {\n process.stdout.write(\n `${JSON.stringify({ result: { command: \"doctor\", [label.kind]: label.value, ...report } })}\\n`,\n );\n return;\n }\n process.stdout.write(`baerly doctor --${label.kind}=${label.value}\\n\\n`);\n let okCount = 0;\n let warningCount = 0;\n let errorCount = 0;\n for (const f of report.findings) {\n const glyph = SEVERITY_GLYPH[f.severity] ?? \"•\";\n process.stdout.write(` ${colorize(f.severity, glyph)} ${f.message}\\n`);\n if (f.fix !== undefined) {\n process.stdout.write(` fix: ${f.fix}\\n`);\n }\n if (f.severity === \"ok\") {\n okCount += 1;\n } else if (f.severity === \"warning\") {\n warningCount += 1;\n } else if (f.severity === \"error\") {\n errorCount += 1;\n }\n }\n process.stdout.write(\n `\\nStatus: ${errorCount} error${errorCount === 1 ? \"\" : \"s\"}, ${warningCount} warning${warningCount === 1 ? \"\" : \"s\"}, ${okCount} ok.\\n`,\n );\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"doctor\",\n meta: {\n description:\n \"Walk the deploy invariants and report findings. Dispatches by baerly.config.ts:target.\",\n },\n args: DOCTOR_ARGS,\n handler: async (args) => {\n // --bucket is a standalone live-probe mode: it connects to a real\n // bucket and checks CAS, independent of baerly.config.ts / --target.\n if (args.bucket !== undefined) {\n const { storage, keyPrefix, gcs } = await parseBucketUri(args.bucket);\n if (gcs !== undefined) {\n // Native GCS's generation-based preconditions reject the CAS\n // probe's default S3/R2-shaped stale-etag sentinel as malformed\n // (400) rather than as a conflict (412) — override with a\n // well-formed-but-stale generation. See doctor/gcs.ts.\n const report = await doctorCas(storage, keyPrefix, {\n staleEtag: GCS_STALE_GENERATION_PROBE_VALUE,\n });\n const gcsReport = await doctorGcsConfig(gcs);\n const merged = mergeReports([report, gcsReport]);\n renderReport({ kind: \"bucket\", value: args.bucket }, merged);\n return merged.status === \"error\" ? 2 : 0;\n }\n const report = await doctorCas(storage, keyPrefix);\n renderReport({ kind: \"bucket\", value: args.bucket }, report);\n return report.status === \"error\" ? 2 : 0;\n }\n const config = await loadAppConfig();\n const target = args.target ?? config.target;\n if (target === \"cloudflare\") {\n const report = await doctorCloudflare(config, {\n runner: defaultRunner(),\n ...(args.fix === true && { fix: true }),\n });\n renderReport({ kind: \"target\", value: target }, report);\n return report.status === \"error\" ? 2 : 0;\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly doctor: target ${JSON.stringify(target)} has no doctor backend. ` +\n `(Node variants self-validate at scaffold time; the example IS the contract.)`,\n );\n },\n});\n\n/** citty `defineCommand` block for `baerly doctor`. */\nexport const doctor = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runDoctor = bundle.run;\n"],"mappings":";;;;;AAkDA,MAAM,cAAc;CAClB,QAAQ;EACN,MAAM;EACN,aACE;EACF,WAAW;CACb;CACA,QAAQ;EACN,MAAM;EACN,aACE;EACF,WAAW;CACb;CACA,KAAK;EACH,MAAM;EACN,aACE;CACJ;CACA,MAAM;AACR;AAEA,MAAM,iBAAyC;CAC7C,IAAI;CACJ,MAAM;CACN,SAAS;CACT,OAAO;AACT;AAEA,MAAM,YAAY,UAAkB,UAA0B;CAC5D,IAAI,aAAa,SACf,OAAO,MAAM,IAAI,KAAK;CAExB,IAAI,aAAa,WACf,OAAO,MAAM,OAAO,KAAK;CAE3B,IAAI,aAAa,QACf,OAAO,MAAM,IAAI,KAAK;CAExB,OAAO;AACT;AAEA,MAAM,gBACJ,OACA,WACS;CACT,IAAI,W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SAAS,MAAM,UAAU,SAAS,SAAS;GACjD,aAAa;IAAE,MAAM;IAAU,OAAO,KAAK;GAAO,GAAG,MAAM;GAC3D,OAAO,OAAO,WAAW,UAAU,IAAI;EACzC;EACA,MAAM,SAAS,MAAM,cAAc;EACnC,MAAM,SAAS,KAAK,UAAU,OAAO;EACrC,IAAI,WAAW,cAAc;GAC3B,MAAM,SAAS,MAAM,iBAAiB,QAAQ;IAC5C,QAAQ,cAAc;IACtB,GAAI,KAAK,QAAQ,QAAQ,EAAE,KAAK,KAAK;GACvC,CAAC;GACD,aAAa;IAAE,MAAM;IAAU,OAAO;GAAO,GAAG,MAAM;GACtD,OAAO,OAAO,WAAW,UAAU,IAAI;EACzC;EACA,MAAM,IAAI,YACR,iBACA,yBAAyB,KAAK,UAAU,MAAM,EAAE,qGAElD;CACF;AACF,CAAC;;AAGD,MAAa,SAAS,OAAO;AAOJ,OAAO"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { r as parseBucketUri } from "./config-
|
|
1
|
+
import { r as parseBucketUri } from "./config-B6nTy8e2.js";
|
|
2
2
|
import { o as BaerlyError, r as emitSuccess } from "./baerly.js";
|
|
3
|
-
import { n as loadMaterialisedView } from "./plan-
|
|
4
|
-
import { a as TENANT_ARG, i as JSON_ARG, n as BUCKET_ARG, o as assertCollectionArg, r as COLLECTION_ARG, s as defineBaerlySubcommand, t as APP_ARG } from "./subcommand-
|
|
3
|
+
import { n as loadMaterialisedView } from "./plan-C4qgiXSg.js";
|
|
4
|
+
import { a as TENANT_ARG, i as JSON_ARG, n as BUCKET_ARG, o as assertCollectionArg, r as COLLECTION_ARG, s as defineBaerlySubcommand, t as APP_ARG } from "./subcommand-BV68pqwJ.js";
|
|
5
5
|
import "node:stream";
|
|
6
6
|
//#region src/admin/dump.ts
|
|
7
7
|
const DUMP_ARGS = {
|
|
@@ -91,4 +91,4 @@ bundle.run;
|
|
|
91
91
|
//#endregion
|
|
92
92
|
export { dumpCmd };
|
|
93
93
|
|
|
94
|
-
//# sourceMappingURL=dump-
|
|
94
|
+
//# sourceMappingURL=dump-m2vEYDNY.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dump-
|
|
1
|
+
{"version":3,"file":"dump-m2vEYDNY.js","names":[],"sources":["../packages/cli/src/admin/dump.ts"],"sourcesContent":["/**\n * `baerly admin dump` — canonical NDJSON of the materialised view.\n *\n * Writes one row per line to stdout, in a strict byte-stable shape so\n * two semantically-equal collections produce byte-equal output. Tests\n * and other programmatic callers can divert the NDJSON output to a\n * file or buffer by passing `{ streams: { stdout } }` to {@link runDump}.\n *\n * Canonical NDJSON dump format:\n *\n * 1. Each row is `{\"_id\":\"<id>\",…}` (no spaces).\n * 2. Row order = ASCII-lex sort on `_id`.\n * 3. Within each row, object keys are sorted ASCII-lex\n * RECURSIVELY — every nested object's keys are sorted too.\n * 4. Numbers as their canonical `JSON.stringify` output.\n * Finite-only (the protocol forbids NaN / Infinity).\n * 5. Strings as `JSON.stringify` output (escape sequences\n * identical to `\\uXXXX` for control codes).\n * 6. One trailing newline at EOF (`\\n`, not `\\r\\n`).\n * 7. No BOM.\n *\n * The round-trip ticket (73) gates byte-equality on this format. A\n * change to any of (1)–(7) is a BREAKING change requiring a\n * round-trip schema-version bump.\n *\n * Empty collection → empty file (no trailing newline) — disambiguates\n * \"zero rows\" from \"one row with empty body\".\n *\n * Args:\n * --bucket Required. Bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Collection name.\n * --json JSON envelope (on stdout). Programmatic callers can\n * divert the NDJSON body to a separate writable via the\n * `streams.stdout` option on {@link runDump}.\n *\n * Exit codes:\n * 0 — dump completed.\n * 1 — InvalidConfig (bad bucket URI, missing args).\n * 2 — Storage / Network / Internal protocol violation.\n * 3 — Protocol invariant (Conflict / Internal / InvalidResponse).\n */\n\nimport { type Writable } from \"node:stream\";\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, type DocumentValue, type DocumentData } from \"@baerly/protocol\";\nimport { loadMaterialisedView } from \"../export/index.ts\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { emitSuccess } from \"../output.ts\";\nimport {\n APP_ARG,\n assertCollectionArg,\n BUCKET_ARG,\n COLLECTION_ARG,\n defineBaerlySubcommand,\n JSON_ARG,\n TENANT_ARG,\n} from \"../subcommand.ts\";\n\nconst DUMP_ARGS = {\n bucket: BUCKET_ARG,\n app: APP_ARG,\n tenant: TENANT_ARG,\n collection: COLLECTION_ARG,\n json: JSON_ARG,\n} as const satisfies ArgsDef;\n\n/**\n * Recursive byte-stable JSON stringifier. Object keys at every nesting\n * level are sorted ASCII-lex; array element order is preserved as-is.\n * Numbers must be finite (protocol forbids NaN / Infinity in bodies).\n */\nexport const canonicalStringify = (value: DocumentValue): string => {\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `baerly admin dump: non-finite number in row body (${String(value)}); protocol violation`,\n );\n }\n return JSON.stringify(value);\n }\n if (typeof value === \"string\" || typeof value === \"boolean\") {\n return JSON.stringify(value);\n }\n if (value === null) {\n // DocumentValue excludes null at the type level, but `unknown` may\n // sneak in via the snapshot fold — be defensive.\n return \"null\";\n }\n if (Array.isArray(value)) {\n const parts = value.map((v) => canonicalStringify(v));\n return `[${parts.join(\",\")}]`;\n }\n if (typeof value === \"object\") {\n const keys = Object.keys(value).toSorted();\n const parts: string[] = [];\n for (const k of keys) {\n const v = (value as Record<string, DocumentValue>)[k];\n if (v === undefined) {\n continue;\n }\n parts.push(`${JSON.stringify(k)}:${canonicalStringify(v)}`);\n }\n return `{${parts.join(\",\")}}`;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `baerly admin dump: unsupported value type ${typeof value}`,\n );\n};\n\n/**\n * Drain rows to the supplied writable, applying back-pressure on every\n * line. We don't `end()` the stream — the caller owns its lifecycle\n * (`process.stdout` shouldn't be closed; a test-supplied\n * `createWriteStream` flushes on its own `end()`).\n */\nconst writeToSink = async (\n sink: Writable,\n rows: ReadonlyMap<string, DocumentData>,\n): Promise<number> => {\n const ids = [...rows.keys()].toSorted();\n let count = 0;\n for (const id of ids) {\n const body = rows.get(id);\n if (body === undefined) {\n continue;\n }\n // Merge `_id` into the body so the row literal carries it. The\n // map key is authoritative; if a stale `_id` field disagrees, we\n // overwrite it.\n const row: DocumentData = { ...body, _id: id };\n const line = `${canonicalStringify(row)}\\n`;\n if (!sink.write(line)) {\n await new Promise<void>((resolve) => sink.once(\"drain\", resolve));\n }\n count++;\n }\n return count;\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.dump\",\n meta: {\n description: \"Canonical NDJSON of the materialised view of one collection.\",\n },\n args: DUMP_ARGS,\n handler: async (args, ctx) => {\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n assertCollectionArg(args.collection, \"baerly admin dump\");\n const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;\n const view = await loadMaterialisedView({\n storage: bucket.storage,\n currentJsonKey,\n collection: args.collection,\n });\n if (view === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin dump: current.json not found at ${currentJsonKey}`,\n );\n }\n const sink: Writable = ctx.streams?.stdout ?? process.stdout;\n const count = await writeToSink(sink, view);\n emitSuccess({\n command: \"admin.dump\",\n status: \"ok\",\n collection: args.collection,\n dumped: count,\n });\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly admin dump`. */\nexport const dumpCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runDump = bundle.run;\n"],"mappings":";;;;;;AA4DA,MAAM,YAAY;CAChB,QAAQ;CACR,KAAK;CACL,QAAQ;CACR,YAAY;CACZ,MAAM;AACR;;;;;;AAOA,MAAa,sBAAsB,UA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AAM,EACJ,aAAa,+DACf;CACA,MAAM;CACN,SAAS,OAAO,MAAM,QAAQ;EAC5B,MAAM,SAAS,MAAM,eAAe,KAAK,MAAM;EAC/C,MAAM,EAAE,KAAK,WAAW,MAAM,IAAI,iBAAiB;GAAE,KAAK,KAAK;GAAK,QAAQ,KAAK;EAAO,CAAC;EACzF,oBAAoB,KAAK,YAAY,mBAAmB;EACxD,MAAM,iBAAiB,GAAG,OAAO,UAAU,MAAM,IAAI,UAAU,OAAO,aAAa,KAAK,WAAW;EACnG,MAAM,OAAO,MAAM,qBAAqB;GACtC,SAAS,OAAO;GAChB;GACA,YAAY,KAAK;EACnB,CAAC;EACD,IAAI,SAAS,MACX,MAAM,IAAI,YACR,iBACA,gDAAgD,gBAClD;EAGF,MAAM,QAAQ,MAAM,YADG,IAAI,SAAS,UAAU,QAAQ,QAChB,IAAI;EAC1C,YAAY;GACV,SAAS;GACT,QAAQ;GACR,YAAY,KAAK;GACjB,QAAQ;EACV,CAAC;EACD,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,UAAU,OAAO;AAOP,OAAO"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { r as parseBucketUri } from "./config-
|
|
1
|
+
import { r as parseBucketUri } from "./config-B6nTy8e2.js";
|
|
2
2
|
import { n as matchesWire, t as validateWire } from "./validate-DtljsCh1.js";
|
|
3
3
|
import { o as BaerlyError, r as emitSuccess } from "./baerly.js";
|
|
4
|
-
import { n as loadMaterialisedView, r as quoteValue, t as inferPlanForCollection } from "./plan-
|
|
5
|
-
import { a as TENANT_ARG, i as JSON_ARG, n as BUCKET_ARG, o as assertCollectionArg, r as COLLECTION_ARG, s as defineBaerlySubcommand, t as APP_ARG } from "./subcommand-
|
|
4
|
+
import { n as loadMaterialisedView, r as quoteValue, t as inferPlanForCollection } from "./plan-C4qgiXSg.js";
|
|
5
|
+
import { a as TENANT_ARG, i as JSON_ARG, n as BUCKET_ARG, o as assertCollectionArg, r as COLLECTION_ARG, s as defineBaerlySubcommand, t as APP_ARG } from "./subcommand-BV68pqwJ.js";
|
|
6
6
|
import { writeFile } from "node:fs/promises";
|
|
7
7
|
//#region src/export/ddl.ts
|
|
8
8
|
/**
|
|
@@ -398,4 +398,4 @@ const describeNonObject = (v) => {
|
|
|
398
398
|
//#endregion
|
|
399
399
|
export { exportCmd };
|
|
400
400
|
|
|
401
|
-
//# sourceMappingURL=export-
|
|
401
|
+
//# sourceMappingURL=export-DenKwEQu.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"export-DtF5tDIM.js","names":[],"sources":["../packages/cli/src/export/ddl.ts","../packages/cli/src/export/rows.ts","../packages/cli/src/export/where.ts","../packages/cli/src/export/plan-sidecar.ts","../packages/cli/src/export.ts"],"sourcesContent":["import { BaerlyError } from \"@baerly/protocol\";\nimport type { ExportPlan } from \"./types.ts\";\n\n/**\n * Emit a `CREATE TABLE` statement for the plan, one line per column,\n * terminated with a semicolon + newline so the output is directly\n * pipeable into `psql` / `sqlite3` / `wrangler d1 execute`.\n *\n * `_id` is the primary key (always first in `plan.columns`).\n *\n * D1 today is sqlite-flavoured: same DDL as `target=sqlite` with a\n * single difference — D1 disallows table names starting with\n * `sqlite_`. We refuse them up front.\n */\nexport const emitCreateTable = (plan: ExportPlan): string => {\n if (plan.columns.length === 0) {\n throw new BaerlyError(\n \"SchemaError\",\n `emitCreateTable: collection ${JSON.stringify(plan.table)} has no observed columns — empty snapshot?`,\n );\n }\n if (plan.target === \"d1\" && plan.table.toLowerCase().startsWith(\"sqlite_\")) {\n throw new BaerlyError(\n \"SchemaError\",\n `emitCreateTable: D1 reserves the sqlite_ table-name prefix (got ${JSON.stringify(plan.table)})`,\n );\n }\n const lines: string[] = [];\n lines.push(`CREATE TABLE ${plan.tableIdentifier} (`);\n const colLines: string[] = [];\n for (const col of plan.columns) {\n const nullClause = col.nullable ? \"\" : \" NOT NULL\";\n const pkClause = col.source === \"_id\" ? \" PRIMARY KEY\" : \"\";\n colLines.push(` ${col.identifier} ${col.sqlType}${nullClause}${pkClause}`);\n }\n lines.push(colLines.join(\",\\n\"));\n lines.push(\");\");\n return lines.join(\"\\n\") + \"\\n\";\n};\n","import type { DocumentValue } from \"@baerly/protocol\";\nimport type { ExportPlan, ExportRow } from \"./types.ts\";\nimport { quoteValue } from \"./sql-escape.ts\";\n\n/**\n * Emit one `INSERT INTO …` statement per row. The emitted SQL is\n * directly pipeable into `psql` / `sqlite3` / `wrangler d1\n * execute`. Per-row statements (not one big VALUES tuple) so a\n * mid-stream failure has bounded blast radius.\n *\n * For columns whose plan has `jsonEncoded: true`, the row's value\n * is JSON-stringified first and then string-quoted. Postgres\n * accepts a literal text JSON in a `jsonb` column. SQLite / D1 see\n * the JSON as plain TEXT.\n *\n * Rows are streamed via the async-iterable protocol so the export\n * never materialises the full SQL output in memory. The caller\n * concatenates the yielded chunks (or pipes them straight to disk\n * / stdout).\n */\nexport async function* emitInsertStatements(\n plan: ExportPlan,\n rows: ReadonlyMap<string, ExportRow>,\n): AsyncIterable<string> {\n const columnList = plan.columns.map((c) => c.identifier).join(\", \");\n // Iterate in `Map` insertion order — stable, and the snapshot\n // body itself sorts by `_id` (compactor.ts: `docs is sorted by\n // _id for deterministic byte output`).\n for (const [id, body] of rows) {\n const values: string[] = [];\n for (const col of plan.columns) {\n const raw: DocumentValue | undefined =\n col.source === \"_id\"\n ? (id as DocumentValue)\n : (body as Record<string, DocumentValue>)[col.source];\n if (raw === undefined) {\n values.push(\"NULL\");\n continue;\n }\n if (col.jsonEncoded) {\n const json = JSON.stringify(raw);\n values.push(quoteValue(json, plan.target));\n } else {\n values.push(quoteValue(raw, plan.target));\n }\n }\n yield `INSERT INTO ${plan.tableIdentifier} (${columnList}) VALUES (${values.join(\", \")});\\n`;\n }\n}\n","/**\n * Wire-predicate → SQL `WHERE` clause translation.\n *\n * Pure function. The translator consumes a validated\n * {@link PredicateWire} — the same shape the read path uses — and\n * an {@link ExportPlan} (from `./plan.ts`), and emits a SQL fragment\n * matched against the plan's columns.\n *\n * Three classes of clause:\n *\n * 1. Flat column, top-level field → direct comparator\n * (`\"status\" = 'open'`, `\"priority\" > 5`).\n * 2. JSON-encoded column → JSON-path operators (Postgres `->`/`->>`\n * chains; SQLite/D1 `json_extract(…, '$.…')`).\n * 3. Unmatchable clause (dotted path against a flat column, or a\n * field naming an unknown column) → `1 = 0` plus a hint the CLI\n * surfaces as a `-- TODO(baerly export):` comment above the\n * emitted statement.\n *\n * Dynamic predicates are invisible at runtime — we see the\n * materialised wire, not the source expression. Callers that know\n * they constructed the wire dynamically can pass\n * `options.dynamicHint` to surface an operator-supplied note.\n */\n\nimport {\n BaerlyError,\n type DocumentValue,\n type PredicateClause,\n type PredicateWire,\n validateWire,\n} from \"@baerly/protocol\";\nimport { quoteValue } from \"./sql-escape.ts\";\nimport type { ColumnPlan, ExportPlan, SqlTarget } from \"./types.ts\";\n\nexport interface WhereTranslation {\n /** SQL fragment without the leading `WHERE`. Empty when no predicate. */\n readonly sql: string;\n /**\n * Hand-edit hints for the operator. One entry per non-matchable\n * clause (§3.6) or per dynamically-constructed sub-clause flagged\n * by the caller. The CLI surfaces these as `-- TODO(baerly export): …`\n * comments above the emitted statement.\n */\n readonly hints: readonly string[];\n}\n\n/**\n * Translate a validated {@link PredicateWire} into a SQL WHERE-clause\n * fragment matched against the plan's columns. The first argument\n * must already have been validated by {@link validateWire} — the\n * function re-validates defensively but the caller's invariant\n * matters for error-message provenance.\n *\n * Pure function. No I/O. Same wire + plan + target → same SQL string.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — wire fails\n * {@link validateWire}; same shape `Query<T>.where` already\n * surfaces.\n */\nexport const translatePredicateWireToSql = (\n wire: PredicateWire,\n plan: ExportPlan,\n options?: { readonly dynamicHint?: string },\n): WhereTranslation => {\n validateWire(wire);\n const hints: string[] = [];\n if (options?.dynamicHint !== undefined && options.dynamicHint.length > 0) {\n hints.push(\n `caller-flagged dynamic predicate: ${options.dynamicHint}. Review the emitted SQL for completeness.`,\n );\n }\n const clauses: string[] = [];\n for (const clause of wire.clauses) {\n clauses.push(...clauseForWire(clause, plan, hints));\n }\n return {\n sql: clauses.length === 0 ? \"\" : clauses.join(\" AND \"),\n hints,\n };\n};\n\nconst clauseForWire = (clause: PredicateClause, plan: ExportPlan, hints: string[]): string[] => {\n const segments = clause.field.includes(\".\") ? clause.field.split(\".\") : [clause.field];\n const head = segments[0];\n if (head === undefined || head.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"translatePredicateWireToSql: empty field path encountered (defensive)\",\n );\n }\n const col = plan.columns.find((c) => c.source === head);\n if (col === undefined) {\n hints.push(\n `predicate field ${JSON.stringify(clause.field)} references a key never observed in the snapshot; this clause cannot match.`,\n );\n return [\"1 = 0\"];\n }\n // §3.2 — flat column, top-level field → direct comparator.\n if (!col.jsonEncoded && segments.length === 1) {\n return [flatColumnClause(col.identifier, clause, plan.target)];\n }\n // §3.6 — flat column, dotted path → unmatchable.\n if (!col.jsonEncoded && segments.length > 1) {\n hints.push(\n `predicate path ${JSON.stringify(clause.field)} addresses a flat column; this clause cannot match. Hand-edit if intended.`,\n );\n return [\"1 = 0\"];\n }\n // §3.3 — JSON column, top-level field.\n if (col.jsonEncoded && segments.length === 1) {\n return [jsonColumnRootClause(col, clause, plan.target)];\n }\n // §3.4 / §3.5 — JSON column, dotted path.\n return [jsonPathClause(col, segments.slice(1), clause, plan.target)];\n};\n\nconst flatColumnClause = (\n identifier: string,\n clause: PredicateClause,\n target: SqlTarget,\n): string => {\n switch (clause.op) {\n case \"eq\": {\n return `${identifier} = ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gt\": {\n return `${identifier} > ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gte\": {\n return `${identifier} >= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lt\": {\n return `${identifier} < ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lte\": {\n return `${identifier} <= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"in\": {\n return `${identifier} IN (${(clause.value as ReadonlyArray<DocumentValue>)\n .map((v) => quoteLeaf(v, target))\n .join(\", \")})`;\n }\n }\n};\n\nconst jsonColumnRootClause = (\n col: ColumnPlan,\n clause: PredicateClause,\n target: SqlTarget,\n): string => {\n // The root JSON column stores the value as JSON-encoded text;\n // we compare against the JSON encoding of the predicate value.\n // Range and `in` ops on a JSON-encoded root column compare the\n // JSON text lexicographically, which is rarely what the caller\n // wanted — for those, the operator is expected to promote the\n // field into a flat column or hand-edit the emitted SQL.\n if (clause.op === \"eq\") {\n const literal = JSON.stringify(clause.value);\n if (target === \"postgres\") {\n return `${col.identifier}::text = ${quoteValue(literal, target)}`;\n }\n return `${col.identifier} = ${quoteValue(literal, target)}`;\n }\n if (clause.op === \"in\") {\n const literals = (clause.value as ReadonlyArray<DocumentValue>).map((v) =>\n quoteValue(JSON.stringify(v), target),\n );\n if (target === \"postgres\") {\n return `${col.identifier}::text IN (${literals.join(\", \")})`;\n }\n return `${col.identifier} IN (${literals.join(\", \")})`;\n }\n // Range against JSON-encoded root: fall back to a lex compare on\n // the JSON serialisation. Surface a comment via the SQL itself;\n // the operator can hand-edit.\n const comparator = rangeComparator(clause.op);\n const literal = JSON.stringify(clause.value);\n if (target === \"postgres\") {\n return `${col.identifier}::text ${comparator} ${quoteValue(literal, target)}`;\n }\n return `${col.identifier} ${comparator} ${quoteValue(literal, target)}`;\n};\n\nconst jsonPathClause = (\n col: ColumnPlan,\n tail: readonly string[],\n clause: PredicateClause,\n target: SqlTarget,\n): string => {\n const accessor = jsonPathAccessor(col.identifier, tail, target);\n switch (clause.op) {\n case \"eq\": {\n return `${accessor} = ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gt\": {\n return `${accessor} > ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gte\": {\n return `${accessor} >= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lt\": {\n return `${accessor} < ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lte\": {\n return `${accessor} <= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"in\": {\n return `${accessor} IN (${(clause.value as ReadonlyArray<DocumentValue>)\n .map((v) => quoteLeaf(v, target))\n .join(\", \")})`;\n }\n }\n};\n\nconst rangeComparator = (op: PredicateClause[\"op\"]): string => {\n if (op === \"gt\") {\n return \">\";\n }\n if (op === \"gte\") {\n return \">=\";\n }\n if (op === \"lt\") {\n return \"<\";\n }\n return \"<=\";\n};\n\nconst jsonPathAccessor = (\n identifier: string,\n tail: readonly string[],\n target: SqlTarget,\n): string => {\n if (target === \"postgres\") {\n let expr = identifier;\n for (let i = 0; i < tail.length; i++) {\n const seg = tail[i]!;\n const isLast = i === tail.length - 1;\n const key = `'${seg.replace(/'/g, \"''\")}'`;\n expr = `${expr}${isLast ? \"->>\" : \"->\"}${key}`;\n }\n return expr;\n }\n const jsonPath = `'$.${tail.map((s) => s.replace(/'/g, \"''\")).join(\".\")}'`;\n return `json_extract(${identifier}, ${jsonPath})`;\n};\n\n/**\n * Quote a leaf primitive for use as the right-hand side of a\n * comparison. Booleans branch on target. Nested objects must never\n * reach here — wire `eq` clauses on nested objects can only come\n * from the callback form `q.eq(\"nested\", { ... })`, which the\n * export translator does not support today.\n */\nconst quoteLeaf = (value: DocumentValue, target: SqlTarget): string => {\n if (typeof value === \"object\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"translatePredicateWireToSql: nested object reached leaf quoter — callback-form q.eq(field, object) is not supported for SQL export. Hand-edit the emitted SQL.\",\n );\n }\n return quoteValue(value, target);\n};\n","/**\n * Sidecar plan serialisation for `baerly export`.\n *\n * `baerly export --output=foo.sql` writes the inferred {@link ExportPlan}\n * alongside the SQL dump as `foo.sql.plan.json`. The round-trip test\n * (`tests/integration/export-round-trip.test.ts`) consumes the sidecar\n * to coerce SQLite-returned values back to their original JS type\n * (e.g. SQLite stores booleans as 0/1; we restore `true`/`false`).\n *\n * Wire shape (`schemaVersion = 1`):\n *\n * ```json\n * {\n * \"schemaVersion\": 1,\n * \"table\": \"tickets\",\n * \"target\": \"sqlite\",\n * \"columns\": [\n * { \"source\": \"_id\", \"sqlType\": \"TEXT\", \"nullable\": false, \"jsonEncoded\": false },\n * ...\n * ]\n * }\n * ```\n *\n * `identifier` is NOT carried on the wire — we re-derive it via\n * {@link quoteIdentifier} on deserialise. An attacker writing the\n * sidecar should not get SQL-emit control over identifiers.\n *\n * `rowCount` is also not preserved across the sidecar boundary; the\n * deserialised plan reports `0`. This is intentional — consumers that\n * care about row count read the SQL stream itself.\n */\n\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { quoteIdentifier } from \"./sql-escape.ts\";\nimport type { ColumnPlan, ExportPlan, SqlTarget, SqlType } from \"./types.ts\";\n\nconst SIDECAR_SCHEMA_VERSION = 1 as const;\n\nconst VALID_TARGETS: ReadonlySet<string> = new Set([\"postgres\", \"sqlite\", \"d1\"]);\n\nconst VALID_SQL_TYPES: ReadonlySet<string> = new Set([\n \"text\",\n \"boolean\",\n \"integer\",\n \"double precision\",\n \"jsonb\",\n \"TEXT\",\n \"INTEGER\",\n \"REAL\",\n]);\n\n/**\n * Encode an {@link ExportPlan} as the canonical sidecar JSON string.\n *\n * Wire format is pretty-printed (`indent=2`) with a trailing newline\n * so `cat sidecar.plan.json` is human-readable and `diff` works on\n * two sidecars without spurious line-end noise. The on-wire bytes\n * embed the `schemaVersion` discriminator so future shape changes\n * are detectable; `identifier` and `tableIdentifier` are NOT carried\n * (they're re-derived via {@link quoteIdentifier} on deserialise).\n */\nexport const serializeExportPlan = (plan: ExportPlan): string => {\n return (\n JSON.stringify(\n {\n schemaVersion: SIDECAR_SCHEMA_VERSION,\n table: plan.table,\n target: plan.target,\n columns: plan.columns.map((c) => ({\n source: c.source,\n sqlType: c.sqlType,\n nullable: c.nullable,\n jsonEncoded: c.jsonEncoded,\n })),\n },\n null,\n 2,\n ) + \"\\n\"\n );\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n/**\n * Parse the sidecar JSON string back into an {@link ExportPlan}.\n *\n * @throws BaerlyError code=\"InvalidConfig\" when the sidecar JSON is\n * malformed, the schema version is unsupported, or any required\n * field is missing / has an unexpected type. Identifiers are\n * re-quoted via {@link quoteIdentifier} rather than copied off the\n * wire — the sidecar cannot smuggle SQL-injection via a\n * pre-quoted identifier.\n */\nexport const deserializeExportPlan = (text: string): ExportPlan => {\n let raw: unknown;\n try {\n raw = JSON.parse(text);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: parse failed: ${(error as Error).message}`,\n );\n }\n if (!isObject(raw)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"deserializeExportPlan: top-level value is not an object\",\n );\n }\n if (raw[\"schemaVersion\"] !== SIDECAR_SCHEMA_VERSION) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: unsupported schemaVersion ${String(raw[\"schemaVersion\"])} (expected ${String(SIDECAR_SCHEMA_VERSION)})`,\n );\n }\n if (typeof raw[\"table\"] !== \"string\" || raw[\"table\"].length === 0) {\n throw new BaerlyError(\"InvalidConfig\", \"deserializeExportPlan: missing or empty table\");\n }\n if (typeof raw[\"target\"] !== \"string\" || !VALID_TARGETS.has(raw[\"target\"])) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: unknown target ${JSON.stringify(raw[\"target\"])}`,\n );\n }\n if (!Array.isArray(raw[\"columns\"])) {\n throw new BaerlyError(\"InvalidConfig\", \"deserializeExportPlan: columns is not an array\");\n }\n const table = raw[\"table\"];\n const target = raw[\"target\"] as SqlTarget;\n const columns: ColumnPlan[] = [];\n for (const [i, col] of raw[\"columns\"].entries()) {\n if (!isObject(col)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}] is not an object`,\n );\n }\n if (typeof col[\"source\"] !== \"string\" || col[\"source\"].length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].source is missing or empty`,\n );\n }\n if (typeof col[\"sqlType\"] !== \"string\" || !VALID_SQL_TYPES.has(col[\"sqlType\"])) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].sqlType ${JSON.stringify(col[\"sqlType\"])} is not a recognised SqlType`,\n );\n }\n if (typeof col[\"nullable\"] !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].nullable is not a boolean`,\n );\n }\n if (typeof col[\"jsonEncoded\"] !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].jsonEncoded is not a boolean`,\n );\n }\n columns.push({\n source: col[\"source\"],\n identifier: quoteIdentifier(col[\"source\"], target),\n sqlType: col[\"sqlType\"] as SqlType,\n nullable: col[\"nullable\"],\n jsonEncoded: col[\"jsonEncoded\"],\n });\n }\n return {\n table,\n target,\n tableIdentifier: quoteIdentifier(table, target),\n columns,\n // Not preserved across the sidecar boundary — see file JSDoc.\n rowCount: 0,\n };\n};\n","/* eslint-disable no-underscore-dangle -- `_id` is the locked\n primary-key field on document shapes; the exporter threads it\n through the materialised view and the emitted INSERT rows. */\n\n/**\n * `baerly export` — snapshot dump of one collection to SQL.\n *\n * Drives the export modules end-to-end: load the materialised view,\n * infer an `ExportPlan` over the row shape, emit `CREATE TABLE` +\n * `INSERT` statements. When `--where=<json>` is supplied the\n * predicate is translated via `translatePredicateToSql` and applied\n * in-memory through `matches(...)` so the emitted INSERTs already\n * match the filter; the translated WHERE clause is also surfaced as a\n * comment above the inserts so operators can inspect / hand-edit it.\n *\n * The sidecar file (`<output>.plan.json`) carries the `ExportPlan` so\n * a follow-up round-trip ingest can verify the column schema. The\n * sidecar is JSON via `JSON.stringify` — the plan shape is the public\n * contract.\n *\n * Args:\n * --bucket Required. Bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Collection name.\n * --target Required. postgres | sqlite | d1.\n * --where Optional. JSON-encoded `Predicate<T>`.\n * --where-comment Optional. Caller hint surfaced as a\n * `-- TODO(baerly export):` comment.\n * --output Optional. Path to write SQL into; default\n * stdout. The sidecar plan is written to\n * `<output>.plan.json` unless `--no-sidecar`.\n * --no-sidecar Skip emitting the sidecar plan file.\n * --json JSON envelope on stdout (or stderr on error).\n *\n * Exit codes:\n * 0 — dump completed.\n * 1 — InvalidConfig (bad args / bucket URI / --where JSON / unknown --target).\n * 2 — Storage / Network error.\n * 3 — Protocol invariant (Internal / InvalidResponse / Conflict).\n */\n\nimport { writeFile } from \"node:fs/promises\";\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, matchesWire, type PredicateWire, validateWire } from \"@baerly/protocol\";\nimport {\n type ExportPlan,\n type ExportRow,\n type SqlTarget,\n emitCreateTable,\n emitInsertStatements,\n inferPlanForCollection,\n loadMaterialisedView,\n serializeExportPlan,\n translatePredicateWireToSql,\n} from \"./export/index.ts\";\nimport { parseBucketUri } from \"./bucket-uri.ts\";\nimport { emitSuccess } from \"./output.ts\";\nimport {\n APP_ARG,\n assertCollectionArg,\n BUCKET_ARG,\n COLLECTION_ARG,\n defineBaerlySubcommand,\n JSON_ARG,\n TENANT_ARG,\n} from \"./subcommand.ts\";\n\nconst EXPORT_ARGS = {\n bucket: BUCKET_ARG,\n app: APP_ARG,\n tenant: TENANT_ARG,\n collection: COLLECTION_ARG,\n target: {\n type: \"enum\",\n options: [\"postgres\", \"sqlite\", \"d1\"],\n required: true,\n description: \"SQL target: postgres | sqlite | d1.\",\n },\n where: {\n type: \"string\",\n required: false,\n description: \"JSON-encoded PredicateWire ({ clauses: [...] }) filtering the rows to export.\",\n valueHint: \"json\",\n },\n \"where-comment\": {\n type: \"string\",\n required: false,\n description: \"Caller hint surfaced as a -- TODO(baerly export): comment.\",\n valueHint: \"text\",\n },\n output: {\n type: \"string\",\n required: false,\n description: \"Path to write SQL into; default stdout.\",\n valueHint: \"path\",\n },\n sidecar: {\n type: \"boolean\",\n default: true,\n description: \"Emit a <output>.plan.json sidecar (default true; pass --no-sidecar to skip).\",\n },\n json: JSON_ARG,\n} as const satisfies ArgsDef;\n\nconst parseWherePredicate = (raw: string): PredicateWire => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly export: --where is not valid JSON: ${(error as Error).message}`,\n );\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly export: --where must decode to a JSON object (got ${describeNonObject(parsed)})`,\n );\n }\n // Re-validate defensively; the translator will reject too, but\n // surfacing the error here gives a single uniform error path.\n validateWire(parsed as PredicateWire);\n return parsed as PredicateWire;\n};\n\nconst filterRows = (\n rows: ReadonlyMap<string, ExportRow>,\n wire: PredicateWire | null,\n): Map<string, ExportRow> => {\n const filtered = new Map<string, ExportRow>();\n for (const [id, body] of rows) {\n if (wire === null) {\n filtered.set(id, body);\n continue;\n }\n if (matchesWire(wire, body)) {\n filtered.set(id, body);\n }\n }\n return filtered;\n};\n\nconst buildSql = async (\n plan: ExportPlan,\n rows: ReadonlyMap<string, ExportRow>,\n whereClause: string,\n whereHints: readonly string[],\n): Promise<string> => {\n let out = emitCreateTable(plan);\n for (const hint of whereHints) {\n out += `-- TODO(baerly export): ${hint}\\n`;\n }\n if (whereClause.length > 0) {\n out += `-- WHERE clause for review: ${whereClause}\\n`;\n }\n for await (const chunk of emitInsertStatements(plan, rows)) {\n out += chunk;\n }\n return out;\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"export\",\n meta: {\n description: \"Snapshot dump of one collection to SQL.\",\n },\n args: EXPORT_ARGS,\n handler: async (args, ctx) => {\n const target: SqlTarget = args.target;\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n assertCollectionArg(args.collection, \"baerly export\");\n const bucket = await parseBucketUri(args.bucket);\n const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;\n const view = await loadMaterialisedView({\n storage: bucket.storage,\n currentJsonKey,\n collection: args.collection,\n });\n if (view === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly export: collection ${JSON.stringify(args.collection)} is not provisioned (no current.json at ${currentJsonKey})`,\n );\n }\n const plan = inferPlanForCollection({\n rows: view,\n target,\n table: args.collection,\n });\n\n let wire: PredicateWire | null = null;\n let whereClause = \"\";\n let whereHints: readonly string[] = [];\n if (typeof args.where === \"string\" && args.where.length > 0) {\n wire = parseWherePredicate(args.where);\n const translation = translatePredicateWireToSql(\n wire,\n plan,\n typeof args[\"where-comment\"] === \"string\" && args[\"where-comment\"].length > 0\n ? { dynamicHint: args[\"where-comment\"] }\n : undefined,\n );\n whereClause = translation.sql;\n whereHints = translation.hints;\n } else if (typeof args[\"where-comment\"] === \"string\" && args[\"where-comment\"].length > 0) {\n // Bare --where-comment with no predicate still surfaces the operator's\n // note so reviewers see the intent.\n whereHints = [\n `caller-flagged dynamic predicate: ${args[\"where-comment\"]}. No predicate supplied; emitted INSERTs cover the full collection.`,\n ];\n }\n\n const filtered = filterRows(view, wire);\n const sql = await buildSql(plan, filtered, whereClause, whereHints);\n\n const outputPath = args.output;\n if (typeof outputPath === \"string\" && outputPath.length > 0) {\n await writeFile(outputPath, sql, \"utf8\");\n if (args.sidecar !== false) {\n await writeFile(`${outputPath}.plan.json`, serializeExportPlan(plan), \"utf8\");\n }\n } else {\n process.stdout.write(sql);\n }\n\n emitSuccess({\n command: \"export\",\n status: \"ok\",\n collection: args.collection,\n target,\n rows: filtered.size,\n hints: whereHints,\n ...(typeof outputPath === \"string\" && outputPath.length > 0 && { output: outputPath }),\n });\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly export`. */\nexport const exportCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runExport = bundle.run;\n\n// Build a human-readable label for the \"expected JSON object\" error.\n// `null`, arrays, and the bare `undefined` need to be disambiguated\n// from `typeof`'s default \"object\".\nconst describeNonObject = (v: unknown): string => {\n if (v === null) {\n return \"null\";\n }\n if (Array.isArray(v)) {\n return \"array\";\n }\n return typeof v;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAcA,MAAa,mBAAmB,SAA6B;CAC3D,IAAI,KAAK,QAAQ,WAAW,GAC1B,MAAM,IAAI,YACR,eACA,+BAA+B,KAAK,UAAU,KAAK,KAAK,EAAE,2CAC5D;CAEF,IAAI,KAAK,WAAW,QAAQ,KAAK,MAAM,YAAY,CAAC,CAAC,WAAW,SAAS,GACvE,MAAM,IAAI,YACR,eACA,mEAAmE,KAAK,UAAU,KAAK,KAAK,EAAE,EAChG;CAEF,MAAM,QAAkB,CAAC;CACzB,MAAM,KAAK,gBAAgB,KAAK,gBAAgB,GAAG;CACnD,MAAM,WAAqB,CAAC;CAC5B,KAAK,MAAM,OAAO,KAAK,SAAS;EAC9B,MAAM,aAAa,IAAI,WAAW,KAAK;EACvC,MAAM,WAAW,IAAI,WAAW,QAAQ,iBAAiB;EACzD,SAAS,KAAK,KAAK,IAAI,WAAW,GAAG,IAAI,UAAU,aAAa,UAAU;CAC5E;CACA,MAAM,KAAK,SAAS,KAAK,KAAK,CAAC;CAC/B,MAAM,KAAK,IAAI;CACf,OAAO,MAAM,KAAK,IAAI,IAAI;AAC5B;;;;;;;;;;;;;;;;;;;AClBA,gBAAuB,qBACrB,MACA,MACuB;CACvB,MAAM,aAAa,KAAK,QAAQ,KAAK,MAAM,EAAE,UAAU,CAAC,CAAC,KAAK,IAAI;CAIlE,KAAK,MAAM,CAAC,IAAI,SAAS,MAAM;EAC7B,MAAM,SAAmB,CAAC;EAC1B,KAAK,MAAM,OAAO,KAAK,SAAS;GAC9B,MAAM,MAC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AO;AAKhC,MAAM,qBAAqB,MAAuB;CAChD,IAAI,MAAM,MACR,OAAO;CAET,IAAI,MAAM,QAAQ,CAAC,GACjB,OAAO;CAET,OAAO,OAAO;AAChB"}
|
|
1
|
+
{"version":3,"file":"export-DenKwEQu.js","names":[],"sources":["../packages/cli/src/export/ddl.ts","../packages/cli/src/export/rows.ts","../packages/cli/src/export/where.ts","../packages/cli/src/export/plan-sidecar.ts","../packages/cli/src/export.ts"],"sourcesContent":["import { BaerlyError } from \"@baerly/protocol\";\nimport type { ExportPlan } from \"./types.ts\";\n\n/**\n * Emit a `CREATE TABLE` statement for the plan, one line per column,\n * terminated with a semicolon + newline so the output is directly\n * pipeable into `psql` / `sqlite3` / `wrangler d1 execute`.\n *\n * `_id` is the primary key (always first in `plan.columns`).\n *\n * D1 today is sqlite-flavoured: same DDL as `target=sqlite` with a\n * single difference — D1 disallows table names starting with\n * `sqlite_`. We refuse them up front.\n */\nexport const emitCreateTable = (plan: ExportPlan): string => {\n if (plan.columns.length === 0) {\n throw new BaerlyError(\n \"SchemaError\",\n `emitCreateTable: collection ${JSON.stringify(plan.table)} has no observed columns — empty snapshot?`,\n );\n }\n if (plan.target === \"d1\" && plan.table.toLowerCase().startsWith(\"sqlite_\")) {\n throw new BaerlyError(\n \"SchemaError\",\n `emitCreateTable: D1 reserves the sqlite_ table-name prefix (got ${JSON.stringify(plan.table)})`,\n );\n }\n const lines: string[] = [];\n lines.push(`CREATE TABLE ${plan.tableIdentifier} (`);\n const colLines: string[] = [];\n for (const col of plan.columns) {\n const nullClause = col.nullable ? \"\" : \" NOT NULL\";\n const pkClause = col.source === \"_id\" ? \" PRIMARY KEY\" : \"\";\n colLines.push(` ${col.identifier} ${col.sqlType}${nullClause}${pkClause}`);\n }\n lines.push(colLines.join(\",\\n\"));\n lines.push(\");\");\n return lines.join(\"\\n\") + \"\\n\";\n};\n","import type { DocumentValue } from \"@baerly/protocol\";\nimport type { ExportPlan, ExportRow } from \"./types.ts\";\nimport { quoteValue } from \"./sql-escape.ts\";\n\n/**\n * Emit one `INSERT INTO …` statement per row. The emitted SQL is\n * directly pipeable into `psql` / `sqlite3` / `wrangler d1\n * execute`. Per-row statements (not one big VALUES tuple) so a\n * mid-stream failure has bounded blast radius.\n *\n * For columns whose plan has `jsonEncoded: true`, the row's value\n * is JSON-stringified first and then string-quoted. Postgres\n * accepts a literal text JSON in a `jsonb` column. SQLite / D1 see\n * the JSON as plain TEXT.\n *\n * Rows are streamed via the async-iterable protocol so the export\n * never materialises the full SQL output in memory. The caller\n * concatenates the yielded chunks (or pipes them straight to disk\n * / stdout).\n */\nexport async function* emitInsertStatements(\n plan: ExportPlan,\n rows: ReadonlyMap<string, ExportRow>,\n): AsyncIterable<string> {\n const columnList = plan.columns.map((c) => c.identifier).join(\", \");\n // Iterate in `Map` insertion order — stable, and the snapshot\n // body itself sorts by `_id` (compactor.ts: `docs is sorted by\n // _id for deterministic byte output`).\n for (const [id, body] of rows) {\n const values: string[] = [];\n for (const col of plan.columns) {\n const raw: DocumentValue | undefined =\n col.source === \"_id\"\n ? (id as DocumentValue)\n : (body as Record<string, DocumentValue>)[col.source];\n if (raw === undefined) {\n values.push(\"NULL\");\n continue;\n }\n if (col.jsonEncoded) {\n const json = JSON.stringify(raw);\n values.push(quoteValue(json, plan.target));\n } else {\n values.push(quoteValue(raw, plan.target));\n }\n }\n yield `INSERT INTO ${plan.tableIdentifier} (${columnList}) VALUES (${values.join(\", \")});\\n`;\n }\n}\n","/**\n * Wire-predicate → SQL `WHERE` clause translation.\n *\n * Pure function. The translator consumes a validated\n * {@link PredicateWire} — the same shape the read path uses — and\n * an {@link ExportPlan} (from `./plan.ts`), and emits a SQL fragment\n * matched against the plan's columns.\n *\n * Three classes of clause:\n *\n * 1. Flat column, top-level field → direct comparator\n * (`\"status\" = 'open'`, `\"priority\" > 5`).\n * 2. JSON-encoded column → JSON-path operators (Postgres `->`/`->>`\n * chains; SQLite/D1 `json_extract(…, '$.…')`).\n * 3. Unmatchable clause (dotted path against a flat column, or a\n * field naming an unknown column) → `1 = 0` plus a hint the CLI\n * surfaces as a `-- TODO(baerly export):` comment above the\n * emitted statement.\n *\n * Dynamic predicates are invisible at runtime — we see the\n * materialised wire, not the source expression. Callers that know\n * they constructed the wire dynamically can pass\n * `options.dynamicHint` to surface an operator-supplied note.\n */\n\nimport {\n BaerlyError,\n type DocumentValue,\n type PredicateClause,\n type PredicateWire,\n validateWire,\n} from \"@baerly/protocol\";\nimport { quoteValue } from \"./sql-escape.ts\";\nimport type { ColumnPlan, ExportPlan, SqlTarget } from \"./types.ts\";\n\nexport interface WhereTranslation {\n /** SQL fragment without the leading `WHERE`. Empty when no predicate. */\n readonly sql: string;\n /**\n * Hand-edit hints for the operator. One entry per non-matchable\n * clause (§3.6) or per dynamically-constructed sub-clause flagged\n * by the caller. The CLI surfaces these as `-- TODO(baerly export): …`\n * comments above the emitted statement.\n */\n readonly hints: readonly string[];\n}\n\n/**\n * Translate a validated {@link PredicateWire} into a SQL WHERE-clause\n * fragment matched against the plan's columns. The first argument\n * must already have been validated by {@link validateWire} — the\n * function re-validates defensively but the caller's invariant\n * matters for error-message provenance.\n *\n * Pure function. No I/O. Same wire + plan + target → same SQL string.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — wire fails\n * {@link validateWire}; same shape `Query<T>.where` already\n * surfaces.\n */\nexport const translatePredicateWireToSql = (\n wire: PredicateWire,\n plan: ExportPlan,\n options?: { readonly dynamicHint?: string },\n): WhereTranslation => {\n validateWire(wire);\n const hints: string[] = [];\n if (options?.dynamicHint !== undefined && options.dynamicHint.length > 0) {\n hints.push(\n `caller-flagged dynamic predicate: ${options.dynamicHint}. Review the emitted SQL for completeness.`,\n );\n }\n const clauses: string[] = [];\n for (const clause of wire.clauses) {\n clauses.push(...clauseForWire(clause, plan, hints));\n }\n return {\n sql: clauses.length === 0 ? \"\" : clauses.join(\" AND \"),\n hints,\n };\n};\n\nconst clauseForWire = (clause: PredicateClause, plan: ExportPlan, hints: string[]): string[] => {\n const segments = clause.field.includes(\".\") ? clause.field.split(\".\") : [clause.field];\n const head = segments[0];\n if (head === undefined || head.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"translatePredicateWireToSql: empty field path encountered (defensive)\",\n );\n }\n const col = plan.columns.find((c) => c.source === head);\n if (col === undefined) {\n hints.push(\n `predicate field ${JSON.stringify(clause.field)} references a key never observed in the snapshot; this clause cannot match.`,\n );\n return [\"1 = 0\"];\n }\n // §3.2 — flat column, top-level field → direct comparator.\n if (!col.jsonEncoded && segments.length === 1) {\n return [flatColumnClause(col.identifier, clause, plan.target)];\n }\n // §3.6 — flat column, dotted path → unmatchable.\n if (!col.jsonEncoded && segments.length > 1) {\n hints.push(\n `predicate path ${JSON.stringify(clause.field)} addresses a flat column; this clause cannot match. Hand-edit if intended.`,\n );\n return [\"1 = 0\"];\n }\n // §3.3 — JSON column, top-level field.\n if (col.jsonEncoded && segments.length === 1) {\n return [jsonColumnRootClause(col, clause, plan.target)];\n }\n // §3.4 / §3.5 — JSON column, dotted path.\n return [jsonPathClause(col, segments.slice(1), clause, plan.target)];\n};\n\nconst flatColumnClause = (\n identifier: string,\n clause: PredicateClause,\n target: SqlTarget,\n): string => {\n switch (clause.op) {\n case \"eq\": {\n return `${identifier} = ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gt\": {\n return `${identifier} > ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gte\": {\n return `${identifier} >= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lt\": {\n return `${identifier} < ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lte\": {\n return `${identifier} <= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"in\": {\n return `${identifier} IN (${(clause.value as ReadonlyArray<DocumentValue>)\n .map((v) => quoteLeaf(v, target))\n .join(\", \")})`;\n }\n }\n};\n\nconst jsonColumnRootClause = (\n col: ColumnPlan,\n clause: PredicateClause,\n target: SqlTarget,\n): string => {\n // The root JSON column stores the value as JSON-encoded text;\n // we compare against the JSON encoding of the predicate value.\n // Range and `in` ops on a JSON-encoded root column compare the\n // JSON text lexicographically, which is rarely what the caller\n // wanted — for those, the operator is expected to promote the\n // field into a flat column or hand-edit the emitted SQL.\n if (clause.op === \"eq\") {\n const literal = JSON.stringify(clause.value);\n if (target === \"postgres\") {\n return `${col.identifier}::text = ${quoteValue(literal, target)}`;\n }\n return `${col.identifier} = ${quoteValue(literal, target)}`;\n }\n if (clause.op === \"in\") {\n const literals = (clause.value as ReadonlyArray<DocumentValue>).map((v) =>\n quoteValue(JSON.stringify(v), target),\n );\n if (target === \"postgres\") {\n return `${col.identifier}::text IN (${literals.join(\", \")})`;\n }\n return `${col.identifier} IN (${literals.join(\", \")})`;\n }\n // Range against JSON-encoded root: fall back to a lex compare on\n // the JSON serialisation. Surface a comment via the SQL itself;\n // the operator can hand-edit.\n const comparator = rangeComparator(clause.op);\n const literal = JSON.stringify(clause.value);\n if (target === \"postgres\") {\n return `${col.identifier}::text ${comparator} ${quoteValue(literal, target)}`;\n }\n return `${col.identifier} ${comparator} ${quoteValue(literal, target)}`;\n};\n\nconst jsonPathClause = (\n col: ColumnPlan,\n tail: readonly string[],\n clause: PredicateClause,\n target: SqlTarget,\n): string => {\n const accessor = jsonPathAccessor(col.identifier, tail, target);\n switch (clause.op) {\n case \"eq\": {\n return `${accessor} = ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gt\": {\n return `${accessor} > ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gte\": {\n return `${accessor} >= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lt\": {\n return `${accessor} < ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lte\": {\n return `${accessor} <= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"in\": {\n return `${accessor} IN (${(clause.value as ReadonlyArray<DocumentValue>)\n .map((v) => quoteLeaf(v, target))\n .join(\", \")})`;\n }\n }\n};\n\nconst rangeComparator = (op: PredicateClause[\"op\"]): string => {\n if (op === \"gt\") {\n return \">\";\n }\n if (op === \"gte\") {\n return \">=\";\n }\n if (op === \"lt\") {\n return \"<\";\n }\n return \"<=\";\n};\n\nconst jsonPathAccessor = (\n identifier: string,\n tail: readonly string[],\n target: SqlTarget,\n): string => {\n if (target === \"postgres\") {\n let expr = identifier;\n for (let i = 0; i < tail.length; i++) {\n const seg = tail[i]!;\n const isLast = i === tail.length - 1;\n const key = `'${seg.replace(/'/g, \"''\")}'`;\n expr = `${expr}${isLast ? \"->>\" : \"->\"}${key}`;\n }\n return expr;\n }\n const jsonPath = `'$.${tail.map((s) => s.replace(/'/g, \"''\")).join(\".\")}'`;\n return `json_extract(${identifier}, ${jsonPath})`;\n};\n\n/**\n * Quote a leaf primitive for use as the right-hand side of a\n * comparison. Booleans branch on target. Nested objects must never\n * reach here — wire `eq` clauses on nested objects can only come\n * from the callback form `q.eq(\"nested\", { ... })`, which the\n * export translator does not support today.\n */\nconst quoteLeaf = (value: DocumentValue, target: SqlTarget): string => {\n if (typeof value === \"object\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"translatePredicateWireToSql: nested object reached leaf quoter — callback-form q.eq(field, object) is not supported for SQL export. Hand-edit the emitted SQL.\",\n );\n }\n return quoteValue(value, target);\n};\n","/**\n * Sidecar plan serialisation for `baerly export`.\n *\n * `baerly export --output=foo.sql` writes the inferred {@link ExportPlan}\n * alongside the SQL dump as `foo.sql.plan.json`. The round-trip test\n * (`tests/integration/export-round-trip.test.ts`) consumes the sidecar\n * to coerce SQLite-returned values back to their original JS type\n * (e.g. SQLite stores booleans as 0/1; we restore `true`/`false`).\n *\n * Wire shape (`schemaVersion = 1`):\n *\n * ```json\n * {\n * \"schemaVersion\": 1,\n * \"table\": \"tickets\",\n * \"target\": \"sqlite\",\n * \"columns\": [\n * { \"source\": \"_id\", \"sqlType\": \"TEXT\", \"nullable\": false, \"jsonEncoded\": false },\n * ...\n * ]\n * }\n * ```\n *\n * `identifier` is NOT carried on the wire — we re-derive it via\n * {@link quoteIdentifier} on deserialise. An attacker writing the\n * sidecar should not get SQL-emit control over identifiers.\n *\n * `rowCount` is also not preserved across the sidecar boundary; the\n * deserialised plan reports `0`. This is intentional — consumers that\n * care about row count read the SQL stream itself.\n */\n\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { quoteIdentifier } from \"./sql-escape.ts\";\nimport type { ColumnPlan, ExportPlan, SqlTarget, SqlType } from \"./types.ts\";\n\nconst SIDECAR_SCHEMA_VERSION = 1 as const;\n\nconst VALID_TARGETS: ReadonlySet<string> = new Set([\"postgres\", \"sqlite\", \"d1\"]);\n\nconst VALID_SQL_TYPES: ReadonlySet<string> = new Set([\n \"text\",\n \"boolean\",\n \"integer\",\n \"double precision\",\n \"jsonb\",\n \"TEXT\",\n \"INTEGER\",\n \"REAL\",\n]);\n\n/**\n * Encode an {@link ExportPlan} as the canonical sidecar JSON string.\n *\n * Wire format is pretty-printed (`indent=2`) with a trailing newline\n * so `cat sidecar.plan.json` is human-readable and `diff` works on\n * two sidecars without spurious line-end noise. The on-wire bytes\n * embed the `schemaVersion` discriminator so future shape changes\n * are detectable; `identifier` and `tableIdentifier` are NOT carried\n * (they're re-derived via {@link quoteIdentifier} on deserialise).\n */\nexport const serializeExportPlan = (plan: ExportPlan): string => {\n return (\n JSON.stringify(\n {\n schemaVersion: SIDECAR_SCHEMA_VERSION,\n table: plan.table,\n target: plan.target,\n columns: plan.columns.map((c) => ({\n source: c.source,\n sqlType: c.sqlType,\n nullable: c.nullable,\n jsonEncoded: c.jsonEncoded,\n })),\n },\n null,\n 2,\n ) + \"\\n\"\n );\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n/**\n * Parse the sidecar JSON string back into an {@link ExportPlan}.\n *\n * @throws BaerlyError code=\"InvalidConfig\" when the sidecar JSON is\n * malformed, the schema version is unsupported, or any required\n * field is missing / has an unexpected type. Identifiers are\n * re-quoted via {@link quoteIdentifier} rather than copied off the\n * wire — the sidecar cannot smuggle SQL-injection via a\n * pre-quoted identifier.\n */\nexport const deserializeExportPlan = (text: string): ExportPlan => {\n let raw: unknown;\n try {\n raw = JSON.parse(text);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: parse failed: ${(error as Error).message}`,\n );\n }\n if (!isObject(raw)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"deserializeExportPlan: top-level value is not an object\",\n );\n }\n if (raw[\"schemaVersion\"] !== SIDECAR_SCHEMA_VERSION) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: unsupported schemaVersion ${String(raw[\"schemaVersion\"])} (expected ${String(SIDECAR_SCHEMA_VERSION)})`,\n );\n }\n if (typeof raw[\"table\"] !== \"string\" || raw[\"table\"].length === 0) {\n throw new BaerlyError(\"InvalidConfig\", \"deserializeExportPlan: missing or empty table\");\n }\n if (typeof raw[\"target\"] !== \"string\" || !VALID_TARGETS.has(raw[\"target\"])) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: unknown target ${JSON.stringify(raw[\"target\"])}`,\n );\n }\n if (!Array.isArray(raw[\"columns\"])) {\n throw new BaerlyError(\"InvalidConfig\", \"deserializeExportPlan: columns is not an array\");\n }\n const table = raw[\"table\"];\n const target = raw[\"target\"] as SqlTarget;\n const columns: ColumnPlan[] = [];\n for (const [i, col] of raw[\"columns\"].entries()) {\n if (!isObject(col)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}] is not an object`,\n );\n }\n if (typeof col[\"source\"] !== \"string\" || col[\"source\"].length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].source is missing or empty`,\n );\n }\n if (typeof col[\"sqlType\"] !== \"string\" || !VALID_SQL_TYPES.has(col[\"sqlType\"])) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].sqlType ${JSON.stringify(col[\"sqlType\"])} is not a recognised SqlType`,\n );\n }\n if (typeof col[\"nullable\"] !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].nullable is not a boolean`,\n );\n }\n if (typeof col[\"jsonEncoded\"] !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].jsonEncoded is not a boolean`,\n );\n }\n columns.push({\n source: col[\"source\"],\n identifier: quoteIdentifier(col[\"source\"], target),\n sqlType: col[\"sqlType\"] as SqlType,\n nullable: col[\"nullable\"],\n jsonEncoded: col[\"jsonEncoded\"],\n });\n }\n return {\n table,\n target,\n tableIdentifier: quoteIdentifier(table, target),\n columns,\n // Not preserved across the sidecar boundary — see file JSDoc.\n rowCount: 0,\n };\n};\n","/* eslint-disable no-underscore-dangle -- `_id` is the locked\n primary-key field on document shapes; the exporter threads it\n through the materialised view and the emitted INSERT rows. */\n\n/**\n * `baerly export` — snapshot dump of one collection to SQL.\n *\n * Drives the export modules end-to-end: load the materialised view,\n * infer an `ExportPlan` over the row shape, emit `CREATE TABLE` +\n * `INSERT` statements. When `--where=<json>` is supplied the\n * predicate is translated via `translatePredicateToSql` and applied\n * in-memory through `matches(...)` so the emitted INSERTs already\n * match the filter; the translated WHERE clause is also surfaced as a\n * comment above the inserts so operators can inspect / hand-edit it.\n *\n * The sidecar file (`<output>.plan.json`) carries the `ExportPlan` so\n * a follow-up round-trip ingest can verify the column schema. The\n * sidecar is JSON via `JSON.stringify` — the plan shape is the public\n * contract.\n *\n * Args:\n * --bucket Required. Bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Collection name.\n * --target Required. postgres | sqlite | d1.\n * --where Optional. JSON-encoded `Predicate<T>`.\n * --where-comment Optional. Caller hint surfaced as a\n * `-- TODO(baerly export):` comment.\n * --output Optional. Path to write SQL into; default\n * stdout. The sidecar plan is written to\n * `<output>.plan.json` unless `--no-sidecar`.\n * --no-sidecar Skip emitting the sidecar plan file.\n * --json JSON envelope on stdout (or stderr on error).\n *\n * Exit codes:\n * 0 — dump completed.\n * 1 — InvalidConfig (bad args / bucket URI / --where JSON / unknown --target).\n * 2 — Storage / Network error.\n * 3 — Protocol invariant (Internal / InvalidResponse / Conflict).\n */\n\nimport { writeFile } from \"node:fs/promises\";\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, matchesWire, type PredicateWire, validateWire } from \"@baerly/protocol\";\nimport {\n type ExportPlan,\n type ExportRow,\n type SqlTarget,\n emitCreateTable,\n emitInsertStatements,\n inferPlanForCollection,\n loadMaterialisedView,\n serializeExportPlan,\n translatePredicateWireToSql,\n} from \"./export/index.ts\";\nimport { parseBucketUri } from \"./bucket-uri.ts\";\nimport { emitSuccess } from \"./output.ts\";\nimport {\n APP_ARG,\n assertCollectionArg,\n BUCKET_ARG,\n COLLECTION_ARG,\n defineBaerlySubcommand,\n JSON_ARG,\n TENANT_ARG,\n} from \"./subcommand.ts\";\n\nconst EXPORT_ARGS = {\n bucket: BUCKET_ARG,\n app: APP_ARG,\n tenant: TENANT_ARG,\n collection: COLLECTION_ARG,\n target: {\n type: \"enum\",\n options: [\"postgres\", \"sqlite\", \"d1\"],\n required: true,\n description: \"SQL target: postgres | sqlite | d1.\",\n },\n where: {\n type: \"string\",\n required: false,\n description: \"JSON-encoded PredicateWire ({ clauses: [...] }) filtering the rows to export.\",\n valueHint: \"json\",\n },\n \"where-comment\": {\n type: \"string\",\n required: false,\n description: \"Caller hint surfaced as a -- TODO(baerly export): comment.\",\n valueHint: \"text\",\n },\n output: {\n type: \"string\",\n required: false,\n description: \"Path to write SQL into; default stdout.\",\n valueHint: \"path\",\n },\n sidecar: {\n type: \"boolean\",\n default: true,\n description: \"Emit a <output>.plan.json sidecar (default true; pass --no-sidecar to skip).\",\n },\n json: JSON_ARG,\n} as const satisfies ArgsDef;\n\nconst parseWherePredicate = (raw: string): PredicateWire => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly export: --where is not valid JSON: ${(error as Error).message}`,\n );\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly export: --where must decode to a JSON object (got ${describeNonObject(parsed)})`,\n );\n }\n // Re-validate defensively; the translator will reject too, but\n // surfacing the error here gives a single uniform error path.\n validateWire(parsed as PredicateWire);\n return parsed as PredicateWire;\n};\n\nconst filterRows = (\n rows: ReadonlyMap<string, ExportRow>,\n wire: PredicateWire | null,\n): Map<string, ExportRow> => {\n const filtered = new Map<string, ExportRow>();\n for (const [id, body] of rows) {\n if (wire === null) {\n filtered.set(id, body);\n continue;\n }\n if (matchesWire(wire, body)) {\n filtered.set(id, body);\n }\n }\n return filtered;\n};\n\nconst buildSql = async (\n plan: ExportPlan,\n rows: ReadonlyMap<string, ExportRow>,\n whereClause: string,\n whereHints: readonly string[],\n): Promise<string> => {\n let out = emitCreateTable(plan);\n for (const hint of whereHints) {\n out += `-- TODO(baerly export): ${hint}\\n`;\n }\n if (whereClause.length > 0) {\n out += `-- WHERE clause for review: ${whereClause}\\n`;\n }\n for await (const chunk of emitInsertStatements(plan, rows)) {\n out += chunk;\n }\n return out;\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"export\",\n meta: {\n description: \"Snapshot dump of one collection to SQL.\",\n },\n args: EXPORT_ARGS,\n handler: async (args, ctx) => {\n const target: SqlTarget = args.target;\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n assertCollectionArg(args.collection, \"baerly export\");\n const bucket = await parseBucketUri(args.bucket);\n const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;\n const view = await loadMaterialisedView({\n storage: bucket.storage,\n currentJsonKey,\n collection: args.collection,\n });\n if (view === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly export: collection ${JSON.stringify(args.collection)} is not provisioned (no current.json at ${currentJsonKey})`,\n );\n }\n const plan = inferPlanForCollection({\n rows: view,\n target,\n table: args.collection,\n });\n\n let wire: PredicateWire | null = null;\n let whereClause = \"\";\n let whereHints: readonly string[] = [];\n if (typeof args.where === \"string\" && args.where.length > 0) {\n wire = parseWherePredicate(args.where);\n const translation = translatePredicateWireToSql(\n wire,\n plan,\n typeof args[\"where-comment\"] === \"string\" && args[\"where-comment\"].length > 0\n ? { dynamicHint: args[\"where-comment\"] }\n : undefined,\n );\n whereClause = translation.sql;\n whereHints = translation.hints;\n } else if (typeof args[\"where-comment\"] === \"string\" && args[\"where-comment\"].length > 0) {\n // Bare --where-comment with no predicate still surfaces the operator's\n // note so reviewers see the intent.\n whereHints = [\n `caller-flagged dynamic predicate: ${args[\"where-comment\"]}. No predicate supplied; emitted INSERTs cover the full collection.`,\n ];\n }\n\n const filtered = filterRows(view, wire);\n const sql = await buildSql(plan, filtered, whereClause, whereHints);\n\n const outputPath = args.output;\n if (typeof outputPath === \"string\" && outputPath.length > 0) {\n await writeFile(outputPath, sql, \"utf8\");\n if (args.sidecar !== false) {\n await writeFile(`${outputPath}.plan.json`, serializeExportPlan(plan), \"utf8\");\n }\n } else {\n process.stdout.write(sql);\n }\n\n emitSuccess({\n command: \"export\",\n status: \"ok\",\n collection: args.collection,\n target,\n rows: filtered.size,\n hints: whereHints,\n ...(typeof outputPath === \"string\" && outputPath.length > 0 && { output: outputPath }),\n });\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly export`. */\nexport const exportCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runExport = bundle.run;\n\n// Build a human-readable label for the \"expected JSON object\" error.\n// `null`, arrays, and the bare `undefined` need to be disambiguated\n// from `typeof`'s default \"object\".\nconst describeNonObject = (v: unknown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|
|
2
|
-
import { c as loadSnapshotAsMap, h as readCurrentJson } from "./log-tail-
|
|
3
|
-
import { i as rebuildIndex } from "./maintenance-
|
|
1
|
+
import { r as parseBucketUri } from "./config-B6nTy8e2.js";
|
|
2
|
+
import { c as loadSnapshotAsMap, h as readCurrentJson } from "./log-tail-QWU4wlu-.js";
|
|
3
|
+
import { i as rebuildIndex } from "./maintenance-fEi-UZ2o.js";
|
|
4
4
|
import { i as isJsonMode, o as BaerlyError, r as emitSuccess } from "./baerly.js";
|
|
5
|
-
import { a as TENANT_ARG, i as JSON_ARG, n as BUCKET_ARG, o as assertCollectionArg, r as COLLECTION_ARG, s as defineBaerlySubcommand, t as APP_ARG } from "./subcommand-
|
|
5
|
+
import { a as TENANT_ARG, i as JSON_ARG, n as BUCKET_ARG, o as assertCollectionArg, r as COLLECTION_ARG, s as defineBaerlySubcommand, t as APP_ARG } from "./subcommand-BV68pqwJ.js";
|
|
6
6
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
7
|
//#region src/admin/fsck.ts
|
|
8
8
|
/**
|
|
@@ -276,4 +276,4 @@ bundle.run;
|
|
|
276
276
|
//#endregion
|
|
277
277
|
export { fsckCmd };
|
|
278
278
|
|
|
279
|
-
//# sourceMappingURL=fsck-
|
|
279
|
+
//# sourceMappingURL=fsck-2Vq-7-e2.js.map
|