@gusto/baerly-storage 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/README.md +93 -52
  4. package/dist/API.md +151 -109
  5. package/dist/CHANGELOG.md +144 -0
  6. package/dist/THIRD-PARTY-LICENSES.txt +312 -0
  7. package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-BIzyAKzy.d.ts} +14 -2
  8. package/dist/app-config.d.ts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.js +288 -288
  11. package/dist/auth.js.map +1 -1
  12. package/dist/baerly.js +10 -10
  13. package/dist/baerly.js.map +1 -1
  14. package/dist/bytes-BXdamO3L.js.map +1 -1
  15. package/dist/{client-DYZfoZb9.d.ts → client-BJXF3XJA.d.ts} +10 -10
  16. package/dist/client-react.d.ts +3 -3
  17. package/dist/client-react.js.map +1 -1
  18. package/dist/client.d.ts +3 -3
  19. package/dist/client.js.map +1 -1
  20. package/dist/{cloudflare-CINJPKCW.js → cloudflare-Cn2ibODt.js} +178 -2
  21. package/dist/cloudflare-Cn2ibODt.js.map +1 -0
  22. package/dist/cloudflare.d.ts +4 -4
  23. package/dist/cloudflare.js +10 -11
  24. package/dist/cloudflare.js.map +1 -1
  25. package/dist/{subcommand-DZcHcsYp.js → config-CGyBopy3.js} +643 -439
  26. package/dist/config-CGyBopy3.js.map +1 -0
  27. package/dist/context-DRZ3tZ5l.js.map +1 -1
  28. package/dist/{cost-CQt1YRkA.js → cost-BZ_MDBmn.js} +6 -4
  29. package/dist/cost-BZ_MDBmn.js.map +1 -0
  30. package/dist/{current-json-C-EyJqs0.js → current-json-DsN7FNY1.js} +47 -13
  31. package/dist/current-json-DsN7FNY1.js.map +1 -0
  32. package/dist/{db-BM3y2JQw.d.ts → db-CCT6tDfY.d.ts} +26 -108
  33. package/dist/{deploy-CrAbfgCq.js → deploy-BKKyGlSJ.js} +11 -4
  34. package/dist/deploy-BKKyGlSJ.js.map +1 -0
  35. package/dist/dev-vite.d.ts +5 -5
  36. package/dist/dev-vite.js +5 -5
  37. package/dist/dev-vite.js.map +1 -1
  38. package/dist/dev.d.ts +1 -1
  39. package/dist/dev.js +1 -1
  40. package/dist/{doctor-Db-hzPmE.js → doctor-BVU4GNXN.js} +13 -132
  41. package/dist/doctor-BVU4GNXN.js.map +1 -0
  42. package/dist/{dump-BYA55NLP.js → dump-DPEAKub6.js} +5 -3
  43. package/dist/dump-DPEAKub6.js.map +1 -0
  44. package/dist/errors-DOdL95kK.js.map +1 -1
  45. package/dist/{export-Bhbz90-z.js → export-BcuCLFFe.js} +6 -4
  46. package/dist/{export-Bhbz90-z.js.map → export-BcuCLFFe.js.map} +1 -1
  47. package/dist/{fsck-CPPZWt9p.js → fsck-RXgLOaJG.js} +23 -11
  48. package/dist/fsck-RXgLOaJG.js.map +1 -0
  49. package/dist/{http-Cw8p6y5b.js → http-Bd4byR4n.js} +45 -61
  50. package/dist/http-Bd4byR4n.js.map +1 -0
  51. package/dist/http.d.ts +15 -15
  52. package/dist/http.js +1 -1
  53. package/dist/{index-cUY-36AN.d.ts → index-BDceQQi-.d.ts} +20 -4
  54. package/dist/{index-C3JAH1Yo.d.ts → index-Cmsxx-ZN.d.ts} +9 -9
  55. package/dist/{index-DSvwEUeF.d.ts → index-DW7GT6M2.d.ts} +50 -42
  56. package/dist/{index-DwDTWPSU.d.ts → index-DnBGSeuU.d.ts} +10 -7
  57. package/dist/index.d.ts +6 -6
  58. package/dist/index.js +4 -4
  59. package/dist/{indexes-DAu2AkTW.d.ts → indexes-Cx7uMXm0.d.ts} +2 -2
  60. package/dist/{inspect-Bdbzvi-_.js → inspect-DhI49PSi.js} +16 -8
  61. package/dist/inspect-DhI49PSi.js.map +1 -0
  62. package/dist/{snapshot-SS8USDUF.js → log-tail-DXeDkWEp.js} +154 -83
  63. package/dist/log-tail-DXeDkWEp.js.map +1 -0
  64. package/dist/{maintenance-BRrThz8V.d.ts → maintenance-BkhUr72A.d.ts} +91 -26
  65. package/dist/{maintenance-ClzBC1Vv.js → maintenance-CWBQpZ2y.js} +368 -161
  66. package/dist/maintenance-CWBQpZ2y.js.map +1 -0
  67. package/dist/{maintenance-BvOv6BMM.js → maintenance-C_KSkVjd.js} +204 -82
  68. package/dist/maintenance-C_KSkVjd.js.map +1 -0
  69. package/dist/maintenance.d.ts +3 -2
  70. package/dist/maintenance.js +3 -2
  71. package/dist/node.d.ts +13 -8
  72. package/dist/node.js +1 -1
  73. package/dist/normalize-XWY25_sG.js.map +1 -1
  74. package/dist/{observability-CpOiEN0k.js → observability-BYd-RzEx.js} +63 -55
  75. package/dist/observability-BYd-RzEx.js.map +1 -0
  76. package/dist/observability.d.ts +3 -3
  77. package/dist/observability.js +1 -1
  78. package/dist/{plan-DOTl21vq.js → plan-DIu_B6fy.js} +7 -4
  79. package/dist/plan-DIu_B6fy.js.map +1 -0
  80. package/dist/{query-BmiQy328.js → query-sQNO5vU_.js} +1071 -1099
  81. package/dist/query-sQNO5vU_.js.map +1 -0
  82. package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-DP4CqSSs.js} +5 -4
  83. package/dist/rebuild-index-DP4CqSSs.js.map +1 -0
  84. package/dist/{restore-C6IcmLeA.js → restore-DpQYef6r.js} +362 -328
  85. package/dist/restore-DpQYef6r.js.map +1 -0
  86. package/dist/shared-secret-BJdSwpgw.js.map +1 -1
  87. package/dist/{src-QQ7jDeL2.js → src-CWpkSbvJ.js} +40 -20
  88. package/dist/src-CWpkSbvJ.js.map +1 -0
  89. package/dist/{src-DU1sCMlr.js → src-D24wDpzR.js} +269 -258
  90. package/dist/src-D24wDpzR.js.map +1 -0
  91. package/dist/{src-zhEAmmF7.js → src-Db4-qVtM.js} +36 -96
  92. package/dist/src-Db4-qVtM.js.map +1 -0
  93. package/dist/subcommand-CP9NY2J4.js +159 -0
  94. package/dist/subcommand-CP9NY2J4.js.map +1 -0
  95. package/dist/{usage-CLjirdD-.js → usage-CTfDq9HR.js} +3 -3
  96. package/dist/{usage-CLjirdD-.js.map → usage-CTfDq9HR.js.map} +1 -1
  97. package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
  98. package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
  99. package/package.json +40 -29
  100. package/dist/cloudflare-CINJPKCW.js.map +0 -1
  101. package/dist/config-DVfDGyw1.js +0 -278
  102. package/dist/config-DVfDGyw1.js.map +0 -1
  103. package/dist/cost-CQt1YRkA.js.map +0 -1
  104. package/dist/current-json-C-EyJqs0.js.map +0 -1
  105. package/dist/deploy-CrAbfgCq.js.map +0 -1
  106. package/dist/doctor-Db-hzPmE.js.map +0 -1
  107. package/dist/dump-BYA55NLP.js.map +0 -1
  108. package/dist/fsck-CPPZWt9p.js.map +0 -1
  109. package/dist/http-Cw8p6y5b.js.map +0 -1
  110. package/dist/inspect-Bdbzvi-_.js.map +0 -1
  111. package/dist/maintenance-BvOv6BMM.js.map +0 -1
  112. package/dist/maintenance-ClzBC1Vv.js.map +0 -1
  113. package/dist/observability-CpOiEN0k.js.map +0 -1
  114. package/dist/plan-DOTl21vq.js.map +0 -1
  115. package/dist/query-BmiQy328.js.map +0 -1
  116. package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
  117. package/dist/restore-C6IcmLeA.js.map +0 -1
  118. package/dist/snapshot-SS8USDUF.js.map +0 -1
  119. package/dist/src-DU1sCMlr.js.map +0 -1
  120. package/dist/src-QQ7jDeL2.js.map +0 -1
  121. package/dist/src-zhEAmmF7.js.map +0 -1
  122. package/dist/subcommand-DZcHcsYp.js.map +0 -1
