@gusto/baerly-storage 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +97 -0
  2. package/dist/API.md +850 -0
  3. package/dist/app-config-Cb5dO2s9.d.ts +480 -0
  4. package/dist/app-config.d.ts +2 -0
  5. package/dist/app-config.js +8 -0
  6. package/dist/app-config.js.map +1 -0
  7. package/dist/auth.d.ts +237 -0
  8. package/dist/auth.js +1335 -0
  9. package/dist/auth.js.map +1 -0
  10. package/dist/baerly.js +761 -0
  11. package/dist/baerly.js.map +1 -0
  12. package/dist/bucket-uri-BrDEYvzy.js +4922 -0
  13. package/dist/bucket-uri-BrDEYvzy.js.map +1 -0
  14. package/dist/chunk-EAsCxrDo.js +14 -0
  15. package/dist/client-BLf3Ae5s.d.ts +233 -0
  16. package/dist/client-react.d.ts +131 -0
  17. package/dist/client-react.js +559 -0
  18. package/dist/client-react.js.map +1 -0
  19. package/dist/client.d.ts +4 -0
  20. package/dist/client.js +160 -0
  21. package/dist/client.js.map +1 -0
  22. package/dist/cloudflare-CINJPKCW.js +911 -0
  23. package/dist/cloudflare-CINJPKCW.js.map +1 -0
  24. package/dist/cloudflare.d.ts +211 -0
  25. package/dist/cloudflare.js +445 -0
  26. package/dist/cloudflare.js.map +1 -0
  27. package/dist/config-Bsg8wgwo.js +198 -0
  28. package/dist/config-Bsg8wgwo.js.map +1 -0
  29. package/dist/context-Oj7ffwD-.js +187 -0
  30. package/dist/context-Oj7ffwD-.js.map +1 -0
  31. package/dist/cost-B1WiZxlf.js +203 -0
  32. package/dist/cost-B1WiZxlf.js.map +1 -0
  33. package/dist/current-json-BkatBzF7.js +252 -0
  34. package/dist/current-json-BkatBzF7.js.map +1 -0
  35. package/dist/db-D62JguBc.d.ts +336 -0
  36. package/dist/deploy-BB-wqbhf.js +83 -0
  37. package/dist/deploy-BB-wqbhf.js.map +1 -0
  38. package/dist/dev-banner-CWHIk8tH.d.ts +26 -0
  39. package/dist/dev-vite.d.ts +146 -0
  40. package/dist/dev-vite.js +223 -0
  41. package/dist/dev-vite.js.map +1 -0
  42. package/dist/dev.d.ts +3 -0
  43. package/dist/dev.js +2 -0
  44. package/dist/doctor-B8h9GCN9.js +331 -0
  45. package/dist/doctor-B8h9GCN9.js.map +1 -0
  46. package/dist/dump-BHo_sIMZ.js +116 -0
  47. package/dist/dump-BHo_sIMZ.js.map +1 -0
  48. package/dist/errors-DOdL95kK.js +58 -0
  49. package/dist/errors-DOdL95kK.js.map +1 -0
  50. package/dist/export-Dz2PZKSR.js +423 -0
  51. package/dist/export-Dz2PZKSR.js.map +1 -0
  52. package/dist/fsck-DEz9lyCy.js +293 -0
  53. package/dist/fsck-DEz9lyCy.js.map +1 -0
  54. package/dist/http-CjUO1Bec.js +1756 -0
  55. package/dist/http-CjUO1Bec.js.map +1 -0
  56. package/dist/http.d.ts +1619 -0
  57. package/dist/http.js +2 -0
  58. package/dist/index-BGC-ENnj.d.ts +1065 -0
  59. package/dist/index-BYv0hb8M.d.ts +1457 -0
  60. package/dist/index-BquQkhJi.d.ts +112 -0
  61. package/dist/index-COsQ-Mlz.d.ts +146 -0
  62. package/dist/index.d.ts +6 -0
  63. package/dist/index.js +6 -0
  64. package/dist/indexes-BXn7a06a.js +297 -0
  65. package/dist/indexes-BXn7a06a.js.map +1 -0
  66. package/dist/indexes-DwOXkn1Y.d.ts +22 -0
  67. package/dist/inspect-x02aFWnh.js +149 -0
  68. package/dist/inspect-x02aFWnh.js.map +1 -0
  69. package/dist/log-walk-DIru96UT.js +260 -0
  70. package/dist/log-walk-DIru96UT.js.map +1 -0
  71. package/dist/maintenance-Bn6ul9aV.js +758 -0
  72. package/dist/maintenance-Bn6ul9aV.js.map +1 -0
  73. package/dist/maintenance.d.ts +323 -0
  74. package/dist/maintenance.js +2 -0
  75. package/dist/node.d.ts +422 -0
  76. package/dist/node.js +2 -0
  77. package/dist/normalize-XWY25_sG.js +133 -0
  78. package/dist/normalize-XWY25_sG.js.map +1 -0
  79. package/dist/observability-2IDYRuZK.js +2333 -0
  80. package/dist/observability-2IDYRuZK.js.map +1 -0
  81. package/dist/observability.d.ts +3 -0
  82. package/dist/observability.js +3 -0
  83. package/dist/plan-Cs17VqjU.js +224 -0
  84. package/dist/plan-Cs17VqjU.js.map +1 -0
  85. package/dist/query-DcSbFLJt.js +1880 -0
  86. package/dist/query-DcSbFLJt.js.map +1 -0
  87. package/dist/rebuild-index-C5gTXryd.js +119 -0
  88. package/dist/rebuild-index-C5gTXryd.js.map +1 -0
  89. package/dist/rebuild-index-DwXM0WfA.js +104 -0
  90. package/dist/rebuild-index-DwXM0WfA.js.map +1 -0
  91. package/dist/request-BEF_OvMh.js +72 -0
  92. package/dist/request-BEF_OvMh.js.map +1 -0
  93. package/dist/restore-CbKVMMpm.js +847 -0
  94. package/dist/restore-CbKVMMpm.js.map +1 -0
  95. package/dist/shared-secret-BJdSwpgw.js +71 -0
  96. package/dist/shared-secret-BJdSwpgw.js.map +1 -0
  97. package/dist/snapshot-D7C4_FSl.js +71 -0
  98. package/dist/snapshot-D7C4_FSl.js.map +1 -0
  99. package/dist/snapshot-z_N9hpTe.js +917 -0
  100. package/dist/snapshot-z_N9hpTe.js.map +1 -0
  101. package/dist/src-Chafbw8r.js +522 -0
  102. package/dist/src-Chafbw8r.js.map +1 -0
  103. package/dist/src-DyET_VPP.js +6199 -0
  104. package/dist/src-DyET_VPP.js.map +1 -0
  105. package/dist/src-n0Te1r98.js +352 -0
  106. package/dist/src-n0Te1r98.js.map +1 -0
  107. package/dist/subcommand-BWs6K7zb.js +110 -0
  108. package/dist/subcommand-BWs6K7zb.js.map +1 -0
  109. package/dist/usage-RVUQMLop.js +339 -0
  110. package/dist/usage-RVUQMLop.js.map +1 -0
  111. package/dist/validate-DhH1lO8I.js +377 -0
  112. package/dist/validate-DhH1lO8I.js.map +1 -0
  113. package/dist/wire-izfGZDvr.js +7 -0
  114. package/dist/wire-izfGZDvr.js.map +1 -0
  115. package/package.json +189 -0
