@gusto/baerly-storage 0.1.2 → 0.3.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/LICENSE +202 -0
- package/NOTICE +29 -0
- package/README.md +108 -44
- package/dist/API.md +192 -121
- package/dist/CHANGELOG.md +144 -0
- package/dist/THIRD-PARTY-LICENSES.txt +312 -0
- package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-BIzyAKzy.d.ts} +14 -2
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.js +288 -288
- package/dist/auth.js.map +1 -1
- package/dist/baerly.js +10 -10
- package/dist/baerly.js.map +1 -1
- package/dist/bytes-BXdamO3L.js.map +1 -1
- package/dist/{client-DYZfoZb9.d.ts → client-BJXF3XJA.d.ts} +10 -10
- package/dist/client-react.d.ts +76 -85
- package/dist/client-react.js +95 -53
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +3 -3
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-CINJPKCW.js → cloudflare-Cn2ibODt.js} +178 -2
- package/dist/cloudflare-Cn2ibODt.js.map +1 -0
- package/dist/cloudflare.d.ts +4 -4
- package/dist/cloudflare.js +10 -11
- package/dist/cloudflare.js.map +1 -1
- package/dist/{subcommand-DZcHcsYp.js → config-CGyBopy3.js} +643 -439
- package/dist/config-CGyBopy3.js.map +1 -0
- package/dist/context-DRZ3tZ5l.js.map +1 -1
- package/dist/{cost-CQt1YRkA.js → cost-BZ_MDBmn.js} +6 -4
- package/dist/cost-BZ_MDBmn.js.map +1 -0
- package/dist/{current-json-C-EyJqs0.js → current-json-DsN7FNY1.js} +47 -13
- package/dist/current-json-DsN7FNY1.js.map +1 -0
- package/dist/{db-BM3y2JQw.d.ts → db-CCT6tDfY.d.ts} +26 -108
- package/dist/{deploy-CrAbfgCq.js → deploy-BKKyGlSJ.js} +11 -4
- package/dist/deploy-BKKyGlSJ.js.map +1 -0
- package/dist/dev-vite.d.ts +5 -5
- package/dist/dev-vite.js +5 -5
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-Db-hzPmE.js → doctor-BVU4GNXN.js} +13 -132
- package/dist/doctor-BVU4GNXN.js.map +1 -0
- package/dist/{dump-BYA55NLP.js → dump-DPEAKub6.js} +5 -3
- package/dist/dump-DPEAKub6.js.map +1 -0
- package/dist/errors-DOdL95kK.js.map +1 -1
- package/dist/{export-Bhbz90-z.js → export-BcuCLFFe.js} +6 -4
- package/dist/{export-Bhbz90-z.js.map → export-BcuCLFFe.js.map} +1 -1
- package/dist/{fsck-CPPZWt9p.js → fsck-RXgLOaJG.js} +23 -11
- package/dist/fsck-RXgLOaJG.js.map +1 -0
- package/dist/{http-Cw8p6y5b.js → http-Bd4byR4n.js} +45 -61
- package/dist/http-Bd4byR4n.js.map +1 -0
- package/dist/http.d.ts +15 -15
- package/dist/http.js +1 -1
- package/dist/{index-cUY-36AN.d.ts → index-BDceQQi-.d.ts} +20 -4
- package/dist/{index-C3JAH1Yo.d.ts → index-Cmsxx-ZN.d.ts} +9 -9
- package/dist/{index-DSvwEUeF.d.ts → index-DW7GT6M2.d.ts} +50 -42
- package/dist/{index-DwDTWPSU.d.ts → index-DnBGSeuU.d.ts} +10 -7
- package/dist/index.d.ts +6 -6
- package/dist/index.js +4 -4
- package/dist/{indexes-DAu2AkTW.d.ts → indexes-Cx7uMXm0.d.ts} +2 -2
- package/dist/{inspect-Bdbzvi-_.js → inspect-DhI49PSi.js} +16 -8
- package/dist/inspect-DhI49PSi.js.map +1 -0
- package/dist/{snapshot-SS8USDUF.js → log-tail-DXeDkWEp.js} +154 -83
- package/dist/log-tail-DXeDkWEp.js.map +1 -0
- package/dist/{maintenance-BRrThz8V.d.ts → maintenance-BkhUr72A.d.ts} +91 -26
- package/dist/{maintenance-ClzBC1Vv.js → maintenance-CWBQpZ2y.js} +368 -161
- package/dist/maintenance-CWBQpZ2y.js.map +1 -0
- package/dist/{maintenance-BvOv6BMM.js → maintenance-C_KSkVjd.js} +204 -82
- package/dist/maintenance-C_KSkVjd.js.map +1 -0
- package/dist/maintenance.d.ts +3 -2
- package/dist/maintenance.js +3 -2
- package/dist/node.d.ts +13 -8
- package/dist/node.js +1 -1
- package/dist/normalize-XWY25_sG.js.map +1 -1
- package/dist/{observability-CpOiEN0k.js → observability-BYd-RzEx.js} +63 -55
- package/dist/observability-BYd-RzEx.js.map +1 -0
- package/dist/observability.d.ts +3 -3
- package/dist/observability.js +1 -1
- package/dist/{plan-DOTl21vq.js → plan-DIu_B6fy.js} +7 -4
- package/dist/plan-DIu_B6fy.js.map +1 -0
- package/dist/{query-BmiQy328.js → query-sQNO5vU_.js} +1071 -1099
- package/dist/query-sQNO5vU_.js.map +1 -0
- package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-DP4CqSSs.js} +5 -4
- package/dist/rebuild-index-DP4CqSSs.js.map +1 -0
- package/dist/{restore-C6IcmLeA.js → restore-DpQYef6r.js} +362 -328
- package/dist/restore-DpQYef6r.js.map +1 -0
- package/dist/shared-secret-BJdSwpgw.js.map +1 -1
- package/dist/{src-QQ7jDeL2.js → src-CWpkSbvJ.js} +40 -20
- package/dist/src-CWpkSbvJ.js.map +1 -0
- package/dist/{src-DU1sCMlr.js → src-D24wDpzR.js} +269 -258
- package/dist/src-D24wDpzR.js.map +1 -0
- package/dist/{src-zhEAmmF7.js → src-Db4-qVtM.js} +36 -96
- package/dist/src-Db4-qVtM.js.map +1 -0
- package/dist/subcommand-CP9NY2J4.js +159 -0
- package/dist/subcommand-CP9NY2J4.js.map +1 -0
- package/dist/{usage-CLjirdD-.js → usage-CTfDq9HR.js} +3 -3
- package/dist/{usage-CLjirdD-.js.map → usage-CTfDq9HR.js.map} +1 -1
- package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
- package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
- package/package.json +42 -31
- package/dist/cloudflare-CINJPKCW.js.map +0 -1
- package/dist/config-DVfDGyw1.js +0 -278
- package/dist/config-DVfDGyw1.js.map +0 -1
- package/dist/cost-CQt1YRkA.js.map +0 -1
- package/dist/current-json-C-EyJqs0.js.map +0 -1
- package/dist/deploy-CrAbfgCq.js.map +0 -1
- package/dist/doctor-Db-hzPmE.js.map +0 -1
- package/dist/dump-BYA55NLP.js.map +0 -1
- package/dist/fsck-CPPZWt9p.js.map +0 -1
- package/dist/http-Cw8p6y5b.js.map +0 -1
- package/dist/inspect-Bdbzvi-_.js.map +0 -1
- package/dist/maintenance-BvOv6BMM.js.map +0 -1
- package/dist/maintenance-ClzBC1Vv.js.map +0 -1
- package/dist/observability-CpOiEN0k.js.map +0 -1
- package/dist/plan-DOTl21vq.js.map +0 -1
- package/dist/query-BmiQy328.js.map +0 -1
- package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
- package/dist/restore-C6IcmLeA.js.map +0 -1
- package/dist/snapshot-SS8USDUF.js.map +0 -1
- package/dist/src-DU1sCMlr.js.map +0 -1
- package/dist/src-QQ7jDeL2.js.map +0 -1
- package/dist/src-zhEAmmF7.js.map +0 -1
- package/dist/subcommand-DZcHcsYp.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
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-
|
|
2
|
-
import { c as Collection, h as Storage, m as CurrentJsonRead, n as LogEntry } from "./index-
|
|
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-BIzyAKzy.js";
|
|
2
|
+
import { c as Collection, h as Storage, m as CurrentJsonRead, n as LogEntry } from "./index-DW7GT6M2.js";
|
|
3
3
|
//#region packages/server/src/schema.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* Run a validator and throw `BaerlyError{code:"SchemaError"}` on failure.
|
|
@@ -37,22 +37,10 @@ interface CollectionReadContext {
|
|
|
37
37
|
/** Physical key prefix — already includes `app/<app>/tenant/<tenant>/manifests/<name>`. */
|
|
38
38
|
readonly collectionPrefix: string;
|
|
39
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
40
|
/**
|
|
53
41
|
* Optional StandardSchemaV1-shaped validator for this collection.
|
|
54
42
|
* When set, `runInsert`, `runUpdate`, and `runReplaceById` validate the
|
|
55
|
-
* post-image before committing
|
|
43
|
+
* post-image before committing — invalid input throws
|
|
56
44
|
* `BaerlyError{code:"SchemaError"}` carrying a `.issues` array of
|
|
57
45
|
* `{ path, message }` entries. `undefined` means no validation
|
|
58
46
|
* (today's behaviour — zero overhead).
|
|
@@ -85,48 +73,6 @@ interface CollectionReadContext {
|
|
|
85
73
|
}
|
|
86
74
|
//#endregion
|
|
87
75
|
//#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
76
|
/**
|
|
131
77
|
* Runtime entry point. One `Db` per `(app, tenant)` request.
|
|
132
78
|
*
|
|
@@ -176,10 +122,14 @@ declare class Db<TConfig extends BaerlyConfig = UnboundConfig> {
|
|
|
176
122
|
/**
|
|
177
123
|
* Build a tenant-scoped `Db`. Throws
|
|
178
124
|
* `BaerlyError{code:"InvalidConfig"}` if either `app` or `tenant`
|
|
179
|
-
* is empty
|
|
125
|
+
* is empty, contains `/`, is `"."` or `".."`, contains control
|
|
126
|
+
* characters, starts with the reserved `"_"` prefix, or exceeds
|
|
127
|
+
* 256 bytes.
|
|
180
128
|
*
|
|
181
129
|
* @throws BaerlyError code="InvalidConfig" when `app` or `tenant` is
|
|
182
|
-
* empty or contains
|
|
130
|
+
* empty, contains `/`, is `"."` or `".."`, contains control
|
|
131
|
+
* characters, starts with the reserved `"_"` prefix, or exceeds
|
|
132
|
+
* 256 bytes.
|
|
183
133
|
*
|
|
184
134
|
* @example
|
|
185
135
|
* ```ts
|
|
@@ -223,8 +173,9 @@ declare class Db<TConfig extends BaerlyConfig = UnboundConfig> {
|
|
|
223
173
|
* `name` returns a FRESH `Collection<T>` object on each call (chain
|
|
224
174
|
* identity is intentional — modifiers return new objects).
|
|
225
175
|
*
|
|
226
|
-
* @throws BaerlyError code="InvalidConfig" when `name` is empty
|
|
227
|
-
* contains
|
|
176
|
+
* @throws BaerlyError code="InvalidConfig" when `name` is empty,
|
|
177
|
+
* contains `/`, is `"."` or `".."`, contains control characters,
|
|
178
|
+
* starts with the reserved `"_"` prefix, or exceeds 256 bytes.
|
|
228
179
|
*
|
|
229
180
|
* @example
|
|
230
181
|
* ```ts
|
|
@@ -250,54 +201,12 @@ declare class Db<TConfig extends BaerlyConfig = UnboundConfig> {
|
|
|
250
201
|
*
|
|
251
202
|
* Runs the same `name`-validation guard as {@link Db.collection}.
|
|
252
203
|
*
|
|
253
|
-
* @throws BaerlyError code="InvalidConfig" when `name` is empty
|
|
254
|
-
* contains
|
|
204
|
+
* @throws BaerlyError code="InvalidConfig" when `name` is empty,
|
|
205
|
+
* contains `/`, is `"."` or `".."`, contains control characters,
|
|
206
|
+
* starts with the reserved `"_"` prefix, or exceeds 256 bytes.
|
|
255
207
|
* @internal
|
|
256
208
|
*/
|
|
257
209
|
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
210
|
/**
|
|
302
211
|
* Read + parse this `Db`'s `manifests/<collection>/current.json`. Returns
|
|
303
212
|
* `null` when the collection has not been provisioned yet (no
|
|
@@ -317,7 +226,7 @@ declare class Db<TConfig extends BaerlyConfig = UnboundConfig> {
|
|
|
317
226
|
}): Promise<CurrentJsonRead | null>;
|
|
318
227
|
/**
|
|
319
228
|
* Read + parse one `LogEntry` by `seq` from
|
|
320
|
-
* `manifests/<collection
|
|
229
|
+
* `manifests/<collection>/log/<seq>.json`. Returns `null`
|
|
321
230
|
* when the entry is missing — this typically means the GC sweeper
|
|
322
231
|
* deleted the entry between a `readCurrentJson` and this GET (the
|
|
323
232
|
* `/v1/since` handler treats the race as silent and skips the
|
|
@@ -330,7 +239,16 @@ declare class Db<TConfig extends BaerlyConfig = UnboundConfig> {
|
|
|
330
239
|
getLogEntry(collection: string, seq: number, opts?: {
|
|
331
240
|
signal?: AbortSignal;
|
|
332
241
|
}): Promise<LogEntry | null>;
|
|
242
|
+
/**
|
|
243
|
+
* Forward-probe the TRUE committed log tail from `hint` (a lower
|
|
244
|
+
* bound, typically `tail_hint`). Backs the `/v1/since` end-bound.
|
|
245
|
+
*
|
|
246
|
+
* @internal — typed seam for the HTTP handler.
|
|
247
|
+
*/
|
|
248
|
+
probeLogTail(collection: string, hint: number, opts?: {
|
|
249
|
+
signal?: AbortSignal;
|
|
250
|
+
}): Promise<number>;
|
|
333
251
|
}
|
|
334
252
|
//#endregion
|
|
335
253
|
export { validateOrThrow as n, Db as t };
|
|
336
|
-
//# sourceMappingURL=db-
|
|
254
|
+
//# sourceMappingURL=db-CCT6tDfY.d.ts.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as loadAppConfig } from "./config-
|
|
1
|
+
import { t as loadAppConfig } from "./config-CGyBopy3.js";
|
|
2
|
+
import { t as deployCloudflare } from "./cloudflare-Cn2ibODt.js";
|
|
2
3
|
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
4
|
//#region src/deploy.ts
|
|
5
5
|
/**
|
|
6
6
|
* `baerly deploy` — citty dispatcher.
|
|
@@ -28,11 +28,18 @@ const DEPLOY_ARGS = {
|
|
|
28
28
|
json: {
|
|
29
29
|
type: "boolean",
|
|
30
30
|
description: "Emit a structured JSON envelope to stdout (success) or stderr (error)"
|
|
31
|
+
},
|
|
32
|
+
probeBucket: {
|
|
33
|
+
type: "string",
|
|
34
|
+
description: "Run a live CAS preflight against this bucket URI before deploying (s3://, file:///, memory://); aborts non-zero if the backend fails the conditional-write / exactly-one-winner probe. Same check as `baerly doctor --bucket`.",
|
|
35
|
+
valueHint: "s3://bucket/prefix"
|
|
31
36
|
}
|
|
32
37
|
};
|
|
33
38
|
const KNOWN_KEYS = new Set([
|
|
34
39
|
"target",
|
|
35
40
|
"json",
|
|
41
|
+
"probeBucket",
|
|
42
|
+
"probe-bucket",
|
|
36
43
|
"_"
|
|
37
44
|
]);
|
|
38
45
|
const errorToExitCode = (code) => {
|
|
@@ -47,7 +54,7 @@ const handleDeploy = async (args) => {
|
|
|
47
54
|
const config = await loadAppConfig();
|
|
48
55
|
const target = args.target ?? config.target;
|
|
49
56
|
if (target === "cloudflare") {
|
|
50
|
-
const exit = await deployCloudflare(config);
|
|
57
|
+
const exit = await deployCloudflare(config, { probeBucketUri: typeof args.probeBucket === "string" && args.probeBucket.length > 0 ? args.probeBucket : void 0 });
|
|
51
58
|
if (exit === 0) emitSuccess({
|
|
52
59
|
command: "deploy",
|
|
53
60
|
status: "ok",
|
|
@@ -80,4 +87,4 @@ const deploy = defineCommand({
|
|
|
80
87
|
//#endregion
|
|
81
88
|
export { deploy };
|
|
82
89
|
|
|
83
|
-
//# sourceMappingURL=deploy-
|
|
90
|
+
//# sourceMappingURL=deploy-BKKyGlSJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deploy-BKKyGlSJ.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 probeBucket: {\n type: \"string\",\n description:\n \"Run a live CAS preflight against this bucket URI before deploying (s3://, file:///, memory://); aborts non-zero if the backend fails the conditional-write / exactly-one-winner probe. Same check as `baerly doctor --bucket`.\",\n valueHint: \"s3://bucket/prefix\",\n },\n} as const satisfies ArgsDef;\n\nconst KNOWN_KEYS: ReadonlySet<string> = new Set([\n \"target\",\n \"json\",\n \"probeBucket\",\n \"probe-bucket\",\n \"_\",\n]);\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 probeBucketUri =\n typeof args.probeBucket === \"string\" && args.probeBucket.length > 0\n ? args.probeBucket\n : undefined;\n const exit = await deployCloudflare(config, { probeBucketUri });\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;CACA,aAAa;EACX,MAAM;EACN,aACE;EACF,WAAW;CACb;AACF;AAEA,MAAM,aAAkC,IAAI,IAAI;CAC9C;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,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;GAK3B,MAAM,OAAO,MAAM,iBAAiB,QAAQ,EAAE,gBAH5C,OAAO,KAAK,gBAAgB,YAAY,KAAK,YAAY,SAAS,IAC9D,KAAK,cACL,KAAA,EACuD,CAAC;GAC9D,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"}
|
package/dist/dev-vite.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as BaerlyAppConfig } from "./app-config-
|
|
2
|
-
import { r as Verifier } from "./index-
|
|
1
|
+
import { n as BaerlyAppConfig } from "./app-config-BIzyAKzy.js";
|
|
2
|
+
import { r as Verifier } from "./index-DW7GT6M2.js";
|
|
3
3
|
import { t as DevBannerHint } from "./dev-banner-CWHIk8tH.js";
|
|
4
|
-
import { t as Db } from "./db-
|
|
4
|
+
import { t as Db } from "./db-CCT6tDfY.js";
|
|
5
5
|
import { Plugin } from "vite";
|
|
6
6
|
|
|
7
7
|
//#region packages/dev/src/vite-plugin.d.ts
|
|
@@ -76,8 +76,8 @@ interface BaerlyDevAuthOptions {
|
|
|
76
76
|
* default `prefix` also covers `/api/*` because that's the canonical
|
|
77
77
|
* namespace for the "wrap `baerly.fetch!`" recipe (a server-side
|
|
78
78
|
* endpoint the SPA client can't run on its own, e.g. an endpoint
|
|
79
|
-
* that
|
|
80
|
-
* namespace, override:
|
|
79
|
+
* that fans a write across several documents server-side). If you
|
|
80
|
+
* mount under a different namespace, override:
|
|
81
81
|
*
|
|
82
82
|
* ```ts
|
|
83
83
|
* baerlyDevAuth({ secret, prefix: ["/v1", "/internal"] });
|
package/dist/dev-vite.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { n as resolveVerifier, t as Db } from "./src-
|
|
2
|
-
import { i as printDevBanner, n as ensureTable, t as LocalFsStorage } from "./src-
|
|
3
|
-
import { n as getRequestListener, t as baerlyNode } from "./src-
|
|
1
|
+
import { n as resolveVerifier, t as Db } from "./src-Db4-qVtM.js";
|
|
2
|
+
import { i as printDevBanner, n as ensureTable, t as LocalFsStorage } from "./src-CWpkSbvJ.js";
|
|
3
|
+
import { n as getRequestListener, t as baerlyNode } from "./src-D24wDpzR.js";
|
|
4
4
|
import { existsSync, readFileSync } from "node:fs";
|
|
5
5
|
//#region packages/dev/src/vite-plugin.ts
|
|
6
6
|
const isV1Path = (url) => url === "/v1" || url.startsWith("/v1/") || url.startsWith("/v1?");
|
|
@@ -49,8 +49,8 @@ const matchesAnyPrefix = (url, prefixes) => {
|
|
|
49
49
|
* default `prefix` also covers `/api/*` because that's the canonical
|
|
50
50
|
* namespace for the "wrap `baerly.fetch!`" recipe (a server-side
|
|
51
51
|
* endpoint the SPA client can't run on its own, e.g. an endpoint
|
|
52
|
-
* that
|
|
53
|
-
* namespace, override:
|
|
52
|
+
* that fans a write across several documents server-side). If you
|
|
53
|
+
* mount under a different namespace, override:
|
|
54
54
|
*
|
|
55
55
|
* ```ts
|
|
56
56
|
* baerlyDevAuth({ secret, prefix: ["/v1", "/internal"] });
|
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 { 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 /** Absolute path to the data directory for LocalFsStorage. */\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 needs `db.transaction(...)`). If you mount under a different\n * 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({ root: opts.dataDir });\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":";;;;;AAoDA,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,GAAI,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,IAAI,OAA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AO;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 { 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 /** Absolute path to the data directory for LocalFsStorage. */\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({ root: opts.dataDir });\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":";;;;;AAoDA,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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H,MAAM,OAAO,UAAmB;IAC9B,QAAQ,MAAM,8BAA8B,KAAK;GACnD,CAAC;GAED,OAAO,YAAY,KAAK,KAAK,KAAK,SAAS;IACzC,MAAM,MAAM,IAAI;IAChB,IAAI,QAAQ,KAAA,KAAa,CAAC,SAAS,GAAG,GAAG;KACvC,KAAK;KACL;IACF;IAOA,IAAI,uBAAuB,KAAA,GACzB,0BAA0B,KAAK,UAAU,oBAAoB;IAE/D,MAAM,MACH,aAAa;KACZ,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,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"}
|
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-DnBGSeuU.js";
|
|
3
3
|
export { type DevBannerHint, type DevBannerOpts, type DevLandingOptions, LocalFsStorage, LocalFsStorageOptions, ensureTable, printDevBanner, renderDevLanding };
|
package/dist/dev.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as printDevBanner, n as ensureTable, r as renderDevLanding, t as LocalFsStorage } from "./src-
|
|
1
|
+
import { i as printDevBanner, n as ensureTable, r as renderDevLanding, t as LocalFsStorage } from "./src-CWpkSbvJ.js";
|
|
2
2
|
export { LocalFsStorage, ensureTable, printDevBanner, renderDevLanding };
|
|
@@ -1,129 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as
|
|
1
|
+
import { g as SHARED_SECRET_MISSING_MESSAGE, r as parseBucketUri, t as loadAppConfig } from "./config-CGyBopy3.js";
|
|
2
|
+
import { a as defaultRunner, i as parse, n as ensureBindings, o as doctorCas, r as parseR2Bindings } from "./cloudflare-Cn2ibODt.js";
|
|
3
3
|
import { i as isJsonMode, o as BaerlyError, t as color } from "./baerly.js";
|
|
4
|
-
import {
|
|
4
|
+
import { n as defineBaerlySubcommand } from "./subcommand-CP9NY2J4.js";
|
|
5
5
|
import { resolve } from "node:path";
|
|
6
6
|
import { existsSync, readFileSync } from "node:fs";
|
|
7
|
-
//#region ../protocol/src/storage/probe-cas.ts
|
|
8
|
-
const isConflict = (error) => error instanceof BaerlyError && error.code === "Conflict";
|
|
9
|
-
/**
|
|
10
|
-
* Runtime probe that a live `Storage` backend honours the conditional
|
|
11
|
-
* writes the protocol depends on. The storage conformance suite asserts
|
|
12
|
-
* the same semantics in CI for every shipped adapter, but a deployment
|
|
13
|
-
* may point baerly at an arbitrary S3-compatible store; a backend that
|
|
14
|
-
* silently *ignores* `If-Match` (returns 200 instead of rejecting a
|
|
15
|
-
* stale write) causes silent lost-update corruption — every commit
|
|
16
|
-
* CAS-advances `current.json`, and the no-lease maintenance fold relies
|
|
17
|
-
* on the same fence. This is the fail-loud, deploy-time analogue of the
|
|
18
|
-
* conformance CAS block.
|
|
19
|
-
*
|
|
20
|
-
* Writes a single throwaway sentinel under `keyPrefix` and deletes it on
|
|
21
|
-
* the way out (even on failure). Two checks, mirroring the conformance
|
|
22
|
-
* suite:
|
|
23
|
-
* - `ifMatch-stale`: a PUT with a stale `ifMatch` must reject (Conflict).
|
|
24
|
-
* - `ifNoneMatch-exists`: a PUT with `ifNoneMatch:"*"` over an existing
|
|
25
|
-
* key must reject (Conflict).
|
|
26
|
-
*
|
|
27
|
-
* A rejected write surfaces as a `BaerlyError` with `code === "Conflict"`
|
|
28
|
-
* (the contract `Storage.put` documents); anything else — a resolved
|
|
29
|
-
* promise, or a non-Conflict error — means the backend does not honour
|
|
30
|
-
* the condition and is reported as a failed check rather than thrown.
|
|
31
|
-
*/
|
|
32
|
-
const probeCas = async (storage, opts) => {
|
|
33
|
-
const key = `${opts?.keyPrefix ?? ""}__baerly_cas_probe__/${uuid()}`;
|
|
34
|
-
const enc = new TextEncoder();
|
|
35
|
-
const signal = opts?.signal;
|
|
36
|
-
const checks = [];
|
|
37
|
-
try {
|
|
38
|
-
await storage.put(key, enc.encode("v1"), { signal });
|
|
39
|
-
try {
|
|
40
|
-
await storage.put(key, enc.encode("v2"), {
|
|
41
|
-
ifMatch: "\"baerly-cas-probe-stale\"",
|
|
42
|
-
signal
|
|
43
|
-
});
|
|
44
|
-
checks.push({
|
|
45
|
-
name: "ifMatch-stale",
|
|
46
|
-
ok: false,
|
|
47
|
-
detail: "PUT with a stale If-Match was ACCEPTED — backend ignores If-Match (silent lost-update risk)."
|
|
48
|
-
});
|
|
49
|
-
} catch (error) {
|
|
50
|
-
checks.push(isConflict(error) ? {
|
|
51
|
-
name: "ifMatch-stale",
|
|
52
|
-
ok: true,
|
|
53
|
-
detail: "stale If-Match rejected (Conflict), as required."
|
|
54
|
-
} : {
|
|
55
|
-
name: "ifMatch-stale",
|
|
56
|
-
ok: false,
|
|
57
|
-
detail: `stale If-Match raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
try {
|
|
61
|
-
await storage.put(key, enc.encode("v3"), {
|
|
62
|
-
ifNoneMatch: "*",
|
|
63
|
-
signal
|
|
64
|
-
});
|
|
65
|
-
checks.push({
|
|
66
|
-
name: "ifNoneMatch-exists",
|
|
67
|
-
ok: false,
|
|
68
|
-
detail: "PUT with If-None-Match:\"*\" over an existing key was ACCEPTED — backend ignores If-None-Match (create-only writes unsafe)."
|
|
69
|
-
});
|
|
70
|
-
} catch (error) {
|
|
71
|
-
checks.push(isConflict(error) ? {
|
|
72
|
-
name: "ifNoneMatch-exists",
|
|
73
|
-
ok: true,
|
|
74
|
-
detail: "If-None-Match:\"*\" over an existing key rejected (Conflict), as required."
|
|
75
|
-
} : {
|
|
76
|
-
name: "ifNoneMatch-exists",
|
|
77
|
-
ok: false,
|
|
78
|
-
detail: `If-None-Match:"*" raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
} finally {
|
|
82
|
-
try {
|
|
83
|
-
await storage.delete(key, signal === void 0 ? void 0 : { signal });
|
|
84
|
-
} catch {}
|
|
85
|
-
}
|
|
86
|
-
return {
|
|
87
|
-
ok: checks.every((c) => c.ok),
|
|
88
|
-
checks
|
|
89
|
-
};
|
|
90
|
-
};
|
|
91
|
-
//#endregion
|
|
92
|
-
//#region src/doctor/cas.ts
|
|
93
|
-
/**
|
|
94
|
-
* `baerly doctor --bucket <uri>` — live backend CAS probe.
|
|
95
|
-
*
|
|
96
|
-
* Unlike the cloudflare deploy-invariant walk (which only inspects
|
|
97
|
-
* config files), this mode connects to a real bucket and verifies it
|
|
98
|
-
* honours the conditional writes the protocol depends on: every commit
|
|
99
|
-
* CAS-advances `current.json` with `If-Match`, and the no-lease
|
|
100
|
-
* maintenance fold relies on the same fence. A store that silently
|
|
101
|
-
* ignores `If-Match` (returns 200 instead of rejecting a stale write)
|
|
102
|
-
* causes silent lost-update corruption — this is the fail-loud,
|
|
103
|
-
* deploy-time analogue of the conformance CAS block.
|
|
104
|
-
*
|
|
105
|
-
* Writes a single throwaway sentinel and deletes it; see
|
|
106
|
-
* {@link probeCas}.
|
|
107
|
-
*/
|
|
108
|
-
const CAS_FIX = "Point baerly at an S3-compatible store that honours conditional writes (If-Match + If-None-Match). Real AWS S3, Cloudflare R2, and GCS do; a custom gateway / proxy may be stripping conditional headers — check it returns 412 on a stale If-Match.";
|
|
109
|
-
/**
|
|
110
|
-
* Run the live CAS round-trip against `storage` and shape the result
|
|
111
|
-
* as a {@link DoctorReport}. Status is `error` iff any sub-check failed
|
|
112
|
-
* (a non-conformant backend is a hard blocker, not a warning).
|
|
113
|
-
*/
|
|
114
|
-
const doctorCas = async (storage, keyPrefix) => {
|
|
115
|
-
const result = await probeCas(storage, { keyPrefix });
|
|
116
|
-
return {
|
|
117
|
-
findings: result.checks.map((c) => ({
|
|
118
|
-
severity: c.ok ? "ok" : "error",
|
|
119
|
-
check: `cas-${c.name}`,
|
|
120
|
-
message: c.detail,
|
|
121
|
-
...c.ok ? {} : { fix: CAS_FIX }
|
|
122
|
-
})),
|
|
123
|
-
status: result.ok ? "ok" : "error"
|
|
124
|
-
};
|
|
125
|
-
};
|
|
126
|
-
//#endregion
|
|
127
7
|
//#region src/doctor/cloudflare.ts
|
|
128
8
|
/**
|
|
129
9
|
* `baerly doctor --target=cloudflare` — walks the Cloudflare
|
|
@@ -140,8 +20,9 @@ const doctorCas = async (storage, keyPrefix) => {
|
|
|
140
20
|
* 4. If `cloudflareAccess` is set in `baerly.config.ts`,
|
|
141
21
|
* `audienceTag` is 64 lowercase-hex chars and `teamDomain`
|
|
142
22
|
* is non-empty.
|
|
143
|
-
* 5.
|
|
144
|
-
*
|
|
23
|
+
* 5. Report `triggers.crons` as optional. In-band write-triggered
|
|
24
|
+
* maintenance is the default; cron only drives an explicit
|
|
25
|
+
* `runScheduledMaintenance` sweep when the operator opts in.
|
|
145
26
|
* 6. If `baerly.config.ts:domain` is set but `wrangler.jsonc`
|
|
146
27
|
* doesn't declare a matching `routes` entry, warn.
|
|
147
28
|
*
|
|
@@ -159,7 +40,8 @@ const rollupStatus = (findings) => {
|
|
|
159
40
|
};
|
|
160
41
|
/**
|
|
161
42
|
* Read the declared cron schedule from `wrangler.jsonc`. Returns
|
|
162
|
-
* `[]` when missing — caller treats empty as
|
|
43
|
+
* `[]` when missing — caller treats empty as ok; in-band
|
|
44
|
+
* write-triggered maintenance is the default and needs no cron.
|
|
163
45
|
*/
|
|
164
46
|
const readDeclaredCrons = (wranglerPath) => {
|
|
165
47
|
const text = readFileSync(wranglerPath, "utf8");
|
|
@@ -342,15 +224,14 @@ const doctorCloudflare = async (config, opts = {}) => {
|
|
|
342
224
|
}
|
|
343
225
|
const crons = readDeclaredCrons(wranglerPath);
|
|
344
226
|
if (crons.length === 0) findings.push({
|
|
345
|
-
severity: "
|
|
227
|
+
severity: "ok",
|
|
346
228
|
check: "triggers.crons",
|
|
347
|
-
message: "no cron triggers declared;
|
|
348
|
-
fix: `Add "triggers": { "crons": ["* * * * *"] } to ${wranglerPath}.`
|
|
229
|
+
message: "no cron triggers declared; in-band write-triggered maintenance is the default."
|
|
349
230
|
});
|
|
350
231
|
else findings.push({
|
|
351
|
-
severity: "
|
|
232
|
+
severity: "info",
|
|
352
233
|
check: "triggers.crons",
|
|
353
|
-
message: `cron trigger${crons.length === 1 ? "" : "s"} ${crons.map((c) => JSON.stringify(c)).join(", ")} declared.`
|
|
234
|
+
message: `cron trigger${crons.length === 1 ? "" : "s"} ${crons.map((c) => JSON.stringify(c)).join(", ")} declared for opt-in scheduled maintenance; write-triggered maintenance still runs by default.`
|
|
354
235
|
});
|
|
355
236
|
if (config.domain !== void 0 && config.domain.length > 0) {
|
|
356
237
|
const patterns = readDeclaredRoutePatterns(wranglerPath);
|
|
@@ -465,4 +346,4 @@ bundle.run;
|
|
|
465
346
|
//#endregion
|
|
466
347
|
export { doctor };
|
|
467
348
|
|
|
468
|
-
//# sourceMappingURL=doctor-
|
|
349
|
+
//# sourceMappingURL=doctor-BVU4GNXN.js.map
|