@@ -1,10 +1,132 @@
1
- import { d as RATE_LIMIT_BACKOFF_MILLIS, t as loadAppConfig } from "./config-DVfDGyw1.js";
2
- import { a as setJsonMode, c as parseArgs, n as emitError, o as BaerlyError, s as defineCommand } from "./baerly.js";
3
- import "node:stream";
1
+ import { o as BaerlyError } from "./baerly.js";
4
2
  import { createHash } from "node:crypto";
5
- import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
3
+ import { link, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
6
4
  import { tmpdir } from "node:os";
7
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
+ /** CF-free profile; the absent-context default. */
92
+ const MAINTENANCE_PROFILE_CF_FREE = {
93
+ gcInterval: 4,
94
+ gcMaxMarks: 20,
95
+ gcMaxSweeps: 10,
96
+ maxFoldEntriesPerPass: 20,
97
+ maxFoldBytes: 512 * 1024,
98
+ maxFoldRows: 2048
99
+ };
100
+ /**
101
+ * Rate-limit the defer-warn off SHARED current.json.last_warned_seq (not per-isolate
102
+ * memory — CF recycles isolates). ~once per this many writes.
103
+ *
104
+ * @see packages/protocol/src/coordination/current-json.ts
105
+ * @see packages/server/src/maintenance.ts
106
+ */
107
+ const MAINTENANCE_WARN_INTERVAL_WRITES = 1e3;
108
+ /**
109
+ * Canonical auth posture identifiers consumed by `BaerlyAppConfig.auth`,
110
+ * the adapter resolution path (`packages/adapter-cloudflare/src/worker.ts`,
111
+ * `packages/adapter-node/src/baerly-node.ts`), and `baerly doctor`.
112
+ *
113
+ * - `"none"` — no header check; pin every request to `config.tenant`.
114
+ * For local dev, intranet, CLI tools — contexts where the network
115
+ * seam itself is the trust boundary.
116
+ * - `"shared-secret"` — bearer-token check; reads `SHARED_SECRET` from
117
+ * the runtime env and pins every request to `config.tenant`.
118
+ *
119
+ * Custom verifiers (`cloudflareAccess`, `bearerJwt`, SigV4, …) bypass
120
+ * this enum — pass a `Verifier` to the adapter factory's `verifier:`
121
+ * option instead.
122
+ */
123
+ const AUTH_CONFIG_VALUES = ["none", "shared-secret"];
124
+ /**
125
+ * Locked error wording for `auth: "shared-secret"` + missing env var.
126
+ * Same pinning rationale as {@link NO_AUTH_CONFIGURED_MESSAGE}.
127
+ */
128
+ 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.";
129
+ //#endregion
8
130
  //#region ../protocol/src/storage/memory.ts
9
131
  const utf8Encoder$1 = new TextEncoder();
10
132
  /**
@@ -135,14 +257,15 @@ const getOrCreateMemoryStorageForBucket = (bucket) => {
135
257
  const uuid = () => crypto.randomUUID();
136
258
  /**
137
259
  * Mint the trailing seq segment of an LSN (`<base32-time>_<sess>_<seq>`).
138
- * `COUNT_BIT_WIDTH = 10` (matches `packages/protocol/src/log.ts:145`)
139
- * gives a 2-char descending base-32 string with a domain of 0..1023.
260
+ * Uses `COUNT_BIT_WIDTH` (see `packages/protocol/src/constants.ts`) to
261
+ * produce an 11-char descending base-32 string with a domain of
262
+ * 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1).
140
263
  *
141
264
  * Used together with {@link timestamp} (the descending base-32
142
265
  * encoding of millis-since-epoch). See {@link uint2strDesc} for the
143
266
  * lex-reversal property both rely on.
144
267
  */
145
- const countKey = (number) => uint2strDesc(number, 10);
268
+ const countKey = (number) => uint2strDesc(number, 53);
146
269
  const uint2str = (num, bits) => {
147
270
  const maxBase32Length = Math.ceil(bits / 5);
148
271
  return num.toString(32).padStart(maxBase32Length, "0");
@@ -169,7 +292,8 @@ const uint2str = (num, bits) => {
169
292
  * bytes-listed reduction is in
170
293
  * `docs/spec/attachments/lsn-reverse-walk-baseline.json`
171
294
  * (run `pnpm bench:lsn-reverse-walk` to reproduce). Spec rationale:
172
- * `docs/spec/sync-protocol.md` §"Subtleties of the manifest key".
295
+ * `docs/spec/sync-protocol.md` §"LSNs, wall clocks, and downstream
296
+ * consumers".
173
297
  */
174
298
  const uint2strDesc = (num, bits) => {
175
299
  return uint2str(Math.pow(2, bits) - 1 - num, bits);
@@ -213,6 +337,11 @@ const delay = (ms, signal) => new Promise((resolve, reject) => {
213
337
  });
214
338
  //#endregion
215
339
  //#region ../dev/src/local-fs.ts
340
+ /**
341
+ * Reserved prefix for the in-directory create-if-absent temp (see `put`).
342
+ * `walk`/`list` skip it; it is internal/transient and never a real key.
343
+ */
344
+ const TEMP_PREFIX = ".baerly-tmp-";
216
345
  const utf8Encoder = new TextEncoder();
217
346
  /**
218
347
  * Compare two keys by their UTF-8 byte sequences — the order S3 and R2
@@ -239,11 +368,14 @@ const compareKeysUtf8 = (a, b) => {
239
368
  * makes this adapter useful for fixture-based tests.
240
369
  *
241
370
  * Writes are atomic via `writeFile(temp) + rename(final)`; readers
242
- * never see a partially-written file. The adapter does NOT coordinate
243
- * cross-process `ifMatch`/`ifNoneMatch` checks (a TOCTOU race is
244
- * possible if two processes write the same key concurrently).
245
- * Single-process `baerlyDev()` is the design center; multi-process
246
- * scenarios use the S3 / Minio path.
371
+ * never see a partially-written file.
372
+ *
373
+ * `ifNoneMatch:"*"` uses a same-dir temp + `link(2)` (atomic exclusive
374
+ * create; `EEXIST` ⇒ key exists) so concurrent creates have exactly one
375
+ * winner. Same-dir avoids `EXDEV`; temp+`link` over `open(…,"wx")` keeps
376
+ * a partially-written new key invisible to a concurrent reader. `ifMatch`
377
+ * keeps the `rename` path (in-process TOCTOU only; cross-process
378
+ * contention uses the S3 / Minio `If-Match` path).
247
379
  *
248
380
  * Node-only — imports `node:fs`, `node:path`, `node:crypto`. Lives in
249
381
  * `@baerly/dev` because the protocol kernel is pure-modules / no I/O
@@ -275,16 +407,29 @@ var LocalFsStorage = class {
275
407
  opts?.signal?.throwIfAborted();
276
408
  const path = this.#pathFor(key);
277
409
  const newEtag = etagOf(body);
278
- if (opts?.ifMatch !== void 0 || opts?.ifNoneMatch === "*") {
279
- const existing = await readExisting(path);
280
- if (opts?.ifNoneMatch === "*" && existing !== null) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifNoneMatch="*" but key exists)`);
281
- if (opts?.ifMatch !== void 0) {
282
- if (existing === null) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`);
283
- const currentEtag = etagOf(existing);
284
- if (currentEtag !== opts.ifMatch) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${currentEtag})`);
410
+ await mkdir(dirname(path), { recursive: true });
411
+ if (opts?.ifNoneMatch === "*") {
412
+ const tmp = join(dirname(path), `${TEMP_PREFIX}${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`);
413
+ try {
414
+ await writeFile(tmp, body);
415
+ await link(tmp, path);
416
+ } catch (error) {
417
+ if (isErrnoException(error) && error.code === "EEXIST") throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifNoneMatch="*" but key exists)`);
418
+ throw new BaerlyError("InvalidResponse", `LocalFsStorage.put(${key}): ${error.message}`, error);
419
+ } finally {
420
+ await rm(tmp, { force: true }).catch(() => {});
285
421
  }
422
+ return {
423
+ etag: newEtag,
424
+ serverDate: /* @__PURE__ */ new Date()
425
+ };
426
+ }
427
+ if (opts?.ifMatch !== void 0) {
428
+ const existing = await readExisting(path);
429
+ if (existing === null) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`);
430
+ const currentEtag = etagOf(existing);
431
+ if (currentEtag !== opts.ifMatch) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${currentEtag})`);
286
432
  }
287
- await mkdir(dirname(path), { recursive: true });
288
433
  const tmp = join(tmpdir(), `baerly-localfs-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`);
289
434
  await writeFile(tmp, body);
290
435
  try {
@@ -377,7 +522,7 @@ const walk = async (root, out) => {
377
522
  for (const entry of entries) {
378
523
  const full = join(dir, entry.name);
379
524
  if (entry.isDirectory()) stack.push(full);
380
- else if (entry.isFile()) out.push(relative(root, full).split(sep).join(posix.sep));
525
+ else if (entry.isFile() && !entry.name.startsWith(TEMP_PREFIX)) out.push(relative(root, full).split(sep).join(posix.sep));
381
526
  }
382
527
  }
383
528
  };
@@ -422,244 +567,6 @@ const criticalProperties = [
422
567
  "prototype"
423
568
  ];
424
569
  //#endregion
425
- //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/validator.js
426
- const defaultOptions$1 = {
427
- allowBooleanAttributes: false,
428
- unpairedTags: []
429
- };
430
- function validate(xmlData, options) {
431
- options = Object.assign({}, defaultOptions$1, options);
432
- const tags = [];
433
- let tagFound = false;
434
- let reachedRoot = false;
435
- if (xmlData[0] === "") xmlData = xmlData.substr(1);
436
- for (let i = 0; i < xmlData.length; i++) if (xmlData[i] === "<" && xmlData[i + 1] === "?") {
437
- i += 2;
438
- i = readPI(xmlData, i);
439
- if (i.err) return i;
440
- } else if (xmlData[i] === "<") {
441
- let tagStartPos = i;
442
- i++;
443
- if (xmlData[i] === "!") {
444
- i = readCommentAndCDATA(xmlData, i);
445
- continue;
446
- } else {
447
- let closingTag = false;
448
- if (xmlData[i] === "/") {
449
- closingTag = true;
450
- i++;
451
- }
452
- let tagName = "";
453
- for (; i < xmlData.length && xmlData[i] !== ">" && xmlData[i] !== " " && xmlData[i] !== " " && xmlData[i] !== "\n" && xmlData[i] !== "\r"; i++) tagName += xmlData[i];
454
- tagName = tagName.trim();
455
- if (tagName[tagName.length - 1] === "/") {
456
- tagName = tagName.substring(0, tagName.length - 1);
457
- i--;
458
- }
459
- if (!validateTagName(tagName)) {
460
- let msg;
461
- if (tagName.trim().length === 0) msg = "Invalid space after '<'.";
462
- else msg = "Tag '" + tagName + "' is an invalid name.";
463
- return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i));
464
- }
465
- const result = readAttributeStr(xmlData, i);
466
- if (result === false) return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i));
467
- let attrStr = result.value;
468
- i = result.index;
469
- if (attrStr[attrStr.length - 1] === "/") {
470
- const attrStrStart = i - attrStr.length;
471
- attrStr = attrStr.substring(0, attrStr.length - 1);
472
- const isValid = validateAttributeString(attrStr, options);
473
- if (isValid === true) tagFound = true;
474
- else return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));
475
- } else if (closingTag) if (!result.tagClosed) return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i));
476
- else if (attrStr.trim().length > 0) return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
477
- else if (tags.length === 0) return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
478
- else {
479
- const otg = tags.pop();
480
- if (tagName !== otg.tagName) {
481
- let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
482
- return getErrorObject("InvalidTag", "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.", getLineNumberForPosition(xmlData, tagStartPos));
483
- }
484
- if (tags.length == 0) reachedRoot = true;
485
- }
486
- else {
487
- const isValid = validateAttributeString(attrStr, options);
488
- if (isValid !== true) return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));
489
- if (reachedRoot === true) return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i));
490
- else if (options.unpairedTags.indexOf(tagName) !== -1) {} else tags.push({
491
- tagName,
492
- tagStartPos
493
- });
494
- tagFound = true;
495
- }
496
- for (i++; i < xmlData.length; i++) if (xmlData[i] === "<") if (xmlData[i + 1] === "!") {
497
- i++;
498
- i = readCommentAndCDATA(xmlData, i);
499
- continue;
500
- } else if (xmlData[i + 1] === "?") {
501
- i = readPI(xmlData, ++i);
502
- if (i.err) return i;
503
- } else break;
504
- else if (xmlData[i] === "&") {
505
- const afterAmp = validateAmpersand(xmlData, i);
506
- if (afterAmp == -1) return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i));
507
- i = afterAmp;
508
- } else if (reachedRoot === true && !isWhiteSpace(xmlData[i])) return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i));
509
- if (xmlData[i] === "<") i--;
510
- }
511
- } else {
512
- if (isWhiteSpace(xmlData[i])) continue;
513
- return getErrorObject("InvalidChar", "char '" + xmlData[i] + "' is not expected.", getLineNumberForPosition(xmlData, i));
514
- }
515
- if (!tagFound) return getErrorObject("InvalidXml", "Start tag expected.", 1);
516
- else if (tags.length == 1) return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
517
- else if (tags.length > 0) return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t) => t.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", {
518
- line: 1,
519
- col: 1
520
- });
521
- return true;
522
- }
523
- function isWhiteSpace(char) {
524
- return char === " " || char === " " || char === "\n" || char === "\r";
525
- }
526
- /**
527
- * Read Processing insstructions and skip
528
- * @param {*} xmlData
529
- * @param {*} i
530
- */
531
- function readPI(xmlData, i) {
532
- const start = i;
533
- for (; i < xmlData.length; i++) if (xmlData[i] == "?" || xmlData[i] == " ") {
534
- const tagname = xmlData.substr(start, i - start);
535
- if (i > 5 && tagname === "xml") return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i));
536
- else if (xmlData[i] == "?" && xmlData[i + 1] == ">") {
537
- i++;
538
- break;
539
- } else continue;
540
- }
541
- return i;
542
- }
543
- function readCommentAndCDATA(xmlData, i) {
544
- if (xmlData.length > i + 5 && xmlData[i + 1] === "-" && xmlData[i + 2] === "-") {
545
- for (i += 3; i < xmlData.length; i++) if (xmlData[i] === "-" && xmlData[i + 1] === "-" && xmlData[i + 2] === ">") {
546
- i += 2;
547
- break;
548
- }
549
- } else if (xmlData.length > i + 8 && xmlData[i + 1] === "D" && xmlData[i + 2] === "O" && xmlData[i + 3] === "C" && xmlData[i + 4] === "T" && xmlData[i + 5] === "Y" && xmlData[i + 6] === "P" && xmlData[i + 7] === "E") {
550
- let angleBracketsCount = 1;
551
- for (i += 8; i < xmlData.length; i++) if (xmlData[i] === "<") angleBracketsCount++;
552
- else if (xmlData[i] === ">") {
553
- angleBracketsCount--;
554
- if (angleBracketsCount === 0) break;
555
- }
556
- } else if (xmlData.length > i + 9 && xmlData[i + 1] === "[" && xmlData[i + 2] === "C" && xmlData[i + 3] === "D" && xmlData[i + 4] === "A" && xmlData[i + 5] === "T" && xmlData[i + 6] === "A" && xmlData[i + 7] === "[") {
557
- for (i += 8; i < xmlData.length; i++) if (xmlData[i] === "]" && xmlData[i + 1] === "]" && xmlData[i + 2] === ">") {
558
- i += 2;
559
- break;
560
- }
561
- }
562
- return i;
563
- }
564
- const doubleQuote = "\"";
565
- const singleQuote = "'";
566
- /**
567
- * Keep reading xmlData until '<' is found outside the attribute value.
568
- * @param {string} xmlData
569
- * @param {number} i
570
- */
571
- function readAttributeStr(xmlData, i) {
572
- let attrStr = "";
573
- let startChar = "";
574
- let tagClosed = false;
575
- for (; i < xmlData.length; i++) {
576
- if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) if (startChar === "") startChar = xmlData[i];
577
- else if (startChar !== xmlData[i]) {} else startChar = "";
578
- else if (xmlData[i] === ">") {
579
- if (startChar === "") {
580
- tagClosed = true;
581
- break;
582
- }
583
- }
584
- attrStr += xmlData[i];
585
- }
586
- if (startChar !== "") return false;
587
- return {
588
- value: attrStr,
589
- index: i,
590
- tagClosed
591
- };
592
- }
593
- /**
594
- * Select all the attributes whether valid or invalid.
595
- */
596
- const validAttrStrRegxp = /* @__PURE__ */ new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?", "g");
597
- function validateAttributeString(attrStr, options) {
598
- const matches = getAllMatches(attrStr, validAttrStrRegxp);
599
- const attrNames = {};
600
- for (let i = 0; i < matches.length; i++) {
601
- if (matches[i][1].length === 0) return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' has no space in starting.", getPositionFromMatch(matches[i]));
602
- else if (matches[i][3] !== void 0 && matches[i][4] === void 0) return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' is without value.", getPositionFromMatch(matches[i]));
603
- else if (matches[i][3] === void 0 && !options.allowBooleanAttributes) return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i][2] + "' is not allowed.", getPositionFromMatch(matches[i]));
604
- const attrName = matches[i][2];
605
- if (!validateAttrName(attrName)) return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i]));
606
- if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) attrNames[attrName] = 1;
607
- else return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i]));
608
- }
609
- return true;
610
- }
611
- function validateNumberAmpersand(xmlData, i) {
612
- let re = /\d/;
613
- if (xmlData[i] === "x") {
614
- i++;
615
- re = /[\da-fA-F]/;
616
- }
617
- for (; i < xmlData.length; i++) {
618
- if (xmlData[i] === ";") return i;
619
- if (!xmlData[i].match(re)) break;
620
- }
621
- return -1;
622
- }
623
- function validateAmpersand(xmlData, i) {
624
- i++;
625
- if (xmlData[i] === ";") return -1;
626
- if (xmlData[i] === "#") {
627
- i++;
628
- return validateNumberAmpersand(xmlData, i);
629
- }
630
- let count = 0;
631
- for (; i < xmlData.length; i++, count++) {
632
- if (xmlData[i].match(/\w/) && count < 20) continue;
633
- if (xmlData[i] === ";") break;
634
- return -1;
635
- }
636
- return i;
637
- }
638
- function getErrorObject(code, message, lineNumber) {
639
- return { err: {
640
- code,
641
- msg: message,
642
- line: lineNumber.line || lineNumber,
643
- col: lineNumber.col
644
- } };
645
- }
646
- function validateAttrName(attrName) {
647
- return isName(attrName);
648
- }
649
- function validateTagName(tagname) {
650
- return isName(tagname);
651
- }
652
- function getLineNumberForPosition(xmlData, index) {
653
- const lines = xmlData.substring(0, index).split(/\r?\n/);
654
- return {
655
- line: lines.length,
656
- col: lines[lines.length - 1].length + 1
657
- };
658
- }
659
- function getPositionFromMatch(match) {
660
- return match.startIndex + match[1].length;
661
- }
662
- //#endregion
663
570
  //#region ../../node_modules/.pnpm/@nodable+entities@2.1.0/node_modules/@nodable/entities/src/entities.js