@@ -0,0 +1,352 @@
1
+ import { t as __commonJSMin } from "./chunk-EAsCxrDo.js";
2
+ import { t as createCurrentJson } from "./current-json-BkatBzF7.js";
3
+ import { t as BaerlyError } from "./errors-DOdL95kK.js";
4
+ import { createHash } from "node:crypto";
5
+ import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
6
+ import { tmpdir } from "node:os";
7
+ import { dirname, join, posix, relative, resolve, sep } from "node:path";
8
+ //#region node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.browser.js
9
+ var require_picocolors_browser = /* @__PURE__ */ __commonJSMin(((exports, module) => {
10
+ var x = String;
11
+ var create = function() {
12
+ return {
13
+ isColorSupported: false,
14
+ reset: x,
15
+ bold: x,
16
+ dim: x,
17
+ italic: x,
18
+ underline: x,
19
+ inverse: x,
20
+ hidden: x,
21
+ strikethrough: x,
22
+ black: x,
23
+ red: x,
24
+ green: x,
25
+ yellow: x,
26
+ blue: x,
27
+ magenta: x,
28
+ cyan: x,
29
+ white: x,
30
+ gray: x,
31
+ bgBlack: x,
32
+ bgRed: x,
33
+ bgGreen: x,
34
+ bgYellow: x,
35
+ bgBlue: x,
36
+ bgMagenta: x,
37
+ bgCyan: x,
38
+ bgWhite: x,
39
+ blackBright: x,
40
+ redBright: x,
41
+ greenBright: x,
42
+ yellowBright: x,
43
+ blueBright: x,
44
+ magentaBright: x,
45
+ cyanBright: x,
46
+ whiteBright: x,
47
+ bgBlackBright: x,
48
+ bgRedBright: x,
49
+ bgGreenBright: x,
50
+ bgYellowBright: x,
51
+ bgBlueBright: x,
52
+ bgMagentaBright: x,
53
+ bgCyanBright: x,
54
+ bgWhiteBright: x
55
+ };
56
+ };
57
+ module.exports = create();
58
+ module.exports.createColors = create;
59
+ }));
60
+ //#endregion
61
+ //#region packages/dev/src/dev-banner.ts
62
+ var import_picocolors_browser = require_picocolors_browser();
63
+ function printDevBanner(opts) {
64
+ const isPlain = opts.plain !== void 0 ? opts.plain : process.env["CI"] !== void 0 || !process.stderr.isTTY;
65
+ const write = opts.write ?? ((chunk) => process.stderr.write(chunk));
66
+ const pc = (0, import_picocolors_browser.createColors)(!isPlain);
67
+ const hints = opts.hints ?? [];
68
+ const lines = [];
69
+ if (isPlain) {
70
+ lines.push(`baerly · ${opts.name}`);
71
+ if (opts.primaryUrl) lines.push(`${opts.primaryUrl.label}: ${opts.primaryUrl.url}`);
72
+ if (opts.apiUrl) {
73
+ const note = opts.apiUrl.note ? ` (${opts.apiUrl.note})` : "";
74
+ lines.push(`${opts.apiUrl.label}: ${opts.apiUrl.url}${note}`);
75
+ }
76
+ for (const hint of hints) lines.push(`${hint.key}: ${hint.value}`);
77
+ write(lines.join("\n") + "\n");
78
+ } else {
79
+ lines.push(pc.bold(pc.cyan(`▎ baerly · ${opts.name}`)));
80
+ lines.push("");
81
+ if (opts.primaryUrl) {
82
+ const marker = ` ${pc.green("← open this")}`;
83
+ lines.push(` ${pc.dim(opts.primaryUrl.label)} → ${opts.primaryUrl.url}${marker}`);
84
+ }
85
+ if (opts.apiUrl) {
86
+ const note = opts.apiUrl.note ? ` ${pc.dim(`(${opts.apiUrl.note})`)}` : "";
87
+ lines.push(` ${pc.dim(opts.apiUrl.label)} → ${opts.apiUrl.url}${note}`);
88
+ }
89
+ if ((opts.primaryUrl || opts.apiUrl) && hints.length > 0) lines.push("");
90
+ if (hints.length > 0) {
91
+ const maxKeyLen = Math.max(...hints.map((h) => h.key.length));
92
+ for (const hint of hints) lines.push(` ${pc.dim(hint.key.padEnd(maxKeyLen))} ${hint.value}`);
93
+ }
94
+ lines.push("");
95
+ write(lines.join("\n"));
96
+ }
97
+ }
98
+ //#endregion
99
+ //#region packages/dev/src/dev-landing.ts
100
+ /**
101
+ * Render the dev landing page HTML. Dependency-free; system fonts
102
+ * only; no JS. All substitutions are HTML-escaped to keep the page
103
+ * inert even when `app` / `uiUrl` come from env vars.
104
+ */
105
+ const renderDevLanding = (opts) => {
106
+ const label = escapeHtml(opts.app);
107
+ const app = escapeHtml(opts.app);
108
+ const uiUrl = escapeHtml(opts.uiUrl);
109
+ return `<!doctype html>
110
+ <html lang="en">
111
+ <head>
112
+ <meta charset="utf-8">
113
+ <title>${label} — baerly api</title>
114
+ <style>
115
+ body { font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; max-width: 40rem; margin: 3rem auto; padding: 0 1.5rem; color: #222; line-height: 1.5; }
116
+ h1 { font-size: 1.25rem; margin: 0 0 0.25rem; }
117
+ p.tag { color: #666; margin: 0 0 1.5rem; font-size: 0.9rem; }
118
+ a { color: #06c; }
119
+ ul { padding-left: 1.25rem; }
120
+ li { margin: 0.25rem 0; }
121
+ code { background: #f3f3f3; padding: 0.1em 0.35em; border-radius: 3px; font-size: 0.9em; }
122
+ </style>
123
+ </head>
124
+ <body>
125
+ <h1>${label}</h1>
126
+ <p class="tag">baerly api server · app <code>${app}</code></p>
127
+ <p>This is the API server. The UI lives at <a href="${uiUrl}">${uiUrl}</a>.</p>
128
+ <ul>
129
+ <li>Open the UI: <a href="${uiUrl}">${uiUrl}</a></li>
130
+ <li>Health probe: <a href="/v1/healthz">/v1/healthz</a></li>
131
+ <li>CRUD routes under <code>/v1/c/*</code> require an auth header and aren't clickable from here.</li>
132
+ </ul>
133
+ </body>
134
+ </html>
135
+ `;
136
+ };
137
+ const escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => {
138
+ switch (c) {
139
+ case "&": return "&amp;";
140
+ case "<": return "&lt;";
141
+ case ">": return "&gt;";
142
+ case "\"": return "&quot;";
143
+ default: return "&#39;";
144
+ }
145
+ });
146
+ //#endregion
147
+ //#region packages/dev/src/ensure-table.ts
148
+ /**
149
+ * Optional pre-warm: idempotently create the `current.json` manifest
150
+ * for a single `(app, tenant, table)` triple. The kernel auto-creates
151
+ * this manifest on the first commit anyway (see `Db.create` and
152
+ * `Writer.commit`), so calling `ensureTable` is **not required** for
153
+ * correctness — it's a one-Class-A-PUT optimization for callers that
154
+ * want the manifest in place before the first request lands (seed
155
+ * scripts, deploy-time provisioning, CI fixtures that snapshot the
156
+ * bucket between phases, etc.).
157
+ *
158
+ * Wraps {@link createCurrentJson} with the canonical key shape
159
+ * (`app/<app>/tenant/<tenant>/manifests/<table>/current.json`) and
160
+ * swallows `BaerlyError{code:"Conflict"}` so re-runs are safe. An
161
+ * existing manifest is preserved verbatim — this function never
162
+ * overwrites a populated manifest. The seed shape matches the
163
+ * kernel's auto-create exactly, so a pre-warm and an
164
+ * auto-provisioned bucket are byte-identical.
165
+ *
166
+ * @example
167
+ * ```ts
168
+ * import { LocalFsStorage, ensureTable } from "@gusto/baerly-storage/dev";
169
+ *
170
+ * const storage = new LocalFsStorage({ root: "./.baerly-data" });
171
+ * // Pre-warm so the first request doesn't pay the bootstrap PUT.
172
+ * await ensureTable(storage, { app: "helpdesk", tenant: "demo", table: "tickets" });
173
+ * // …then `baerlyNode({ config, storage, verifier })`.
174
+ * ```
175
+ */
176
+ const ensureTable = async (storage, args) => {
177
+ const key = `app/${args.app}/tenant/${args.tenant}/manifests/${args.table}/current.json`;
178
+ try {
179
+ await createCurrentJson(storage, key, {
180
+ schema_version: 1,
181
+ snapshot: null,
182
+ next_seq: 0,
183
+ log_seq_start: 0,
184
+ writer_fence: {
185
+ epoch: 0,
186
+ owner: "",
187
+ claimed_at: ""
188
+ }
189
+ });
190
+ } catch (error) {
191
+ if (error instanceof BaerlyError && error.code === "Conflict") return;
192
+ throw error;
193
+ }
194
+ };
195
+ //#endregion
196
+ //#region packages/dev/src/local-fs.ts
197
+ /**
198
+ * `Storage` backed by a directory tree. Keys may contain `/` and map
199
+ * to nested directories on disk so `ls`/`cat` work as expected.
200
+ *
201
+ * ETags are content-addressed: `"<sha-256-hex>"` (the surrounding
202
+ * double-quotes match S3's wire format for non-multipart objects).
203
+ * Identical bodies share an ETag across runs — the property that
204
+ * makes this adapter useful for fixture-based tests.
205
+ *
206
+ * Writes are atomic via `writeFile(temp) + rename(final)`; readers
207
+ * never see a partially-written file. The adapter does NOT coordinate
208
+ * cross-process `ifMatch`/`ifNoneMatch` checks (a TOCTOU race is
209
+ * possible if two processes write the same key concurrently).
210
+ * Single-process `baerlyDev()` is the design center; multi-process
211
+ * scenarios use the S3 / Minio path.
212
+ *
213
+ * Node-only — imports `node:fs`, `node:path`, `node:crypto`. Lives in
214
+ * `@baerly/dev` because the protocol kernel is pure-modules / no I/O
215
+ * and must remain Worker-bundleable.
216
+ */
217
+ var LocalFsStorage = class {
218
+ #root;
219
+ constructor(opts) {
220
+ this.#root = resolve(opts.root);
221
+ }
222
+ async get(key, opts) {
223
+ opts?.signal?.throwIfAborted();
224
+ const path = this.#pathFor(key);
225
+ let body;
226
+ try {
227
+ body = await readFile(path);
228
+ } catch (error) {
229
+ if (isErrnoException(error) && error.code === "ENOENT") return null;
230
+ throw new BaerlyError("InvalidResponse", `LocalFsStorage.get(${key}): ${error.message}`, error);
231
+ }
232
+ const etag = etagOf(body);
233
+ if (opts?.ifNoneMatch !== void 0 && opts.ifNoneMatch === etag) return null;
234
+ return {
235
+ body: toUint8Array(body),
236
+ etag
237
+ };
238
+ }
239
+ async put(key, body, opts) {
240
+ opts?.signal?.throwIfAborted();
241
+ const path = this.#pathFor(key);
242
+ const newEtag = etagOf(body);
243
+ if (opts?.ifMatch !== void 0 || opts?.ifNoneMatch === "*") {
244
+ const existing = await readExisting(path);
245
+ if (opts?.ifNoneMatch === "*" && existing !== null) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifNoneMatch="*" but key exists)`);
246
+ if (opts?.ifMatch !== void 0) {
247
+ if (existing === null) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`);
248
+ const currentEtag = etagOf(existing);
249
+ if (currentEtag !== opts.ifMatch) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${currentEtag})`);
250
+ }
251
+ }
252
+ await mkdir(dirname(path), { recursive: true });
253
+ const tmp = join(tmpdir(), `baerly-localfs-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`);
254
+ await writeFile(tmp, body);
255
+ try {
256
+ await rename(tmp, path);
257
+ } catch (error) {
258
+ await rm(tmp, { force: true }).catch(() => {});
259
+ throw new BaerlyError("InvalidResponse", `LocalFsStorage.put(${key}): ${error.message}`, error);
260
+ }
261
+ return {
262
+ etag: newEtag,
263
+ serverDate: /* @__PURE__ */ new Date()
264
+ };
265
+ }
266
+ async delete(key, opts) {
267
+ opts?.signal?.throwIfAborted();
268
+ const path = this.#pathFor(key);
269
+ try {
270
+ await rm(path);
271
+ } catch (error) {
272
+ if (isErrnoException(error) && error.code === "ENOENT") return;
273
+ throw new BaerlyError("InvalidResponse", `LocalFsStorage.delete(${key}): ${error.message}`, error);
274
+ }
275
+ }
276
+ async *list(prefix, opts) {
277
+ opts?.signal?.throwIfAborted();
278
+ const startAfter = opts?.startAfter ?? "";
279
+ const maxKeys = opts?.maxKeys ?? Infinity;
280
+ const keys = [];
281
+ await walk(this.#root, keys);
282
+ keys.sort();
283
+ let yielded = 0;
284
+ for (const key of keys) {
285
+ if (!key.startsWith(prefix)) continue;
286
+ if (key <= startAfter) continue;
287
+ if (yielded >= maxKeys) return;
288
+ opts?.signal?.throwIfAborted();
289
+ yield {
290
+ key,
291
+ etag: etagOf(await readFile(this.#pathFor(key)))
292
+ };
293
+ yielded += 1;
294
+ }
295
+ }
296
+ /**
297
+ * Map an S3-style key to a filesystem path under `#root`, rejecting
298
+ * anything that could escape the root (path traversal, absolute
299
+ * paths, empty segments, backslashes). All rejections throw
300
+ * `BaerlyError("InvalidConfig", …)`.
301
+ */
302
+ #pathFor(key) {
303
+ if (key.length === 0) throw new BaerlyError("InvalidConfig", "LocalFsStorage: empty key");
304
+ if (key.startsWith("/")) throw new BaerlyError("InvalidConfig", `LocalFsStorage: leading "/" in key: ${key}`);
305
+ if (key.includes("\\")) throw new BaerlyError("InvalidConfig", `LocalFsStorage: backslash in key: ${key}`);
306
+ const segments = key.split("/");
307
+ if (segments.some((s) => s === "" || s === "." || s === "..")) throw new BaerlyError("InvalidConfig", `LocalFsStorage: illegal segment in key: ${key}`);
308
+ const path = join(this.#root, ...segments);
309
+ if (path !== this.#root && !path.startsWith(this.#root + sep)) throw new BaerlyError("InvalidConfig", `LocalFsStorage: resolved path escapes root: ${key}`);
310
+ return path;
311
+ }
312
+ };
313
+ const etagOf = (body) => {
314
+ return `"${createHash("sha256").update(body).digest("hex")}"`;
315
+ };
316
+ const toUint8Array = (buf) => new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
317
+ const isErrnoException = (e) => typeof e === "object" && e !== null && "code" in e;
318
+ const readExisting = async (path) => {
319
+ try {
320
+ return await readFile(path);
321
+ } catch (error) {
322
+ if (isErrnoException(error) && error.code === "ENOENT") return null;
323
+ throw error;
324
+ }
325
+ };
326
+ /**
327
+ * Recursive directory walk. Yields filesystem-relative paths in
328
+ * forward-slash form so callers can use them as S3-style keys
329
+ * regardless of the host's path separator.
330
+ */
331
+ const walk = async (root, out) => {
332
+ const stack = [root];
333
+ while (stack.length > 0) {
334
+ const dir = stack.pop();
335
+ let entries;
336
+ try {
337
+ entries = await readdir(dir, { withFileTypes: true });
338
+ } catch (error) {
339
+ if (isErrnoException(error) && error.code === "ENOENT") continue;
340
+ throw error;
341
+ }
342
+ for (const entry of entries) {
343
+ const full = join(dir, entry.name);
344
+ if (entry.isDirectory()) stack.push(full);
345
+ else if (entry.isFile()) out.push(relative(root, full).split(sep).join(posix.sep));
346
+ }
347
+ }
348
+ };
349
+ //#endregion
350
+ export { require_picocolors_browser as a, printDevBanner as i, ensureTable as n, renderDevLanding as r, LocalFsStorage as t };
351
+
352
+ //# sourceMappingURL=src-n0Te1r98.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-n0Te1r98.js","names":["#root","#pathFor"],"sources":["../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.browser.js","../packages/dev/src/dev-banner.ts","../packages/dev/src/dev-landing.ts","../packages/dev/src/ensure-table.ts","../packages/dev/src/local-fs.ts"],"sourcesContent":["var x=String;\nvar create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x,blackBright:x,redBright:x,greenBright:x,yellowBright:x,blueBright:x,magentaBright:x,cyanBright:x,whiteBright:x,bgBlackBright:x,bgRedBright:x,bgGreenBright:x,bgYellowBright:x,bgBlueBright:x,bgMagentaBright:x,bgCyanBright:x,bgWhiteBright:x}};\nmodule.exports=create();\nmodule.exports.createColors = create;\n","import { createColors } from \"picocolors\";\n\nexport interface DevBannerHint {\n readonly key: string;\n readonly value: string;\n}\n\nexport interface DevBannerOpts {\n readonly name: string;\n readonly primaryUrl?: { readonly label: string; readonly url: string };\n readonly apiUrl?: { readonly label: string; readonly url: string; readonly note?: string };\n readonly hints?: ReadonlyArray<DevBannerHint>;\n /** Force plain-text output (no color, no `←`). Defaults to !isTTY || CI. */\n readonly plain?: boolean;\n /** Sink. Defaults to process.stderr. */\n readonly write?: (chunk: string) => void;\n}\n\nexport function printDevBanner(opts: DevBannerOpts): void {\n const isPlain =\n opts.plain !== undefined\n ? opts.plain\n : process.env[\"CI\"] !== undefined || !process.stderr.isTTY;\n const write = opts.write ?? ((chunk) => process.stderr.write(chunk));\n const pc = createColors(!isPlain);\n const hints = opts.hints ?? [];\n\n const lines: string[] = [];\n\n if (isPlain) {\n lines.push(`baerly · ${opts.name}`);\n\n if (opts.primaryUrl) {\n lines.push(`${opts.primaryUrl.label}: ${opts.primaryUrl.url}`);\n }\n if (opts.apiUrl) {\n const note = opts.apiUrl.note ? ` (${opts.apiUrl.note})` : \"\";\n lines.push(`${opts.apiUrl.label}: ${opts.apiUrl.url}${note}`);\n }\n for (const hint of hints) {\n lines.push(`${hint.key}: ${hint.value}`);\n }\n write(lines.join(\"\\n\") + \"\\n\");\n } else {\n lines.push(pc.bold(pc.cyan(`▎ baerly · ${opts.name}`)));\n lines.push(\"\");\n\n if (opts.primaryUrl) {\n const marker = ` ${pc.green(\"← open this\")}`;\n lines.push(` ${pc.dim(opts.primaryUrl.label)} → ${opts.primaryUrl.url}${marker}`);\n }\n if (opts.apiUrl) {\n const note = opts.apiUrl.note ? ` ${pc.dim(`(${opts.apiUrl.note})`)}` : \"\";\n lines.push(` ${pc.dim(opts.apiUrl.label)} → ${opts.apiUrl.url}${note}`);\n }\n if ((opts.primaryUrl || opts.apiUrl) && hints.length > 0) {\n lines.push(\"\");\n }\n if (hints.length > 0) {\n const maxKeyLen = Math.max(...hints.map((h) => h.key.length));\n for (const hint of hints) {\n lines.push(` ${pc.dim(hint.key.padEnd(maxKeyLen))} ${hint.value}`);\n }\n }\n lines.push(\"\");\n write(lines.join(\"\\n\"));\n }\n}\n","/**\n * Dev landing page for the API root (`GET /`).\n *\n * The HTTP surface is API-only: every path outside `/v1/*`\n * returns the {@link HttpErrorEnvelope} 404 shape. That's correct for\n * production but confusing in local dev — a user who clicks the\n * `http://localhost:3000` link in their terminal sees a JSON 404 and\n * assumes the server is broken.\n *\n * Adapters that wire the {@link DevLandingOptions} opt-in surface a\n * small HTML page on `GET /` instead: app label, a clickable link to\n * the UI, a `/v1/healthz` probe link, and a note that `/v1/c/*` is\n * auth-gated. `GET /favicon.ico` answers 204 so browsers don't pin a\n * second JSON 404 next to the landing page.\n *\n * Production deployments leave the option unset; the 404 falls\n * through to the existing envelope.\n */\n\n/** Options for {@link renderDevLanding}. */\nexport interface DevLandingOptions {\n /** Bucket-prefix / app name (typically passed through from the adapter's `app` option). */\n readonly app: string;\n /** URL of the human-facing UI (e.g., `\"http://localhost:5173\"`). */\n readonly uiUrl: string;\n}\n\n/**\n * Render the dev landing page HTML. Dependency-free; system fonts\n * only; no JS. All substitutions are HTML-escaped to keep the page\n * inert even when `app` / `uiUrl` come from env vars.\n */\nexport const renderDevLanding = (opts: DevLandingOptions): string => {\n const label = escapeHtml(opts.app);\n const app = escapeHtml(opts.app);\n const uiUrl = escapeHtml(opts.uiUrl);\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>${label} — baerly api</title>\n<style>\n body { font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; max-width: 40rem; margin: 3rem auto; padding: 0 1.5rem; color: #222; line-height: 1.5; }\n h1 { font-size: 1.25rem; margin: 0 0 0.25rem; }\n p.tag { color: #666; margin: 0 0 1.5rem; font-size: 0.9rem; }\n a { color: #06c; }\n ul { padding-left: 1.25rem; }\n li { margin: 0.25rem 0; }\n code { background: #f3f3f3; padding: 0.1em 0.35em; border-radius: 3px; font-size: 0.9em; }\n</style>\n</head>\n<body>\n<h1>${label}</h1>\n<p class=\"tag\">baerly api server · app <code>${app}</code></p>\n<p>This is the API server. The UI lives at <a href=\"${uiUrl}\">${uiUrl}</a>.</p>\n<ul>\n <li>Open the UI: <a href=\"${uiUrl}\">${uiUrl}</a></li>\n <li>Health probe: <a href=\"/v1/healthz\">/v1/healthz</a></li>\n <li>CRUD routes under <code>/v1/c/*</code> require an auth header and aren't clickable from here.</li>\n</ul>\n</body>\n</html>\n`;\n};\n\nconst escapeHtml = (s: string): string =>\n s.replace(/[&<>\"']/g, (c) => {\n switch (c) {\n case \"&\": {\n return \"&amp;\";\n }\n case \"<\": {\n return \"&lt;\";\n }\n case \">\": {\n return \"&gt;\";\n }\n case '\"': {\n return \"&quot;\";\n }\n default: {\n return \"&#39;\";\n }\n }\n });\n","import {\n BaerlyError,\n CURRENT_JSON_SCHEMA_VERSION,\n createCurrentJson,\n type Storage,\n} from \"@baerly/protocol\";\n\n/**\n * Optional pre-warm: idempotently create the `current.json` manifest\n * for a single `(app, tenant, table)` triple. The kernel auto-creates\n * this manifest on the first commit anyway (see `Db.create` and\n * `Writer.commit`), so calling `ensureTable` is **not required** for\n * correctness — it's a one-Class-A-PUT optimization for callers that\n * want the manifest in place before the first request lands (seed\n * scripts, deploy-time provisioning, CI fixtures that snapshot the\n * bucket between phases, etc.).\n *\n * Wraps {@link createCurrentJson} with the canonical key shape\n * (`app/<app>/tenant/<tenant>/manifests/<table>/current.json`) and\n * swallows `BaerlyError{code:\"Conflict\"}` so re-runs are safe. An\n * existing manifest is preserved verbatim — this function never\n * overwrites a populated manifest. The seed shape matches the\n * kernel's auto-create exactly, so a pre-warm and an\n * auto-provisioned bucket are byte-identical.\n *\n * @example\n * ```ts\n * import { LocalFsStorage, ensureTable } from \"@gusto/baerly-storage/dev\";\n *\n * const storage = new LocalFsStorage({ root: \"./.baerly-data\" });\n * // Pre-warm so the first request doesn't pay the bootstrap PUT.\n * await ensureTable(storage, { app: \"helpdesk\", tenant: \"demo\", table: \"tickets\" });\n * // …then `baerlyNode({ config, storage, verifier })`.\n * ```\n */\nexport const ensureTable = async (\n storage: Storage,\n args: { app: string; tenant: string; table: string },\n): Promise<void> => {\n const key = `app/${args.app}/tenant/${args.tenant}/manifests/${args.table}/current.json`;\n try {\n await createCurrentJson(storage, key, {\n schema_version: CURRENT_JSON_SCHEMA_VERSION,\n snapshot: null,\n next_seq: 0,\n log_seq_start: 0,\n writer_fence: { epoch: 0, owner: \"\", claimed_at: \"\" },\n });\n } catch (error) {\n if (error instanceof BaerlyError && error.code === \"Conflict\") {\n return;\n }\n throw error;\n }\n};\n","import { createHash } from \"node:crypto\";\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, posix, relative, resolve, sep } from \"node:path\";\nimport {\n BaerlyError,\n type Storage,\n type StorageGetOptions,\n type StorageGetResult,\n type StorageListEntry,\n type StoragePutOptions,\n type StoragePutResult,\n} from \"@baerly/protocol\";\n\nexport interface LocalFsStorageOptions {\n /** Root directory; treated as \"the bucket\". */\n root: string;\n}\n\n/**\n * `Storage` backed by a directory tree. Keys may contain `/` and map\n * to nested directories on disk so `ls`/`cat` work as expected.\n *\n * ETags are content-addressed: `\"<sha-256-hex>\"` (the surrounding\n * double-quotes match S3's wire format for non-multipart objects).\n * Identical bodies share an ETag across runs — the property that\n * makes this adapter useful for fixture-based tests.\n *\n * Writes are atomic via `writeFile(temp) + rename(final)`; readers\n * never see a partially-written file. The adapter does NOT coordinate\n * cross-process `ifMatch`/`ifNoneMatch` checks (a TOCTOU race is\n * possible if two processes write the same key concurrently).\n * Single-process `baerlyDev()` is the design center; multi-process\n * scenarios use the S3 / Minio path.\n *\n * Node-only — imports `node:fs`, `node:path`, `node:crypto`. Lives in\n * `@baerly/dev` because the protocol kernel is pure-modules / no I/O\n * and must remain Worker-bundleable.\n */\nexport class LocalFsStorage implements Storage {\n readonly #root: string;\n\n constructor(opts: LocalFsStorageOptions) {\n this.#root = resolve(opts.root);\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n let body: Buffer;\n try {\n body = await readFile(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return null;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.get(${key}): ${(error as Error).message}`,\n error,\n );\n }\n const etag = etagOf(body);\n if (opts?.ifNoneMatch !== undefined && opts.ifNoneMatch === etag) {\n // 304 Not Modified — caller's cached copy is current.\n return null;\n }\n return { body: toUint8Array(body), etag };\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n const newEtag = etagOf(body);\n\n if (opts?.ifMatch !== undefined || opts?.ifNoneMatch === \"*\") {\n // TOCTOU within a process — fine. Cross-process callers should\n // not rely on these guards (see class JSDoc).\n const existing = await readExisting(path);\n if (opts?.ifNoneMatch === \"*\" && existing !== null) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifNoneMatch=\"*\" but key exists)`,\n );\n }\n if (opts?.ifMatch !== undefined) {\n if (existing === null) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`,\n );\n }\n const currentEtag = etagOf(existing);\n if (currentEtag !== opts.ifMatch) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${currentEtag})`,\n );\n }\n }\n }\n\n await mkdir(dirname(path), { recursive: true });\n // Write to a unique temp path then rename for atomicity. Temp lives\n // in `os.tmpdir()` so a half-written file never appears under the\n // bucket root where `list` might see it. PID + timestamp + random\n // tail makes the name unique across concurrent writers in the same\n // process.\n const tmp = join(\n tmpdir(),\n `baerly-localfs-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,\n );\n await writeFile(tmp, body);\n try {\n await rename(tmp, path);\n } catch (error) {\n // Best-effort cleanup of the temp file; swallow any error there\n // so the original failure surfaces unchanged.\n await rm(tmp, { force: true }).catch(() => {});\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.put(${key}): ${(error as Error).message}`,\n error,\n );\n }\n return { etag: newEtag, serverDate: new Date() };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n try {\n await rm(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return;\n } // idempotent\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.delete(${key}): ${(error as Error).message}`,\n error,\n );\n }\n }\n\n async *list(\n prefix: string,\n opts?: {\n startAfter?: string;\n maxKeys?: number;\n signal?: AbortSignal;\n },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n const startAfter = opts?.startAfter ?? \"\";\n const maxKeys = opts?.maxKeys ?? Infinity;\n const keys: string[] = [];\n await walk(this.#root, keys);\n keys.sort();\n let yielded = 0;\n for (const key of keys) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n if (key <= startAfter) {\n continue;\n }\n if (yielded >= maxKeys) {\n return;\n }\n opts?.signal?.throwIfAborted();\n const buf = await readFile(this.#pathFor(key));\n yield { key, etag: etagOf(buf) };\n yielded += 1;\n }\n }\n\n /**\n * Map an S3-style key to a filesystem path under `#root`, rejecting\n * anything that could escape the root (path traversal, absolute\n * paths, empty segments, backslashes). All rejections throw\n * `BaerlyError(\"InvalidConfig\", …)`.\n */\n #pathFor(key: string): string {\n if (key.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", \"LocalFsStorage: empty key\");\n }\n if (key.startsWith(\"/\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: leading \"/\" in key: ${key}`);\n }\n if (key.includes(\"\\\\\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: backslash in key: ${key}`);\n }\n const segments = key.split(\"/\");\n if (segments.some((s) => s === \"\" || s === \".\" || s === \"..\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: illegal segment in key: ${key}`);\n }\n const path = join(this.#root, ...segments);\n if (path !== this.#root && !path.startsWith(this.#root + sep)) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: resolved path escapes root: ${key}`);\n }\n return path;\n }\n}\n\nconst etagOf = (body: Uint8Array): string => {\n const h = createHash(\"sha256\").update(body).digest(\"hex\");\n return `\"${h}\"`;\n};\n\nconst toUint8Array = (buf: Buffer): Uint8Array =>\n new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n\nconst isErrnoException = (e: unknown): e is NodeJS.ErrnoException =>\n typeof e === \"object\" && e !== null && \"code\" in e;\n\nconst readExisting = async (path: string): Promise<Buffer | null> => {\n try {\n return await readFile(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n};\n\n/**\n * Recursive directory walk. Yields filesystem-relative paths in\n * forward-slash form so callers can use them as S3-style keys\n * regardless of the host's path separator.\n */\nconst walk = async (root: string, out: string[]): Promise<void> => {\n const stack: string[] = [root];\n while (stack.length > 0) {\n const dir = stack.pop()!;\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n continue;\n }\n throw error;\n }\n for (const entry of entries) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n stack.push(full);\n } else if (entry.isFile()) {\n out.push(relative(root, full).split(sep).join(posix.sep));\n }\n }\n }\n};\n"],"x_google_ignoreList":[0],"mappings":";;;;;;;;;CAAA,IAAI,IAAE;CACN,IAAI,SAAO,WAAW;EAAC,OAAO;GAAC,kBAAiB;GAAM,OAAM;GAAE,MAAK;GAAE,KAAI;GAAE,QAAO;GAAE,WAAU;GAAE,SAAQ;GAAE,QAAO;GAAE,eAAc;GAAE,OAAM;GAAE,KAAI;GAAE,OAAM;GAAE,QAAO;GAAE,MAAK;GAAE,SAAQ;GAAE,MAAK;GAAE,OAAM;GAAE,MAAK;GAAE,SAAQ;GAAE,OAAM;GAAE,SAAQ;GAAE,UAAS;GAAE,QAAO;GAAE,WAAU;GAAE,QAAO;GAAE,SAAQ;GAAE,aAAY;GAAE,WAAU;GAAE,aAAY;GAAE,cAAa;GAAE,YAAW;GAAE,eAAc;GAAE,YAAW;GAAE,aAAY;GAAE,eAAc;GAAE,aAAY;GAAE,eAAc;GAAE,gBAAe;GAAE,cAAa;GAAE,iBAAgB;GAAE,cAAa;GAAE,eAAc;EAAC;CAAC;CACtgB,OAAO,UAAQ,OAAO;CACtB,OAAO,QAAQ,eAAe;;;;;ACe9B,SAAgB,eAAe,MAA2B;CACxD,MAAM,UACJ,KAAK,UAAU,KAAA,IACX,KAAK,QACL,QAAQ,IAAI,UAAU,KAAA,KAAa,CAAC,QAAQ,OAAO;CACzD,MAAM,QAAQ,KAAK,WAAW,UAAU,QAAQ,OAAO,MAAM,KAAK;CAClE,MAAM,MAAA,GAAA,0BAAA,cAAkB,CAAC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 -0,0 +1,110 @@
1
+ import { t as loadAppConfig } from "./config-Bsg8wgwo.js";
2
+ import { a as setJsonMode, c as parseArgs, n as emitError, o as BaerlyError, s as defineCommand } from "./baerly.js";
3
+ import "node:stream";
4
+ //#region src/subcommand.ts
5
+ /** Shared exit-code mapping for caught `BaerlyError`s. */
6
+ const errorToExitCode = (code) => {
7
+ if (code === "InvalidConfig") return 1;
8
+ if (code === "Conflict" || code === "Internal" || code === "InvalidResponse") return 3;
9
+ return 2;
10
+ };
11
+ /**
12
+ * Build the app/tenant resolver. Captures `name` to surface the
13
+ * calling subcommand in the InvalidConfig hint.
14
+ */
15
+ const makeResolveAppTenant = (name) => {
16
+ return async (args) => {
17
+ const flagApp = typeof args.app === "string" && args.app.length > 0 ? args.app : void 0;
18
+ const flagTenant = typeof args.tenant === "string" && args.tenant.length > 0 ? args.tenant : void 0;
19
+ if (flagApp !== void 0 && flagTenant !== void 0) return {
20
+ app: flagApp,
21
+ tenant: flagTenant
22
+ };
23
+ try {
24
+ const cfg = await loadAppConfig();
25
+ return {
26
+ app: flagApp ?? cfg.app,
27
+ tenant: flagTenant ?? cfg.tenant
28
+ };
29
+ } catch (error) {
30
+ throw new BaerlyError("InvalidConfig", `baerly ${name}: --app / --tenant not supplied and no baerly.config.{ts,js,mjs,json} in cwd (${error instanceof BaerlyError ? error.message : error.message})`, error);
31
+ }
32
+ };
33
+ };
34
+ /**
35
+ * Wrap `def.handler` with the standard JSON-mode toggle, unknown-key
36
+ * rejection, and error-to-exit-code mapping. Shared by both the citty
37
+ * `run({ args })` path and the test `run(argv)` path. The caller
38
+ * supplies the {@link SubcommandContext}; this lets each `run(argv)`
39
+ * invocation attach its own `streams` override without leaking across
40
+ * invocations.
41
+ */
42
+ const kebabToCamel = (s) => s.replace(/-(\w)/g, (_, c) => c.toUpperCase());
43
+ const wrapHandler = (def) => {
44
+ const allowedKeys = new Set(Object.keys(def.args).flatMap((k) => k.includes("-") ? [k, kebabToCamel(k)] : [k]).concat(["_"]));
45
+ return async (args, ctx) => {
46
+ if ("json" in def.args) setJsonMode(args.json === true);
47
+ try {
48
+ for (const k of Object.keys(args)) if (!allowedKeys.has(k)) throw new BaerlyError("InvalidConfig", `baerly ${def.name}: unknown flag --${k}`);
49
+ return await def.handler(args, ctx);
50
+ } catch (error) {
51
+ if (error instanceof BaerlyError) {
52
+ emitError(def.name, error.code, error.message);
53
+ return errorToExitCode(error.code);
54
+ }
55
+ emitError(def.name, "Unknown", error.message);
56
+ return 2;
57
+ }
58
+ };
59
+ };
60
+ /**
61
+ * Wrap a baerly subcommand. Returns `{ cmd, run }` —
62
+ * - `cmd` is a citty `defineCommand` block; mount it in
63
+ * `baerly.ts`'s `subCommands`. It calls `process.exit(code)` on a
64
+ * non-zero exit so the parent process surfaces the failure.
65
+ * - `run(argv)` is the in-process test entry. It parses `argv` with
66
+ * citty's `parseArgs`, dispatches through the same wrapped
67
+ * handler, and returns the integer exit code (does NOT call
68
+ * `process.exit`).
69
+ *
70
+ * The two paths share `wrapHandler` so JSON-mode toggling,
71
+ * unknown-flag rejection, and error-to-exit-code mapping behave
72
+ * identically.
73
+ */
74
+ const defineBaerlySubcommand = (def) => {
75
+ const resolveAppTenant = makeResolveAppTenant(def.name);
76
+ const wrapped = wrapHandler(def);
77
+ const cmd = defineCommand({
78
+ meta: {
79
+ name: def.name,
80
+ description: def.meta.description
81
+ },
82
+ args: def.args,
83
+ run: async ({ args }) => {
84
+ const code = await wrapped(args, { resolveAppTenant });
85
+ if (code !== 0) process.exit(code);
86
+ }
87
+ });
88
+ const run = async (argv, options) => {
89
+ let parsed;
90
+ try {
91
+ parsed = parseArgs(argv, def.args);
92
+ } catch (error) {
93
+ setJsonMode(argv.includes("--json"));
94
+ emitError(def.name, "InvalidConfig", error.message);
95
+ return 1;
96
+ }
97
+ return wrapped(parsed, {
98
+ resolveAppTenant,
99
+ streams: options?.streams
100
+ });
101
+ };
102
+ return {
103
+ cmd,
104
+ run
105
+ };
106
+ };
107
+ //#endregion
108
+ export { defineBaerlySubcommand as t };
109
+
110
+ //# sourceMappingURL=subcommand-BWs6K7zb.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subcommand-BWs6K7zb.js","names":[],"sources":["../packages/cli/src/subcommand.ts"],"sourcesContent":["/**\n * Shared subcommand scaffolding for `baerly`.\n *\n * Every operator-facing subcommand (`inspect`, `export`, `doctor`, and\n * every `admin/*` command) was independently re-implementing the same\n * five pieces of boilerplate:\n *\n * 1. `setJsonMode(args.json === true)` before any emission.\n * 2. A `KNOWN_KEYS` whitelist asserting unknown `--flag` rejection.\n * 3. An `errorToExitCode(code)` mapping —\n * `InvalidConfig → 1`, `Conflict|Internal|InvalidResponse → 3`,\n * else `2`.\n * 4. `resolveAppTenant(args)` falling back through `baerly.config.*`\n * to either real values or hard-coded `\"app\"` / `\"tenant\"`\n * literals.\n * 5. Two parallel entry points: a citty `defineCommand` block that\n * calls `process.exit(code)` on failure, and a `runXxx(argv)`\n * function for in-process tests that returns the exit code.\n *\n * The five copies drifted: some commands suppressed protocol-level\n * errors (no `Conflict|Internal|InvalidResponse → 3` arm), and the\n * config-fallback silently produced `\"app\"` / `\"tenant\"` literals\n * (confidently-wrong output when no config is present).\n *\n * {@link defineBaerlySubcommand} centralizes the five pieces:\n * - Computes the known-keys set from `Object.keys(args)` itself, so\n * a new flag is picked up automatically.\n * - Applies the full 3-bucket exit-code mapping uniformly.\n * - {@link SubcommandContext.resolveAppTenant} throws\n * `BaerlyError(\"InvalidConfig\", …)` with a `--app` / `--tenant`\n * hint when neither flags nor a loadable `baerly.config.*` supply\n * the values.\n * - Returns a bundle of {@link SubcommandBundle.cmd} (citty wiring)\n * and {@link SubcommandBundle.run} (test entry) sharing one\n * wrapped handler.\n */\n\nimport { type Readable, type Writable } from \"node:stream\";\nimport {\n defineCommand,\n parseArgs,\n type ArgsDef,\n type ParsedArgs,\n type CommandDef,\n} from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { emitError, setJsonMode } from \"./output.ts\";\n\n/**\n * Optional stdin / stdout streams that a programmatic caller (today:\n * `runDump` / `runRestore` tests, and the export round-trip\n * integration test) can divert in place of `process.stdin` /\n * `process.stdout`. The citty entry point always uses the process\n * streams; only {@link SubcommandBundle.run} accepts these overrides.\n */\nexport interface SubcommandStreams {\n readonly stdin?: Readable;\n readonly stdout?: Writable;\n}\n\n/**\n * Capabilities the subcommand handler receives. Today: app/tenant\n * resolution. Kept narrow so the handler signature stays load-bearing\n * (the helper isn't a god object).\n */\nexport interface SubcommandContext {\n /**\n * Returns `{ app, tenant }` resolved from explicit flags or\n * `baerly.config.{ts,js,mjs,json}` in the cwd.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — neither flag was\n * supplied AND no loadable config was found. The error message\n * includes a hint mentioning `--app` / `--tenant`.\n */\n readonly resolveAppTenant: (args: {\n readonly app?: string;\n readonly tenant?: string;\n }) => Promise<{ app: string; tenant: string }>;\n /**\n * Programmatic stdin / stdout overrides. `undefined` (or any\n * missing field) means \"use the process stream\". Only\n * `admin dump` / `admin restore` consume this; other commands\n * ignore the field.\n */\n readonly streams?: SubcommandStreams;\n}\n\n/**\n * Definition fed to {@link defineBaerlySubcommand}. `name` is the JSON\n * envelope tag (`\"inspect\"`, `\"admin.compact\"`, etc.); `args` is the\n * citty ArgsDef; `handler` returns the integer exit code.\n */\nexport interface SubcommandDef<TArgs extends ArgsDef> {\n /** JSON envelope `command` tag and the prefix of every emitted error. */\n readonly name: string;\n readonly meta: { readonly description: string };\n readonly args: TArgs;\n readonly handler: (args: ParsedArgs<TArgs>, ctx: SubcommandContext) => Promise<number>;\n}\n\n/**\n * Output of {@link defineBaerlySubcommand}. `cmd` plugs into\n * `subCommands` in `baerly.ts`; `run` is the in-process entry for\n * unit tests.\n */\nexport interface SubcommandBundle<TArgs extends ArgsDef> {\n readonly cmd: CommandDef<TArgs>;\n readonly run: (\n argv: readonly string[],\n options?: { readonly streams?: SubcommandStreams },\n ) => Promise<number>;\n}\n\n/** Shared exit-code mapping for caught `BaerlyError`s. */\nconst errorToExitCode = (code: string): number => {\n if (code === \"InvalidConfig\") {\n return 1;\n }\n if (code === \"Conflict\" || code === \"Internal\" || code === \"InvalidResponse\") {\n return 3;\n }\n return 2;\n};\n\n/**\n * Build the app/tenant resolver. Captures `name` to surface the\n * calling subcommand in the InvalidConfig hint.\n */\nconst makeResolveAppTenant = (name: string): SubcommandContext[\"resolveAppTenant\"] => {\n return async (args) => {\n const flagApp = typeof args.app === \"string\" && args.app.length > 0 ? args.app : undefined;\n const flagTenant =\n typeof args.tenant === \"string\" && args.tenant.length > 0 ? args.tenant : undefined;\n if (flagApp !== undefined && flagTenant !== undefined) {\n return { app: flagApp, tenant: flagTenant };\n }\n try {\n const cfg = await loadAppConfig();\n return {\n app: flagApp ?? cfg.app,\n tenant: flagTenant ?? cfg.tenant,\n };\n } catch (error) {\n // Re-throw with our own wording so the operator sees the\n // calling-command name and the hint to pass --app / --tenant\n // explicitly. The underlying loadAppConfig error is preserved\n // as the cause.\n const inner = error instanceof BaerlyError ? error.message : (error as Error).message;\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly ${name}: --app / --tenant not supplied and no baerly.config.{ts,js,mjs,json} in cwd (${inner})`,\n error,\n );\n }\n };\n};\n\n/**\n * Wrap `def.handler` with the standard JSON-mode toggle, unknown-key\n * rejection, and error-to-exit-code mapping. Shared by both the citty\n * `run({ args })` path and the test `run(argv)` path. The caller\n * supplies the {@link SubcommandContext}; this lets each `run(argv)`\n * invocation attach its own `streams` override without leaking across\n * invocations.\n */\nconst kebabToCamel = (s: string): string =>\n s.replace(/-(\\w)/g, (_, c: string) => c.toUpperCase());\n\nconst wrapHandler = <TArgs extends ArgsDef>(\n def: SubcommandDef<TArgs>,\n): ((args: ParsedArgs<TArgs>, ctx: SubcommandContext) => Promise<number>) => {\n // Compute the allow-list once from the ArgsDef. citty injects `_`\n // for positional captures, so it must stay allowed. citty 0.2.2\n // also auto-injects a camelCase alias for every kebab-case flag\n // (e.g. `--where-comment` produces both `whereComment` and\n // `where-comment` on the parsed args), so each kebab key is\n // expanded to its camelCase variant in the allow-list too.\n const allowedKeys: ReadonlySet<string> = new Set(\n Object.keys(def.args)\n .flatMap((k) => (k.includes(\"-\") ? [k, kebabToCamel(k)] : [k]))\n .concat([\"_\"]),\n );\n return async (args, ctx) => {\n // `json` is conventional but not required — only toggle when it's\n // both declared in the ArgsDef and truthy on the parsed args.\n if (\"json\" in def.args) {\n setJsonMode((args as ParsedArgs<TArgs> & { json?: boolean }).json === true);\n }\n try {\n for (const k of Object.keys(args)) {\n if (!allowedKeys.has(k)) {\n throw new BaerlyError(\"InvalidConfig\", `baerly ${def.name}: unknown flag --${k}`);\n }\n }\n return await def.handler(args, ctx);\n } catch (error) {\n if (error instanceof BaerlyError) {\n emitError(def.name, error.code, error.message);\n return errorToExitCode(error.code);\n }\n emitError(def.name, \"Unknown\", (error as Error).message);\n return 2;\n }\n };\n};\n\n/**\n * Wrap a baerly subcommand. Returns `{ cmd, run }` —\n * - `cmd` is a citty `defineCommand` block; mount it in\n * `baerly.ts`'s `subCommands`. It calls `process.exit(code)` on a\n * non-zero exit so the parent process surfaces the failure.\n * - `run(argv)` is the in-process test entry. It parses `argv` with\n * citty's `parseArgs`, dispatches through the same wrapped\n * handler, and returns the integer exit code (does NOT call\n * `process.exit`).\n *\n * The two paths share `wrapHandler` so JSON-mode toggling,\n * unknown-flag rejection, and error-to-exit-code mapping behave\n * identically.\n */\nexport const defineBaerlySubcommand = <TArgs extends ArgsDef>(\n def: SubcommandDef<TArgs>,\n): SubcommandBundle<TArgs> => {\n const resolveAppTenant = makeResolveAppTenant(def.name);\n const wrapped = wrapHandler(def);\n\n const cmd = defineCommand({\n meta: { name: def.name, description: def.meta.description },\n args: def.args,\n run: async ({ args }) => {\n const code = await wrapped(args as ParsedArgs<TArgs>, { resolveAppTenant });\n if (code !== 0) {\n process.exit(code);\n }\n },\n });\n\n const run = async (\n argv: readonly string[],\n options?: { readonly streams?: SubcommandStreams },\n ): Promise<number> => {\n let parsed: ParsedArgs<TArgs>;\n try {\n parsed = parseArgs<TArgs>(argv as string[], def.args);\n } catch (error) {\n // Parse-time error from citty (missing required flag,\n // malformed value). Toggle JSON mode by sniffing argv since\n // we never reached the handler.\n setJsonMode(argv.includes(\"--json\"));\n emitError(def.name, \"InvalidConfig\", (error as Error).message);\n return 1;\n }\n return wrapped(parsed, { resolveAppTenant, streams: options?.streams });\n };\n\n return { cmd, run };\n};\n"],"mappings":";;;;;AAmHA,MAAM,mBAAmB,SAAyB;CAChD,IAAI,SAAS,iBACX,OAAO;CAET,IAAI,SAAS,cAAc,SAAS,cAAc,SAAS,mBACzD,OAAO;CAET,OAAO;AACT;;;;;AAMA,MAAM,wBAAwB,SAAwD;CACpF,OAAO,OAAO,SAAS;EACrB,MAAM,UAAU,OAAO,KAAK,QAAQ,YAAY,KAAK,IAAI,SAAS,IAAI,KAAK,MAAM,KAAA;EACjF,MAAM,aACJ,OAAO,KAAK,WAAW,YAAY,KAAK,OAAO,SAAS,IAAI,KAAK,SAAS,KAAA;EAC5E,IAAI,YAAY,KAAA,KAAa,eAAe,KAAA,GAC1C,OAAO;GAAE,KAAK;GAAS,QAAQ;EAAW;EAE5C,IAAI;GACF,MAAM,MAAM,MAAM,cAAc;GAChC,OAAO;IACL,KAAK,WAAW,IAAI;IACpB,QAAQ,cAAc,IAAI;GAC5B;EACF,SAAS,OAAO;GAMd,MAAM,IAAI,YACR,iBACA,UAAU,KAAK,gFAHH,iBAAiB,cAAc,MAAM,UAAW,MAAgB,QAGyB,IACrG,KACF;EACF;CACF;AACF;;;;;;;;;AAUA,MAAM,gBAAgB,MACpB,EAAE,QAAQ,WAAW,GAAG,MAAc,EAAE,YAAY,CAAC;AAEvD,MAAM,eACJ,QAC2E;CAO3E,MAAM,cAAmC,IAAI,IAC3C,OAAO,KAAK,IAAI,IAAI,EACjB,SAAS,MAAO,EAAE,SAAS,GAAG,IAAI,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