@gusto/baerly-storage 0.2.0 → 0.4.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 (155) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/README.md +176 -70
  4. package/dist/API.md +213 -139
  5. package/dist/CHANGELOG.md +434 -0
  6. package/dist/RECIPES.md +125 -0
  7. package/dist/THIRD-PARTY-LICENSES.txt +238 -0
  8. package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-DyiFK3_k.d.ts} +55 -11
  9. package/dist/app-config.d.ts +1 -1
  10. package/dist/auth.d.ts +1 -1
  11. package/dist/auth.js +301 -301
  12. package/dist/auth.js.map +1 -1
  13. package/dist/aws4fetch.esm-p7eEzLCs.js +1702 -0
  14. package/dist/aws4fetch.esm-p7eEzLCs.js.map +1 -0
  15. package/dist/baerly.js +35 -15
  16. package/dist/baerly.js.map +1 -1
  17. package/dist/baerly.spec.json +342 -0
  18. package/dist/bytes-BXdamO3L.js.map +1 -1
  19. package/dist/{client-DYZfoZb9.d.ts → client-Fe8CwB73.d.ts} +10 -10
  20. package/dist/client-react.d.ts +3 -3
  21. package/dist/client-react.js +4 -4
  22. package/dist/client-react.js.map +1 -1
  23. package/dist/client.d.ts +4 -4
  24. package/dist/client.js +3 -3
  25. package/dist/client.js.map +1 -1
  26. package/dist/{cloudflare-CINJPKCW.js → cloudflare-DzKBrUlg.js} +178 -2
  27. package/dist/cloudflare-DzKBrUlg.js.map +1 -0
  28. package/dist/cloudflare.d.ts +49 -6
  29. package/dist/cloudflare.js +59 -26
  30. package/dist/cloudflare.js.map +1 -1
  31. package/dist/config-1tv0-Yzm.js +2693 -0
  32. package/dist/config-1tv0-Yzm.js.map +1 -0
  33. package/dist/constants-CfeMWQWk.js +222 -0
  34. package/dist/constants-CfeMWQWk.js.map +1 -0
  35. package/dist/context-DRZ3tZ5l.js.map +1 -1
  36. package/dist/{cost-CQt1YRkA.js → cost-DSMIVqzL.js} +43 -42
  37. package/dist/cost-DSMIVqzL.js.map +1 -0
  38. package/dist/current-json-C6nhPOm1.js +190 -0
  39. package/dist/current-json-C6nhPOm1.js.map +1 -0
  40. package/dist/{db-BM3y2JQw.d.ts → db-DsPkOVEH.d.ts} +26 -108
  41. package/dist/{deploy-CrAbfgCq.js → deploy-DonTr-CV.js} +12 -5
  42. package/dist/deploy-DonTr-CV.js.map +1 -0
  43. package/dist/dev-vite.d.ts +11 -7
  44. package/dist/dev-vite.js +7 -6
  45. package/dist/dev-vite.js.map +1 -1
  46. package/dist/dev.d.ts +1 -1
  47. package/dist/dev.js +1 -1
  48. package/dist/{doctor-Db-hzPmE.js → doctor-DSIyCDg_.js} +14 -136
  49. package/dist/doctor-DSIyCDg_.js.map +1 -0
  50. package/dist/{dump-BYA55NLP.js → dump-Bh5k26VQ.js} +10 -31
  51. package/dist/dump-Bh5k26VQ.js.map +1 -0
  52. package/dist/{errors-DOdL95kK.js → errors-Dfa3p78c.js} +25 -5
  53. package/dist/errors-Dfa3p78c.js.map +1 -0
  54. package/dist/{export-Bhbz90-z.js → export-DtF5tDIM.js} +11 -32
  55. package/dist/{export-Bhbz90-z.js.map → export-DtF5tDIM.js.map} +1 -1
  56. package/dist/{fsck-CPPZWt9p.js → fsck-D_djMO5D.js} +28 -39
  57. package/dist/fsck-D_djMO5D.js.map +1 -0
  58. package/dist/{http-Cw8p6y5b.js → http-DxM9MflO.js} +151 -79
  59. package/dist/http-DxM9MflO.js.map +1 -0
  60. package/dist/http.d.ts +42 -26
  61. package/dist/http.js +3 -2
  62. package/dist/{index-DwDTWPSU.d.ts → index-0rZcMBwy.d.ts} +10 -7
  63. package/dist/{index-C3JAH1Yo.d.ts → index-B6oexfOB.d.ts} +9 -9
  64. package/dist/{index-cUY-36AN.d.ts → index-BNRh23K9.d.ts} +21 -5
  65. package/dist/{index-DSvwEUeF.d.ts → index-BYk9oCNf.d.ts} +240 -202
  66. package/dist/index.d.ts +6 -6
  67. package/dist/index.js +5 -5
  68. package/dist/{indexes-DAu2AkTW.d.ts → indexes-Dn9hbGQG.d.ts} +2 -2
  69. package/dist/{inspect-Bdbzvi-_.js → inspect-6WZ-pC7-.js} +21 -36
  70. package/dist/inspect-6WZ-pC7-.js.map +1 -0
  71. package/dist/key-Di6yyxFu.js +35 -0
  72. package/dist/key-Di6yyxFu.js.map +1 -0
  73. package/dist/{snapshot-SS8USDUF.js → log-tail-D98U1JBo.js} +179 -84
  74. package/dist/log-tail-D98U1JBo.js.map +1 -0
  75. package/dist/{maintenance-ClzBC1Vv.js → maintenance-B4Dki6Ig.js} +438 -176
  76. package/dist/maintenance-B4Dki6Ig.js.map +1 -0
  77. package/dist/{maintenance-BRrThz8V.d.ts → maintenance-B_e0T99L.d.ts} +114 -26
  78. package/dist/{maintenance-BvOv6BMM.js → maintenance-C7coQp4c.js} +217 -94
  79. package/dist/maintenance-C7coQp4c.js.map +1 -0
  80. package/dist/maintenance.d.ts +3 -2
  81. package/dist/maintenance.js +3 -2
  82. package/dist/node.d.ts +176 -68
  83. package/dist/node.js +3 -2
  84. package/dist/{normalize-XWY25_sG.js → normalize-rjnZLwS4.js} +2 -2
  85. package/dist/normalize-rjnZLwS4.js.map +1 -0
  86. package/dist/{observability-CpOiEN0k.js → observability-wzs3-BL_.js} +279 -109
  87. package/dist/observability-wzs3-BL_.js.map +1 -0
  88. package/dist/observability.d.ts +3 -3
  89. package/dist/observability.js +1 -1
  90. package/dist/{plan-DOTl21vq.js → plan-a7PJHBCy.js} +7 -4
  91. package/dist/plan-a7PJHBCy.js.map +1 -0
  92. package/dist/{query-BmiQy328.js → query-rAtXNQQB.js} +1063 -1202
  93. package/dist/query-rAtXNQQB.js.map +1 -0
  94. package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-BVzQSZlm.js} +10 -32
  95. package/dist/rebuild-index-BVzQSZlm.js.map +1 -0
  96. package/dist/{request-BEF_OvMh.js → request-u0M51mhJ.js} +3 -3
  97. package/dist/{request-BEF_OvMh.js.map → request-u0M51mhJ.js.map} +1 -1
  98. package/dist/restore-R-4rbciV.js +778 -0
  99. package/dist/restore-R-4rbciV.js.map +1 -0
  100. package/dist/runtime-spec-qL3_lTTU.js +391 -0
  101. package/dist/runtime-spec-qL3_lTTU.js.map +1 -0
  102. package/dist/s3-http-B-z8th6O.d.ts +60 -0
  103. package/dist/s3.d.ts +47 -0
  104. package/dist/s3.js +45 -0
  105. package/dist/s3.js.map +1 -0
  106. package/dist/{shared-secret-BJdSwpgw.js → shared-secret-DgEicd3x.js} +13 -5
  107. package/dist/shared-secret-DgEicd3x.js.map +1 -0
  108. package/dist/src-BG20LZs7.js +2271 -0
  109. package/dist/src-BG20LZs7.js.map +1 -0
  110. package/dist/{src-zhEAmmF7.js → src-CYHFDrKz.js} +82 -99
  111. package/dist/src-CYHFDrKz.js.map +1 -0
  112. package/dist/{src-QQ7jDeL2.js → src-DYZ4H1aF.js} +44 -23
  113. package/dist/src-DYZ4H1aF.js.map +1 -0
  114. package/dist/subcommand-DoDA-K7d.js +197 -0
  115. package/dist/subcommand-DoDA-K7d.js.map +1 -0
  116. package/dist/time-DUqvFMHq.js +119 -0
  117. package/dist/time-DUqvFMHq.js.map +1 -0
  118. package/dist/{usage-CLjirdD-.js → usage-DBV1eQHC.js} +7 -22
  119. package/dist/usage-DBV1eQHC.js.map +1 -0
  120. package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
  121. package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
  122. package/dist/wire-izfGZDvr.js.map +1 -1
  123. package/package.json +77 -42
  124. package/dist/cloudflare-CINJPKCW.js.map +0 -1
  125. package/dist/config-DVfDGyw1.js +0 -278
  126. package/dist/config-DVfDGyw1.js.map +0 -1
  127. package/dist/cost-CQt1YRkA.js.map +0 -1
  128. package/dist/current-json-C-EyJqs0.js +0 -354
  129. package/dist/current-json-C-EyJqs0.js.map +0 -1
  130. package/dist/deploy-CrAbfgCq.js.map +0 -1
  131. package/dist/doctor-Db-hzPmE.js.map +0 -1
  132. package/dist/dump-BYA55NLP.js.map +0 -1
  133. package/dist/errors-DOdL95kK.js.map +0 -1
  134. package/dist/fsck-CPPZWt9p.js.map +0 -1
  135. package/dist/http-Cw8p6y5b.js.map +0 -1
  136. package/dist/inspect-Bdbzvi-_.js.map +0 -1
  137. package/dist/maintenance-BvOv6BMM.js.map +0 -1
  138. package/dist/maintenance-ClzBC1Vv.js.map +0 -1
  139. package/dist/normalize-XWY25_sG.js.map +0 -1
  140. package/dist/observability-CpOiEN0k.js.map +0 -1
  141. package/dist/plan-DOTl21vq.js.map +0 -1
  142. package/dist/query-BmiQy328.js.map +0 -1
  143. package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
  144. package/dist/restore-C6IcmLeA.js +0 -771
  145. package/dist/restore-C6IcmLeA.js.map +0 -1
  146. package/dist/shared-secret-BJdSwpgw.js.map +0 -1
  147. package/dist/snapshot-SS8USDUF.js.map +0 -1
  148. package/dist/src-DU1sCMlr.js +0 -6236
  149. package/dist/src-DU1sCMlr.js.map +0 -1
  150. package/dist/src-QQ7jDeL2.js.map +0 -1
  151. package/dist/src-zhEAmmF7.js.map +0 -1
  152. package/dist/subcommand-DZcHcsYp.js +0 -5122
  153. package/dist/subcommand-DZcHcsYp.js.map +0 -1
  154. package/dist/usage-CLjirdD-.js.map +0 -1
  155. /package/dist/{chunk-EAsCxrDo.js → rolldown-runtime-EAsCxrDo.js} +0 -0