664
571
  /**
665
572
  * Basic Latin & Special Characters
@@ -2209,7 +2116,7 @@ const defaultOnDangerousProperty = (name) => {
2209
2116
  if (DANGEROUS_PROPERTY_NAMES.includes(name)) return "__" + name;
2210
2117
  return name;
2211
2118
  };
2212
- const defaultOptions = {
2119
+ const defaultOptions$1 = {
2213
2120
  preserveOrder: false,
2214
2121
  attributeNamePrefix: "@_",
2215
2122
  attributesGroupName: false,
@@ -2296,7 +2203,7 @@ function normalizeProcessEntities(value, htmlEntities) {
2296
2203
  return normalizeProcessEntities(true);
2297
2204
  }
2298
2205
  const buildOptions = function(options) {
2299
- const built = Object.assign({}, defaultOptions, options);
2206
+ const built = Object.assign({}, defaultOptions$1, options);
2300
2207
  const propertyNameOptions = [
2301
2208
  {
2302
2209
  value: built.attributeNamePrefix,
@@ -4001,110 +3908,348 @@ function transformTagName(fn, tagName, tagExp, options) {
4001
3908
  tagExp
4002
3909
  };
4003
3910
  }
4004
- function sanitizeName(name, options) {
4005
- if (criticalProperties.includes(name)) throw new Error(`[SECURITY] Invalid name: "${name}" is a reserved JavaScript keyword that could cause prototype pollution`);
4006
- else if (DANGEROUS_PROPERTY_NAMES.includes(name)) return options.onDangerousProperty(name);
4007
- return name;
3911
+ function sanitizeName(name, options) {
3912
+ if (criticalProperties.includes(name)) throw new Error(`[SECURITY] Invalid name: "${name}" is a reserved JavaScript keyword that could cause prototype pollution`);
3913
+ else if (DANGEROUS_PROPERTY_NAMES.includes(name)) return options.onDangerousProperty(name);
3914
+ return name;
3915
+ }
3916
+ //#endregion
3917
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/node2json.js
3918
+ const METADATA_SYMBOL = XmlNode.getMetaDataSymbol();
3919
+ /**
3920
+ * Helper function to strip attribute prefix from attribute map
3921
+ * @param {object} attrs - Attributes with prefix (e.g., {"@_class": "code"})
3922
+ * @param {string} prefix - Attribute prefix to remove (e.g., "@_")
3923
+ * @returns {object} Attributes without prefix (e.g., {"class": "code"})
3924
+ */
3925
+ function stripAttributePrefix(attrs, prefix) {
3926
+ if (!attrs || typeof attrs !== "object") return {};
3927
+ if (!prefix) return attrs;
3928
+ const rawAttrs = {};
3929
+ for (const key in attrs) if (key.startsWith(prefix)) {
3930
+ const rawName = key.substring(prefix.length);
3931
+ rawAttrs[rawName] = attrs[key];
3932
+ } else rawAttrs[key] = attrs[key];
3933
+ return rawAttrs;
3934
+ }
3935
+ /**
3936
+ *
3937
+ * @param {array} node
3938
+ * @param {any} options
3939
+ * @param {Matcher} matcher - Path matcher instance
3940
+ * @returns
3941
+ */
3942
+ function prettify(node, options, matcher, readonlyMatcher) {
3943
+ return compress(node, options, matcher, readonlyMatcher);
3944
+ }
3945
+ /**
3946
+ * @param {array} arr
3947
+ * @param {object} options
3948
+ * @param {Matcher} matcher - Path matcher instance
3949
+ * @returns object
3950
+ */
3951
+ function compress(arr, options, matcher, readonlyMatcher) {
3952
+ let text;
3953
+ const compressedObj = {};
3954
+ for (let i = 0; i < arr.length; i++) {
3955
+ const tagObj = arr[i];
3956
+ const property = propName(tagObj);
3957
+ if (property !== void 0 && property !== options.textNodeName) {
3958
+ const rawAttrs = stripAttributePrefix(tagObj[":@"] || {}, options.attributeNamePrefix);
3959
+ matcher.push(property, rawAttrs);
3960
+ }
3961
+ if (property === options.textNodeName) if (text === void 0) text = tagObj[property];
3962
+ else text += "" + tagObj[property];
3963
+ else if (property === void 0) continue;
3964
+ else if (tagObj[property]) {
3965
+ let val = compress(tagObj[property], options, matcher, readonlyMatcher);
3966
+ const isLeaf = isLeafTag(val, options);
3967
+ if (Object.keys(val).length === 0 && options.alwaysCreateTextNode) val[options.textNodeName] = "";
3968
+ if (tagObj[":@"]) assignAttributes(val, tagObj[":@"], readonlyMatcher, options);
3969
+ else if (Object.keys(val).length === 1 && val[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode) val = val[options.textNodeName];
3970
+ else if (Object.keys(val).length === 0) if (options.alwaysCreateTextNode) val[options.textNodeName] = "";
3971
+ else val = "";
3972
+ if (tagObj[METADATA_SYMBOL] !== void 0 && typeof val === "object" && val !== null) val[METADATA_SYMBOL] = tagObj[METADATA_SYMBOL];
3973
+ if (compressedObj[property] !== void 0 && Object.prototype.hasOwnProperty.call(compressedObj, property)) {
3974
+ if (!Array.isArray(compressedObj[property])) compressedObj[property] = [compressedObj[property]];
3975
+ compressedObj[property].push(val);
3976
+ } else {
3977
+ const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() : readonlyMatcher;
3978
+ if (options.isArray(property, jPathOrMatcher, isLeaf)) compressedObj[property] = [val];
3979
+ else compressedObj[property] = val;
3980
+ }
3981
+ if (property !== void 0 && property !== options.textNodeName) matcher.pop();
3982
+ }
3983
+ }
3984
+ if (typeof text === "string") {
3985
+ if (text.length > 0) compressedObj[options.textNodeName] = text;
3986
+ } else if (text !== void 0) compressedObj[options.textNodeName] = text;
3987
+ return compressedObj;
3988
+ }
3989
+ function propName(obj) {
3990
+ const keys = Object.keys(obj);
3991
+ for (let i = 0; i < keys.length; i++) {
3992
+ const key = keys[i];
3993
+ if (key !== ":@") return key;
3994
+ }
3995
+ }
3996
+ function assignAttributes(obj, attrMap, readonlyMatcher, options) {
3997
+ if (attrMap) {
3998
+ const keys = Object.keys(attrMap);
3999
+ const len = keys.length;
4000
+ for (let i = 0; i < len; i++) {
4001
+ const atrrName = keys[i];
4002
+ const rawAttrName = atrrName.startsWith(options.attributeNamePrefix) ? atrrName.substring(options.attributeNamePrefix.length) : atrrName;
4003
+ const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() + "." + rawAttrName : readonlyMatcher;
4004
+ if (options.isArray(atrrName, jPathOrMatcher, true, true)) obj[atrrName] = [attrMap[atrrName]];
4005
+ else obj[atrrName] = attrMap[atrrName];
4006
+ }
4007
+ }
4008
+ }
4009
+ function isLeafTag(obj, options) {
4010
+ const { textNodeName } = options;
4011
+ const propCount = Object.keys(obj).length;
4012
+ if (propCount === 0) return true;
4013
+ if (propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)) return true;
4014
+ return false;
4015
+ }
4016
+ //#endregion
4017
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/validator.js
4018
+ const defaultOptions = {
4019
+ allowBooleanAttributes: false,
4020
+ unpairedTags: []
4021
+ };
4022
+ function validate(xmlData, options) {
4023
+ options = Object.assign({}, defaultOptions, options);
4024
+ const tags = [];
4025
+ let tagFound = false;
4026
+ let reachedRoot = false;
4027
+ if (xmlData[0] === "") xmlData = xmlData.substr(1);
4028
+ for (let i = 0; i < xmlData.length; i++) if (xmlData[i] === "<" && xmlData[i + 1] === "?") {
4029
+ i += 2;
4030
+ i = readPI(xmlData, i);
4031
+ if (i.err) return i;
4032
+ } else if (xmlData[i] === "<") {
4033
+ let tagStartPos = i;
4034
+ i++;
4035
+ if (xmlData[i] === "!") {
4036
+ i = readCommentAndCDATA(xmlData, i);
4037
+ continue;
4038
+ } else {
4039
+ let closingTag = false;
4040
+ if (xmlData[i] === "/") {
4041
+ closingTag = true;
4042
+ i++;
4043
+ }
4044
+ let tagName = "";
4045
+ for (; i < xmlData.length && xmlData[i] !== ">" && xmlData[i] !== " " && xmlData[i] !== " " && xmlData[i] !== "\n" && xmlData[i] !== "\r"; i++) tagName += xmlData[i];
4046
+ tagName = tagName.trim();
4047
+ if (tagName[tagName.length - 1] === "/") {
4048
+ tagName = tagName.substring(0, tagName.length - 1);
4049
+ i--;
4050
+ }
4051
+ if (!validateTagName(tagName)) {
4052
+ let msg;
4053
+ if (tagName.trim().length === 0) msg = "Invalid space after '<'.";
4054
+ else msg = "Tag '" + tagName + "' is an invalid name.";
4055
+ return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i));
4056
+ }
4057
+ const result = readAttributeStr(xmlData, i);
4058
+ if (result === false) return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i));
4059
+ let attrStr = result.value;
4060
+ i = result.index;
4061
+ if (attrStr[attrStr.length - 1] === "/") {
4062
+ const attrStrStart = i - attrStr.length;
4063
+ attrStr = attrStr.substring(0, attrStr.length - 1);
4064
+ const isValid = validateAttributeString(attrStr, options);
4065
+ if (isValid === true) tagFound = true;
4066
+ else return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));
4067
+ } else if (closingTag) if (!result.tagClosed) return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i));
4068
+ else if (attrStr.trim().length > 0) return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
4069
+ else if (tags.length === 0) return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
4070
+ else {
4071
+ const otg = tags.pop();
4072
+ if (tagName !== otg.tagName) {
4073
+ let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
4074
+ return getErrorObject("InvalidTag", "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.", getLineNumberForPosition(xmlData, tagStartPos));
4075
+ }
4076
+ if (tags.length == 0) reachedRoot = true;
4077
+ }
4078
+ else {
4079
+ const isValid = validateAttributeString(attrStr, options);
4080
+ if (isValid !== true) return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));
4081
+ if (reachedRoot === true) return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i));
4082
+ else if (options.unpairedTags.indexOf(tagName) !== -1) {} else tags.push({
4083
+ tagName,
4084
+ tagStartPos
4085
+ });
4086
+ tagFound = true;
4087
+ }
4088
+ for (i++; i < xmlData.length; i++) if (xmlData[i] === "<") if (xmlData[i + 1] === "!") {
4089
+ i++;
4090
+ i = readCommentAndCDATA(xmlData, i);
4091
+ continue;
4092
+ } else if (xmlData[i + 1] === "?") {
4093
+ i = readPI(xmlData, ++i);
4094
+ if (i.err) return i;
4095
+ } else break;
4096
+ else if (xmlData[i] === "&") {
4097
+ const afterAmp = validateAmpersand(xmlData, i);
4098
+ if (afterAmp == -1) return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i));
4099
+ i = afterAmp;
4100
+ } else if (reachedRoot === true && !isWhiteSpace(xmlData[i])) return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i));
4101
+ if (xmlData[i] === "<") i--;
4102
+ }
4103
+ } else {
4104
+ if (isWhiteSpace(xmlData[i])) continue;
4105
+ return getErrorObject("InvalidChar", "char '" + xmlData[i] + "' is not expected.", getLineNumberForPosition(xmlData, i));
4106
+ }
4107
+ if (!tagFound) return getErrorObject("InvalidXml", "Start tag expected.", 1);
4108
+ else if (tags.length == 1) return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
4109
+ else if (tags.length > 0) return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t) => t.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", {
4110
+ line: 1,
4111
+ col: 1
4112
+ });
4113
+ return true;
4114
+ }
4115
+ function isWhiteSpace(char) {
4116
+ return char === " " || char === " " || char === "\n" || char === "\r";
4008
4117
  }
