@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,336 @@
1
+ import { a as CollectionNames, d as IndexDefinition, f as DocumentData, o as RowOf, r as BaerlyConfig, s as UnboundConfig, u as SchemaValidator } from "./app-config-Cb5dO2s9.js";
2
+ import { c as Collection, m as Storage, n as LogEntry, p as CurrentJsonRead } from "./index-BGC-ENnj.js";
3
+ //#region packages/server/src/schema.d.ts
4
+ /**
5
+ * Run a validator and throw `BaerlyError{code:"SchemaError"}` on failure.
6
+ * On success returns the validator's output (which for transforming
7
+ * validators may differ from the input).
8
+ *
9
+ * Field paths are normalised to `(string | number)[]` so the wire shape
10
+ * is JSON-clean. Symbol keys (rare; StandardSchemaV1 permits them) are
11
+ * coerced to `String(sym)` — we never emit `symbol` on the wire.
12
+ *
13
+ * The thrown error's `message` carries a one-line summary
14
+ * (`"<collection>.<verb>: <issuesCount> field(s) failed validation: <first>"`)
15
+ * for stderr-readable logs; the structured `issues` are on `.issues`.
16
+ */
17
+ declare const validateOrThrow: <TIn, TOut>(schema: SchemaValidator<TIn, TOut>, candidate: unknown, context: {
18
+ readonly collection: string;
19
+ readonly verb: "insert" | "update" | "replace";
20
+ }) => Promise<TOut>;
21
+ //#endregion
22
+ //#region packages/server/src/query.d.ts
23
+ /**
24
+ * What a `Query<T>` needs to issue a read against the bucket. The
25
+ * `Db` builds this once and hands it to `Collection` / `Query`; the chain
26
+ * carries it forward unchanged.
27
+ *
28
+ * The `collectionPrefix` shape matches what `Writer` writes under —
29
+ * e.g. `"app/<app>/tenant/<tenant>/manifests/<name>"`. Drift between
30
+ * the reader and writer prefix is the most likely bug class; both
31
+ * compose the same string from `app`/`tenant`/`name`.
32
+ *
33
+ * @internal
34
+ */
35
+ interface CollectionReadContext {
36
+ readonly storage: Storage;
37
+ /** Physical key prefix — already includes `app/<app>/tenant/<tenant>/manifests/<name>`. */
38
+ readonly collectionPrefix: string;
39
+ readonly collectionName: string;
40
+ /**
41
+ * When defined, mutation verbs (`Collection.insert`, `Query.update`,
42
+ * `Collection.replace`, `Query.delete`) buffer a {@link BufferedMutation}
43
+ * onto `txCtx.mutations` instead of calling `Writer.commit`
44
+ * directly. Reads ignore `txCtx` entirely — they go through
45
+ * `Storage` live, by design (no MVCC; see `Db.transaction`'s JSDoc
46
+ * in `./db.ts`). Threaded in by `Db.transaction(...)`; `undefined`
47
+ * outside a transaction.
48
+ *
49
+ * @internal
50
+ */
51
+ readonly txCtx?: TxContext;
52
+ /**
53
+ * Optional StandardSchemaV1-shaped validator for this collection.
54
+ * When set, `runInsert`, `runUpdate`, and `runReplaceById` validate the
55
+ * post-image before committing or buffering — invalid input throws
56
+ * `BaerlyError{code:"SchemaError"}` carrying a `.issues` array of
57
+ * `{ path, message }` entries. `undefined` means no validation
58
+ * (today's behaviour — zero overhead).
59
+ *
60
+ * Threaded in by {@link Db.collectionReadContext} from the per-collection
61
+ * map handed to {@link Db.create}; the boundary calls happen in
62
+ * `query.ts`, not `writer.ts`, so schemas plug in at the
63
+ * read/write API surface rather than at the writer layer.
64
+ *
65
+ * @internal
66
+ */
67
+ readonly schema?: SchemaValidator;
68
+ /**
69
+ * Per-collection {@link IndexDefinition}s threaded onto every
70
+ * read. Consumed by `planQuery(...)` inside `runRead` to pick an
71
+ * index-walk plan when the predicate's equality fields cover a
72
+ * declared index's `on` tuple left-to-right. Empty array means
73
+ * "no indexes declared" — every read falls through to the
74
+ * snapshot + log fold path.
75
+ *
76
+ * Mirrors the shape callers build when flattening
77
+ * `BaerlyConfig.collections[*].indexes` into a map keyed by name
78
+ * before constructing the `Db`; we keep the `Db` itself library-
79
+ * agnostic by accepting the pre-flattened map (not the full
80
+ * `BaerlyConfig`).
81
+ *
82
+ * @internal
83
+ */
84
+ readonly indexes: ReadonlyArray<IndexDefinition>;
85
+ }
86
+ //#endregion
87
+ //#region packages/server/src/db.d.ts
88
+ /**
89
+ * In-memory buffer for a single in-flight {@link Db.transaction}
90
+ * call. The `Collection<T>` instance passed to the transaction body holds
91
+ * a reference to this object; every mutation verb appends to
92
+ * `mutations` instead of calling `Writer.commit` directly.
93
+ *
94
+ * After the body resolves, `Db.transaction` performs ONE
95
+ * `Writer.commitBatch(...)` to commit every buffered mutation
96
+ * in a single CAS attempt.
97
+ *
98
+ * @internal — referenced by `collection.ts` and `query.ts`; not part of
99
+ * the public API surface for app code.
100
+ */
101
+ interface TxContext {
102
+ /**
103
+ * The collection name the transaction is scoped to. Mutation verbs
104
+ * runtime-assert that their `Collection<T>`'s `name` matches this
105
+ * field before appending — the type system already prevents the
106
+ * legitimate path, this catches the bug path (a stale `Query<T>`
107
+ * re-attached to a different collection's transaction).
108
+ */
109
+ readonly collection: string;
110
+ /**
111
+ * Mutations buffered in order of issuance. The commit converts
112
+ * each into one `CommitInput` (`Writer`'s single-mutation
113
+ * shape) and passes the array to `Writer.commitBatch`.
114
+ */
115
+ readonly mutations: BufferedMutation[];
116
+ }
117
+ /**
118
+ * One buffered mutation. Mirrors {@link CommitInput} minus
119
+ * `collection` (which is constant per transaction and lives on
120
+ * `TxContext.collection`).
121
+ *
122
+ * @internal — only used inside the `Db.transaction` path.
123
+ */
124
+ interface BufferedMutation {
125
+ readonly op: "I" | "U" | "D";
126
+ readonly docId: string;
127
+ readonly body?: DocumentData;
128
+ readonly origin?: string;
129
+ }
130
+ /**
131
+ * Runtime entry point. One `Db` per `(app, tenant)` request.
132
+ *
133
+ * Construct via {@link Db.create} — the constructor is private so
134
+ * callers don't accidentally bypass validation.
135
+ *
136
+ * **Collection provisioning.** `Db` provisions collections implicitly on
137
+ * the first commit — the writer auto-creates the per-collection
138
+ * `current.json` manifest with a zero-state seed, costing one extra
139
+ * Class A PUT on the very first write per collection and zero
140
+ * thereafter. There is no `ensureCollection` method on this class. For
141
+ * eager pre-warm (seed scripts, deploy-time provisioning, CI fixtures
142
+ * that want byte-identical bytes before the first request), use
143
+ * {@link "@gusto/baerly-storage/dev".ensureTable}.
144
+ *
145
+ * @example
146
+ * ```ts
147
+ * import { Db } from "@gusto/baerly-storage";
148
+ * import { MemoryStorage } from "@gusto/baerly-storage";
149
+ *
150
+ * const db = Db.create({
151
+ * storage: new MemoryStorage(),
152
+ * app: "tickets",
153
+ * tenant: "acme-co",
154
+ * });
155
+ *
156
+ * await db.collection("tickets").insert({ title: "first ticket", status: "open" });
157
+ * const open = await db.collection("tickets").where({ status: "open" }).all();
158
+ * ```
159
+ *
160
+ * @remarks
161
+ * **Anti-patterns** (TS compile errors, not runtime rejections):
162
+ * - `db.collection(name).insertOne({...})` / `.insert({...})` —
163
+ * the Mongo verb. Use `.insert(row)` (returns `{ _id }`).
164
+ * - `db.collection(name).findOne({...})` / `.find({...})` —
165
+ * the Mongo read verbs. Use `.get(id)` for by-id reads and
166
+ * `.where({...}).first()` / `.all()` for predicate reads.
167
+ * - `db.collection(name).aggregate([...])` — no pipeline stage
168
+ * model. Compose via `.where().order().limit()` modifiers.
169
+ * - Raw SQL strings of any shape. The kernel has no SQL parser.
170
+ */
171
+ declare class Db<TConfig extends BaerlyConfig = UnboundConfig> {
172
+ #private;
173
+ readonly app: string;
174
+ readonly tenant: string;
175
+ private constructor();
176
+ /**
177
+ * Build a tenant-scoped `Db`. Throws
178
+ * `BaerlyError{code:"InvalidConfig"}` if either `app` or `tenant`
179
+ * is empty or contains `/` (the segment separator).
180
+ *
181
+ * @throws BaerlyError code="InvalidConfig" when `app` or `tenant` is
182
+ * empty or contains `/`.
183
+ *
184
+ * @example
185
+ * ```ts
186
+ * const db = Db.create({ storage, app: "tickets", tenant: "acme" });
187
+ * await db.collection("tickets").insert({ title: "hi" });
188
+ * ```
189
+ */
190
+ static create<TConfig extends BaerlyConfig = UnboundConfig>(config: {
191
+ storage: Storage;
192
+ app: string;
193
+ tenant: string;
194
+ /**
195
+ * Optional. Pass the value returned by {@link defineConfig} from
196
+ * your `baerly.config.ts`. Two things happen:
197
+ *
198
+ * 1. **Types.** `db.collection(name)` narrows `name` to declared
199
+ * collection names and infers the row type from
200
+ * `collections[name].schema` via {@link RowOf}.
201
+ * 2. **Runtime.** Schemas and indexes are derived from
202
+ * `config.collections` via {@link collectionsToMaps}. Schema
203
+ * validation and index routing are wired automatically — no
204
+ * second hand-off step.
205
+ *
206
+ * @example
207
+ * ```ts
208
+ * import config from "../baerly.config.ts";
209
+ * const db = Db.create({
210
+ * storage: new MemoryStorage(),
211
+ * app: "helpdesk",
212
+ * tenant: "test",
213
+ * config,
214
+ * });
215
+ * // db.collection("tickets") is typed AND validates writes against
216
+ * // the schema declared in baerly.config.ts.
217
+ * ```
218
+ */
219
+ config?: TConfig;
220
+ }): Db<TConfig>;
221
+ /**
222
+ * Typed handle for a single collection. Cheap; creates no I/O. Same
223
+ * `name` returns a FRESH `Collection<T>` object on each call (chain
224
+ * identity is intentional — modifiers return new objects).
225
+ *
226
+ * @throws BaerlyError code="InvalidConfig" when `name` is empty or
227
+ * contains `/`.
228
+ *
229
+ * @example
230
+ * ```ts
231
+ * // With a baerly.config.ts bound via Db.create({..., config}),
232
+ * // db.collection(name) infers the row type from the declared schema —
233
+ * // no <Ticket> generic needed.
234
+ * const open = await db.collection("tickets")
235
+ * .where({ status: "open" })
236
+ * .order({ commit_ts: "desc" })
237
+ * .limit(50)
238
+ * .all();
239
+ * ```
240
+ */
241
+ collection<N extends CollectionNames<TConfig>>(name: N): Collection<RowOf<TConfig, N> & DocumentData>;
242
+ /**
243
+ * Build a freshly-seeded {@link CollectionReadContext} for `name`. The
244
+ * HTTP router uses this so it can drive `runAllWithMeta` directly
245
+ * (the return shape carries the manifest-pointer cursor used to
246
+ * pack `_meta` onto the read response envelope). Application
247
+ * callers should keep using
248
+ * {@link Db.collection}; the chainable terminals destructure the cursor
249
+ * out and discard it to keep the locked `Query<T>` signature.
250
+ *
251
+ * Runs the same `name`-validation guard as {@link Db.collection}.
252
+ *
253
+ * @throws BaerlyError code="InvalidConfig" when `name` is empty or
254
+ * contains `/`.
255
+ * @internal
256
+ */
257
+ collectionReadContext(name: string): CollectionReadContext;
258
+ /**
259
+ * Atomic mutation over a single collection. The callback receives a
260
+ * `Collection<T>` (not a `Db`) so cross-collection writes inside a
261
+ * transaction are a TypeScript error at compile time — not a
262
+ * runtime trap. Mutation verbs (`insert`, `update`, `replace`,
263
+ * `delete`) buffer; reads (`first`, `all`, `count`) go through
264
+ * `Storage` live (no MVCC snapshot, no read-your-writes).
265
+ *
266
+ * Single-attempt: on CAS conflict throws
267
+ * `BaerlyError{code:"Conflict"}`. The body MAY have already run its
268
+ * read side-effects (no rollback of in-memory state); the write
269
+ * side-effects either all landed or none did. Wrap in a retry
270
+ * loop you wrote if you want one.
271
+ *
272
+ * Empty body (or a body that buffers nothing) resolves without
273
+ * touching `current.json`.
274
+ *
275
+ * @throws BaerlyError code="Conflict" — CAS lost on the collection's
276
+ * `current.json`. Caller decides whether to re-run the body.
277
+ * @throws Whatever the body throws — re-thrown as-is. The commit
278
+ * is skipped when the body throws.
279
+ * @throws BaerlyError code="InvalidConfig" — `collection` is empty or
280
+ * contains `/`.
281
+ *
282
+ * @remarks
283
+ * Single-collection by design. Cross-collection 2PC was rejected on
284
+ * cost grounds — multiple round-trips per commit, no native fencing
285
+ * primitive on S3-compatible storage, no rollback to undo a
286
+ * successful PUT — and because in-doubt-transaction recovery state
287
+ * would contradict the stateless-writer model. Applications that
288
+ * need cross-collection atomicity re-express it at the app layer: an
289
+ * idempotent move keyed off source-row state, or a single
290
+ * denormalized collection with a `status` column.
291
+ *
292
+ * @example
293
+ * ```ts
294
+ * await db.transaction("tickets", async (tx) => {
295
+ * const open = await tx.where({ status: "open" }).count();
296
+ * if (open < 100) await tx.insert({ title: "another", status: "open" });
297
+ * });
298
+ * ```
299
+ */
300
+ transaction<T extends DocumentData = DocumentData>(collection: string, body: (tx: Collection<T>) => Promise<void>): Promise<void>;
301
+ /**
302
+ * Read + parse this `Db`'s `manifests/<collection>/current.json`. Returns
303
+ * `null` when the collection has not been provisioned yet (no
304
+ * `current.json` exists). Throws `BaerlyError{code:"InvalidResponse"}`
305
+ * on a malformed body — same contract as the underlying
306
+ * {@link readCurrentJson} helper in `@baerly/protocol`.
307
+ *
308
+ * Backs the `/v1/since` long-poll handler in
309
+ * `packages/server/src/http/since.ts`; that handler needs the parsed
310
+ * `CurrentJson` plus an ETag for the follow-up reads.
311
+ *
312
+ * @internal — typed seam for the HTTP handler; app code should use
313
+ * the collection API.
314
+ */
315
+ getCurrentJson(collection: string, opts?: {
316
+ signal?: AbortSignal;
317
+ }): Promise<CurrentJsonRead | null>;
318
+ /**
319
+ * Read + parse one `LogEntry` by `seq` from
320
+ * `manifests/<collection>/${LOG_KEY_PREFIX}/<seq>.json`. Returns `null`
321
+ * when the entry is missing — this typically means the GC sweeper
322
+ * deleted the entry between a `readCurrentJson` and this GET (the
323
+ * `/v1/since` handler treats the race as silent and skips the
324
+ * entry). Throws `BaerlyError{code:"InvalidResponse"}` on a body
325
+ * that isn't valid JSON.
326
+ *
327
+ * @internal — typed seam for the HTTP handler; app code should use
328
+ * the collection API.
329
+ */
330
+ getLogEntry(collection: string, seq: number, opts?: {
331
+ signal?: AbortSignal;
332
+ }): Promise<LogEntry | null>;
333
+ }
334
+ //#endregion
335
+ export { validateOrThrow as n, Db as t };
336
+ //# sourceMappingURL=db-D62JguBc.d.ts.map
@@ -0,0 +1,83 @@
1
+ import { t as loadAppConfig } from "./config-Bsg8wgwo.js";
2
+ import { a as setJsonMode, n as emitError, o as BaerlyError, r as emitSuccess, s as defineCommand } from "./baerly.js";
3
+ import { t as deployCloudflare } from "./cloudflare-CINJPKCW.js";
4
+ //#region src/deploy.ts
5
+ /**
6
+ * `baerly deploy` — citty dispatcher.
7
+ *
8
+ * Reads `baerly.config.ts:target` and routes to the matching
9
+ * deploy backend. Today: `cloudflare` only — the `node` example
10
+ * embodies its deployment shape directly (self-host via `node
11
+ * server.js` after your PaaS or container build), so `baerly
12
+ * deploy` rejects `target: "node"` with an actionable InvalidConfig.
13
+ *
14
+ * Exit-code contract (standard CLI shape):
15
+ * - 0 success.
16
+ * - 1 user error (InvalidConfig, missing config, unknown target).
17
+ * - 2 storage / external error (NetworkError, Wrangler returned
18
+ * non-zero, anything non-BaerlyError).
19
+ * - 3 protocol invariant (Conflict, Internal, InvalidResponse —
20
+ * should not happen here unless someone hand-edited mid-flight).
21
+ */
22
+ const DEPLOY_ARGS = {
23
+ target: {
24
+ type: "string",
25
+ description: "Override `baerly.config.ts:target`. Only \"cloudflare\" supported (\"node\" self-deploys via your PaaS or container build).",
26
+ valueHint: "cloudflare"
27
+ },
28
+ json: {
29
+ type: "boolean",
30
+ description: "Emit a structured JSON envelope to stdout (success) or stderr (error)"
31
+ }
32
+ };
33
+ const KNOWN_KEYS = new Set([
34
+ "target",
35
+ "json",
36
+ "_"
37
+ ]);
38
+ const errorToExitCode = (code) => {
39
+ if (code === "InvalidConfig") return 1;
40
+ if (code === "Conflict" || code === "Internal" || code === "InvalidResponse") return 3;
41
+ return 2;
42
+ };
43
+ const handleDeploy = async (args) => {
44
+ setJsonMode(args.json === true);
45
+ try {
46
+ for (const k of Object.keys(args)) if (!KNOWN_KEYS.has(k)) throw new BaerlyError("InvalidConfig", `baerly deploy: unknown flag --${k}`);
47
+ const config = await loadAppConfig();
48
+ const target = args.target ?? config.target;
49
+ if (target === "cloudflare") {
50
+ const exit = await deployCloudflare(config);
51
+ if (exit === 0) emitSuccess({
52
+ command: "deploy",
53
+ status: "ok",
54
+ target
55
+ });
56
+ return exit;
57
+ }
58
+ throw new BaerlyError("InvalidConfig", `baerly deploy: target ${JSON.stringify(target)} has no deploy backend. Self-host: \`node server.js\` after your PaaS or container build. Cloudflare Workers is the only managed deploy backend today.`);
59
+ } catch (error) {
60
+ if (error instanceof BaerlyError) {
61
+ emitError("deploy", error.code, error.message);
62
+ return errorToExitCode(error.code);
63
+ }
64
+ emitError("deploy", "Unknown", error.message);
65
+ return 2;
66
+ }
67
+ };
68
+ /** citty `defineCommand` block for `baerly deploy`. */
69
+ const deploy = defineCommand({
70
+ meta: {
71
+ name: "deploy",
72
+ description: "Deploy this baerly app. Dispatches by baerly.config.ts:target."
73
+ },
74
+ args: DEPLOY_ARGS,
75
+ run: async ({ args }) => {
76
+ const code = await handleDeploy(args);
77
+ if (code !== 0) process.exit(code);
78
+ }
79
+ });
80
+ //#endregion
81
+ export { deploy };
82
+
83
+ //# sourceMappingURL=deploy-BB-wqbhf.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deploy-BB-wqbhf.js","names":[],"sources":["../packages/cli/src/deploy.ts"],"sourcesContent":["/**\n * `baerly deploy` — citty dispatcher.\n *\n * Reads `baerly.config.ts:target` and routes to the matching\n * deploy backend. Today: `cloudflare` only — the `node` example\n * embodies its deployment shape directly (self-host via `node\n * server.js` after your PaaS or container build), so `baerly\n * deploy` rejects `target: \"node\"` with an actionable InvalidConfig.\n *\n * Exit-code contract (standard CLI shape):\n * - 0 success.\n * - 1 user error (InvalidConfig, missing config, unknown target).\n * - 2 storage / external error (NetworkError, Wrangler returned\n * non-zero, anything non-BaerlyError).\n * - 3 protocol invariant (Conflict, Internal, InvalidResponse —\n * should not happen here unless someone hand-edited mid-flight).\n */\n\nimport { defineCommand, type ArgsDef, type ParsedArgs } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { deployCloudflare } from \"./deploy/cloudflare.ts\";\nimport { emitError, emitSuccess, setJsonMode } from \"./output.ts\";\n\nconst DEPLOY_ARGS = {\n target: {\n type: \"string\",\n description:\n 'Override `baerly.config.ts:target`. Only \"cloudflare\" supported (\"node\" self-deploys via your PaaS or container build).',\n valueHint: \"cloudflare\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\nconst KNOWN_KEYS: ReadonlySet<string> = new Set([\"target\", \"json\", \"_\"]);\n\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\nconst handleDeploy = async (args: ParsedArgs<typeof DEPLOY_ARGS>): Promise<number> => {\n setJsonMode(args.json === true);\n try {\n for (const k of Object.keys(args)) {\n if (!KNOWN_KEYS.has(k)) {\n throw new BaerlyError(\"InvalidConfig\", `baerly deploy: unknown flag --${k}`);\n }\n }\n const config = await loadAppConfig();\n const target = args.target ?? config.target;\n if (target === \"cloudflare\") {\n const exit = await deployCloudflare(config);\n if (exit === 0) {\n emitSuccess({ command: \"deploy\", status: \"ok\", target });\n }\n return exit;\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly deploy: target ${JSON.stringify(target)} has no deploy backend. ` +\n `Self-host: \\`node server.js\\` after your PaaS or container build. ` +\n `Cloudflare Workers is the only managed deploy backend today.`,\n );\n } catch (error) {\n if (error instanceof BaerlyError) {\n emitError(\"deploy\", error.code, error.message);\n return errorToExitCode(error.code);\n }\n emitError(\"deploy\", \"Unknown\", (error as Error).message);\n return 2;\n }\n};\n\n/** citty `defineCommand` block for `baerly deploy`. */\nexport const deploy = defineCommand({\n meta: {\n name: \"deploy\",\n description: \"Deploy this baerly app. Dispatches by baerly.config.ts:target.\",\n },\n args: DEPLOY_ARGS,\n run: async ({ args }) => {\n const code = await handleDeploy(args);\n if (code !== 0) {\n process.exit(code);\n }\n },\n});\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 runDeploy = async (argv: readonly string[]): Promise<number> => {\n const { parseArgs } = await import(\"citty\");\n let parsed: ParsedArgs<typeof DEPLOY_ARGS>;\n try {\n parsed = parseArgs<typeof DEPLOY_ARGS>(argv as string[], DEPLOY_ARGS);\n } catch (error) {\n setJsonMode(argv.includes(\"--json\"));\n emitError(\"deploy\", \"InvalidConfig\", (error as Error).message);\n return 1;\n }\n return handleDeploy(parsed);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,cAAc;CAClB,QAAQ;EACN,MAAM;EACN,aACE;EACF,WAAW;CACb;CACA,MAAM;EACJ,MAAM;EACN,aAAa;CACf;AACF;AAEA,MAAM,aAAkC,IAAI,IAAI;CAAC;CAAU;CAAQ;AAAG,CAAC;AAEvE,MAAM,mBAAmB,SAAyB;CAChD,IAAI,SAAS,iBACX,OAAO;CAET,IAAI,SAAS,cAAc,SAAS,cAAc,SAAS,mBACzD,OAAO;CAET,OAAO;AACT;AAEA,MAAM,eAAe,OAAO,SAA0D;CACpF,YAAY,KAAK,SAAS,IAAI;CAC9B,IAAI;EACF,KAAK,MAAM,KAAK,OAAO,KAAK,IAAI,GAC9B,IAAI,CAAC,WAAW,IAAI,CAAC,GACnB,MAAM,IAAI,YAAY,iBAAiB,iCAAiC,GAAG;EAG/E,MAAM,SAAS,MAAM,cAAc;EACnC,MAAM,SAAS,KAAK,UAAU,OAAO;EACrC,IAAI,WAAW,cAAc;GAC3B,MAAM,OAAO,MAAM,iBAAiB,MAAM;GAC1C,IAAI,SAAS,GACX,YAAY;IAAE,SAAS;IAAU,QAAQ;IAAM;GAAO,CAAC;GAEzD,OAAO;EACT;EACA,MAAM,IAAI,YACR,iBACA,yBAAyB,KAAK,UAAU,MAAM,EAAE,uJAGlD;CACF,SAAS,OAAO;EACd,IAAI,iBAAiB,aAAa;GAChC,UAAU,UAAU,MAAM,MAAM,MAAM,OAAO;GAC7C,OAAO,gBAAgB,MAAM,IAAI;EACnC;EACA,UAAU,UAAU,WAAY,MAAgB,OAAO;EACvD,OAAO;CACT;AACF;;AAGA,MAAa,SAAS,cAAc;CAClC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM;CACN,KAAK,OAAO,EAAE,WAAW;EACvB,MAAM,OAAO,MAAM,aAAa,IAAI;EACpC,IAAI,SAAS,GACX,QAAQ,KAAK,IAAI;CAErB;AACF,CAAC"}
@@ -0,0 +1,26 @@
1
+ //#region packages/dev/src/dev-banner.d.ts
2
+ interface DevBannerHint {
3
+ readonly key: string;
4
+ readonly value: string;
5
+ }
6
+ interface DevBannerOpts {
7
+ readonly name: string;
8
+ readonly primaryUrl?: {
9
+ readonly label: string;
10
+ readonly url: string;
11
+ };
12
+ readonly apiUrl?: {
13
+ readonly label: string;
14
+ readonly url: string;
15
+ readonly note?: string;
16
+ };
17
+ readonly hints?: ReadonlyArray<DevBannerHint>;
18
+ /** Force plain-text output (no color, no `←`). Defaults to !isTTY || CI. */
19
+ readonly plain?: boolean;
20
+ /** Sink. Defaults to process.stderr. */
21
+ readonly write?: (chunk: string) => void;
22
+ }
23
+ declare function printDevBanner(opts: DevBannerOpts): void;
24
+ //#endregion
25
+ export { DevBannerOpts as n, printDevBanner as r, DevBannerHint as t };
26
+ //# sourceMappingURL=dev-banner-CWHIk8tH.d.ts.map
@@ -0,0 +1,146 @@
1
+ import { n as BaerlyAppConfig } from "./app-config-Cb5dO2s9.js";
2
+ import { r as Verifier } from "./index-BGC-ENnj.js";
3
+ import { t as DevBannerHint } from "./dev-banner-CWHIk8tH.js";
4
+ import { t as Db } from "./db-D62JguBc.js";
5
+ import { Plugin } from "vite";
6
+
7
+ //#region packages/dev/src/vite-plugin.d.ts
8
+ interface BaerlyDevOptions {
9
+ /**
10
+ * The project's `baerly.config.ts`. `app`, `tenant`, `auth`, and the
11
+ * table set (`Object.keys(config.collections)`) are derived from it.
12
+ * Per-collection schemas/indexes flow through to the in-process
13
+ * listener the same way `baerlyNode` / `baerlyWorker` pipe them.
14
+ */
15
+ readonly config: BaerlyAppConfig;
16
+ /**
17
+ * Shared-secret token. **Optional.** Required only when
18
+ * `config.auth === "shared-secret"` and `verifier` is unset — in
19
+ * that branch, clients must send `Authorization: Bearer <secret>`
20
+ * AND the middleware injects the same bearer server-side before
21
+ * forwarding to the in-process listener.
22
+ *
23
+ * Ignored when `config.auth === "none"` (no bearer to inject) or
24
+ * when `verifier` is supplied (the operator owns the auth seam).
25
+ *
26
+ * Throwing the symmetric `InvalidConfig` on a misconfig matches
27
+ * production behaviour: forgetting `SHARED_SECRET` in dev fails
28
+ * fast at `vite dev` startup with the same locked wording the
29
+ * adapter would emit.
30
+ */
31
+ readonly secret?: string;
32
+ /**
33
+ * Per-request `Verifier`. **Optional.** When set, overrides both
34
+ * `config.auth` and `secret` (same precedence as the production
35
+ * adapter factories). Use for dev-mode JWT validation against a
36
+ * staging IdP, or any custom auth shape.
37
+ */
38
+ readonly verifier?: Verifier;
39
+ /** Absolute path to the data directory for LocalFsStorage. */
40
+ readonly dataDir: string;
41
+ /** Optional async seed callback, invoked after ensureTable, before mount. */
42
+ readonly seed?: (db: Db) => Promise<void>;
43
+ /** Extra hints appended to the dev banner. */
44
+ readonly hints?: readonly DevBannerHint[];
45
+ /** Set to false to suppress the dev banner. Default: true. */
46
+ readonly banner?: boolean;
47
+ }
48
+ interface BaerlyDevAuthOptions {
49
+ /** Bearer token to inject on matched paths. */
50
+ readonly secret: string;
51
+ /**
52
+ * Pathname prefixes to match. Default `["/v1", "/api"]` — the
53
+ * baerly cascade lives at `/v1/*`, and `/api/*` is the canonical
54
+ * namespace for custom Worker routes (the "wrap `baerly.fetch!`"
55
+ * recipe in the scaffold's AGENTS.md). Covering both by default
56
+ * closes a recurring "added a custom route, browser silently 401s"
57
+ * trap: agents typically edit `src/server/index.ts` without touching
58
+ * `vite.config.ts`, so a `"/v1"`-only default leaves their new route
59
+ * unauthenticated in `vite dev` and `pnpm verify` is silent on it.
60
+ *
61
+ * Override when you mount under a different namespace, or pass
62
+ * `prefix: "/v1"` to opt out of `/api/*` injection entirely (rare —
63
+ * the bearer is a harmless extra header on unmatched routes).
64
+ */
65
+ readonly prefix?: string | readonly string[];
66
+ }
67
+ /**
68
+ * Vite dev plugin: inject `Authorization: Bearer ${secret}` on every
69
+ * request whose URL starts with one of `prefix` (default
70
+ * `["/v1", "/api"]`). Use this to keep the bearer token out of the
71
+ * SPA bundle — the browser sends the request, Vite's middleware adds
72
+ * the header, and the upstream handler (in-process worker or proxied
73
+ * Node server) sees an authenticated request.
74
+ *
75
+ * **Custom Worker routes.** `baerlyWorker` only sees `/v1/*`; the
76
+ * default `prefix` also covers `/api/*` because that's the canonical
77
+ * namespace for the "wrap `baerly.fetch!`" recipe (a server-side
78
+ * endpoint the SPA client can't run on its own, e.g. an endpoint
79
+ * that needs `db.transaction(...)`). If you mount under a different
80
+ * namespace, override:
81
+ *
82
+ * ```ts
83
+ * baerlyDevAuth({ secret, prefix: ["/v1", "/internal"] });
84
+ * ```
85
+ *
86
+ * The bearer is dev-only convenience — production deploys put the
87
+ * SPA, the baerly cascade, AND your custom routes behind the same
88
+ * tenant boundary (CF Access, an upstream JWT, …), so this matters
89
+ * exclusively while `vite dev` is the front door.
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * import { baerlyDevAuth, loadDevVars } from "@gusto/baerly-storage/dev/vite";
94
+ *
95
+ * const { SHARED_SECRET } = loadDevVars(".dev.vars", "SHARED_SECRET");
96
+ * export default defineConfig({
97
+ * plugins: [
98
+ * cloudflare(),
99
+ * baerlyDevAuth({ secret: SHARED_SECRET ?? "" }),
100
+ * ],
101
+ * });
102
+ * ```
103
+ */
104
+ declare function baerlyDevAuth(opts: BaerlyDevAuthOptions): Plugin;
105
+ /**
106
+ * Parse a `.dev.vars` / `.env` file and return the values for the
107
+ * requested `keys`. Supports `KEY=value`, `# comments`, blank lines,
108
+ * and single- or double-quoted values. Keys missing from the file
109
+ * (or the whole file when it does not exist) come back as
110
+ * `undefined` — fall back with `??` at the call site.
111
+ *
112
+ * The return type is `Record<K, string | undefined>` where `K` is
113
+ * the union of literal key names you pass in, so property access
114
+ * works under strict `noPropertyAccessFromIndexSignature`:
115
+ *
116
+ * ```ts
117
+ * const { SHARED_SECRET } = loadDevVars(".dev.vars", "SHARED_SECRET");
118
+ * // ^? string | undefined
119
+ * ```
120
+ */
121
+ declare function loadDevVars<K extends string>(path: string, ...keys: readonly K[]): Record<K, string | undefined>;
122
+ /**
123
+ * Resolution order for the in-process verifier (mirrors
124
+ * `baerlyNode` / `baerlyWorker`):
125
+ *
126
+ * 1. `opts.verifier` set → use as-is.
127
+ * 2. else `opts.config.auth === "shared-secret"` → require
128
+ * `opts.secret`; build `sharedSecret({ secret, tenantPrefix:
129
+ * config.tenant })`. Throws `BaerlyError("InvalidConfig", ...)`
130
+ * at Vite startup when `opts.secret` is empty/unset — same
131
+ * locked wording the production adapter would emit.
132
+ * 3. else `opts.config.auth === "none"` → pin every request to
133
+ * `config.tenant`; no header check.
134
+ *
135
+ * Bearer injection on `/v1/*` only fires in branch 2 (and only when
136
+ * branch 1 didn't win) — the dev convenience that lets the SPA call
137
+ * the listener without putting the secret in the browser bundle.
138
+ * Branch 3 leaves the `Authorization` header alone.
139
+ *
140
+ * Verifier resolution happens eagerly at factory time so a misconfig
141
+ * fails Vite startup, not the first `/v1/*` round-trip.
142
+ */
143
+ declare function baerlyDev(opts: BaerlyDevOptions): Plugin;
144
+ //#endregion
145
+ export { BaerlyDevAuthOptions, BaerlyDevOptions, baerlyDev, baerlyDevAuth, loadDevVars };
146
+ //# sourceMappingURL=dev-vite.d.ts.map