@@ -0,0 +1,2693 @@
1
+ import { l as __commonJSMin, o as BaerlyError } from "./baerly.js";
2
+ import { createHash } from "node:crypto";
3
+ import { link, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join, posix, relative, resolve, sep } from "node:path";
6
+ import { existsSync } from "node:fs";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
8
+ //#region ../protocol/src/constants.ts
9
+ /**
10
+ * Max total object-key length S3 and R2 accept (UTF-8 bytes). A key
11
+ * over this fails the PUT with an opaque provider 400; baerly surfaces
12
+ * it early as InvalidConfig. See docs/spec/storage-compatibility.md.
13
+ */
14
+ const MAX_KEY_BYTES = 1024;
15
+ /**
16
+ * Backoff (in milliseconds) inserted between LIST attempts when S3
17
+ * returns 429 (rate-limited).
18
+ */
19
+ const RATE_LIMIT_BACKOFF_MILLIS = 1e3;
20
+ /**
21
+ * Runaway guard on the tolerant forward-probe walk (`probeTailFrom`):
22
+ * max `log/<seq>` GETs past `tail_hint` before it THROWS `Internal`
23
+ * (rather than silently truncating reads). A runaway alarm only — the
24
+ * maintenance tick keeps `tail_hint` near the tail, so a >cap gap means
25
+ * maintenance is off or the collection is far past graduation.
26
+ *
27
+ * @see packages/server/src/log-tail.ts (`probeTailFrom`)
28
+ */
29
+ const LOG_FORWARD_PROBE_CAP = 1e5;
30
+ /**
31
+ * MIME type written for `current.json` PUTs. S3 round-trips this on
32
+ * subsequent GETs; useful for diagnostics when staring at a bucket
33
+ * via the AWS console.
34
+ *
35
+ * @see packages/protocol/src/coordination/current-json.ts
36
+ */
37
+ const CURRENT_JSON_CONTENT_TYPE = "application/json";
38
+ /**
39
+ * MIME type written for `gc/pending.json` PUTs.
40
+ *
41
+ * @see packages/protocol/src/coordination/gc-pending.ts
42
+ */
43
+ const GC_PENDING_CONTENT_TYPE = "application/json";
44
+ /**
45
+ * Default grace period between "marking" a key for GC and "sweeping"
46
+ * (deleting) it. 7 days, chosen to span the worst plausible writer-
47
+ * retry window (a paused-process writer that resumes hours later
48
+ * should still find its idempotency anchor on the bucket). The
49
+ * `runGc()` function accepts an override for tests.
50
+ *
51
+ * Why 7 days specifically:
52
+ * - **1 day is too aggressive for batch workloads.** Worker isolate
53
+ * scheduling pauses, cross-region replication lag, and
54
+ * {@link RATE_LIMIT_BACKOFF_MILLIS} retry cascades can plausibly
55
+ * exceed an hour under pathological conditions.
56
+ * - **30 days is conservative beyond the worst plausible pause.**
57
+ * Doubles `gc/pending.json` size at steady state and slows
58
+ * visibility into "did GC actually run?" by 4×.
59
+ * - **7 days spans the realistic upper bound** — long-running batch
60
+ * jobs, multi-region propagation delays, queue backlogs, and
61
+ * downstream outages the writer is retrying through. The protocol
62
+ * is unaffected by the choice of value within the [hours, weeks]
63
+ * range; this constant is the operator-tunable knob.
64
+ *
65
+ * Production code MUST NOT call `runGc` with `graceMillis` below the
66
+ * default outside maintenance windows — going below the longest
67
+ * plausible writer-retry latency risks deleting an anchor a writer
68
+ * is about to find on retry. Test code that sets `graceMillis: 0` is
69
+ * exercising the sweep path deliberately, not modelling production.
70
+ *
71
+ * @see packages/server/src/gc.ts
72
+ */
73
+ const GC_GRACE_PERIOD_MILLIS = 10080 * 60 * 1e3;
74
+ /**
75
+ * Cap on candidates kept in `gc/pending.json` to bound the size of
76
+ * the file. The compactor marks at most this many candidates per
77
+ * pass; subsequent passes pick up the rest. Larger collections will
78
+ * lag GC by one pass per `GC_MAX_PENDING_CANDIDATES` orphans, which
79
+ * is acceptable.
80
+ *
81
+ * @see packages/server/src/gc.ts
82
+ */
83
+ const GC_MAX_PENDING_CANDIDATES = 1e3;
84
+ /**
85
+ * Floor for the ratio denominator — avoid div-by-tiny on a fresh collection. Also
86
+ * sets the first-fold threshold: until a snapshot exists, fold fires at tail ≈ this.
87
+ *
88
+ * @see packages/server/src/maintenance.ts
89
+ */
90
+ const MAINTENANCE_MIN_LIVE_BYTES = 64 * 1024;
91
+ /**
92
+ * SNAPSHOT-rebuild ceiling `C` (the unsliceable axis — Decision 3a), memory. Default sized
93
+ * ~5.5 ms under CF-free ~10 ms. Raise via BAERLY_MAINTENANCE_MAX_FOLD_BYTES on capable
94
+ * hosts. Auto-maintained snapshot ceiling S_max = C. NOT snapshot+tail (tail is sliced).
95
+ *
96
+ * @see docs/about/graduation.md
97
+ * @see packages/server/src/maintenance.ts
98
+ */
99
+ const MAINTENANCE_MAX_FOLD_BYTES_DEFAULT = 512 * 1024;
100
+ /**
101
+ * SNAPSHOT-rebuild ceiling `E`, per-entry CPU axis: gates `snapshot_rows` (per-entry
102
+ * parse/merge/serialize is ~half of fold CPU and scales with ROW COUNT not bytes, VLDB 2021
103
+ * Sarkar — a tiny-doc snapshot can blow CPU under C). PROVISIONAL — bench
104
+ * landed; paid recalibration deferred.
105
+ *
106
+ * @see docs/about/graduation.md
107
+ * @see packages/server/src/maintenance.ts
108
+ */
109
+ const MAINTENANCE_MAX_FOLD_ROWS = 2048;
110
+ /** CF-free profile; the absent-context default. */
111
+ const MAINTENANCE_PROFILE_CF_FREE = {
112
+ gcInterval: 4,
113
+ gcMaxMarks: 20,
114
+ gcMaxSweeps: 10,
115
+ maxFoldEntriesPerPass: 20,
116
+ maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,
117
+ maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS
118
+ };
119
+ /**
120
+ * CF-paid profile — opt-in via `BAERLY_MAINTENANCE_PROFILE=cf-paid`. A paid
121
+ * isolate keeps the CPU-killable single-phase shape but has the 10,000-
122
+ * subrequest budget (vs free's 50), so it reuses the `NODE_MAINTENANCE_*`
123
+ * per-pass caps. CRITICAL: snapshot ceilings `maxFoldBytes` (`C`) /
124
+ * `maxFoldRows` (`E`) are UNCHANGED — a profile moves rate, never correctness
125
+ * (the equivalence invariant); the memory wall is raised via
126
+ * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`.
127
+ *
128
+ * @see packages/adapter-cloudflare/src/worker.ts
129
+ * @see docs/about/graduation.md
130
+ */
131
+ const MAINTENANCE_PROFILE_CF_PAID = {
132
+ gcInterval: 2,
133
+ gcMaxMarks: 200,
134
+ gcMaxSweeps: 100,
135
+ maxFoldEntriesPerPass: 200,
136
+ maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,
137
+ maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS
138
+ };
139
+ /**
140
+ * Rate-limit the defer-warn off SHARED current.json.last_warned_seq (not per-isolate
141
+ * memory — CF recycles isolates). ~once per this many writes.
142
+ *
143
+ * @see packages/protocol/src/coordination/current-json.ts
144
+ * @see packages/server/src/maintenance.ts
145
+ */
146
+ const MAINTENANCE_WARN_INTERVAL_WRITES = 1e3;
147
+ /**
148
+ * Canonical auth posture identifiers consumed by `BaerlyAppConfig.auth`,
149
+ * the adapter resolution path (`packages/adapter-cloudflare/src/worker.ts`,
150
+ * `packages/adapter-node/src/baerly-node.ts`), and `baerly doctor`.
151
+ *
152
+ * - `"none"` — no header check; pin every request to `config.tenant`.
153
+ * For local dev, intranet, CLI tools — contexts where the network
154
+ * seam itself is the trust boundary.
155
+ * - `"shared-secret"` — bearer-token check; reads `SHARED_SECRET` from
156
+ * the runtime env and pins every request to `config.tenant`.
157
+ *
158
+ * Custom verifiers (`cloudflareAccess`, `bearerJwt`, SigV4, …) bypass
159
+ * this enum — pass a `Verifier` to the adapter factory's `verifier:`
160
+ * option instead.
161
+ */
162
+ const AUTH_CONFIG_VALUES = ["none", "shared-secret"];
163
+ /**
164
+ * Locked error wording for `auth: "shared-secret"` + missing env var.
165
+ * Same pinning rationale as {@link NO_AUTH_CONFIGURED_MESSAGE}.
166
+ */
167
+ const SHARED_SECRET_MISSING_MESSAGE = "baerly: auth=\"shared-secret\" but SHARED_SECRET env is empty/unset. Cloudflare: `wrangler secret put SHARED_SECRET`, or add to .dev.vars for local dev. Node: set in process env.";
168
+ //#endregion
169
+ //#region ../protocol/src/env.ts
170
+ const PAAS_MARKERS = [
171
+ "RAILWAY_ENVIRONMENT",
172
+ "RENDER",
173
+ "FLY_APP_NAME",
174
+ "K_SERVICE",
175
+ "DYNO",
176
+ "KUBERNETES_SERVICE_HOST",
177
+ "ECS_CONTAINER_METADATA_URI_V4"
178
+ ];
179
+ /**
180
+ * True when `env` looks like a deployed environment: `NODE_ENV=production`
181
+ * or any {@link PAAS_MARKERS} set to a non-empty value. Decides whether a
182
+ * non-durable store (in-memory, local-fs) should fail loud instead of
183
+ * silently serving a production workload. A CI runner (`CI` set to a
184
+ * non-empty, non-`false` value) is never treated as deployed, so PaaS
185
+ * markers from an in-cluster CI agent do not trip it.
186
+ */
187
+ const isDeployedEnv = (env) => {
188
+ const inCi = (env["CI"] ?? "") !== "" && env["CI"] !== "false";
189
+ return env["NODE_ENV"] === "production" || !inCi && PAAS_MARKERS.some((m) => (env[m] ?? "") !== "");
190
+ };
191
+ //#endregion
192
+ //#region ../protocol/src/storage/key.ts
193
+ /**
194
+ * Validate a raw {@link Storage} object key against the portable baerly key
195
+ * grammar before it is used to address an object. A key MUST be non-empty
196
+ * and `/`-delimited, with **no path segment equal to `.` or `..`**.
197
+ *
198
+ * The dot-segment rule is not a vendor quirk — it is a *client-side*
199
+ * universal: RFC 3986 §5.2.4 "remove dot segments" is mandatory for every
200
+ * conformant URL parser, so `<endpoint>/<bucket>/.` normalizes to
201
+ * `<endpoint>/<bucket>/` and `<endpoint>/<bucket>/..` escapes the bucket
202
+ * entirely — *before* the request is signed or sent, in TypeScript, Go,
203
+ * Rust, Python, or any language a `Storage` port is written in. Such a key
204
+ * cannot be addressed over the S3/R2 HTTP API regardless of backend; a bare
205
+ * `.` PUT surfaces as a confusing bucket-root 403 rather than a clear
206
+ * rejection. The kernel never emits such keys (caller-controlled segments
207
+ * are already screened by `assertPathSegment` one layer up), so this is the
208
+ * boundary guard that makes every adapter reject them *identically* and
209
+ * gives ports a single, testable contract.
210
+ *
211
+ * Thrown as `BaerlyError{code:"InvalidConfig"}` to match the sibling
212
+ * key/segment guards (`assertKeyWithinLimit`, `assertPathSegment`). The
213
+ * full-key 1024-byte ceiling is enforced separately on the write path
214
+ * (`assertKeyWithinLimit`), where multi-segment keys are assembled.
215
+ *
216
+ * @see docs/spec/storage-compatibility.md — "Key namespace"
217
+ */
218
+ function assertValidStorageKey(key) {
219
+ if (key.length === 0) throw new BaerlyError("InvalidConfig", "storage key must be a non-empty string");
220
+ for (const segment of key.split("/")) if (segment === "." || segment === "..") throw new BaerlyError("InvalidConfig", `storage key may not contain a "." or ".." path segment — RFC 3986 dot-segment removal makes it unaddressable over the S3/R2 HTTP API: ${JSON.stringify(key)}`);
221
+ }
222
+ //#endregion
223
+ //#region ../protocol/src/storage/memory.ts
224
+ const utf8Encoder$1 = new TextEncoder();
225
+ const EPHEMERAL_ENV_OPT_IN = "BAERLY_ALLOW_EPHEMERAL_STORAGE";
226
+ const readProcessEnv = () => globalThis.process?.env ?? {};
227
+ let warnedEphemeralInDeployment = false;
228
+ const assertEphemeralAllowed = (explicitOptIn) => {
229
+ const env = readProcessEnv();
230
+ if (!isDeployedEnv(env)) return;
231
+ if (!explicitOptIn && env[EPHEMERAL_ENV_OPT_IN] !== "true") throw new BaerlyError("InvalidConfig", `Refusing to use in-memory storage in a deployed environment — all data is lost on restart. MemoryStorage is for tests/local dev only; configure a durable bucket (AWS S3 / Cloudflare R2). To intentionally opt in: new MemoryStorage({ ephemeral: true }) or ${EPHEMERAL_ENV_OPT_IN}=true.`);
232
+ if (!warnedEphemeralInDeployment) {
233
+ warnedEphemeralInDeployment = true;
234
+ console.warn("[baerly] in-memory storage in a deployed environment — ALL DATA IS LOST ON RESTART.");
235
+ }
236
+ };
237
+ /**
238
+ * Compare two keys by their UTF-8 byte sequences — the order S3 and
239
+ * R2 use for `list`. JavaScript's default string sort compares UTF-16
240
+ * code units, which diverges from UTF-8 byte order for supplementary-
241
+ * plane characters (e.g. emoji sort before high-BMP characters under
242
+ * UTF-16 but after them in UTF-8). Using this keeps the in-memory
243
+ * reference backend faithful to the real adapters. (All kernel keys
244
+ * are ASCII base-32, where the two orders coincide — this only
245
+ * matters for adversarial / non-ASCII keys.)
246
+ */
247
+ const compareKeysUtf8$1 = (a, b) => {
248
+ const ba = utf8Encoder$1.encode(a);
249
+ const bb = utf8Encoder$1.encode(b);
250
+ const n = Math.min(ba.length, bb.length);
251
+ for (let i = 0; i < n; i++) if (ba[i] !== bb[i]) return ba[i] - bb[i];
252
+ return ba.length - bb.length;
253
+ };
254
+ /**
255
+ * In-memory `Storage`. The randomized property test runs against
256
+ * this; it must be deterministic — no clocks beyond the caller's,
257
+ * no randomness, no I/O.
258
+ *
259
+ * ETags are a monotonically increasing hex counter formatted in the
260
+ * `"<hex>"` shape S3 returns (the surrounding double-quotes are part
261
+ * of the ETag header value). Keys are stored verbatim.
262
+ *
263
+ * **Test-confidence caveat:** every method resolves on the microtask
264
+ * queue with no real concurrency, so `put` reads `existing` and writes
265
+ * back with no interleaving. MemoryStorage therefore CANNOT exercise the
266
+ * compare-and-swap race the writer-fence model depends on — two writers
267
+ * contending on one `current.json` always serialize here, so a green run
268
+ * is necessary but not sufficient. That race is covered only by the
269
+ * randomized integration tests against real S3 / Minio
270
+ * (`tests/integration/randomized.test.ts`, `node-minio` variant).
271
+ * Relatedly, `serverDate` returns the local clock, not an independent
272
+ * server clock (see the `put` return below).
273
+ */
274
+ var MemoryStorage = class {
275
+ #objects = /* @__PURE__ */ new Map();
276
+ #etagCounter = 0;
277
+ constructor(opts) {
278
+ assertEphemeralAllowed(opts?.ephemeral === true);
279
+ }
280
+ #nextEtag() {
281
+ this.#etagCounter += 1;
282
+ return `"${this.#etagCounter.toString(16)}"`;
283
+ }
284
+ async get(key, opts) {
285
+ assertValidStorageKey(key);
286
+ opts?.signal?.throwIfAborted();
287
+ const stored = this.#objects.get(key);
288
+ if (stored === void 0) return null;
289
+ if (opts?.ifNoneMatch !== void 0 && opts.ifNoneMatch === stored.etag) return null;
290
+ return {
291
+ body: stored.body,
292
+ etag: stored.etag
293
+ };
294
+ }
295
+ async put(key, body, opts) {
296
+ assertValidStorageKey(key);
297
+ opts?.signal?.throwIfAborted();
298
+ const existing = this.#objects.get(key);
299
+ if (opts?.ifNoneMatch === "*" && existing !== void 0) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifNoneMatch="*" but key exists)`);
300
+ if (opts?.ifMatch !== void 0) {
301
+ if (existing === void 0) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`);
302
+ if (existing.etag !== opts.ifMatch) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${existing.etag})`);
303
+ }
304
+ const etag = this.#nextEtag();
305
+ this.#objects.set(key, {
306
+ body,
307
+ etag,
308
+ ...opts?.contentType !== void 0 && { contentType: opts.contentType }
309
+ });
310
+ return {
311
+ etag,
312
+ serverDate: /* @__PURE__ */ new Date()
313
+ };
314
+ }
315
+ async delete(key, opts) {
316
+ assertValidStorageKey(key);
317
+ opts?.signal?.throwIfAborted();
318
+ this.#objects.delete(key);
319
+ }
320
+ async *list(prefix, opts) {
321
+ opts?.signal?.throwIfAborted();
322
+ const startAfter = opts?.startAfter ?? "";
323
+ const maxKeys = opts?.maxKeys ?? Infinity;
324
+ const sorted = [...this.#objects.keys()].filter((k) => k.startsWith(prefix) && compareKeysUtf8$1(k, startAfter) > 0).toSorted(compareKeysUtf8$1);
325
+ let yielded = 0;
326
+ for (const key of sorted) {
327
+ if (yielded >= maxKeys) return;
328
+ opts?.signal?.throwIfAborted();
329
+ const stored = this.#objects.get(key);
330
+ if (stored === void 0) continue;
331
+ yield {
332
+ key,
333
+ etag: stored.etag
334
+ };
335
+ yielded += 1;
336
+ }
337
+ }
338
+ /**
339
+ * Test-only: drop all objects.
340
+ * @internal
341
+ */
342
+ _clear() {
343
+ this.#objects.clear();
344
+ this.#etagCounter = 0;
345
+ }
346
+ };
347
+ const sharedPerBucket = /* @__PURE__ */ new Map();
348
+ /**
349
+ * Get the process-singleton {@link MemoryStorage} for the named
350
+ * bucket, creating one on first access. Use this when constructing
351
+ * a `Storage` directly so multiple consumers in the same process
352
+ * see each other's writes for the same bucket name.
353
+ */
354
+ const getOrCreateMemoryStorageForBucket = (bucket) => {
355
+ let s = sharedPerBucket.get(bucket);
356
+ if (s === void 0) {
357
+ s = new MemoryStorage();
358
+ sharedPerBucket.set(bucket, s);
359
+ }
360
+ return s;
361
+ };
362
+ //#endregion
363
+ //#region ../protocol/src/types.ts
364
+ /**
365
+ * Mint a fresh {@link UUID}. The cast lives here so callers don't sprinkle
366
+ * `<UUID>crypto.randomUUID()` throughout the codebase.
367
+ */
368
+ const uuid = () => crypto.randomUUID();
369
+ /**
370
+ * Mint the trailing seq segment of an LSN (`<base32-time>_<sess>_<seq>`).
371
+ * Uses `COUNT_BIT_WIDTH` (see `packages/protocol/src/constants.ts`) to
372
+ * produce an 11-char descending base-32 string with a domain of
373
+ * 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1).
374
+ *
375
+ * Used together with {@link timestamp} (the descending base-32
376
+ * encoding of millis-since-epoch). See {@link uint2strDesc} for the
377
+ * lex-reversal property both rely on.
378
+ */
379
+ const countKey = (number) => uint2strDesc(number, 53);
380
+ const uint2str = (num, bits) => {
381
+ const maxBase32Length = Math.ceil(bits / 5);
382
+ return num.toString(32).padStart(maxBase32Length, "0");
383
+ };
384
+ /**
385
+ * Lex-reversed base-32 encoder for an unsigned integer in `[0, 2^bits)`.
386
+ * Pads to `Math.ceil(bits/5)` chars so all values in the domain compare
387
+ * lex against each other.
388
+ *
389
+ * **Order-reversal property:** for any pair of integers `a < b` (with
390
+ * `a, b ∈ [0, 2^bits)`), `uint2strDesc(a, bits) > uint2strDesc(b, bits)`
391
+ * lexicographically. Composed into an LSN of shape
392
+ * `<base32-time>_<session>_<seq>` (where both `<base32-time>` and
393
+ * `<seq>` use this encoder), a forward `Storage.list(prefix)`
394
+ * returns log entries in reverse-causal order — newer entries first.
395
+ *
396
+ * This is the structural property the read path leans on:
397
+ * `ListObjectsV2` is forward-only on S3, but the descending encoding
398
+ * makes "fetch the K newest entries" a single bounded LIST with
399
+ * `maxKeys=K` instead of a full-population LIST + in-memory reverse.
400
+ *
401
+ * Behaviourally verified across randomized populations in
402
+ * `packages/protocol/src/lsn-reverse-list.test.ts`. Quantified
403
+ * bytes-listed reduction is in
404
+ * `docs/spec/attachments/lsn-reverse-walk-baseline.json`
405
+ * (run `pnpm bench:lsn-reverse-walk` to reproduce). Spec rationale:
406
+ * `docs/spec/sync-protocol.md` §"LSNs, wall clocks, and downstream
407
+ * consumers".
408
+ */
409
+ const uint2strDesc = (num, bits) => {
410
+ return uint2str(Math.pow(2, bits) - 1 - num, bits);
411
+ };
412
+ //#endregion
413
+ //#region ../protocol/src/time.ts
414
+ /**
415
+ * Encode an epoch-millis instant as a lexicographically-DEScending
416
+ * base-32 key (newer sorts first). The load-bearing LSN ordering
417
+ * primitive — see {@link uint2strDesc}.
418
+ *
419
+ * `epoch` is REQUIRED and validated. There is no default: an argless
420
+ * call used to encode `0`, which descending-sorts as the most-ancient
421
+ * instant and would silently invert ordering. A non-finite, negative,
422
+ * or out-of-range `epoch` (e.g. a broken `Date.now()` returning `NaN`)
423
+ * would corrupt the key silently rather than fail loud, so it throws
424
+ * `Internal` instead — this is an invariant violation, not caller config
425
+ * (the only legitimate argument is `Date.now()`).
426
+ */
427
+ const timestamp = (epoch) => {
428
+ if (!Number.isInteger(epoch) || epoch < 0 || epoch >= 2 ** 42) throw new BaerlyError("Internal", `timestamp(): epoch must be a non-negative integer < 2^42 (got ${epoch})`);
429
+ return uint2strDesc(epoch, 42);
430
+ };
431
+ /**
432
+ * Delay for `ms` milliseconds, with optional cancellation. If
433
+ * `signal` aborts before the delay elapses, the returned promise
434
+ * rejects with `signal.reason`. Used by `S3HttpStorage`'s retry
435
+ * loop so shutdown can interrupt an in-flight backoff instead of
436
+ * waiting for it to complete.
437
+ */
438
+ const delay = (ms, signal) => new Promise((resolve, reject) => {
439
+ if (signal?.aborted) {
440
+ reject(signal.reason);
441
+ return;
442
+ }
443
+ const timer = setTimeout(resolve, ms);
444
+ signal?.addEventListener("abort", () => {
445
+ clearTimeout(timer);
446
+ reject(signal.reason);
447
+ }, { once: true });
448
+ });
449
+ //#endregion
450
+ //#region ../dev/src/local-fs.ts
451
+ /**
452
+ * Reserved prefix for the in-directory create-if-absent temp (see `put`).
453
+ * `walk`/`list` skip it; it is internal/transient and never a real key.
454
+ */
455
+ const TEMP_PREFIX = ".baerly-tmp-";
456
+ const utf8Encoder = new TextEncoder();
457
+ /**
458
+ * Compare two keys by their UTF-8 byte sequences — the order S3 and R2
459
+ * use for `list`. JS's default string sort compares UTF-16 code units,
460
+ * which diverges from UTF-8 byte order for supplementary-plane
461
+ * characters; using this keeps `list` ordering faithful to the real
462
+ * adapters. (All kernel keys are ASCII base-32, where both orders
463
+ * coincide.)
464
+ */
465
+ const compareKeysUtf8 = (a, b) => {
466
+ const ba = utf8Encoder.encode(a);
467
+ const bb = utf8Encoder.encode(b);
468
+ const n = Math.min(ba.length, bb.length);
469
+ for (let i = 0; i < n; i++) if (ba[i] !== bb[i]) return ba[i] - bb[i];
470
+ return ba.length - bb.length;
471
+ };
472
+ /**
473
+ * `Storage` backed by a directory tree. Keys may contain `/` and map
474
+ * to nested directories on disk so `ls`/`cat` work as expected.
475
+ *
476
+ * ETags are content-addressed: `"<sha-256-hex>"` (the surrounding
477
+ * double-quotes match S3's wire format for non-multipart objects).
478
+ * Identical bodies share an ETag across runs — the property that
479
+ * makes this adapter useful for fixture-based tests.
480
+ *
481
+ * Writes are atomic via `writeFile(temp) + rename(final)`; readers
482
+ * never see a partially-written file.
483
+ *
484
+ * `ifNoneMatch:"*"` uses a same-dir temp + `link(2)` (atomic exclusive
485
+ * create; `EEXIST` ⇒ key exists) so concurrent creates have exactly one
486
+ * winner. Same-dir avoids `EXDEV`; temp+`link` over `open(…,"wx")` keeps
487
+ * a partially-written new key invisible to a concurrent reader. `ifMatch`
488
+ * keeps the `rename` path (in-process TOCTOU only; cross-process
489
+ * contention uses the S3 / Minio `If-Match` path).
490
+ *
491
+ * Node-only — imports `node:fs`, `node:path`, `node:crypto`. Lives in
492
+ * `@baerly/dev` because the protocol kernel is pure-modules / no I/O
493
+ * and must remain Worker-bundleable.
494
+ */
495
+ var LocalFsStorage = class {
496
+ #root;
497
+ constructor(opts) {
498
+ this.#root = resolve(opts.root);
499
+ }
500
+ async get(key, opts) {
501
+ opts?.signal?.throwIfAborted();
502
+ const path = this.#pathFor(key);
503
+ let body;
504
+ try {
505
+ body = await readFile(path);
506
+ } catch (error) {
507
+ if (isErrnoException(error) && error.code === "ENOENT") return null;
508
+ throw new BaerlyError("InvalidResponse", `LocalFsStorage.get(${key}): ${error.message}`, error);
509
+ }
510
+ const etag = etagOf(body);
511
+ if (opts?.ifNoneMatch !== void 0 && opts.ifNoneMatch === etag) return null;
512
+ return {
513
+ body: toUint8Array(body),
514
+ etag
515
+ };
516
+ }
517
+ async put(key, body, opts) {
518
+ opts?.signal?.throwIfAborted();
519
+ const path = this.#pathFor(key);
520
+ const newEtag = etagOf(body);
521
+ await mkdir(dirname(path), { recursive: true });
522
+ if (opts?.ifNoneMatch === "*") {
523
+ const tmp = join(dirname(path), `${TEMP_PREFIX}${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`);
524
+ try {
525
+ await writeFile(tmp, body);
526
+ await link(tmp, path);
527
+ } catch (error) {
528
+ if (isErrnoException(error) && error.code === "EEXIST") throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifNoneMatch="*" but key exists)`);
529
+ throw new BaerlyError("InvalidResponse", `LocalFsStorage.put(${key}): ${error.message}`, error);
530
+ } finally {
531
+ await rm(tmp, { force: true }).catch(() => {});
532
+ }
533
+ return {
534
+ etag: newEtag,
535
+ serverDate: /* @__PURE__ */ new Date()
536
+ };
537
+ }
538
+ if (opts?.ifMatch !== void 0) {
539
+ const existing = await readExisting(path);
540
+ if (existing === null) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`);
541
+ const currentEtag = etagOf(existing);
542
+ if (currentEtag !== opts.ifMatch) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${currentEtag})`);
543
+ }
544
+ const tmp = join(tmpdir(), `baerly-localfs-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`);
545
+ await writeFile(tmp, body);
546
+ try {
547
+ await rename(tmp, path);
548
+ } catch (error) {
549
+ await rm(tmp, { force: true }).catch(() => {});
550
+ throw new BaerlyError("InvalidResponse", `LocalFsStorage.put(${key}): ${error.message}`, error);
551
+ }
552
+ return {
553
+ etag: newEtag,
554
+ serverDate: /* @__PURE__ */ new Date()
555
+ };
556
+ }
557
+ async delete(key, opts) {
558
+ opts?.signal?.throwIfAborted();
559
+ const path = this.#pathFor(key);
560
+ try {
561
+ await rm(path);
562
+ } catch (error) {
563
+ if (isErrnoException(error) && error.code === "ENOENT") return;
564
+ throw new BaerlyError("InvalidResponse", `LocalFsStorage.delete(${key}): ${error.message}`, error);
565
+ }
566
+ }
567
+ async *list(prefix, opts) {
568
+ opts?.signal?.throwIfAborted();
569
+ const startAfter = opts?.startAfter ?? "";
570
+ const maxKeys = opts?.maxKeys ?? Infinity;
571
+ const keys = [];
572
+ await walk(this.#root, keys);
573
+ keys.sort(compareKeysUtf8);
574
+ let yielded = 0;
575
+ for (const key of keys) {
576
+ if (!key.startsWith(prefix)) continue;
577
+ if (compareKeysUtf8(key, startAfter) <= 0) continue;
578
+ if (yielded >= maxKeys) return;
579
+ opts?.signal?.throwIfAborted();
580
+ yield {
581
+ key,
582
+ etag: etagOf(await readFile(this.#pathFor(key)))
583
+ };
584
+ yielded += 1;
585
+ }
586
+ }
587
+ /**
588
+ * Map an S3-style key to a filesystem path under `#root`, rejecting
589
+ * anything that could escape the root (path traversal, absolute
590
+ * paths, empty segments, backslashes). All rejections throw
591
+ * `BaerlyError("InvalidConfig", …)`.
592
+ */
593
+ #pathFor(key) {
594
+ assertValidStorageKey(key);
595
+ if (key.startsWith("/")) throw new BaerlyError("InvalidConfig", `LocalFsStorage: leading "/" in key: ${key}`);
596
+ if (key.includes("\\")) throw new BaerlyError("InvalidConfig", `LocalFsStorage: backslash in key: ${key}`);
597
+ const segments = key.split("/");
598
+ if (segments.some((s) => s === "" || s === "." || s === "..")) throw new BaerlyError("InvalidConfig", `LocalFsStorage: illegal segment in key: ${key}`);
599
+ const path = join(this.#root, ...segments);
600
+ if (path !== this.#root && !path.startsWith(this.#root + sep)) throw new BaerlyError("InvalidConfig", `LocalFsStorage: resolved path escapes root: ${key}`);
601
+ return path;
602
+ }
603
+ };
604
+ const etagOf = (body) => {
605
+ return `"${createHash("sha256").update(body).digest("hex")}"`;
606
+ };
607
+ const toUint8Array = (buf) => new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
608
+ const isErrnoException = (e) => typeof e === "object" && e !== null && "code" in e;
609
+ const readExisting = async (path) => {
610
+ try {
611
+ return await readFile(path);
612
+ } catch (error) {
613
+ if (isErrnoException(error) && error.code === "ENOENT") return null;
614
+ throw error;
615
+ }
616
+ };
617
+ /**
618
+ * Recursive directory walk. Yields filesystem-relative paths in
619
+ * forward-slash form so callers can use them as S3-style keys
620
+ * regardless of the host's path separator.
621
+ */
622
+ const walk = async (root, out) => {
623
+ const stack = [root];
624
+ while (stack.length > 0) {
625
+ const dir = stack.pop();
626
+ let entries;
627
+ try {
628
+ entries = await readdir(dir, { withFileTypes: true });
629
+ } catch (error) {
630
+ if (isErrnoException(error) && error.code === "ENOENT") continue;
631
+ throw error;
632
+ }
633
+ for (const entry of entries) {
634
+ const full = join(dir, entry.name);
635
+ if (entry.isDirectory()) stack.push(full);
636
+ else if (entry.isFile() && !entry.name.startsWith(TEMP_PREFIX)) out.push(relative(root, full).split(sep).join(posix.sep));
637
+ }
638
+ }
639
+ };
640
+ /*! @rgrove/parse-xml v4.2.1 | ISC License | Copyright Ryan Grove */
641
+ //#endregion
642
+ //#region ../adapter-node/src/xml.ts
643
+ var import_browser = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
644
+ var __defProp = Object.defineProperty;
645
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
646
+ var __getOwnPropNames = Object.getOwnPropertyNames;
647
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
648
+ var __export = (target, all) => {
649
+ for (var name in all) __defProp(target, name, {
650
+ get: all[name],
651
+ enumerable: true
652
+ });
653
+ };
654
+ var __copyProps = (to, from, except, desc) => {
655
+ if (from && typeof from === "object" || typeof from === "function") {
656
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
657
+ get: () => from[key],
658
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
659
+ });
660
+ }
661
+ return to;
662
+ };
663
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
664
+ var src_exports = {};
665
+ __export(src_exports, {
666
+ XmlCdata: () => XmlCdata,
667
+ XmlComment: () => XmlComment,
668
+ XmlDeclaration: () => XmlDeclaration,
669
+ XmlDocument: () => XmlDocument,
670
+ XmlDocumentType: () => XmlDocumentType,
671
+ XmlElement: () => XmlElement,
672
+ XmlError: () => XmlError,
673
+ XmlNode: () => XmlNode,
674
+ XmlProcessingInstruction: () => XmlProcessingInstruction,
675
+ XmlText: () => XmlText,
676
+ parseXml: () => parseXml
677
+ });
678
+ module.exports = __toCommonJS(src_exports);
679
+ var emptyString = "";
680
+ var surrogatePair = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
681
+ var StringScanner = class {
682
+ constructor(string) {
683
+ this.k = this.u(string, true);
684
+ this.d = 0;
685
+ this.length = string.length;
686
+ this.l = this.k !== this.length;
687
+ this.h = string;
688
+ if (this.l) {
689
+ let charsToBytes = [];
690
+ for (let byteIndex = 0, charIndex = 0; charIndex < this.k; ++charIndex) {
691
+ charsToBytes[charIndex] = byteIndex;
692
+ byteIndex += string.codePointAt(byteIndex) > 65535 ? 2 : 1;
693
+ }
694
+ this.A = charsToBytes;
695
+ }
696
+ }
697
+ /**
698
+ * Whether the current character index is at the end of the input string.
699
+ */
700
+ get B() {
701
+ return this.d >= this.k;
702
+ }
703
+ /**
704
+ * Returns the number of characters in the given string, which may differ from
705
+ * the byte length if the string contains multibyte characters.
706
+ */
707
+ u(string, multiByteSafe = this.l) {
708
+ return multiByteSafe ? string.replace(surrogatePair, "_").length : string.length;
709
+ }
710
+ /**
711
+ * Advances the scanner by the given number of characters, stopping if the end
712
+ * of the string is reached.
713
+ */
714
+ p(count = 1) {
715
+ this.d = Math.min(this.k, this.d + count);
716
+ }
717
+ /**
718
+ * Returns the byte index of the given character index in the string. The two
719
+ * may differ in strings that contain multibyte characters.
720
+ */
721
+ f(charIndex = this.d) {
722
+ var _a;
723
+ return this.l ? (_a = this.A[charIndex]) != null ? _a : Infinity : charIndex;
724
+ }
725
+ /**
726
+ * Consumes and returns the given number of characters if possible, advancing
727
+ * the scanner and stopping if the end of the string is reached.
728
+ *
729
+ * If no characters could be consumed, an empty string will be returned.
730
+ */
731
+ G(charCount = 1) {
732
+ let chars = this.m(charCount);
733
+ this.p(charCount);
734
+ return chars;
735
+ }
736
+ /**
737
+ * Consumes and returns the given number of bytes if possible, advancing the
738
+ * scanner and stopping if the end of the string is reached.
739
+ *
740
+ * It's up to the caller to ensure that the given byte count doesn't split a
741
+ * multibyte character.
742
+ *
743
+ * If no bytes could be consumed, an empty string will be returned.
744
+ */
745
+ v(byteCount) {
746
+ let byteIndex = this.f();
747
+ let result = this.h.slice(byteIndex, byteIndex + byteCount);
748
+ this.p(this.u(result));
749
+ return result;
750
+ }
751
+ /**
752
+ * Consumes and returns all characters for which the given function returns
753
+ * `true`, stopping when `false` is returned or the end of the input is
754
+ * reached.
755
+ */
756
+ w(fn) {
757
+ let { length, l: multiByteMode, h: string } = this;
758
+ let startByteIndex = this.f();
759
+ let endByteIndex = startByteIndex;
760
+ if (multiByteMode) while (endByteIndex < length) {
761
+ let char = string[endByteIndex];
762
+ let isSurrogatePair = char >= "\ud800" && char <= "\udbff";
763
+ if (isSurrogatePair) char += string[endByteIndex + 1];
764
+ if (!fn(char)) break;
765
+ endByteIndex += isSurrogatePair ? 2 : 1;
766
+ }
767
+ else while (endByteIndex < length && fn(string[endByteIndex])) ++endByteIndex;
768
+ return this.v(endByteIndex - startByteIndex);
769
+ }
770
+ /**
771
+ * Consumes the given string if it exists at the current character index, and
772
+ * advances the scanner.
773
+ *
774
+ * If the given string doesn't exist at the current character index, an empty
775
+ * string will be returned and the scanner will not be advanced.
776
+ */
777
+ b(stringToConsume) {
778
+ let { length } = stringToConsume;
779
+ let byteIndex = this.f();
780
+ if (stringToConsume === this.h.slice(byteIndex, byteIndex + length)) {
781
+ this.p(length === 1 ? 1 : this.u(stringToConsume));
782
+ return stringToConsume;
783
+ }
784
+ return emptyString;
785
+ }
786
+ /**
787
+ * Consumes characters until the given global regex is matched, advancing the
788
+ * scanner up to (but not beyond) the beginning of the match. If the regex
789
+ * doesn't match, nothing will be consumed.
790
+ *
791
+ * Returns the consumed string, or an empty string if nothing was consumed.
792
+ */
793
+ x(regex) {
794
+ let matchByteIndex = this.h.slice(this.f()).search(regex);
795
+ return matchByteIndex > 0 ? this.v(matchByteIndex) : emptyString;
796
+ }
797
+ /**
798
+ * Consumes characters until the given string is found, advancing the scanner
799
+ * up to (but not beyond) that point. If the string is never found, nothing
800
+ * will be consumed.
801
+ *
802
+ * Returns the consumed string, or an empty string if nothing was consumed.
803
+ */
804
+ s(searchString) {
805
+ let byteIndex = this.f();
806
+ let matchByteIndex = this.h.indexOf(searchString, byteIndex);
807
+ return matchByteIndex > 0 ? this.v(matchByteIndex - byteIndex) : emptyString;
808
+ }
809
+ /**
810
+ * Returns the given number of characters starting at the current character
811
+ * index, without advancing the scanner and without exceeding the end of the
812
+ * input string.
813
+ */
814
+ m(count = 1) {
815
+ let { d: charIndex, h: string } = this;
816
+ return this.l ? string.slice(this.f(charIndex), this.f(charIndex + count)) : string.slice(charIndex, charIndex + count);
817
+ }
818
+ /**
819
+ * Resets the scanner position to the given character _index_, or to the start
820
+ * of the input string if no index is given.
821
+ *
822
+ * If _index_ is negative, the scanner position will be moved backward by that
823
+ * many characters, stopping if the beginning of the string is reached.
824
+ */
825
+ n(index = 0) {
826
+ this.d = index >= 0 ? Math.min(this.k, index) : Math.max(0, this.d + index);
827
+ }
828
+ };
829
+ var attValueCharDoubleQuote = /["&<]/;
830
+ var attValueCharSingleQuote = /['&<]/;
831
+ var attValueNormalizedWhitespace = /\r\n|[\n\r\t]/g;
832
+ var endCharData = /<|&|]]>/;
833
+ var predefinedEntities = Object.freeze(Object.assign(/* @__PURE__ */ Object.create(null), {
834
+ amp: "&",
835
+ apos: "'",
836
+ gt: ">",
837
+ lt: "<",
838
+ quot: "\""
839
+ }));
840
+ function isNameChar(char) {
841
+ let cp = char.codePointAt(0);
842
+ return cp >= 97 && cp <= 122 || cp >= 65 && cp <= 90 || cp >= 48 && cp <= 57 || cp === 45 || cp === 46 || cp === 183 || cp >= 768 && cp <= 879 || cp === 8255 || cp === 8256 || isNameStartChar(char, cp);
843
+ }
844
+ function isNameStartChar(char, cp = char.codePointAt(0)) {
845
+ return cp >= 97 && cp <= 122 || cp >= 65 && cp <= 90 || cp === 58 || cp === 95 || cp >= 192 && cp <= 214 || cp >= 216 && cp <= 246 || cp >= 248 && cp <= 767 || cp >= 880 && cp <= 893 || cp >= 895 && cp <= 8191 || cp === 8204 || cp === 8205 || cp >= 8304 && cp <= 8591 || cp >= 11264 && cp <= 12271 || cp >= 12289 && cp <= 55295 || cp >= 63744 && cp <= 64975 || cp >= 65008 && cp <= 65533 || cp >= 65536 && cp <= 983039;
846
+ }
847
+ function isReferenceChar(char) {
848
+ return char === "#" || isNameChar(char);
849
+ }
850
+ function isWhitespace(char) {
851
+ let cp = char.codePointAt(0);
852
+ return cp === 32 || cp === 9 || cp === 10 || cp === 13;
853
+ }
854
+ function isXmlCodePoint(cp) {
855
+ return cp >= 32 && cp <= 55295 || cp === 10 || cp === 9 || cp === 13 || cp >= 57344 && cp <= 65533 || cp >= 65536 && cp <= 1114111;
856
+ }
857
+ var _XmlNode = class _XmlNode {
858
+ constructor() {
859
+ /**
860
+ * Parent node of this node, or `null` if this node has no parent.
861
+ */
862
+ this.parent = null;
863
+ /**
864
+ * Starting byte offset of this node in the original XML string, or `-1` if
865
+ * the offset is unknown.
866
+ */
867
+ this.start = -1;
868
+ /**
869
+ * Ending byte offset of this node in the original XML string, or `-1` if the
870
+ * offset is unknown.
871
+ */
872
+ this.end = -1;
873
+ }
874
+ /**
875
+ * Document that contains this node, or `null` if this node is not associated
876
+ * with a document.
877
+ */
878
+ get document() {
879
+ var _a, _b;
880
+ return (_b = (_a = this.parent) == null ? void 0 : _a.document) != null ? _b : null;
881
+ }
882
+ /**
883
+ * Whether this node is the root node of the document (also known as the
884
+ * document element).
885
+ */
886
+ get isRootNode() {
887
+ return this.parent !== null && this.parent === this.document && this.type === _XmlNode.TYPE_ELEMENT;
888
+ }
889
+ /**
890
+ * Whether whitespace should be preserved in the content of this element and
891
+ * its children.
892
+ *
893
+ * This is influenced by the value of the special `xml:space` attribute, and
894
+ * will be `true` for any node whose `xml:space` attribute is set to
895
+ * "preserve". If a node has no such attribute, it will inherit the value of
896
+ * the nearest ancestor that does (if any).
897
+ *
898
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-white-space
899
+ */
900
+ get preserveWhitespace() {
901
+ var _a;
902
+ return !!((_a = this.parent) == null ? void 0 : _a.preserveWhitespace);
903
+ }
904
+ /**
905
+ * Type of this node.
906
+ *
907
+ * The value of this property is a string that matches one of the static
908
+ * `TYPE_*` properties on the `XmlNode` class (e.g. `TYPE_ELEMENT`,
909
+ * `TYPE_TEXT`, etc.).
910
+ *
911
+ * The `XmlNode` class itself is a base class and doesn't have its own type
912
+ * name.
913
+ */
914
+ get type() {
915
+ return "";
916
+ }
917
+ /**
918
+ * Returns a JSON-serializable object representing this node, minus properties
919
+ * that could result in circular references.
920
+ */
921
+ toJSON() {
922
+ let json = { type: this.type };
923
+ if (this.isRootNode) json.isRootNode = true;
924
+ if (this.preserveWhitespace) json.preserveWhitespace = true;
925
+ if (this.start !== -1) {
926
+ json.start = this.start;
927
+ json.end = this.end;
928
+ }
929
+ return json;
930
+ }
931
+ };
932
+ /**
933
+ * Type value for an `XmlCdata` node.
934
+ */
935
+ _XmlNode.TYPE_CDATA = "cdata";
936
+ /**
937
+ * Type value for an `XmlComment` node.
938
+ */
939
+ _XmlNode.TYPE_COMMENT = "comment";
940
+ /**
941
+ * Type value for an `XmlDocument` node.
942
+ */
943
+ _XmlNode.TYPE_DOCUMENT = "document";
944
+ /**
945
+ * Type value for an `XmlDocumentType` node.
946
+ */
947
+ _XmlNode.TYPE_DOCUMENT_TYPE = "doctype";
948
+ /**
949
+ * Type value for an `XmlElement` node.
950
+ */
951
+ _XmlNode.TYPE_ELEMENT = "element";
952
+ /**
953
+ * Type value for an `XmlProcessingInstruction` node.
954
+ */
955
+ _XmlNode.TYPE_PROCESSING_INSTRUCTION = "pi";
956
+ /**
957
+ * Type value for an `XmlText` node.
958
+ */
959
+ _XmlNode.TYPE_TEXT = "text";
960
+ /**
961
+ * Type value for an `XmlDeclaration` node.
962
+ */
963
+ _XmlNode.TYPE_XML_DECLARATION = "xmldecl";
964
+ var XmlNode = _XmlNode;
965
+ var XmlText = class extends XmlNode {
966
+ constructor(text = "") {
967
+ super();
968
+ this.text = text;
969
+ }
970
+ get type() {
971
+ return XmlNode.TYPE_TEXT;
972
+ }
973
+ toJSON() {
974
+ return Object.assign(XmlNode.prototype.toJSON.call(this), { text: this.text });
975
+ }
976
+ };
977
+ var XmlCdata = class extends XmlText {
978
+ get type() {
979
+ return XmlNode.TYPE_CDATA;
980
+ }
981
+ };
982
+ var XmlComment = class extends XmlNode {
983
+ constructor(content = "") {
984
+ super();
985
+ this.content = content;
986
+ }
987
+ get type() {
988
+ return XmlNode.TYPE_COMMENT;
989
+ }
990
+ toJSON() {
991
+ return Object.assign(XmlNode.prototype.toJSON.call(this), { content: this.content });
992
+ }
993
+ };
994
+ var XmlDeclaration = class extends XmlNode {
995
+ constructor(version, encoding, standalone) {
996
+ super();
997
+ this.version = version;
998
+ this.encoding = encoding != null ? encoding : null;
999
+ this.standalone = standalone != null ? standalone : null;
1000
+ }
1001
+ get type() {
1002
+ return XmlNode.TYPE_XML_DECLARATION;
1003
+ }
1004
+ toJSON() {
1005
+ let json = XmlNode.prototype.toJSON.call(this);
1006
+ json.version = this.version;
1007
+ for (let key of ["encoding", "standalone"]) if (this[key] !== null) json[key] = this[key];
1008
+ return json;
1009
+ }
1010
+ };
1011
+ var XmlElement = class _XmlElement extends XmlNode {
1012
+ constructor(name, attributes = /* @__PURE__ */ Object.create(null), children = []) {
1013
+ super();
1014
+ this.name = name;
1015
+ this.attributes = attributes;
1016
+ this.children = children;
1017
+ }
1018
+ /**
1019
+ * Whether this element is empty (meaning it has no children).
1020
+ */
1021
+ get isEmpty() {
1022
+ return this.children.length === 0;
1023
+ }
1024
+ get preserveWhitespace() {
1025
+ let node = this;
1026
+ while (node instanceof _XmlElement) {
1027
+ if ("xml:space" in node.attributes) return node.attributes["xml:space"] === "preserve";
1028
+ node = node.parent;
1029
+ }
1030
+ return false;
1031
+ }
1032
+ /**
1033
+ * Text content of this element and all its descendants.
1034
+ */
1035
+ get text() {
1036
+ return this.children.map((child) => "text" in child ? child.text : "").join("");
1037
+ }
1038
+ get type() {
1039
+ return XmlNode.TYPE_ELEMENT;
1040
+ }
1041
+ toJSON() {
1042
+ return Object.assign(XmlNode.prototype.toJSON.call(this), {
1043
+ name: this.name,
1044
+ attributes: this.attributes,
1045
+ children: this.children.map((child) => child.toJSON())
1046
+ });
1047
+ }
1048
+ };
1049
+ var XmlDocument = class extends XmlNode {
1050
+ constructor(children = []) {
1051
+ super();
1052
+ this.children = children;
1053
+ }
1054
+ get document() {
1055
+ return this;
1056
+ }
1057
+ /**
1058
+ * Root element of this document, or `null` if this document is empty.
1059
+ */
1060
+ get root() {
1061
+ for (let child of this.children) if (child instanceof XmlElement) return child;
1062
+ return null;
1063
+ }
1064
+ /**
1065
+ * Text content of this document and all its descendants.
1066
+ */
1067
+ get text() {
1068
+ return this.children.map((child) => "text" in child ? child.text : "").join("");
1069
+ }
1070
+ get type() {
1071
+ return XmlNode.TYPE_DOCUMENT;
1072
+ }
1073
+ toJSON() {
1074
+ return Object.assign(XmlNode.prototype.toJSON.call(this), { children: this.children.map((child) => child.toJSON()) });
1075
+ }
1076
+ };
1077
+ var XmlDocumentType = class extends XmlNode {
1078
+ constructor(name, publicId, systemId, internalSubset) {
1079
+ super();
1080
+ this.name = name;
1081
+ this.publicId = publicId != null ? publicId : null;
1082
+ this.systemId = systemId != null ? systemId : null;
1083
+ this.internalSubset = internalSubset != null ? internalSubset : null;
1084
+ }
1085
+ get type() {
1086
+ return XmlNode.TYPE_DOCUMENT_TYPE;
1087
+ }
1088
+ toJSON() {
1089
+ let json = XmlNode.prototype.toJSON.call(this);
1090
+ json.name = this.name;
1091
+ for (let key of [
1092
+ "publicId",
1093
+ "systemId",
1094
+ "internalSubset"
1095
+ ]) if (this[key] !== null) json[key] = this[key];
1096
+ return json;
1097
+ }
1098
+ };
1099
+ var XmlError = class extends Error {
1100
+ constructor(message, charIndex, xml) {
1101
+ let column = 1;
1102
+ let excerpt = "";
1103
+ let line = 1;
1104
+ for (let i = 0; i < charIndex; ++i) {
1105
+ let char = xml[i];
1106
+ if (char === "\n") {
1107
+ column = 1;
1108
+ excerpt = "";
1109
+ line += 1;
1110
+ } else {
1111
+ column += 1;
1112
+ excerpt += char;
1113
+ }
1114
+ }
1115
+ let eol = xml.indexOf("\n", charIndex);
1116
+ excerpt += eol === -1 ? xml.slice(charIndex) : xml.slice(charIndex, eol);
1117
+ let excerptStart = 0;
1118
+ if (excerpt.length > 50) if (column < 40) excerpt = excerpt.slice(0, 50);
1119
+ else {
1120
+ excerptStart = column - 20;
1121
+ excerpt = excerpt.slice(excerptStart, column + 30);
1122
+ }
1123
+ super(`${message} (line ${line}, column ${column})
1124
+ ${excerpt}
1125
+ ` + " ".repeat(column - excerptStart + 1) + "^\n");
1126
+ this.column = column;
1127
+ this.excerpt = excerpt;
1128
+ this.line = line;
1129
+ this.name = "XmlError";
1130
+ this.pos = charIndex;
1131
+ }
1132
+ };
1133
+ var XmlProcessingInstruction = class extends XmlNode {
1134
+ constructor(name, content = "") {
1135
+ super();
1136
+ this.name = name;
1137
+ this.content = content;
1138
+ }
1139
+ get type() {
1140
+ return XmlNode.TYPE_PROCESSING_INSTRUCTION;
1141
+ }
1142
+ toJSON() {
1143
+ return Object.assign(XmlNode.prototype.toJSON.call(this), {
1144
+ name: this.name,
1145
+ content: this.content
1146
+ });
1147
+ }
1148
+ };
1149
+ var emptyString2 = "";
1150
+ var Parser = class {
1151
+ /**
1152
+ * @param xml XML string to parse.
1153
+ * @param options Parser options.
1154
+ */
1155
+ constructor(xml, options = {}) {
1156
+ let doc = this.document = new XmlDocument();
1157
+ this.j = doc;
1158
+ this.g = options;
1159
+ this.c = new StringScanner(xml);
1160
+ if (this.g.includeOffsets) {
1161
+ doc.start = 0;
1162
+ doc.end = xml.length;
1163
+ }
1164
+ this.parse();
1165
+ }
1166
+ /**
1167
+ * Adds the given `XmlNode` as a child of `this.currentNode`.
1168
+ */
1169
+ i(node, charIndex) {
1170
+ node.parent = this.j;
1171
+ if (this.g.includeOffsets) {
1172
+ node.start = this.c.f(charIndex);
1173
+ node.end = this.c.f();
1174
+ }
1175
+ this.j.children.push(node);
1176
+ return true;
1177
+ }
1178
+ /**
1179
+ * Adds the given _text_ to the document, either by appending it to a
1180
+ * preceding `XmlText` node (if possible) or by creating a new `XmlText` node.
1181
+ *
1182
+ * When _normalize_ is `true` (the default), line breaks in _text_ are
1183
+ * normalized per section 2.11 of the XML spec. This must be `false` for text
1184
+ * that comes from a character or entity reference, since references aren't
1185
+ * subject to line break normalization.
1186
+ */
1187
+ y(text, charIndex, normalize = true) {
1188
+ let { children } = this.j;
1189
+ let { length } = children;
1190
+ if (normalize) text = normalizeLineBreaks(text);
1191
+ if (length > 0) {
1192
+ let prevNode = children[length - 1];
1193
+ if ((prevNode == null ? void 0 : prevNode.type) === XmlNode.TYPE_TEXT) {
1194
+ let textNode = prevNode;
1195
+ textNode.text += text;
1196
+ if (this.g.includeOffsets) textNode.end = this.c.f();
1197
+ return true;
1198
+ }
1199
+ }
1200
+ return this.i(new XmlText(text), charIndex);
1201
+ }
1202
+ /**
1203
+ * Consumes element attributes.
1204
+ *
1205
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-starttags
1206
+ */
1207
+ H() {
1208
+ let attributes = /* @__PURE__ */ Object.create(null);
1209
+ while (this.e()) {
1210
+ let attrName = this.q();
1211
+ if (!attrName) break;
1212
+ let attrValue = this.t() && this.I();
1213
+ if (attrValue === false) throw this.a("Attribute value expected");
1214
+ if (attrName in attributes) throw this.a(`Duplicate attribute: ${attrName}`);
1215
+ if (attrName === "xml:space" && attrValue !== "default" && attrValue !== "preserve") throw this.a("Value of the `xml:space` attribute must be \"default\" or \"preserve\"");
1216
+ attributes[attrName] = attrValue;
1217
+ }
1218
+ if (this.g.sortAttributes) {
1219
+ let attrNames = Object.keys(attributes).sort();
1220
+ let sortedAttributes = /* @__PURE__ */ Object.create(null);
1221
+ for (let i = 0; i < attrNames.length; ++i) {
1222
+ let attrName = attrNames[i];
1223
+ sortedAttributes[attrName] = attributes[attrName];
1224
+ }
1225
+ attributes = sortedAttributes;
1226
+ }
1227
+ return attributes;
1228
+ }
1229
+ /**
1230
+ * Consumes an `AttValue` (attribute value) if possible.
1231
+ *
1232
+ * @returns
1233
+ * Contents of the `AttValue` minus quotes, or `false` if nothing was
1234
+ * consumed. An empty string indicates that an `AttValue` was consumed but
1235
+ * was empty.
1236
+ *
1237
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-AttValue
1238
+ */
1239
+ I() {
1240
+ let { c: scanner } = this;
1241
+ let quote = scanner.m();
1242
+ if (quote !== "\"" && quote !== "'") return false;
1243
+ scanner.p();
1244
+ let chars;
1245
+ let isClosed = false;
1246
+ let value = emptyString2;
1247
+ let regex = quote === "\"" ? attValueCharDoubleQuote : attValueCharSingleQuote;
1248
+ matchLoop: while (!scanner.B) {
1249
+ chars = scanner.x(regex);
1250
+ if (chars) {
1251
+ this.o(chars);
1252
+ value += chars.replace(attValueNormalizedWhitespace, " ");
1253
+ }
1254
+ switch (scanner.m()) {
1255
+ case quote:
1256
+ isClosed = true;
1257
+ break matchLoop;
1258
+ case "&":
1259
+ value += this.C();
1260
+ continue;
1261
+ case "<": throw this.a("Unescaped `<` is not allowed in an attribute value");
1262
+ default: break matchLoop;
1263
+ }
1264
+ }
1265
+ if (!isClosed) throw this.a("Unclosed attribute");
1266
+ scanner.p();
1267
+ return value;
1268
+ }
1269
+ /**
1270
+ * Consumes a CDATA section if possible.
1271
+ *
1272
+ * @returns Whether a CDATA section was consumed.
1273
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-cdata-sect
1274
+ */
1275
+ J() {
1276
+ let { c: scanner } = this;
1277
+ let startIndex = scanner.d;
1278
+ if (!scanner.b("<![CDATA[")) return false;
1279
+ let text = scanner.s("]]>");
1280
+ this.o(text);
1281
+ if (!scanner.b("]]>")) throw this.a("Unclosed CDATA section");
1282
+ return this.g.preserveCdata ? this.i(new XmlCdata(normalizeLineBreaks(text)), startIndex) : this.y(text, startIndex);
1283
+ }
1284
+ /**
1285
+ * Consumes character data if possible.
1286
+ *
1287
+ * @returns Whether character data was consumed.
1288
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#dt-chardata
1289
+ */
1290
+ K() {
1291
+ let { c: scanner } = this;
1292
+ let startIndex = scanner.d;
1293
+ let charData = scanner.x(endCharData);
1294
+ if (!charData) return false;
1295
+ this.o(charData);
1296
+ if (scanner.m(3) === "]]>") throw this.a("Element content may not contain the CDATA section close delimiter `]]>`");
1297
+ return this.y(charData, startIndex);
1298
+ }
1299
+ /**
1300
+ * Consumes a comment if possible.
1301
+ *
1302
+ * @returns Whether a comment was consumed.
1303
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-Comment
1304
+ */
1305
+ D() {
1306
+ let { c: scanner } = this;
1307
+ let startIndex = scanner.d;
1308
+ if (!scanner.b("<!--")) return false;
1309
+ let content = scanner.s("--");
1310
+ this.o(content);
1311
+ if (!scanner.b("-->")) {
1312
+ if (scanner.m(2) === "--") throw this.a("The string `--` isn't allowed inside a comment");
1313
+ throw this.a("Unclosed comment");
1314
+ }
1315
+ return this.g.preserveComments ? this.i(new XmlComment(normalizeLineBreaks(content)), startIndex) : true;
1316
+ }
1317
+ /**
1318
+ * Consumes a reference in a content context if possible.
1319
+ *
1320
+ * This differs from `consumeReference()` in that a consumed reference will be
1321
+ * added to the document as a text node instead of returned.
1322
+ *
1323
+ * @returns Whether a reference was consumed.
1324
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#entproc
1325
+ */
1326
+ L() {
1327
+ let startIndex = this.c.d;
1328
+ let ref = this.C();
1329
+ return ref ? this.y(ref, startIndex, false) : false;
1330
+ }
1331
+ /**
1332
+ * Consumes a doctype declaration if possible.
1333
+ *
1334
+ * This is a loose implementation since doctype declarations are currently
1335
+ * discarded without further parsing.
1336
+ *
1337
+ * @returns Whether a doctype declaration was consumed.
1338
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#dtd
1339
+ */
1340
+ M() {
1341
+ let { c: scanner } = this;
1342
+ let startIndex = scanner.d;
1343
+ if (!scanner.b("<!DOCTYPE")) return false;
1344
+ let name = this.e() && this.q();
1345
+ if (!name) throw this.a("Expected a name");
1346
+ let publicId;
1347
+ let systemId;
1348
+ if (this.e()) {
1349
+ if (scanner.b("PUBLIC")) {
1350
+ publicId = this.e() && this.N();
1351
+ if (publicId === false) throw this.a("Expected a public identifier");
1352
+ this.e();
1353
+ }
1354
+ if (publicId !== void 0 || scanner.b("SYSTEM")) {
1355
+ this.e();
1356
+ systemId = this.r();
1357
+ if (systemId === false) throw this.a("Expected a system identifier");
1358
+ this.e();
1359
+ }
1360
+ }
1361
+ let internalSubset;
1362
+ if (scanner.b("[")) {
1363
+ internalSubset = scanner.x(/\][\x20\t\r\n]*>/);
1364
+ if (!scanner.b("]")) throw this.a("Unclosed internal subset");
1365
+ this.e();
1366
+ }
1367
+ if (!scanner.b(">")) throw this.a("Unclosed doctype declaration");
1368
+ return this.g.preserveDocumentType ? this.i(new XmlDocumentType(name, publicId, systemId, internalSubset), startIndex) : true;
1369
+ }
1370
+ /**
1371
+ * Consumes an element if possible.
1372
+ *
1373
+ * @returns Whether an element was consumed.
1374
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-element
1375
+ */
1376
+ E() {
1377
+ let { c: scanner } = this;
1378
+ let startIndex = scanner.d;
1379
+ if (!scanner.b("<")) return false;
1380
+ let name = this.q();
1381
+ if (!name) {
1382
+ scanner.n(startIndex);
1383
+ return false;
1384
+ }
1385
+ let attributes = this.H();
1386
+ let isEmpty = !!scanner.b("/>");
1387
+ let element = new XmlElement(name, attributes);
1388
+ element.parent = this.j;
1389
+ if (!isEmpty) {
1390
+ if (!scanner.b(">")) throw this.a(`Unclosed start tag for element \`${name}\``);
1391
+ this.j = element;
1392
+ do
1393
+ this.K();
1394
+ while (this.E() || this.L() || this.J() || this.F() || this.D());
1395
+ let endTagMark = scanner.d;
1396
+ let endTagName;
1397
+ if (!scanner.b("</") || !(endTagName = this.q()) || endTagName !== name) {
1398
+ scanner.n(endTagMark);
1399
+ throw this.a(`Missing end tag for element ${name}`);
1400
+ }
1401
+ this.e();
1402
+ if (!scanner.b(">")) throw this.a(`Unclosed end tag for element ${name}`);
1403
+ this.j = element.parent;
1404
+ }
1405
+ return this.i(element, startIndex);
1406
+ }
1407
+ /**
1408
+ * Consumes an `Eq` production if possible.
1409
+ *
1410
+ * @returns Whether an `Eq` production was consumed.
1411
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-Eq
1412
+ */
1413
+ t() {
1414
+ this.e();
1415
+ if (this.c.b("=")) {
1416
+ this.e();
1417
+ return true;
1418
+ }
1419
+ return false;
1420
+ }
1421
+ /**
1422
+ * Consumes `Misc` content if possible.
1423
+ *
1424
+ * @returns Whether anything was consumed.
1425
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-Misc
1426
+ */
1427
+ z() {
1428
+ return this.D() || this.F() || this.e();
1429
+ }
1430
+ /**
1431
+ * Consumes one or more `Name` characters if possible.
1432
+ *
1433
+ * @returns `Name` characters, or an empty string if none were consumed.
1434
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-Name
1435
+ */
1436
+ q() {
1437
+ return isNameStartChar(this.c.m()) ? this.c.w(isNameChar) : emptyString2;
1438
+ }
1439
+ /**
1440
+ * Consumes a processing instruction if possible.
1441
+ *
1442
+ * @returns Whether a processing instruction was consumed.
1443
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-pi
1444
+ */
1445
+ F() {
1446
+ let { c: scanner } = this;
1447
+ let startIndex = scanner.d;
1448
+ if (!scanner.b("<?")) return false;
1449
+ let name = this.q();
1450
+ if (name) {
1451
+ if (name.toLowerCase() === "xml") {
1452
+ scanner.n(startIndex);
1453
+ throw this.a("XML declaration isn't allowed here");
1454
+ }
1455
+ } else throw this.a("Invalid processing instruction");
1456
+ if (!this.e()) {
1457
+ if (scanner.b("?>")) return this.i(new XmlProcessingInstruction(name), startIndex);
1458
+ throw this.a("Whitespace is required after a processing instruction name");
1459
+ }
1460
+ let content = scanner.s("?>");
1461
+ this.o(content);
1462
+ if (!scanner.b("?>")) throw this.a("Unterminated processing instruction");
1463
+ return this.i(new XmlProcessingInstruction(name, normalizeLineBreaks(content)), startIndex);
1464
+ }
1465
+ /**
1466
+ * Consumes a prolog if possible.
1467
+ *
1468
+ * @returns Whether a prolog was consumed.
1469
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-prolog-dtd
1470
+ */
1471
+ O() {
1472
+ let { c: scanner } = this;
1473
+ let startIndex = scanner.d;
1474
+ this.P();
1475
+ while (this.z());
1476
+ if (this.M()) while (this.z());
1477
+ return startIndex < scanner.d;
1478
+ }
1479
+ /**
1480
+ * Consumes a public identifier literal if possible.
1481
+ *
1482
+ * @returns
1483
+ * Value of the public identifier literal minus quotes, or `false` if
1484
+ * nothing was consumed. An empty string indicates that a public id literal
1485
+ * was consumed but was empty.
1486
+ *
1487
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-PubidLiteral
1488
+ */
1489
+ N() {
1490
+ let startIndex = this.c.d;
1491
+ let value = this.r();
1492
+ if (value !== false && !/^[-\x20\r\na-zA-Z0-9'()+,./:=?;!*#@$_%]*$/.test(value)) {
1493
+ this.c.n(startIndex);
1494
+ throw this.a("Invalid character in public identifier");
1495
+ }
1496
+ return value;
1497
+ }
1498
+ /**
1499
+ * Consumes a reference if possible.
1500
+ *
1501
+ * This differs from `consumeContentReference()` in that a consumed reference
1502
+ * will be returned rather than added to the document.
1503
+ *
1504
+ * @returns
1505
+ * Parsed reference value, or `false` if nothing was consumed (to
1506
+ * distinguish from a reference that resolves to an empty string).
1507
+ *
1508
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-Reference
1509
+ */
1510
+ C() {
1511
+ let { c: scanner } = this;
1512
+ if (!scanner.b("&")) return false;
1513
+ let ref = scanner.w(isReferenceChar);
1514
+ if (scanner.G() !== ";") throw this.a("Unterminated reference (a reference must end with `;`)");
1515
+ let parsedValue;
1516
+ if (ref[0] === "#") {
1517
+ let codePoint = ref[1] === "x" ? parseInt(ref.slice(2), 16) : parseInt(ref.slice(1), 10);
1518
+ if (isNaN(codePoint)) throw this.a("Invalid character reference");
1519
+ if (!isXmlCodePoint(codePoint)) throw this.a("Character reference resolves to an invalid character");
1520
+ parsedValue = String.fromCodePoint(codePoint);
1521
+ } else {
1522
+ parsedValue = predefinedEntities[ref];
1523
+ if (parsedValue === void 0) {
1524
+ let { ignoreUndefinedEntities, resolveUndefinedEntity } = this.g;
1525
+ let wrappedRef = `&${ref};`;
1526
+ if (resolveUndefinedEntity) {
1527
+ let resolvedValue = resolveUndefinedEntity(wrappedRef);
1528
+ if (resolvedValue !== null && resolvedValue !== void 0) {
1529
+ let type = typeof resolvedValue;
1530
+ if (type !== "string") throw new TypeError(`\`resolveUndefinedEntity()\` must return a string, \`null\`, or \`undefined\`, but returned a value of type ${type}`);
1531
+ return resolvedValue;
1532
+ }
1533
+ }
1534
+ if (ignoreUndefinedEntities) return wrappedRef;
1535
+ scanner.n(-wrappedRef.length);
1536
+ throw this.a(`Named entity isn't defined: ${wrappedRef}`);
1537
+ }
1538
+ }
1539
+ return parsedValue;
1540
+ }
1541
+ /**
1542
+ * Consumes a `SystemLiteral` if possible.
1543
+ *
1544
+ * A `SystemLiteral` is similar to an attribute value, but allows the
1545
+ * characters `<` and `&` and doesn't replace references.
1546
+ *
1547
+ * @returns
1548
+ * Value of the `SystemLiteral` minus quotes, or `false` if nothing was
1549
+ * consumed. An empty string indicates that a `SystemLiteral` was consumed
1550
+ * but was empty.
1551
+ *
1552
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-SystemLiteral
1553
+ */
1554
+ r() {
1555
+ let { c: scanner } = this;
1556
+ let quote = scanner.b("\"") || scanner.b("'");
1557
+ if (!quote) return false;
1558
+ let value = scanner.s(quote);
1559
+ this.o(value);
1560
+ if (!scanner.b(quote)) throw this.a("Missing end quote");
1561
+ return value;
1562
+ }
1563
+ /**
1564
+ * Consumes one or more whitespace characters if possible.
1565
+ *
1566
+ * @returns Whether any whitespace characters were consumed.
1567
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#white
1568
+ */
1569
+ e() {
1570
+ return !!this.c.w(isWhitespace);
1571
+ }
1572
+ /**
1573
+ * Consumes an XML declaration if possible.
1574
+ *
1575
+ * @returns Whether an XML declaration was consumed.
1576
+ * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-XMLDecl
1577
+ */
1578
+ P() {
1579
+ let { c: scanner } = this;
1580
+ let startIndex = scanner.d;
1581
+ if (!scanner.b("<?xml")) return false;
1582
+ if (!this.e()) throw this.a("Invalid XML declaration");
1583
+ let version = !!scanner.b("version") && this.t() && this.r();
1584
+ if (version === false) throw this.a("XML version is missing or invalid");
1585
+ else if (!/^1\.[0-9]+$/.test(version)) throw this.a("Invalid character in version number");
1586
+ let encoding;
1587
+ let standalone;
1588
+ if (this.e()) {
1589
+ encoding = !!scanner.b("encoding") && this.t() && this.r();
1590
+ if (encoding) {
1591
+ if (!/^[A-Za-z][\w.-]*$/.test(encoding)) throw this.a("Invalid character in encoding name");
1592
+ this.e();
1593
+ }
1594
+ standalone = !!scanner.b("standalone") && this.t() && this.r();
1595
+ if (standalone) {
1596
+ if (standalone !== "yes" && standalone !== "no") throw this.a("Only \"yes\" and \"no\" are permitted as values of `standalone`");
1597
+ this.e();
1598
+ }
1599
+ }
1600
+ if (!scanner.b("?>")) throw this.a("Invalid or unclosed XML declaration");
1601
+ return this.g.preserveXmlDeclaration ? this.i(new XmlDeclaration(version, encoding || void 0, standalone || void 0), startIndex) : true;
1602
+ }
1603
+ /**
1604
+ * Returns an `XmlError` for the current scanner position.
1605
+ */
1606
+ a(message) {
1607
+ let { c: scanner } = this;
1608
+ return new XmlError(message, scanner.d, scanner.h);
1609
+ }
1610
+ /**
1611
+ * Parses the XML input.
1612
+ */
1613
+ parse() {
1614
+ this.c.b("");
1615
+ this.O();
1616
+ if (!this.E()) throw this.a("Root element is missing or invalid");
1617
+ while (this.z());
1618
+ if (!this.c.B) throw this.a("Extra content at the end of the document");
1619
+ }
1620
+ /**
1621
+ * Throws an invalid character error if any character in the given _string_
1622
+ * isn't a valid XML character.
1623
+ */
1624
+ o(string) {
1625
+ let { length } = string;
1626
+ for (let i = 0; i < length; ++i) {
1627
+ let cp = string.codePointAt(i);
1628
+ if (!isXmlCodePoint(cp)) {
1629
+ this.c.n(-([...string].length - i));
1630
+ throw this.a("Invalid character");
1631
+ }
1632
+ if (cp > 65535) i += 1;
1633
+ }
1634
+ }
1635
+ };
1636
+ function normalizeLineBreaks(text) {
1637
+ let i = 0;
1638
+ while ((i = text.indexOf("\r", i)) !== -1) text = text[i + 1] === "\n" ? text.slice(0, i) + text.slice(i + 1) : text.slice(0, i) + "\n" + text.slice(i + 1);
1639
+ return text;
1640
+ }
1641
+ function parseXml(xml, options) {
1642
+ return new Parser(xml, options).document;
1643
+ }
1644
+ })))();
1645
+ const localName = (name) => name.includes(":") ? name.split(":")[1] : name;
1646
+ const isElement = (node) => node.type === "element";
1647
+ const isText = (node) => node.type === "text";
1648
+ const child = (el, name) => {
1649
+ for (const node of el.children) if (isElement(node) && localName(node.name) === name) return node;
1650
+ };
1651
+ const textOf = (el) => {
1652
+ if (el === void 0) return;
1653
+ let result = "";
1654
+ for (const node of el.children) if (isText(node)) result += node.text;
1655
+ return result === "" ? void 0 : result;
1656
+ };
1657
+ const docRoot = (doc) => doc.root ?? void 0;
1658
+ const xmlVal = (el, name) => {
1659
+ const v = el !== void 0 ? textOf(child(el, name)) : void 0;
1660
+ if (v === void 0 || v === "") return;
1661
+ try {
1662
+ return decodeURIComponent(v.replace(/\+/g, " "));
1663
+ } catch {
1664
+ throw new BaerlyError("InvalidResponse", `Malformed percent-escape in S3 <${name}>: ${v}`);
1665
+ }
1666
+ };
1667
+ const rawXmlVal = (el, name) => {
1668
+ return el !== void 0 ? textOf(child(el, name)) : void 0;
1669
+ };
1670
+ /**
1671
+ * Build a {@link ParsedS3Error} from the element that directly carries
1672
+ * the `<Code>` / `<Message>` children — `<Error>` for S3, the inner
1673
+ * `<Error>` for STS. Returns `undefined` when neither child is present
1674
+ * so callers can fall back to the raw status. Shared by
1675
+ * {@link parseS3Error} and {@link parseStsError}, which differ only in
1676
+ * how they locate that element.
1677
+ */
1678
+ const codeMessageFrom = (el) => {
1679
+ const code = rawXmlVal(el, "Code");
1680
+ const message = rawXmlVal(el, "Message");
1681
+ if (code === void 0 && message === void 0) return;
1682
+ return {
1683
+ ...code !== void 0 && { Code: code },
1684
+ ...message !== void 0 && { Message: message }
1685
+ };
1686
+ };
1687
+ /**
1688
+ * Parse an S3 `<Error><Code>…</Code><Message>…</Message></Error>`
1689
+ * body. Returns `undefined` when the body is not a recognizable S3
1690
+ * error document (empty, HTML, a success payload, or a DTD), so
1691
+ * callers can fall back to the raw response text. This never throws:
1692
+ * it runs on a path that is already reporting an error.
1693
+ */
1694
+ const parseS3Error = (xml) => {
1695
+ if (!/<Error\b/i.test(xml) || /<!DOCTYPE\b/i.test(xml)) return;
1696
+ let root;
1697
+ try {
1698
+ root = docRoot((0, import_browser.parseXml)(xml));
1699
+ } catch {
1700
+ return;
1701
+ }
1702
+ if (root === void 0) return;
1703
+ if (localName(root.name) !== "Error") return;
1704
+ return codeMessageFrom(root);
1705
+ };
1706
+ const parseLastModified = (lm) => {
1707
+ if (lm === void 0) return;
1708
+ const d = new Date(lm);
1709
+ return Number.isNaN(d.getTime()) ? void 0 : d;
1710
+ };
1711
+ const parseListObjectsV2CommandOutput = (xml) => {
1712
+ if (/<!DOCTYPE\b/i.test(xml)) throw new BaerlyError("InvalidResponse", "DTD not allowed in S3 XML responses");
1713
+ let root;
1714
+ try {
1715
+ root = docRoot((0, import_browser.parseXml)(xml));
1716
+ } catch {
1717
+ throw new BaerlyError("InvalidResponse", `Invalid XML: ${xml}`);
1718
+ }
1719
+ if (root === void 0) return {};
1720
+ if (localName(root.name) !== "ListBucketResult") return {};
1721
+ return {
1722
+ Contents: root.children.filter(isElement).filter((c) => localName(c.name) === "Contents").map((contentEl) => {
1723
+ return {
1724
+ ETag: rawXmlVal(contentEl, "ETag"),
1725
+ Key: xmlVal(contentEl, "Key"),
1726
+ LastModified: parseLastModified(rawXmlVal(contentEl, "LastModified"))
1727
+ };
1728
+ }),
1729
+ NextContinuationToken: rawXmlVal(root, "NextContinuationToken")
1730
+ };
1731
+ };
1732
+ //#endregion
1733
+ //#region ../adapter-node/src/s3-http.ts
1734
+ /**
1735
+ * Permanent {@link BaerlyError} codes that must short-circuit `retry`.
1736
+ * These represent caller- or environment-level faults where retrying
1737
+ * cannot succeed: `AccessDenied` (403 — credentials/policy),
1738
+ * `InvalidConfig` (bad bucket / unsupported credential type),
1739
+ * `InvalidResponse` (server returned unparseable data), and
1740
+ * `Conflict` (CAS guard lost — retrying would just re-lose against
1741
+ * the same state). `NetworkError` is intentionally absent — it covers
1742
+ * transient transport faults and stays retryable.
1743
+ *
1744
+ * Transport-layer set, distinct from `RETRIABLE_CODES` in `@baerly/protocol`'s
1745
+ * `errors.ts` (the default wire `retriable` hint). `Conflict` is "permanent"
1746
+ * here (a blind re-PUT re-loses the CAS race) yet retryable for logical CAS
1747
+ * callers that can fresh-read + re-apply. Same code, two different questions.
1748
+ */
1749
+ const PERMANENT_ERROR_CODES = /* @__PURE__ */ new Set([
1750
+ "AccessDenied",
1751
+ "InvalidConfig",
1752
+ "InvalidResponse",
1753
+ "Conflict"
1754
+ ]);
1755
+ /**
1756
+ * Parse an HTTP `Retry-After` header into a non-negative seconds value,
1757
+ * clamped to {@link RETRY_AFTER_MAX_SECONDS}. Returns `undefined` if
1758
+ * the header is absent, malformed, or whitespace.
1759
+ *
1760
+ * RFC 7231 §7.1.3 admits two forms: delta-seconds (non-negative
1761
+ * integer) and HTTP-date. Both are accepted; dates in the past return
1762
+ * `0`. Fractional seconds, negatives, and arbitrary strings reject.
1763
+ *
1764
+ * The `now` injection point exists for the unit test; production
1765
+ * callers should pass nothing.
1766
+ */
1767
+ function parseRetryAfter(header, now = Date.now) {
1768
+ if (header === null) return;
1769
+ const trimmed = header.trim();
1770
+ if (trimmed === "") return;
1771
+ if (/^\d+$/.test(trimmed)) {
1772
+ const n = Number.parseInt(trimmed, 10);
1773
+ return Number.isFinite(n) ? Math.min(n, 60) : void 0;
1774
+ }
1775
+ if (!/[a-z]/i.test(trimmed)) return;
1776
+ const t = Date.parse(trimmed);
1777
+ if (Number.isNaN(t)) return;
1778
+ const seconds = Math.max(0, Math.ceil((t - now()) / 1e3));
1779
+ return Math.min(seconds, 60);
1780
+ }
1781
+ const retryAfterCause = (res) => {
1782
+ const hint = parseRetryAfter(res.headers.get("Retry-After"));
1783
+ return hint !== void 0 ? { retryAfterSeconds: hint } : {};
1784
+ };
1785
+ const s3ErrorDetail = (status, body) => {
1786
+ const parsed = parseS3Error(body);
1787
+ if (parsed !== void 0) {
1788
+ const code = parsed.Code ?? "UnknownError";
1789
+ return parsed.Message !== void 0 ? `${status} ${code}: ${parsed.Message}` : `${status} ${code}`;
1790
+ }
1791
+ return `${status} ${body}`;
1792
+ };
1793
+ const retry = async (fn, { retries = 8, backoffMs = 100, maxDelayMs = 1e4 } = {}) => {
1794
+ let wait = backoffMs;
1795
+ for (let attempt = 0; attempt <= retries; attempt++) try {
1796
+ return await fn();
1797
+ } catch (error) {
1798
+ if (error instanceof BaerlyError && PERMANENT_ERROR_CODES.has(error.code)) throw error;
1799
+ if (attempt === retries) throw error;
1800
+ const hintMs = retryAfterHintMs(error, maxDelayMs);
1801
+ await delay(hintMs ?? wait);
1802
+ if (hintMs === void 0) wait = Math.min(wait * 1.5, maxDelayMs);
1803
+ else wait = backoffMs;
1804
+ }
1805
+ throw new BaerlyError("Internal", "s3-http retry loop exited without returning or throwing");
1806
+ };
1807
+ const retryAfterHintMs = (e, maxDelayMs) => {
1808
+ if (!(e instanceof BaerlyError)) return;
1809
+ const cause = e.cause;
1810
+ if (cause?.retryAfterSeconds === void 0) return;
1811
+ return Math.min(cause.retryAfterSeconds * 1e3, maxDelayMs);
1812
+ };
1813
+ /**
1814
+ * `Storage` impl that speaks the S3 REST API directly. Works against
1815
+ * any S3-compatible endpoint — AWS S3, R2 (S3-compat), GCS (S3-compat),
1816
+ * Minio. Does not depend on any AWS SDK.
1817
+ *
1818
+ * Authentication is plugged in via the `sign` callback; this class
1819
+ * itself does no SigV4. For Cloudflare Workers, the R2 binding fast
1820
+ * path lives in `@baerly/adapter-cloudflare`.
1821
+ */
1822
+ var S3HttpStorage = class {
1823
+ #endpoint;
1824
+ #bucket;
1825
+ #fetch;
1826
+ #sign;
1827
+ #retries;
1828
+ #backoffMs;
1829
+ constructor(options) {
1830
+ this.#endpoint = options.endpoint.replace(/\/+$/, "");
1831
+ this.#bucket = options.bucket;
1832
+ this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
1833
+ this.#sign = options.sign;
1834
+ this.#retries = options.retries ?? 8;
1835
+ this.#backoffMs = options.backoffMs ?? 100;
1836
+ }
1837
+ #objectUrl(key, versionId) {
1838
+ assertValidStorageKey(key);
1839
+ const base = `${this.#endpoint}/${this.#bucket}/${encodeURIComponent(key)}`;
1840
+ return versionId !== void 0 ? `${base}?versionId=${encodeURIComponent(versionId)}` : base;
1841
+ }
1842
+ async #dispatch(req) {
1843
+ const signed = this.#sign ? await this.#sign(req) : req;
1844
+ try {
1845
+ return await this.#fetch(signed);
1846
+ } catch (error) {
1847
+ if (error instanceof BaerlyError) throw error;
1848
+ throw new BaerlyError("NetworkError", error instanceof Error ? error.message : String(error), error);
1849
+ }
1850
+ }
1851
+ #retry(fn) {
1852
+ return retry(fn, {
1853
+ retries: this.#retries,
1854
+ backoffMs: this.#backoffMs
1855
+ });
1856
+ }
1857
+ async get(key, opts) {
1858
+ opts?.signal?.throwIfAborted();
1859
+ const url = this.#objectUrl(key, opts?.versionId);
1860
+ const headers = new Headers();
1861
+ if (opts?.ifNoneMatch !== void 0) headers.set("If-None-Match", opts.ifNoneMatch);
1862
+ return this.#retry(async () => {
1863
+ const res = await this.#dispatch(new Request(url, {
1864
+ method: "GET",
1865
+ headers,
1866
+ signal: opts?.signal ?? null
1867
+ }));
1868
+ switch (res.status) {
1869
+ case 200: {
1870
+ const etag = res.headers.get("ETag");
1871
+ if (etag === null) throw new BaerlyError("InvalidResponse", `GET ${key}: missing ETag`);
1872
+ const body = new Uint8Array(await res.arrayBuffer());
1873
+ const versionId = res.headers.get("x-amz-version-id") ?? void 0;
1874
+ return versionId !== void 0 ? {
1875
+ body,
1876
+ etag,
1877
+ versionId
1878
+ } : {
1879
+ body,
1880
+ etag
1881
+ };
1882
+ }
1883
+ case 304:
1884
+ case 404: return null;
1885
+ case 403: throw new BaerlyError("AccessDenied", `GET ${key}: 403`);
1886
+ default:
1887
+ if (res.status === 429 || res.status >= 500) throw new BaerlyError("NetworkError", `GET ${key}: ${res.status} ${await res.text()}`, {
1888
+ status: res.status,
1889
+ ...retryAfterCause(res)
1890
+ });
1891
+ throw new BaerlyError("InvalidResponse", `GET ${key}: ${s3ErrorDetail(res.status, await res.text())}`);
1892
+ }
1893
+ });
1894
+ }
1895
+ async put(key, body, opts) {
1896
+ opts?.signal?.throwIfAborted();
1897
+ const url = this.#objectUrl(key);
1898
+ const headers = new Headers();
1899
+ headers.set("Content-Type", opts?.contentType ?? "application/octet-stream");
1900
+ if (opts?.ifMatch !== void 0) headers.set("If-Match", opts.ifMatch);
1901
+ if (opts?.ifNoneMatch === "*") headers.set("If-None-Match", "*");
1902
+ return this.#retry(async () => {
1903
+ const res = await this.#dispatch(new Request(url, {
1904
+ method: "PUT",
1905
+ headers,
1906
+ body,
1907
+ signal: opts?.signal ?? null
1908
+ }));
1909
+ if (res.status === 412) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed`);
1910
+ if (res.status === 409 && opts?.ifNoneMatch === "*") throw new BaerlyError("NetworkError", `PUT ${key}: 409 ConditionalRequestConflict (contended conditional create; retryable)`, {
1911
+ status: res.status,
1912
+ ...retryAfterCause(res)
1913
+ });
1914
+ if (res.status === 404 && opts?.ifMatch !== void 0) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`);
1915
+ if (res.status === 403) throw new BaerlyError("AccessDenied", `PUT ${key}: 403`);
1916
+ if (res.status === 429 || res.status >= 500) throw new BaerlyError("NetworkError", `PUT ${key}: ${res.status} ${await res.text()}`, {
1917
+ status: res.status,
1918
+ ...retryAfterCause(res)
1919
+ });
1920
+ if (res.status !== 200 && res.status !== 204) throw new BaerlyError("InvalidResponse", `PUT ${key}: ${s3ErrorDetail(res.status, await res.text())}`);
1921
+ const etag = res.headers.get("ETag");
1922
+ if (etag === null) throw new BaerlyError("InvalidResponse", `PUT ${key}: missing ETag`);
1923
+ const dateStr = res.headers.get("Date");
1924
+ const versionId = res.headers.get("x-amz-version-id") ?? void 0;
1925
+ const result = { etag };
1926
+ if (dateStr !== null) result.serverDate = new Date(dateStr);
1927
+ if (versionId !== void 0) result.versionId = versionId;
1928
+ return result;
1929
+ });
1930
+ }
1931
+ async delete(key, opts) {
1932
+ opts?.signal?.throwIfAborted();
1933
+ const url = this.#objectUrl(key);
1934
+ await this.#retry(async () => {
1935
+ const res = await this.#dispatch(new Request(url, {
1936
+ method: "DELETE",
1937
+ signal: opts?.signal ?? null
1938
+ }));
1939
+ if (res.status === 403) throw new BaerlyError("AccessDenied", `DELETE ${key}: 403`);
1940
+ if (res.status === 429 || res.status >= 500) throw new BaerlyError("NetworkError", `DELETE ${key}: ${res.status} ${await res.text()}`, {
1941
+ status: res.status,
1942
+ ...retryAfterCause(res)
1943
+ });
1944
+ });
1945
+ }
1946
+ async *list(prefix, opts) {
1947
+ opts?.signal?.throwIfAborted();
1948
+ let yielded = 0;
1949
+ let continuationToken;
1950
+ const startAfter = opts?.startAfter ?? "";
1951
+ while (true) {
1952
+ opts?.signal?.throwIfAborted();
1953
+ const params = new URLSearchParams();
1954
+ params.set("list-type", "2");
1955
+ params.set("prefix", prefix);
1956
+ params.set("encoding-type", "url");
1957
+ if (continuationToken !== void 0) params.set("continuation-token", continuationToken);
1958
+ else if (startAfter !== "") params.set("start-after", startAfter);
1959
+ if (opts?.maxKeys !== void 0) {
1960
+ const remaining = opts.maxKeys - yielded;
1961
+ params.set("max-keys", String(Math.min(remaining, 1e3)));
1962
+ }
1963
+ const url = `${this.#endpoint}/${this.#bucket}/?${params.toString()}`;
1964
+ let parsed;
1965
+ let lastHint;
1966
+ for (let attempt = 0; attempt < 10; attempt++) {
1967
+ const outcome = await this.#retry(async () => {
1968
+ const res = await this.#dispatch(new Request(url, {
1969
+ method: "GET",
1970
+ signal: opts?.signal ?? null
1971
+ }));
1972
+ if (res.status === 200) return {
1973
+ kind: "ok",
1974
+ body: await res.text()
1975
+ };
1976
+ if (res.status === 429) return {
1977
+ kind: "ratelimited",
1978
+ retryAfterSeconds: parseRetryAfter(res.headers.get("Retry-After"))
1979
+ };
1980
+ if (res.status === 403) throw new BaerlyError("AccessDenied", `LIST ${prefix}: 403`);
1981
+ if (res.status >= 500) throw new BaerlyError("NetworkError", `LIST ${prefix}: ${res.status} ${await res.text()}`, {
1982
+ status: res.status,
1983
+ ...retryAfterCause(res)
1984
+ });
1985
+ throw new BaerlyError("InvalidResponse", `LIST ${prefix}: ${s3ErrorDetail(res.status, await res.text())}`);
1986
+ });
1987
+ if (outcome.kind === "ok") {
1988
+ parsed = parseListObjectsV2CommandOutput(outcome.body);
1989
+ break;
1990
+ }
1991
+ lastHint = outcome.retryAfterSeconds;
1992
+ const hintMs = outcome.retryAfterSeconds !== void 0 ? outcome.retryAfterSeconds * 1e3 : 0;
1993
+ await delay(Math.max(hintMs, RATE_LIMIT_BACKOFF_MILLIS));
1994
+ }
1995
+ if (parsed === void 0) throw new BaerlyError("NetworkError", `LIST ${prefix}: rate-limited`, {
1996
+ status: 429,
1997
+ ...lastHint !== void 0 ? { retryAfterSeconds: lastHint } : {}
1998
+ });
1999
+ for (const entry of parsed.Contents ?? []) {
2000
+ if (entry.Key === void 0) continue;
2001
+ yield {
2002
+ key: entry.Key,
2003
+ etag: entry.ETag ?? "",
2004
+ ...entry.LastModified !== void 0 && { lastModified: entry.LastModified }
2005
+ };
2006
+ yielded += 1;
2007
+ if (opts?.maxKeys !== void 0 && yielded >= opts.maxKeys) return;
2008
+ }
2009
+ continuationToken = parsed.NextContinuationToken;
2010
+ if (continuationToken === void 0 || continuationToken === "") return;
2011
+ }
2012
+ }
2013
+ };
2014
+ //#endregion
2015
+ //#region ../../node_modules/.pnpm/aws4fetch@1.0.20/node_modules/aws4fetch/dist/aws4fetch.esm.mjs
2016
+ /**
2017
+ * @license MIT <https://opensource.org/licenses/MIT>
2018
+ * @copyright Michael Hart 2024
2019
+ */
2020
+ const encoder = new TextEncoder();
2021
+ const HOST_SERVICES = {
2022
+ appstream2: "appstream",
2023
+ cloudhsmv2: "cloudhsm",
2024
+ email: "ses",
2025
+ marketplace: "aws-marketplace",
2026
+ mobile: "AWSMobileHubService",
2027
+ pinpoint: "mobiletargeting",
2028
+ queue: "sqs",
2029
+ "git-codecommit": "codecommit",
2030
+ "mturk-requester-sandbox": "mturk-requester",
2031
+ "personalize-runtime": "personalize"
2032
+ };
2033
+ const UNSIGNABLE_HEADERS = /* @__PURE__ */ new Set([
2034
+ "authorization",
2035
+ "content-type",
2036
+ "content-length",
2037
+ "user-agent",
2038
+ "presigned-expires",
2039
+ "expect",
2040
+ "x-amzn-trace-id",
2041
+ "range",
2042
+ "connection"
2043
+ ]);
2044
+ var AwsClient = class {
2045
+ constructor({ accessKeyId, secretAccessKey, sessionToken, service, region, cache, retries, initRetryMs }) {
2046
+ if (accessKeyId == null) throw new TypeError("accessKeyId is a required option");
2047
+ if (secretAccessKey == null) throw new TypeError("secretAccessKey is a required option");
2048
+ this.accessKeyId = accessKeyId;
2049
+ this.secretAccessKey = secretAccessKey;
2050
+ this.sessionToken = sessionToken;
2051
+ this.service = service;
2052
+ this.region = region;
2053
+ this.cache = cache || /* @__PURE__ */ new Map();
2054
+ this.retries = retries != null ? retries : 10;
2055
+ this.initRetryMs = initRetryMs || 50;
2056
+ }
2057
+ async sign(input, init) {
2058
+ if (input instanceof Request) {
2059
+ const { method, url, headers, body } = input;
2060
+ init = Object.assign({
2061
+ method,
2062
+ url,
2063
+ headers
2064
+ }, init);
2065
+ if (init.body == null && headers.has("Content-Type")) init.body = body != null && headers.has("X-Amz-Content-Sha256") ? body : await input.clone().arrayBuffer();
2066
+ input = url;
2067
+ }
2068
+ const signer = new AwsV4Signer(Object.assign({ url: input.toString() }, init, this, init && init.aws));
2069
+ const signed = Object.assign({}, init, await signer.sign());
2070
+ delete signed.aws;
2071
+ try {
2072
+ return new Request(signed.url.toString(), signed);
2073
+ } catch (e) {
2074
+ if (e instanceof TypeError) return new Request(signed.url.toString(), Object.assign({ duplex: "half" }, signed));
2075
+ throw e;
2076
+ }
2077
+ }
2078
+ async fetch(input, init) {
2079
+ for (let i = 0; i <= this.retries; i++) {
2080
+ const fetched = fetch(await this.sign(input, init));
2081
+ if (i === this.retries) return fetched;
2082
+ const res = await fetched;
2083
+ if (res.status < 500 && res.status !== 429) return res;
2084
+ await new Promise((resolve) => setTimeout(resolve, Math.random() * this.initRetryMs * Math.pow(2, i)));
2085
+ }
2086
+ throw new Error("An unknown error occurred, ensure retries is not negative");
2087
+ }
2088
+ };
2089
+ var AwsV4Signer = class {
2090
+ constructor({ method, url, headers, body, accessKeyId, secretAccessKey, sessionToken, service, region, cache, datetime, signQuery, appendSessionToken, allHeaders, singleEncode }) {
2091
+ if (url == null) throw new TypeError("url is a required option");
2092
+ if (accessKeyId == null) throw new TypeError("accessKeyId is a required option");
2093
+ if (secretAccessKey == null) throw new TypeError("secretAccessKey is a required option");
2094
+ this.method = method || (body ? "POST" : "GET");
2095
+ this.url = new URL(url);
2096
+ this.headers = new Headers(headers || {});
2097
+ this.body = body;
2098
+ this.accessKeyId = accessKeyId;
2099
+ this.secretAccessKey = secretAccessKey;
2100
+ this.sessionToken = sessionToken;
2101
+ let guessedService, guessedRegion;
2102
+ if (!service || !region) [guessedService, guessedRegion] = guessServiceRegion(this.url, this.headers);
2103
+ this.service = service || guessedService || "";
2104
+ this.region = region || guessedRegion || "us-east-1";
2105
+ this.cache = cache || /* @__PURE__ */ new Map();
2106
+ this.datetime = datetime || (/* @__PURE__ */ new Date()).toISOString().replace(/[:-]|\.\d{3}/g, "");
2107
+ this.signQuery = signQuery;
2108
+ this.appendSessionToken = appendSessionToken || this.service === "iotdevicegateway";
2109
+ this.headers.delete("Host");
2110
+ if (this.service === "s3" && !this.signQuery && !this.headers.has("X-Amz-Content-Sha256")) this.headers.set("X-Amz-Content-Sha256", "UNSIGNED-PAYLOAD");
2111
+ const params = this.signQuery ? this.url.searchParams : this.headers;
2112
+ params.set("X-Amz-Date", this.datetime);
2113
+ if (this.sessionToken && !this.appendSessionToken) params.set("X-Amz-Security-Token", this.sessionToken);
2114
+ this.signableHeaders = ["host", ...this.headers.keys()].filter((header) => allHeaders || !UNSIGNABLE_HEADERS.has(header)).sort();
2115
+ this.signedHeaders = this.signableHeaders.join(";");
2116
+ this.canonicalHeaders = this.signableHeaders.map((header) => header + ":" + (header === "host" ? this.url.host : (this.headers.get(header) || "").replace(/\s+/g, " "))).join("\n");
2117
+ this.credentialString = [
2118
+ this.datetime.slice(0, 8),
2119
+ this.region,
2120
+ this.service,
2121
+ "aws4_request"
2122
+ ].join("/");
2123
+ if (this.signQuery) {
2124
+ if (this.service === "s3" && !params.has("X-Amz-Expires")) params.set("X-Amz-Expires", "86400");
2125
+ params.set("X-Amz-Algorithm", "AWS4-HMAC-SHA256");
2126
+ params.set("X-Amz-Credential", this.accessKeyId + "/" + this.credentialString);
2127
+ params.set("X-Amz-SignedHeaders", this.signedHeaders);
2128
+ }
2129
+ if (this.service === "s3") try {
2130
+ this.encodedPath = decodeURIComponent(this.url.pathname.replace(/\+/g, " "));
2131
+ } catch (e) {
2132
+ this.encodedPath = this.url.pathname;
2133
+ }
2134
+ else this.encodedPath = this.url.pathname.replace(/\/+/g, "/");
2135
+ if (!singleEncode) this.encodedPath = encodeURIComponent(this.encodedPath).replace(/%2F/g, "/");
2136
+ this.encodedPath = encodeRfc3986(this.encodedPath);
2137
+ const seenKeys = /* @__PURE__ */ new Set();
2138
+ this.encodedSearch = [...this.url.searchParams].filter(([k]) => {
2139
+ if (!k) return false;
2140
+ if (this.service === "s3") {
2141
+ if (seenKeys.has(k)) return false;
2142
+ seenKeys.add(k);
2143
+ }
2144
+ return true;
2145
+ }).map((pair) => pair.map((p) => encodeRfc3986(encodeURIComponent(p)))).sort(([k1, v1], [k2, v2]) => k1 < k2 ? -1 : k1 > k2 ? 1 : v1 < v2 ? -1 : v1 > v2 ? 1 : 0).map((pair) => pair.join("=")).join("&");
2146
+ }
2147
+ async sign() {
2148
+ if (this.signQuery) {
2149
+ this.url.searchParams.set("X-Amz-Signature", await this.signature());
2150
+ if (this.sessionToken && this.appendSessionToken) this.url.searchParams.set("X-Amz-Security-Token", this.sessionToken);
2151
+ } else this.headers.set("Authorization", await this.authHeader());
2152
+ return {
2153
+ method: this.method,
2154
+ url: this.url,
2155
+ headers: this.headers,
2156
+ body: this.body
2157
+ };
2158
+ }
2159
+ async authHeader() {
2160
+ return [
2161
+ "AWS4-HMAC-SHA256 Credential=" + this.accessKeyId + "/" + this.credentialString,
2162
+ "SignedHeaders=" + this.signedHeaders,
2163
+ "Signature=" + await this.signature()
2164
+ ].join(", ");
2165
+ }
2166
+ async signature() {
2167
+ const date = this.datetime.slice(0, 8);
2168
+ const cacheKey = [
2169
+ this.secretAccessKey,
2170
+ date,
2171
+ this.region,
2172
+ this.service
2173
+ ].join();
2174
+ let kCredentials = this.cache.get(cacheKey);
2175
+ if (!kCredentials) {
2176
+ kCredentials = await hmac(await hmac(await hmac(await hmac("AWS4" + this.secretAccessKey, date), this.region), this.service), "aws4_request");
2177
+ this.cache.set(cacheKey, kCredentials);
2178
+ }
2179
+ return buf2hex(await hmac(kCredentials, await this.stringToSign()));
2180
+ }
2181
+ async stringToSign() {
2182
+ return [
2183
+ "AWS4-HMAC-SHA256",
2184
+ this.datetime,
2185
+ this.credentialString,
2186
+ buf2hex(await hash(await this.canonicalString()))
2187
+ ].join("\n");
2188
+ }
2189
+ async canonicalString() {
2190
+ return [
2191
+ this.method.toUpperCase(),
2192
+ this.encodedPath,
2193
+ this.encodedSearch,
2194
+ this.canonicalHeaders + "\n",
2195
+ this.signedHeaders,
2196
+ await this.hexBodyHash()
2197
+ ].join("\n");
2198
+ }
2199
+ async hexBodyHash() {
2200
+ let hashHeader = this.headers.get("X-Amz-Content-Sha256") || (this.service === "s3" && this.signQuery ? "UNSIGNED-PAYLOAD" : null);
2201
+ if (hashHeader == null) {
2202
+ if (this.body && typeof this.body !== "string" && !("byteLength" in this.body)) throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");
2203
+ hashHeader = buf2hex(await hash(this.body || ""));
2204
+ }
2205
+ return hashHeader;
2206
+ }
2207
+ };
2208
+ async function hmac(key, string) {
2209
+ const cryptoKey = await crypto.subtle.importKey("raw", typeof key === "string" ? encoder.encode(key) : key, {
2210
+ name: "HMAC",
2211
+ hash: { name: "SHA-256" }
2212
+ }, false, ["sign"]);
2213
+ return crypto.subtle.sign("HMAC", cryptoKey, encoder.encode(string));
2214
+ }
2215
+ async function hash(content) {
2216
+ return crypto.subtle.digest("SHA-256", typeof content === "string" ? encoder.encode(content) : content);
2217
+ }
2218
+ const HEX_CHARS = [
2219
+ "0",
2220
+ "1",
2221
+ "2",
2222
+ "3",
2223
+ "4",
2224
+ "5",
2225
+ "6",
2226
+ "7",
2227
+ "8",
2228
+ "9",
2229
+ "a",
2230
+ "b",
2231
+ "c",
2232
+ "d",
2233
+ "e",
2234
+ "f"
2235
+ ];
2236
+ function buf2hex(arrayBuffer) {
2237
+ const buffer = new Uint8Array(arrayBuffer);
2238
+ let out = "";
2239
+ for (let idx = 0; idx < buffer.length; idx++) {
2240
+ const n = buffer[idx];
2241
+ out += HEX_CHARS[n >>> 4 & 15];
2242
+ out += HEX_CHARS[n & 15];
2243
+ }
2244
+ return out;
2245
+ }
2246
+ function encodeRfc3986(urlEncodedStr) {
2247
+ return urlEncodedStr.replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());
2248
+ }
2249
+ function guessServiceRegion(url, headers) {
2250
+ const { hostname, pathname } = url;
2251
+ if (hostname.endsWith(".on.aws")) {
2252
+ const match = hostname.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);
2253
+ return match != null ? ["lambda", match[1] || ""] : ["", ""];
2254
+ }
2255
+ if (hostname.endsWith(".r2.cloudflarestorage.com")) return ["s3", "auto"];
2256
+ if (hostname.endsWith(".backblazeb2.com")) {
2257
+ const match = hostname.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);
2258
+ return match != null ? ["s3", match[1] || ""] : ["", ""];
2259
+ }
2260
+ const match = hostname.replace("dualstack.", "").match(/([^.]{1,63})\.(?:([^.]{0,63})\.)?amazonaws\.com(?:\.cn)?$/);
2261
+ let service = match && match[1] || "";
2262
+ let region = match && match[2];
2263
+ if (region === "us-gov") region = "us-gov-west-1";
2264
+ else if (region === "s3" || region === "s3-accelerate") {
2265
+ region = "us-east-1";
2266
+ service = "s3";
2267
+ } else if (service === "iot") if (hostname.startsWith("iot.")) service = "execute-api";
2268
+ else if (hostname.startsWith("data.jobs.iot.")) service = "iot-jobs-data";
2269
+ else service = pathname === "/mqtt" ? "iotdevicegateway" : "iotdata";
2270
+ else if (service === "autoscaling") {
2271
+ const targetPrefix = (headers.get("X-Amz-Target") || "").split(".")[0];
2272
+ if (targetPrefix === "AnyScaleFrontendService") service = "application-autoscaling";
2273
+ else if (targetPrefix === "AnyScaleScalingPlannerFrontendService") service = "autoscaling-plans";
2274
+ } else if (region == null && service.startsWith("s3-")) {
2275
+ region = service.slice(3).replace(/^fips-|^external-1/, "");
2276
+ service = "s3";
2277
+ } else if (service.endsWith("-fips")) service = service.slice(0, -5);
2278
+ else if (region && /-\d$/.test(service) && !/-\d$/.test(region)) [service, region] = [region, service];
2279
+ return [HOST_SERVICES[service] || service, region || ""];
2280
+ }
2281
+ //#endregion
2282
+ //#region ../adapter-node/src/credentials/signer.ts
2283
+ const REFRESH_BUFFER_MS = 300 * 1e3;
2284
+ function buildAwsClient(creds, region) {
2285
+ return new AwsClient({
2286
+ accessKeyId: creds.accessKeyId,
2287
+ secretAccessKey: creds.secretAccessKey,
2288
+ sessionToken: creds.sessionToken,
2289
+ region,
2290
+ service: "s3"
2291
+ });
2292
+ }
2293
+ function refreshingSigner(opts) {
2294
+ const region = opts.region;
2295
+ const now = opts.now ?? (() => Date.now());
2296
+ if (typeof opts.credentials !== "function") {
2297
+ const aws = buildAwsClient(opts.credentials, region);
2298
+ return (req) => aws.sign(req);
2299
+ }
2300
+ const provider = opts.credentials;
2301
+ let cached = null;
2302
+ let inFlight = null;
2303
+ const resolve = async () => {
2304
+ if (cached !== null && cached.expiresAt - REFRESH_BUFFER_MS > now()) return cached.aws;
2305
+ if (inFlight !== null) return inFlight;
2306
+ inFlight = (async () => {
2307
+ try {
2308
+ const creds = await provider();
2309
+ const aws = buildAwsClient(creds, region);
2310
+ cached = {
2311
+ aws,
2312
+ expiresAt: creds.expiration?.getTime() ?? Number.POSITIVE_INFINITY
2313
+ };
2314
+ return aws;
2315
+ } finally {
2316
+ inFlight = null;
2317
+ }
2318
+ })();
2319
+ return inFlight;
2320
+ };
2321
+ return async (req) => {
2322
+ return (await resolve()).sign(req);
2323
+ };
2324
+ }
2325
+ //#endregion
2326
+ //#region ../adapter-node/src/storage-factories.ts
2327
+ function buildS3Storage(opts) {
2328
+ const sign = refreshingSigner({
2329
+ region: opts.region,
2330
+ credentials: opts.credentials
2331
+ });
2332
+ return new S3HttpStorage({
2333
+ endpoint: opts.endpoint,
2334
+ bucket: opts.bucket,
2335
+ sign
2336
+ });
2337
+ }
2338
+ /**
2339
+ * AWS S3 `Storage` factory. Wraps `S3HttpStorage` with the standard
2340
+ * `aws4fetch` SigV4 signer. The endpoint is derived from the region as
2341
+ * `https://s3.<region>.amazonaws.com`.
2342
+ *
2343
+ * @example Static credentials
2344
+ * ```ts
2345
+ * import { s3Storage } from "@gusto/baerly-storage/node";
2346
+ *
2347
+ * const storage = s3Storage({
2348
+ * region: process.env["AWS_REGION"] ?? "us-east-1",
2349
+ * bucket: process.env["BUCKET"]!,
2350
+ * credentials: {
2351
+ * accessKeyId: process.env["AWS_ACCESS_KEY_ID"]!,
2352
+ * secretAccessKey: process.env["AWS_SECRET_ACCESS_KEY"]!,
2353
+ * },
2354
+ * });
2355
+ * ```
2356
+ *
2357
+ * @example EKS (refreshing) — auto-detects Pod Identity or IRSA
2358
+ * ```ts
2359
+ * import { s3Storage, fromEks } from "@gusto/baerly-storage/node";
2360
+ *
2361
+ * const storage = s3Storage({
2362
+ * region: process.env["AWS_REGION"] ?? "us-east-1",
2363
+ * bucket: process.env["BUCKET"]!,
2364
+ * credentials: fromEks(),
2365
+ * });
2366
+ * ```
2367
+ */
2368
+ function s3Storage(opts) {
2369
+ return buildS3Storage({
2370
+ endpoint: `https://s3.${opts.region}.amazonaws.com`,
2371
+ region: opts.region,
2372
+ bucket: opts.bucket,
2373
+ credentials: opts.credentials
2374
+ });
2375
+ }
2376
+ /**
2377
+ * Cloudflare R2 `Storage` factory (S3-compat endpoint). Derives the
2378
+ * endpoint from `accountId` as
2379
+ * `https://<accountId>.r2.cloudflarestorage.com` and pins region
2380
+ * `"auto"` — R2 ignores region but `aws4fetch`'s signer requires
2381
+ * the field to be set.
2382
+ *
2383
+ * For Workers that have a native R2 binding (no HTTP hop), see
2384
+ * `r2BindingStorage` in `@baerly/adapter-cloudflare`. This factory
2385
+ * is for Node hosts that talk to R2 over its public S3-compat URL.
2386
+ *
2387
+ * @example
2388
+ * ```ts
2389
+ * import { r2Storage } from "@gusto/baerly-storage/node";
2390
+ *
2391
+ * const storage = r2Storage({
2392
+ * accountId: process.env["R2_ACCOUNT_ID"]!,
2393
+ * bucket: process.env["BUCKET"]!,
2394
+ * credentials: {
2395
+ * accessKeyId: process.env["AWS_ACCESS_KEY_ID"]!,
2396
+ * secretAccessKey: process.env["AWS_SECRET_ACCESS_KEY"]!,
2397
+ * },
2398
+ * });
2399
+ * ```
2400
+ */
2401
+ function r2Storage(opts) {
2402
+ return buildS3Storage({
2403
+ endpoint: `https://${opts.accountId}.r2.cloudflarestorage.com`,
2404
+ region: "auto",
2405
+ bucket: opts.bucket,
2406
+ credentials: opts.credentials
2407
+ });
2408
+ }
2409
+ /**
2410
+ * Minio `Storage` factory — for local-dev / self-hosted S3-compat.
2411
+ * Endpoint is fully caller-supplied (e.g. `http://localhost:9102`)
2412
+ * because Minio deployments don't follow a URL template. Region is
2413
+ * pinned to `"us-east-1"`; Minio ignores it but `aws4fetch` requires
2414
+ * a value.
2415
+ *
2416
+ * @example
2417
+ * ```ts
2418
+ * import { minioStorage } from "@gusto/baerly-storage/node";
2419
+ *
2420
+ * const storage = minioStorage({
2421
+ * endpoint: process.env["BAERLY_S3_ENDPOINT"] ?? "http://localhost:9102",
2422
+ * bucket: "baerly",
2423
+ * credentials: {
2424
+ * accessKeyId: process.env["MINIO_ACCESS_KEY"]!,
2425
+ * secretAccessKey: process.env["MINIO_SECRET_KEY"]!,
2426
+ * },
2427
+ * });
2428
+ * ```
2429
+ */
2430
+ function minioStorage(opts) {
2431
+ return buildS3Storage({
2432
+ endpoint: opts.endpoint,
2433
+ region: "us-east-1",
2434
+ bucket: opts.bucket,
2435
+ credentials: opts.credentials
2436
+ });
2437
+ }
2438
+ //#endregion
2439
+ //#region src/bucket-uri.ts
2440
+ /**
2441
+ * Bucket URI parsing for the CLI surface. Consumed by every
2442
+ * `baerly admin <cmd>`, `baerly inspect`, and `baerly export`.
2443
+ *
2444
+ * Grammar:
2445
+ * - `s3://<bucket>[/<prefix>]` — S3-compatible HTTP. Creds via env
2446
+ * vars (`BAERLY_S3_ENDPOINT`, `BAERLY_S3_ACCESS_KEY_ID`,
2447
+ * `BAERLY_S3_SECRET_ACCESS_KEY`, `BAERLY_S3_REGION` — region
2448
+ * defaults to `us-east-1`).
2449
+ * - `file:///<absolute-path>` — `LocalFsStorage` rooted at the path.
2450
+ * Relative paths are rejected by the three-slash prefix.
2451
+ * - `memory://<bucket>` — `MemoryStorage` keyed via
2452
+ * `getOrCreateMemoryStorageForBucket`. Test-only.
2453
+ */
2454
+ /**
2455
+ * Parse a bucket URI into a constructed `Storage` handle + optional
2456
+ * key prefix.
2457
+ *
2458
+ * @throws BaerlyError code="InvalidConfig" — unsupported scheme, or an
2459
+ * `s3://` URI with a missing env var.
2460
+ */
2461
+ const parseBucketUri = async (uri) => {
2462
+ if (uri.startsWith("s3://")) {
2463
+ const rest = uri.slice(5);
2464
+ const slash = rest.indexOf("/");
2465
+ const bucket = slash === -1 ? rest : rest.slice(0, slash);
2466
+ const prefix = slash === -1 ? "" : rest.slice(slash + 1);
2467
+ if (bucket.length === 0) throw new BaerlyError("InvalidConfig", `bucket URI: s3:// URI requires a bucket name (got ${JSON.stringify(uri)})`);
2468
+ const accessKeyId = requireEnv("BAERLY_S3_ACCESS_KEY_ID");
2469
+ const secretAccessKey = requireEnv("BAERLY_S3_SECRET_ACCESS_KEY");
2470
+ const region = process.env["BAERLY_S3_REGION"] ?? "us-east-1";
2471
+ const endpoint = requireEnv("BAERLY_S3_ENDPOINT");
2472
+ return {
2473
+ storage: pickS3Storage({
2474
+ r2Host: endpoint.match(/^https?:\/\/([^./]+)\.r2\.cloudflarestorage\.com\b/i),
2475
+ isAws: /^https?:\/\/s3(\.[^.]+)?\.amazonaws\.com\b/i.test(endpoint),
2476
+ endpoint,
2477
+ bucket,
2478
+ accessKeyId,
2479
+ secretAccessKey,
2480
+ region
2481
+ }),
2482
+ keyPrefix: normalizeKeyPrefix(prefix)
2483
+ };
2484
+ }
2485
+ if (uri.startsWith("file:///")) return {
2486
+ storage: new LocalFsStorage({ root: uri.slice(7) }),
2487
+ keyPrefix: ""
2488
+ };
2489
+ if (uri.startsWith("memory://")) {
2490
+ const bucket = uri.slice(9);
2491
+ if (bucket.length === 0) throw new BaerlyError("InvalidConfig", `bucket URI: memory:// URI requires a bucket name (got ${JSON.stringify(uri)})`);
2492
+ return {
2493
+ storage: getOrCreateMemoryStorageForBucket(bucket),
2494
+ keyPrefix: ""
2495
+ };
2496
+ }
2497
+ throw new BaerlyError("InvalidConfig", `bucket URI: unsupported URI ${JSON.stringify(uri)}`);
2498
+ };
2499
+ const requireEnv = (name) => {
2500
+ const v = process.env[name];
2501
+ if (v === void 0 || v === "") throw new BaerlyError("InvalidConfig", `bucket URI: env var ${name} unset`);
2502
+ return v;
2503
+ };
2504
+ const pickS3Storage = (opts) => {
2505
+ const { r2Host, isAws, endpoint, bucket, accessKeyId, secretAccessKey, region } = opts;
2506
+ if (r2Host !== null) return r2Storage({
2507
+ accountId: r2Host[1],
2508
+ bucket,
2509
+ credentials: {
2510
+ accessKeyId,
2511
+ secretAccessKey
2512
+ }
2513
+ });
2514
+ if (isAws) return s3Storage({
2515
+ region,
2516
+ bucket,
2517
+ credentials: {
2518
+ accessKeyId,
2519
+ secretAccessKey
2520
+ }
2521
+ });
2522
+ return minioStorage({
2523
+ endpoint,
2524
+ bucket,
2525
+ credentials: {
2526
+ accessKeyId,
2527
+ secretAccessKey
2528
+ }
2529
+ });
2530
+ };
2531
+ const normalizeKeyPrefix = (prefix) => {
2532
+ if (prefix === "") return "";
2533
+ if (prefix.endsWith("/")) return prefix;
2534
+ return `${prefix}/`;
2535
+ };
2536
+ //#endregion
2537
+ //#region src/config.ts
2538
+ /**
2539
+ * `baerly.config.ts` loader for `baerly deploy` / `baerly doctor`.
2540
+ *
2541
+ * Mirrors the shape of `BaerlyAppConfig` from `@gusto/baerly-storage/config`
2542
+ * but lives in `@baerly/cli` so the validator/loader doesn't depend on
2543
+ * the rolldown'd umbrella bundle. The scaffolder emits the config file;
2544
+ * the CLI reads it. Both sides agree on the wire shape (informally —
2545
+ * the duplication is small and intentional).
2546
+ *
2547
+ * Resolution order:
2548
+ * 1. `<cwd>/baerly.config.ts`
2549
+ * 2. `<cwd>/baerly.config.js`
2550
+ * 3. `<cwd>/baerly.config.mjs`
2551
+ * 4. `<cwd>/baerly.config.json`
2552
+ *
2553
+ * The `.ts` form requires the user to have a TS-aware Node entry
2554
+ * point (`tsx`, `--experimental-strip-types`, or a build step that
2555
+ * produced the `.js` alongside). If `import()` throws on the `.ts`
2556
+ * file, we re-wrap as `InvalidConfig` with a hint pointing at the
2557
+ * `.js` / `.json` fallbacks.
2558
+ */
2559
+ const CONFIG_BASENAMES = [
2560
+ "baerly.config.ts",
2561
+ "baerly.config.js",
2562
+ "baerly.config.mjs",
2563
+ "baerly.config.json"
2564
+ ];
2565
+ /**
2566
+ * Locate the first `baerly.config.*` file under `cwd`. Returns the
2567
+ * absolute path or `null` if none exists.
2568
+ *
2569
+ * Exported so the collection-aware loader (and future consumers) can
2570
+ * reuse the same resolution order without re-implementing it.
2571
+ */
2572
+ const locateConfig = (cwd) => {
2573
+ for (const base of CONFIG_BASENAMES) {
2574
+ const abs = resolve(cwd, base);
2575
+ if (existsSync(abs)) return abs;
2576
+ }
2577
+ return null;
2578
+ };
2579
+ /**
2580
+ * Load `baerly.config.{ts,js,mjs,json}` from `cwd` (defaults to
2581
+ * `process.cwd()`). Validates the required fields and the
2582
+ * locked-shape optionals; returns an `AppConfig` decorated with the
2583
+ * `repoRoot` it was loaded from.
2584
+ *
2585
+ * @throws BaerlyError code="InvalidConfig" — file missing, default
2586
+ * export missing, or any field has the wrong shape / type.
2587
+ */
2588
+ const loadAppConfig = async (cwd = process.cwd()) => {
2589
+ const cfgPath = locateConfig(cwd);
2590
+ if (cfgPath === null) throw new BaerlyError("InvalidConfig", `baerly: no baerly.config.{ts,js,mjs,json} at ${cwd}. Are you in a baerly app directory?`);
2591
+ let raw;
2592
+ if (cfgPath.endsWith(".json")) {
2593
+ let text;
2594
+ try {
2595
+ text = await readFile(cfgPath, "utf8");
2596
+ } catch (error) {
2597
+ throw new BaerlyError("InvalidConfig", `baerly: failed to read ${cfgPath}: ${error.message}`, error);
2598
+ }
2599
+ try {
2600
+ raw = JSON.parse(text);
2601
+ } catch (error) {
2602
+ throw new BaerlyError("InvalidConfig", `baerly: failed to parse ${cfgPath}: ${error.message}`, error);
2603
+ }
2604
+ } else {
2605
+ let mod;
2606
+ try {
2607
+ mod = await import(pathToFileURL(cfgPath).href);
2608
+ } catch (error) {
2609
+ const hint = cfgPath.endsWith(".ts") ? " (Node cannot import .ts directly without a TS loader — point at the compiled .js or use a .json config)" : "";
2610
+ throw new BaerlyError("InvalidConfig", `baerly: failed to load ${cfgPath}: ${error.message}${hint}`, error);
2611
+ }
2612
+ raw = mod.default;
2613
+ }
2614
+ if (raw === void 0 || typeof raw !== "object" || raw === null) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath} must default-export a BaerlyAppConfig object`);
2615
+ const obj = raw;
2616
+ const app = obj["app"];
2617
+ const tenant = obj["tenant"];
2618
+ const target = obj["target"];
2619
+ if (typeof app !== "string" || app.length === 0) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`app\` must be a non-empty string`);
2620
+ if (typeof tenant !== "string" || tenant.length === 0) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`tenant\` must be a non-empty string`);
2621
+ if (target !== "cloudflare" && target !== "node") throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`target\` must be "cloudflare" or "node" (got ${JSON.stringify(target)})`);
2622
+ const authRaw = obj["auth"];
2623
+ if (typeof authRaw !== "string" || !AUTH_CONFIG_VALUES.includes(authRaw)) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`auth\` is required and must be one of ${JSON.stringify(AUTH_CONFIG_VALUES)} (got ${JSON.stringify(authRaw)})`);
2624
+ const auth = authRaw;
2625
+ const domainRaw = obj["domain"];
2626
+ if (domainRaw !== void 0 && typeof domainRaw !== "string") throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`domain\` must be a string when set`);
2627
+ const secretsRaw = obj["requiredSecrets"];
2628
+ let requiredSecrets;
2629
+ if (secretsRaw !== void 0) {
2630
+ if (!Array.isArray(secretsRaw) || !secretsRaw.every((s) => typeof s === "string")) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`requiredSecrets\` must be an array of strings`);
2631
+ requiredSecrets = secretsRaw;
2632
+ }
2633
+ const cfaRaw = obj["cloudflareAccess"];
2634
+ let cloudflareAccess;
2635
+ if (cfaRaw !== void 0) {
2636
+ if (typeof cfaRaw !== "object" || cfaRaw === null) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`cloudflareAccess\` must be an object when set`);
2637
+ const cfa = cfaRaw;
2638
+ const td = cfa["teamDomain"];
2639
+ const aud = cfa["audienceTag"];
2640
+ if (typeof td !== "string" || td.length === 0) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`cloudflareAccess.teamDomain\` must be a non-empty string`);
2641
+ if (typeof aud !== "string" || aud.length === 0) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`cloudflareAccess.audienceTag\` must be a non-empty string`);
2642
+ cloudflareAccess = {
2643
+ teamDomain: td,
2644
+ audienceTag: aud
2645
+ };
2646
+ }
2647
+ return {
2648
+ app,
2649
+ tenant,
2650
+ target,
2651
+ auth,
2652
+ ...domainRaw !== void 0 && { domain: domainRaw },
2653
+ ...requiredSecrets !== void 0 && { requiredSecrets },
2654
+ ...cloudflareAccess !== void 0 && { cloudflareAccess },
2655
+ repoRoot: cwd
2656
+ };
2657
+ };
2658
+ /**
2659
+ * Load the declared `IndexDefinition[]` for a single collection from a
2660
+ * `baerly.config.{js,mjs,json}`. Used by `baerly inspect` (key-count
2661
+ * probes) and `baerly admin rebuild-index` (resolving the `on` field).
2662
+ *
2663
+ * `.ts` configs are rejected — Node can't `import` them without a TS
2664
+ * loader; point at the compiled `.js` output instead.
2665
+ *
2666
+ * `commandName` is woven into thrown error messages so the operator
2667
+ * sees the calling command name in the prefix.
2668
+ *
2669
+ * @throws BaerlyError code="InvalidConfig" — `.ts` extension, JSON
2670
+ * parse error, missing default export, or missing
2671
+ * `collections[collection]`.
2672
+ */
2673
+ const loadCollectionIndexes = async (configPath, collection, commandName) => {
2674
+ if (configPath.endsWith(".ts")) throw new BaerlyError("InvalidConfig", `${commandName}: --config must point at compiled JS / JSON (got .ts: ${JSON.stringify(configPath)})`);
2675
+ let cfg;
2676
+ if (configPath.endsWith(".json")) {
2677
+ const text = await readFile(configPath, "utf8");
2678
+ try {
2679
+ cfg = JSON.parse(text);
2680
+ } catch (error) {
2681
+ throw new BaerlyError("InvalidConfig", `${commandName}: --config JSON parse error in ${JSON.stringify(configPath)}: ${error.message}`);
2682
+ }
2683
+ } else {
2684
+ const mod = await import(pathToFileURL(configPath.startsWith("file://") ? fileURLToPath(configPath) : resolve(configPath)).href);
2685
+ if (mod.default === void 0) throw new BaerlyError("InvalidConfig", `${commandName}: --config ${JSON.stringify(configPath)} has no default export`);
2686
+ cfg = mod.default;
2687
+ }
2688
+ return cfg.collections?.[collection]?.indexes ?? [];
2689
+ };
2690
+ //#endregion
2691
+ export { SHARED_SECRET_MISSING_MESSAGE as _, countKey as a, GC_GRACE_PERIOD_MILLIS as c, LOG_FORWARD_PROBE_CAP as d, MAINTENANCE_MIN_LIVE_BYTES as f, MAX_KEY_BYTES as g, MAINTENANCE_WARN_INTERVAL_WRITES as h, timestamp as i, GC_MAX_PENDING_CANDIDATES as l, MAINTENANCE_PROFILE_CF_PAID as m, loadCollectionIndexes as n, uuid as o, MAINTENANCE_PROFILE_CF_FREE as p, parseBucketUri as r, CURRENT_JSON_CONTENT_TYPE as s, loadAppConfig as t, GC_PENDING_CONTENT_TYPE as u };
2692
+
2693
+ //# sourceMappingURL=config-1tv0-Yzm.js.map