4009
- //#endregion
4010
- //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/node2json.js
4011
- const METADATA_SYMBOL = XmlNode.getMetaDataSymbol();
4012
4118
  /**
4013
- * Helper function to strip attribute prefix from attribute map
4014
- * @param {object} attrs - Attributes with prefix (e.g., {"@_class": "code"})
4015
- * @param {string} prefix - Attribute prefix to remove (e.g., "@_")
4016
- * @returns {object} Attributes without prefix (e.g., {"class": "code"})
4119
+ * Read Processing insstructions and skip
4120
+ * @param {*} xmlData
4121
+ * @param {*} i
4017
4122
  */
4018
- function stripAttributePrefix(attrs, prefix) {
4019
- if (!attrs || typeof attrs !== "object") return {};
4020
- if (!prefix) return attrs;
4021
- const rawAttrs = {};
4022
- for (const key in attrs) if (key.startsWith(prefix)) {
4023
- const rawName = key.substring(prefix.length);
4024
- rawAttrs[rawName] = attrs[key];
4025
- } else rawAttrs[key] = attrs[key];
4026
- return rawAttrs;
4123
+ function readPI(xmlData, i) {
4124
+ const start = i;
4125
+ for (; i < xmlData.length; i++) if (xmlData[i] == "?" || xmlData[i] == " ") {
4126
+ const tagname = xmlData.substr(start, i - start);
4127
+ if (i > 5 && tagname === "xml") return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i));
4128
+ else if (xmlData[i] == "?" && xmlData[i + 1] == ">") {
4129
+ i++;
4130
+ break;
4131
+ } else continue;
4132
+ }
4133
+ return i;
4027
4134
  }
4028
- /**
4029
- *
4030
- * @param {array} node
4031
- * @param {any} options
4032
- * @param {Matcher} matcher - Path matcher instance
4033
- * @returns
4034
- */
4035
- function prettify(node, options, matcher, readonlyMatcher) {
4036
- return compress(node, options, matcher, readonlyMatcher);
4135
+ function readCommentAndCDATA(xmlData, i) {
4136
+ if (xmlData.length > i + 5 && xmlData[i + 1] === "-" && xmlData[i + 2] === "-") {
4137
+ for (i += 3; i < xmlData.length; i++) if (xmlData[i] === "-" && xmlData[i + 1] === "-" && xmlData[i + 2] === ">") {
4138
+ i += 2;
4139
+ break;
4140
+ }
4141
+ } else if (xmlData.length > i + 8 && xmlData[i + 1] === "D" && xmlData[i + 2] === "O" && xmlData[i + 3] === "C" && xmlData[i + 4] === "T" && xmlData[i + 5] === "Y" && xmlData[i + 6] === "P" && xmlData[i + 7] === "E") {
4142
+ let angleBracketsCount = 1;
4143
+ for (i += 8; i < xmlData.length; i++) if (xmlData[i] === "<") angleBracketsCount++;
4144
+ else if (xmlData[i] === ">") {
4145
+ angleBracketsCount--;
4146
+ if (angleBracketsCount === 0) break;
4147
+ }
4148
+ } else if (xmlData.length > i + 9 && xmlData[i + 1] === "[" && xmlData[i + 2] === "C" && xmlData[i + 3] === "D" && xmlData[i + 4] === "A" && xmlData[i + 5] === "T" && xmlData[i + 6] === "A" && xmlData[i + 7] === "[") {
4149
+ for (i += 8; i < xmlData.length; i++) if (xmlData[i] === "]" && xmlData[i + 1] === "]" && xmlData[i + 2] === ">") {
4150
+ i += 2;
4151
+ break;
4152
+ }
4153
+ }
4154
+ return i;
4037
4155
  }
4156
+ const doubleQuote = "\"";
4157
+ const singleQuote = "'";
4038
4158
  /**
4039
- * @param {array} arr
4040
- * @param {object} options
4041
- * @param {Matcher} matcher - Path matcher instance
4042
- * @returns object
4159
+ * Keep reading xmlData until '<' is found outside the attribute value.
4160
+ * @param {string} xmlData
4161
+ * @param {number} i
4043
4162
  */
4044
- function compress(arr, options, matcher, readonlyMatcher) {
4045
- let text;
4046
- const compressedObj = {};
4047
- for (let i = 0; i < arr.length; i++) {
4048
- const tagObj = arr[i];
4049
- const property = propName(tagObj);
4050
- if (property !== void 0 && property !== options.textNodeName) {
4051
- const rawAttrs = stripAttributePrefix(tagObj[":@"] || {}, options.attributeNamePrefix);
4052
- matcher.push(property, rawAttrs);
4053
- }
4054
- if (property === options.textNodeName) if (text === void 0) text = tagObj[property];
4055
- else text += "" + tagObj[property];
4056
- else if (property === void 0) continue;
4057
- else if (tagObj[property]) {
4058
- let val = compress(tagObj[property], options, matcher, readonlyMatcher);
4059
- const isLeaf = isLeafTag(val, options);
4060
- if (Object.keys(val).length === 0 && options.alwaysCreateTextNode) val[options.textNodeName] = "";
4061
- if (tagObj[":@"]) assignAttributes(val, tagObj[":@"], readonlyMatcher, options);
4062
- else if (Object.keys(val).length === 1 && val[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode) val = val[options.textNodeName];
4063
- else if (Object.keys(val).length === 0) if (options.alwaysCreateTextNode) val[options.textNodeName] = "";
4064
- else val = "";
4065
- if (tagObj[METADATA_SYMBOL] !== void 0 && typeof val === "object" && val !== null) val[METADATA_SYMBOL] = tagObj[METADATA_SYMBOL];
4066
- if (compressedObj[property] !== void 0 && Object.prototype.hasOwnProperty.call(compressedObj, property)) {
4067
- if (!Array.isArray(compressedObj[property])) compressedObj[property] = [compressedObj[property]];
4068
- compressedObj[property].push(val);
4069
- } else {
4070
- const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() : readonlyMatcher;
4071
- if (options.isArray(property, jPathOrMatcher, isLeaf)) compressedObj[property] = [val];
4072
- else compressedObj[property] = val;
4163
+ function readAttributeStr(xmlData, i) {
4164
+ let attrStr = "";
4165
+ let startChar = "";
4166
+ let tagClosed = false;
4167
+ for (; i < xmlData.length; i++) {
4168
+ if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) if (startChar === "") startChar = xmlData[i];
4169
+ else if (startChar !== xmlData[i]) {} else startChar = "";
4170
+ else if (xmlData[i] === ">") {
4171
+ if (startChar === "") {
4172
+ tagClosed = true;
4173
+ break;
4073
4174
  }
4074
- if (property !== void 0 && property !== options.textNodeName) matcher.pop();
4075
4175
  }
4176
+ attrStr += xmlData[i];
4076
4177
  }
4077
- if (typeof text === "string") {
4078
- if (text.length > 0) compressedObj[options.textNodeName] = text;
4079
- } else if (text !== void 0) compressedObj[options.textNodeName] = text;
4080
- return compressedObj;
4178
+ if (startChar !== "") return false;
4179
+ return {
4180
+ value: attrStr,
4181
+ index: i,
4182
+ tagClosed
4183
+ };
4081
4184
  }
4082
- function propName(obj) {
4083
- const keys = Object.keys(obj);
4084
- for (let i = 0; i < keys.length; i++) {
4085
- const key = keys[i];
4086
- if (key !== ":@") return key;
4185
+ /**
4186
+ * Select all the attributes whether valid or invalid.
4187
+ */
4188
+ const validAttrStrRegxp = /* @__PURE__ */ new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?", "g");
4189
+ function validateAttributeString(attrStr, options) {
4190
+ const matches = getAllMatches(attrStr, validAttrStrRegxp);
4191
+ const attrNames = {};
4192
+ for (let i = 0; i < matches.length; i++) {
4193
+ if (matches[i][1].length === 0) return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' has no space in starting.", getPositionFromMatch(matches[i]));
4194
+ else if (matches[i][3] !== void 0 && matches[i][4] === void 0) return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' is without value.", getPositionFromMatch(matches[i]));
4195
+ else if (matches[i][3] === void 0 && !options.allowBooleanAttributes) return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i][2] + "' is not allowed.", getPositionFromMatch(matches[i]));
4196
+ const attrName = matches[i][2];
4197
+ if (!validateAttrName(attrName)) return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i]));
4198
+ if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) attrNames[attrName] = 1;
4199
+ else return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i]));
4087
4200
  }
4201
+ return true;
4088
4202
  }
4089
- function assignAttributes(obj, attrMap, readonlyMatcher, options) {
4090
- if (attrMap) {
4091
- const keys = Object.keys(attrMap);
4092
- const len = keys.length;
4093
- for (let i = 0; i < len; i++) {
4094
- const atrrName = keys[i];
4095
- const rawAttrName = atrrName.startsWith(options.attributeNamePrefix) ? atrrName.substring(options.attributeNamePrefix.length) : atrrName;
4096
- const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() + "." + rawAttrName : readonlyMatcher;
4097
- if (options.isArray(atrrName, jPathOrMatcher, true, true)) obj[atrrName] = [attrMap[atrrName]];
4098
- else obj[atrrName] = attrMap[atrrName];
4099
- }
4203
+ function validateNumberAmpersand(xmlData, i) {
4204
+ let re = /\d/;
4205
+ if (xmlData[i] === "x") {
4206
+ i++;
4207
+ re = /[\da-fA-F]/;
4208
+ }
4209
+ for (; i < xmlData.length; i++) {
4210
+ if (xmlData[i] === ";") return i;
4211
+ if (!xmlData[i].match(re)) break;
4100
4212
  }
4213
+ return -1;
4101
4214
  }
4102
- function isLeafTag(obj, options) {
4103
- const { textNodeName } = options;
4104
- const propCount = Object.keys(obj).length;
4105
- if (propCount === 0) return true;
4106
- if (propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)) return true;
4107
- return false;
4215
+ function validateAmpersand(xmlData, i) {
4216
+ i++;
4217
+ if (xmlData[i] === ";") return -1;
4218
+ if (xmlData[i] === "#") {
4219
+ i++;
4220
+ return validateNumberAmpersand(xmlData, i);
4221
+ }
4222
+ let count = 0;
4223
+ for (; i < xmlData.length; i++, count++) {
4224
+ if (xmlData[i].match(/\w/) && count < 20) continue;
4225
+ if (xmlData[i] === ";") break;
4226
+ return -1;
4227
+ }
4228
+ return i;
4229
+ }
4230
+ function getErrorObject(code, message, lineNumber) {
4231
+ return { err: {
4232
+ code,
4233
+ msg: message,
4234
+ line: lineNumber.line || lineNumber,
4235
+ col: lineNumber.col
4236
+ } };
4237
+ }
4238
+ function validateAttrName(attrName) {
4239
+ return isName(attrName);
4240
+ }
4241
+ function validateTagName(tagname) {
4242
+ return isName(tagname);
4243
+ }
4244
+ function getLineNumberForPosition(xmlData, index) {
4245
+ const lines = xmlData.substring(0, index).split(/\r?\n/);
4246
+ return {
4247
+ line: lines.length,
4248
+ col: lines[lines.length - 1].length + 1
4249
+ };
4250
+ }
4251
+ function getPositionFromMatch(match) {
4252
+ return match.startIndex + match[1].length;
4108
4253
  }
4109
4254
  //#endregion
4110
4255
  //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js
@@ -4329,7 +4474,12 @@ var S3HttpStorage = class {
4329
4474
  }
4330
4475
  async #dispatch(req) {
4331
4476
  const signed = this.#sign ? await this.#sign(req) : req;
4332
- return this.#fetch(signed);
4477
+ try {
4478
+ return await this.#fetch(signed);
4479
+ } catch (error) {
4480
+ if (error instanceof BaerlyError) throw error;
4481
+ throw new BaerlyError("NetworkError", error instanceof Error ? error.message : String(error), error);
4482
+ }
4333
4483
  }
4334
4484
  #retry(fn) {
4335
4485
  return retry(fn, {
@@ -4390,6 +4540,10 @@ var S3HttpStorage = class {
4390
4540
  signal: opts?.signal ?? null
4391
4541
  }));
4392
4542
  if (res.status === 412) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed`);
4543
+ if (res.status === 409 && opts?.ifNoneMatch === "*") throw new BaerlyError("NetworkError", `PUT ${key}: 409 ConditionalRequestConflict (contended conditional create; retryable)`, {
4544
+ status: res.status,
4545
+ ...retryAfterCause(res)
4546
+ });
4393
4547
  if (res.status === 404 && opts?.ifMatch !== void 0) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`);
4394
4548
  if (res.status === 403) throw new BaerlyError("AccessDenied", `PUT ${key}: 403`);
4395
4549
  if (res.status === 429 || res.status >= 500) throw new BaerlyError("NetworkError", `PUT ${key}: ${res.status} ${await res.text()}`, {
@@ -5013,110 +5167,160 @@ const normalizeKeyPrefix = (prefix) => {
5013
5167
  return `${prefix}/`;
5014
5168
  };
5015
5169
  //#endregion
5016
- //#region src/subcommand.ts
5017
- /** Shared exit-code mapping for caught `BaerlyError`s. */
5018
- const errorToExitCode = (code) => {
5019
- if (code === "InvalidConfig") return 1;
5020
- if (code === "Conflict" || code === "Internal" || code === "InvalidResponse") return 3;
5021
- return 2;
5170
+ //#region src/config.ts
5171
+ /**
5172
+ * `baerly.config.ts` loader for `baerly deploy` / `baerly doctor`.
5173
+ *
5174
+ * Mirrors the shape of `BaerlyAppConfig` from `@gusto/baerly-storage/config`
5175
+ * but lives in `@baerly/cli` so the validator/loader doesn't depend on
5176
+ * the rolldown'd umbrella bundle. The scaffolder emits the config file;
5177
+ * the CLI reads it. Both sides agree on the wire shape (informally —
5178
+ * the duplication is small and intentional).
5179
+ *
5180
+ * Resolution order:
5181
+ * 1. `<cwd>/baerly.config.ts`
5182
+ * 2. `<cwd>/baerly.config.js`
5183
+ * 3. `<cwd>/baerly.config.mjs`
5184
+ * 4. `<cwd>/baerly.config.json`
5185
+ *
5186
+ * The `.ts` form requires the user to have a TS-aware Node entry
5187
+ * point (`tsx`, `--experimental-strip-types`, or a build step that
5188
+ * produced the `.js` alongside). If `import()` throws on the `.ts`
5189
+ * file, we re-wrap as `InvalidConfig` with a hint pointing at the
5190
+ * `.js` / `.json` fallbacks.
5191
+ */
5192
+ const CONFIG_BASENAMES = [
5193
+ "baerly.config.ts",
5194
+ "baerly.config.js",
5195
+ "baerly.config.mjs",
5196
+ "baerly.config.json"
5197
+ ];
5198
+ /**
5199
+ * Locate the first `baerly.config.*` file under `cwd`. Returns the
5200
+ * absolute path or `null` if none exists.
5201
+ *
5202
+ * Exported so the collection-aware loader (and future consumers) can
5203
+ * reuse the same resolution order without re-implementing it.
5204
+ */
5205
+ const locateConfig = (cwd) => {
5206
+ for (const base of CONFIG_BASENAMES) {
5207
+ const abs = resolve(cwd, base);
5208
+ if (existsSync(abs)) return abs;
5209
+ }
5210
+ return null;
5022
5211
  };
5023
5212
  /**
5024
- * Build the app/tenant resolver. Captures `name` to surface the
5025
- * calling subcommand in the InvalidConfig hint.
5213
+ * Load `baerly.config.{ts,js,mjs,json}` from `cwd` (defaults to
5214
+ * `process.cwd()`). Validates the required fields and the
5215
+ * locked-shape optionals; returns an `AppConfig` decorated with the
5216
+ * `repoRoot` it was loaded from.
5217
+ *
5218
+ * @throws BaerlyError code="InvalidConfig" — file missing, default
5219
+ * export missing, or any field has the wrong shape / type.
5026
5220
  */
5027
- const makeResolveAppTenant = (name) => {
5028
- return async (args) => {
5029
- const flagApp = typeof args.app === "string" && args.app.length > 0 ? args.app : void 0;
5030
- const flagTenant = typeof args.tenant === "string" && args.tenant.length > 0 ? args.tenant : void 0;
5031
- if (flagApp !== void 0 && flagTenant !== void 0) return {
5032
- app: flagApp,
5033
- tenant: flagTenant
5034
- };
5221
+ const loadAppConfig = async (cwd = process.cwd()) => {
5222
+ const cfgPath = locateConfig(cwd);
5223
+ if (cfgPath === null) throw new BaerlyError("InvalidConfig", `baerly: no baerly.config.{ts,js,mjs,json} at ${cwd}. Are you in a baerly app directory?`);
5224
+ let raw;
5225
+ if (cfgPath.endsWith(".json")) {
5226
+ let text;
5035
5227
  try {
5036
- const cfg = await loadAppConfig();
5037
- return {
5038
- app: flagApp ?? cfg.app,
5039
- tenant: flagTenant ?? cfg.tenant
5040
- };
5228
+ text = await readFile(cfgPath, "utf8");
5041
5229
  } catch (error) {
5042
- throw new BaerlyError("InvalidConfig", `baerly ${name}: --app / --tenant not supplied and no baerly.config.{ts,js,mjs,json} in cwd (${error instanceof BaerlyError ? error.message : error.message})`, error);
5230
+ throw new BaerlyError("InvalidConfig", `baerly: failed to read ${cfgPath}: ${error.message}`, error);
5043
5231
  }
5044
- };
5045
- };
5046
- /**
5047
- * Wrap `def.handler` with the standard JSON-mode toggle, unknown-key
5048
- * rejection, and error-to-exit-code mapping. Shared by both the citty
5049
- * `run({ args })` path and the test `run(argv)` path. The caller
5050
- * supplies the {@link SubcommandContext}; this lets each `run(argv)`
5051
- * invocation attach its own `streams` override without leaking across
5052
- * invocations.
5053
- */
5054
- const kebabToCamel = (s) => s.replace(/-(\w)/g, (_, c) => c.toUpperCase());
5055
- const wrapHandler = (def) => {
5056
- const allowedKeys = new Set(Object.keys(def.args).flatMap((k) => k.includes("-") ? [k, kebabToCamel(k)] : [k]).concat(["_"]));
5057
- return async (args, ctx) => {
5058
- if ("json" in def.args) setJsonMode(args.json === true);
5059
5232
  try {
5060
- for (const k of Object.keys(args)) if (!allowedKeys.has(k)) throw new BaerlyError("InvalidConfig", `baerly ${def.name}: unknown flag --${k}`);
5061
- return await def.handler(args, ctx);
5233
+ raw = JSON.parse(text);
5062
5234
  } catch (error) {
5063
- if (error instanceof BaerlyError) {
5064
- emitError(def.name, error.code, error.message);
5065
- return errorToExitCode(error.code);
5066
- }
5067
- emitError(def.name, "Unknown", error.message);
5068
- return 2;
5235
+ throw new BaerlyError("InvalidConfig", `baerly: failed to parse ${cfgPath}: ${error.message}`, error);
5236
+ }
5237
+ } else {
5238
+ let mod;
5239
+ try {
5240
+ mod = await import(pathToFileURL(cfgPath).href);
5241
+ } catch (error) {
5242
+ const hint = cfgPath.endsWith(".ts") ? " (Node cannot import .ts directly without a TS loader — point at the compiled .js or use a .json config)" : "";
5243
+ throw new BaerlyError("InvalidConfig", `baerly: failed to load ${cfgPath}: ${error.message}${hint}`, error);
5069
5244
  }
5245
+ raw = mod.default;
5246
+ }
5247
+ if (raw === void 0 || typeof raw !== "object" || raw === null) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath} must default-export a BaerlyAppConfig object`);
5248
+ const obj = raw;
5249
+ const app = obj["app"];
5250
+ const tenant = obj["tenant"];
5251
+ const target = obj["target"];
5252
+ if (typeof app !== "string" || app.length === 0) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`app\` must be a non-empty string`);
5253
+ if (typeof tenant !== "string" || tenant.length === 0) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`tenant\` must be a non-empty string`);
5254
+ if (target !== "cloudflare" && target !== "node") throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`target\` must be "cloudflare" or "node" (got ${JSON.stringify(target)})`);
5255
+ const authRaw = obj["auth"];
5256
+ 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)})`);
5257
+ const auth = authRaw;
5258
+ const domainRaw = obj["domain"];
5259
+ if (domainRaw !== void 0 && typeof domainRaw !== "string") throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`domain\` must be a string when set`);
5260
+ const secretsRaw = obj["requiredSecrets"];
5261
+ let requiredSecrets;
5262
+ if (secretsRaw !== void 0) {
5263
+ if (!Array.isArray(secretsRaw) || !secretsRaw.every((s) => typeof s === "string")) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`requiredSecrets\` must be an array of strings`);
5264
+ requiredSecrets = secretsRaw;
5265
+ }
5266
+ const cfaRaw = obj["cloudflareAccess"];
5267
+ let cloudflareAccess;
5268
+ if (cfaRaw !== void 0) {
5269
+ if (typeof cfaRaw !== "object" || cfaRaw === null) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`cloudflareAccess\` must be an object when set`);
5270
+ const cfa = cfaRaw;
5271
+ const td = cfa["teamDomain"];
5272
+ const aud = cfa["audienceTag"];
5273
+ if (typeof td !== "string" || td.length === 0) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`cloudflareAccess.teamDomain\` must be a non-empty string`);
5274
+ if (typeof aud !== "string" || aud.length === 0) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`cloudflareAccess.audienceTag\` must be a non-empty string`);
5275
+ cloudflareAccess = {
5276
+ teamDomain: td,
5277
+ audienceTag: aud
5278
+ };
5279
+ }
5280
+ return {
5281
+ app,
5282
+ tenant,
5283
+ target,
5284
+ auth,
5285
+ ...domainRaw !== void 0 && { domain: domainRaw },
5286
+ ...requiredSecrets !== void 0 && { requiredSecrets },
5287
+ ...cloudflareAccess !== void 0 && { cloudflareAccess },
5288
+ repoRoot: cwd
5070
5289
  };
5071
5290
  };
5072
5291
  /**
5073
- * Wrap a baerly subcommand. Returns `{ cmd, run }` —
5074
- * - `cmd` is a citty `defineCommand` block; mount it in
5075
- * `baerly.ts`'s `subCommands`. It calls `process.exit(code)` on a
5076
- * non-zero exit so the parent process surfaces the failure.
5077
- * - `run(argv)` is the in-process test entry. It parses `argv` with
5078
- * citty's `parseArgs`, dispatches through the same wrapped
5079
- * handler, and returns the integer exit code (does NOT call
5080
- * `process.exit`).
5292
+ * Load the declared `IndexDefinition[]` for a single collection from a
5293
+ * `baerly.config.{js,mjs,json}`. Used by `baerly inspect` (key-count
5294
+ * probes) and `baerly admin rebuild-index` (resolving the `on` field).
5295
+ *
5296
+ * `.ts` configs are rejected — Node can't `import` them without a TS
5297
+ * loader; point at the compiled `.js` output instead.
5081
5298
  *
5082
- * The two paths share `wrapHandler` so JSON-mode toggling,
5083
- * unknown-flag rejection, and error-to-exit-code mapping behave
5084
- * identically.
5299
+ * `commandName` is woven into thrown error messages so the operator
5300
+ * sees the calling command name in the prefix.
5301
+ *
5302
+ * @throws BaerlyError code="InvalidConfig" — `.ts` extension, JSON
5303
+ * parse error, missing default export, or missing
5304
+ * `collections[collection]`.
5085
5305
  */
5086
- const defineBaerlySubcommand = (def) => {
5087
- const resolveAppTenant = makeResolveAppTenant(def.name);
5088
- const wrapped = wrapHandler(def);
5089
- const cmd = defineCommand({
5090
- meta: {
5091
- name: def.name,
5092
- description: def.meta.description
5093
- },
5094
- args: def.args,
5095
- run: async ({ args }) => {
5096
- const code = await wrapped(args, { resolveAppTenant });
5097
- if (code !== 0) process.exit(code);
5098
- }
5099
- });
5100
- const run = async (argv, options) => {
5101
- let parsed;
5306
+ const loadCollectionIndexes = async (configPath, collection, commandName) => {
5307
+ if (configPath.endsWith(".ts")) throw new BaerlyError("InvalidConfig", `${commandName}: --config must point at compiled JS / JSON (got .ts: ${JSON.stringify(configPath)})`);
5308
+ let cfg;
5309
+ if (configPath.endsWith(".json")) {
5310
+ const text = await readFile(configPath, "utf8");
5102
5311
  try {
5103
- parsed = parseArgs(argv, def.args);
5312
+ cfg = JSON.parse(text);
5104
5313
  } catch (error) {
5105
- setJsonMode(argv.includes("--json"));
5106
- emitError(def.name, "InvalidConfig", error.message);
5107
- return 1;
5314
+ throw new BaerlyError("InvalidConfig", `${commandName}: --config JSON parse error in ${JSON.stringify(configPath)}: ${error.message}`);
5108
5315
  }
5109
- return wrapped(parsed, {
5110
- resolveAppTenant,
5111
- streams: options?.streams
5112
- });
5113
- };
5114
- return {
5115
- cmd,
5116
- run
5117
- };
5316
+ } else {
5317
+ const mod = await import(pathToFileURL(configPath.startsWith("file://") ? fileURLToPath(configPath) : resolve(configPath)).href);
5318
+ if (mod.default === void 0) throw new BaerlyError("InvalidConfig", `${commandName}: --config ${JSON.stringify(configPath)} has no default export`);
5319
+ cfg = mod.default;
5320
+ }
5321
+ return cfg.collections?.[collection]?.indexes ?? [];
5118
5322
  };
5119
5323
  //#endregion
5120
- export { uuid as a, countKey as i, parseBucketUri as n, timestamp as r, defineBaerlySubcommand as t };
5324
+ export { countKey as a, GC_GRACE_PERIOD_MILLIS as c, LOG_FORWARD_PROBE_CAP as d, MAINTENANCE_MIN_LIVE_BYTES as f, SHARED_SECRET_MISSING_MESSAGE as g, MAX_KEY_BYTES as h, timestamp as i, GC_MAX_PENDING_CANDIDATES as l, MAINTENANCE_WARN_INTERVAL_WRITES 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 };
5121
5325
 
5122
- //# sourceMappingURL=subcommand-DZcHcsYp.js.map
5326
+ //# sourceMappingURL=config-CGyBopy3.js.map