@gusto/baerly-storage 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +97 -0
  2. package/dist/API.md +850 -0
  3. package/dist/app-config-Cb5dO2s9.d.ts +480 -0
  4. package/dist/app-config.d.ts +2 -0
  5. package/dist/app-config.js +8 -0
  6. package/dist/app-config.js.map +1 -0
  7. package/dist/auth.d.ts +237 -0
  8. package/dist/auth.js +1335 -0
  9. package/dist/auth.js.map +1 -0
  10. package/dist/baerly.js +761 -0
  11. package/dist/baerly.js.map +1 -0
  12. package/dist/bucket-uri-BrDEYvzy.js +4922 -0
  13. package/dist/bucket-uri-BrDEYvzy.js.map +1 -0
  14. package/dist/chunk-EAsCxrDo.js +14 -0
  15. package/dist/client-BLf3Ae5s.d.ts +233 -0
  16. package/dist/client-react.d.ts +131 -0
  17. package/dist/client-react.js +559 -0
  18. package/dist/client-react.js.map +1 -0
  19. package/dist/client.d.ts +4 -0
  20. package/dist/client.js +160 -0
  21. package/dist/client.js.map +1 -0
  22. package/dist/cloudflare-CINJPKCW.js +911 -0
  23. package/dist/cloudflare-CINJPKCW.js.map +1 -0
  24. package/dist/cloudflare.d.ts +211 -0
  25. package/dist/cloudflare.js +445 -0
  26. package/dist/cloudflare.js.map +1 -0
  27. package/dist/config-Bsg8wgwo.js +198 -0
  28. package/dist/config-Bsg8wgwo.js.map +1 -0
  29. package/dist/context-Oj7ffwD-.js +187 -0
  30. package/dist/context-Oj7ffwD-.js.map +1 -0
  31. package/dist/cost-B1WiZxlf.js +203 -0
  32. package/dist/cost-B1WiZxlf.js.map +1 -0
  33. package/dist/current-json-BkatBzF7.js +252 -0
  34. package/dist/current-json-BkatBzF7.js.map +1 -0
  35. package/dist/db-D62JguBc.d.ts +336 -0
  36. package/dist/deploy-BB-wqbhf.js +83 -0
  37. package/dist/deploy-BB-wqbhf.js.map +1 -0
  38. package/dist/dev-banner-CWHIk8tH.d.ts +26 -0
  39. package/dist/dev-vite.d.ts +146 -0
  40. package/dist/dev-vite.js +223 -0
  41. package/dist/dev-vite.js.map +1 -0
  42. package/dist/dev.d.ts +3 -0
  43. package/dist/dev.js +2 -0
  44. package/dist/doctor-B8h9GCN9.js +331 -0
  45. package/dist/doctor-B8h9GCN9.js.map +1 -0
  46. package/dist/dump-BHo_sIMZ.js +116 -0
  47. package/dist/dump-BHo_sIMZ.js.map +1 -0
  48. package/dist/errors-DOdL95kK.js +58 -0
  49. package/dist/errors-DOdL95kK.js.map +1 -0
  50. package/dist/export-Dz2PZKSR.js +423 -0
  51. package/dist/export-Dz2PZKSR.js.map +1 -0
  52. package/dist/fsck-DEz9lyCy.js +293 -0
  53. package/dist/fsck-DEz9lyCy.js.map +1 -0
  54. package/dist/http-CjUO1Bec.js +1756 -0
  55. package/dist/http-CjUO1Bec.js.map +1 -0
  56. package/dist/http.d.ts +1619 -0
  57. package/dist/http.js +2 -0
  58. package/dist/index-BGC-ENnj.d.ts +1065 -0
  59. package/dist/index-BYv0hb8M.d.ts +1457 -0
  60. package/dist/index-BquQkhJi.d.ts +112 -0
  61. package/dist/index-COsQ-Mlz.d.ts +146 -0
  62. package/dist/index.d.ts +6 -0
  63. package/dist/index.js +6 -0
  64. package/dist/indexes-BXn7a06a.js +297 -0
  65. package/dist/indexes-BXn7a06a.js.map +1 -0
  66. package/dist/indexes-DwOXkn1Y.d.ts +22 -0
  67. package/dist/inspect-x02aFWnh.js +149 -0
  68. package/dist/inspect-x02aFWnh.js.map +1 -0
  69. package/dist/log-walk-DIru96UT.js +260 -0
  70. package/dist/log-walk-DIru96UT.js.map +1 -0
  71. package/dist/maintenance-Bn6ul9aV.js +758 -0
  72. package/dist/maintenance-Bn6ul9aV.js.map +1 -0
  73. package/dist/maintenance.d.ts +323 -0
  74. package/dist/maintenance.js +2 -0
  75. package/dist/node.d.ts +422 -0
  76. package/dist/node.js +2 -0
  77. package/dist/normalize-XWY25_sG.js +133 -0
  78. package/dist/normalize-XWY25_sG.js.map +1 -0
  79. package/dist/observability-2IDYRuZK.js +2333 -0
  80. package/dist/observability-2IDYRuZK.js.map +1 -0
  81. package/dist/observability.d.ts +3 -0
  82. package/dist/observability.js +3 -0
  83. package/dist/plan-Cs17VqjU.js +224 -0
  84. package/dist/plan-Cs17VqjU.js.map +1 -0
  85. package/dist/query-DcSbFLJt.js +1880 -0
  86. package/dist/query-DcSbFLJt.js.map +1 -0
  87. package/dist/rebuild-index-C5gTXryd.js +119 -0
  88. package/dist/rebuild-index-C5gTXryd.js.map +1 -0
  89. package/dist/rebuild-index-DwXM0WfA.js +104 -0
  90. package/dist/rebuild-index-DwXM0WfA.js.map +1 -0
  91. package/dist/request-BEF_OvMh.js +72 -0
  92. package/dist/request-BEF_OvMh.js.map +1 -0
  93. package/dist/restore-CbKVMMpm.js +847 -0
  94. package/dist/restore-CbKVMMpm.js.map +1 -0
  95. package/dist/shared-secret-BJdSwpgw.js +71 -0
  96. package/dist/shared-secret-BJdSwpgw.js.map +1 -0
  97. package/dist/snapshot-D7C4_FSl.js +71 -0
  98. package/dist/snapshot-D7C4_FSl.js.map +1 -0
  99. package/dist/snapshot-z_N9hpTe.js +917 -0
  100. package/dist/snapshot-z_N9hpTe.js.map +1 -0
  101. package/dist/src-Chafbw8r.js +522 -0
  102. package/dist/src-Chafbw8r.js.map +1 -0
  103. package/dist/src-DyET_VPP.js +6199 -0
  104. package/dist/src-DyET_VPP.js.map +1 -0
  105. package/dist/src-n0Te1r98.js +352 -0
  106. package/dist/src-n0Te1r98.js.map +1 -0
  107. package/dist/subcommand-BWs6K7zb.js +110 -0
  108. package/dist/subcommand-BWs6K7zb.js.map +1 -0
  109. package/dist/usage-RVUQMLop.js +339 -0
  110. package/dist/usage-RVUQMLop.js.map +1 -0
  111. package/dist/validate-DhH1lO8I.js +377 -0
  112. package/dist/validate-DhH1lO8I.js.map +1 -0
  113. package/dist/wire-izfGZDvr.js +7 -0
  114. package/dist/wire-izfGZDvr.js.map +1 -0
  115. package/package.json +189 -0
@@ -0,0 +1,4922 @@
1
+ import { i as RATE_LIMIT_BACKOFF_MILLIS } from "./config-Bsg8wgwo.js";
2
+ import { o as BaerlyError } from "./baerly.js";
3
+ import { createHash } from "node:crypto";
4
+ import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import { dirname, join, posix, relative, resolve, sep } from "node:path";
7
+ //#region ../protocol/src/bytes.ts
8
+ /**
9
+ * UTF-8 JSON byte helpers — names the encode/decode idiom used by
10
+ * every content body, log entry, snapshot, and current.json payload.
11
+ */
12
+ const encodeJsonBytes = (value) => new TextEncoder().encode(JSON.stringify(value));
13
+ const decodeJsonBytes = (bytes) => JSON.parse(new TextDecoder().decode(bytes));
14
+ //#endregion
15
+ //#region ../protocol/src/storage/memory.ts
16
+ /**
17
+ * In-memory `Storage`. The randomized property test runs against
18
+ * this; it must be deterministic — no clocks beyond the caller's,
19
+ * no randomness, no I/O.
20
+ *
21
+ * ETags are a monotonically increasing hex counter formatted in the
22
+ * `"<hex>"` shape S3 returns (the surrounding double-quotes are part
23
+ * of the ETag header value). Keys are stored verbatim.
24
+ */
25
+ var MemoryStorage = class {
26
+ #objects = /* @__PURE__ */ new Map();
27
+ #etagCounter = 0;
28
+ #nextEtag() {
29
+ this.#etagCounter += 1;
30
+ return `"${this.#etagCounter.toString(16)}"`;
31
+ }
32
+ async get(key, opts) {
33
+ opts?.signal?.throwIfAborted();
34
+ const stored = this.#objects.get(key);
35
+ if (stored === void 0) return null;
36
+ if (opts?.ifNoneMatch !== void 0 && opts.ifNoneMatch === stored.etag) return null;
37
+ return {
38
+ body: stored.body,
39
+ etag: stored.etag
40
+ };
41
+ }
42
+ async put(key, body, opts) {
43
+ opts?.signal?.throwIfAborted();
44
+ const existing = this.#objects.get(key);
45
+ if (opts?.ifNoneMatch === "*" && existing !== void 0) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifNoneMatch="*" but key exists)`);
46
+ if (opts?.ifMatch !== void 0) {
47
+ if (existing === void 0) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`);
48
+ if (existing.etag !== opts.ifMatch) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${existing.etag})`);
49
+ }
50
+ const etag = this.#nextEtag();
51
+ this.#objects.set(key, {
52
+ body,
53
+ etag,
54
+ ...opts?.contentType !== void 0 && { contentType: opts.contentType }
55
+ });
56
+ return {
57
+ etag,
58
+ serverDate: /* @__PURE__ */ new Date()
59
+ };
60
+ }
61
+ async delete(key, opts) {
62
+ opts?.signal?.throwIfAborted();
63
+ this.#objects.delete(key);
64
+ }
65
+ async *list(prefix, opts) {
66
+ opts?.signal?.throwIfAborted();
67
+ const startAfter = opts?.startAfter ?? "";
68
+ const maxKeys = opts?.maxKeys ?? Infinity;
69
+ const sorted = [...this.#objects.keys()].filter((k) => k.startsWith(prefix) && k > startAfter).toSorted();
70
+ let yielded = 0;
71
+ for (const key of sorted) {
72
+ if (yielded >= maxKeys) return;
73
+ opts?.signal?.throwIfAborted();
74
+ const stored = this.#objects.get(key);
75
+ if (stored === void 0) continue;
76
+ yield {
77
+ key,
78
+ etag: stored.etag
79
+ };
80
+ yielded += 1;
81
+ }
82
+ }
83
+ /**
84
+ * Test-only: drop all objects.
85
+ * @internal
86
+ */
87
+ _clear() {
88
+ this.#objects.clear();
89
+ this.#etagCounter = 0;
90
+ }
91
+ };
92
+ const sharedPerBucket = /* @__PURE__ */ new Map();
93
+ /**
94
+ * Get the process-singleton {@link MemoryStorage} for the named
95
+ * bucket, creating one on first access. Use this when constructing
96
+ * a `Storage` directly so multiple consumers in the same process
97
+ * see each other's writes for the same bucket name.
98
+ */
99
+ const getOrCreateMemoryStorageForBucket = (bucket) => {
100
+ let s = sharedPerBucket.get(bucket);
101
+ if (s === void 0) {
102
+ s = new MemoryStorage();
103
+ sharedPerBucket.set(bucket, s);
104
+ }
105
+ return s;
106
+ };
107
+ //#endregion
108
+ //#region ../protocol/src/types.ts
109
+ /**
110
+ * Mint a fresh {@link UUID}. The cast lives here so callers don't sprinkle
111
+ * `<UUID>crypto.randomUUID()` throughout the codebase.
112
+ */
113
+ const uuid = () => crypto.randomUUID();
114
+ /**
115
+ * Mint the trailing seq segment of an LSN (`<base32-time>_<sess>_<seq>`).
116
+ * `COUNT_BIT_WIDTH = 10` (matches `packages/protocol/src/log.ts:145`)
117
+ * gives a 2-char descending base-32 string with a domain of 0..1023.
118
+ *
119
+ * Used together with {@link timestamp} (the descending base-32
120
+ * encoding of millis-since-epoch). See {@link uint2strDesc} for the
121
+ * lex-reversal property both rely on.
122
+ */
123
+ const countKey = (number) => uint2strDesc(number, 10);
124
+ const uint2str = (num, bits) => {
125
+ const maxBase32Length = Math.ceil(bits / 5);
126
+ return num.toString(32).padStart(maxBase32Length, "0");
127
+ };
128
+ /**
129
+ * Lex-reversed base-32 encoder for an unsigned integer in `[0, 2^bits)`.
130
+ * Pads to `Math.ceil(bits/5)` chars so all values in the domain compare
131
+ * lex against each other.
132
+ *
133
+ * **Order-reversal property:** for any pair of integers `a < b` (with
134
+ * `a, b ∈ [0, 2^bits)`), `uint2strDesc(a, bits) > uint2strDesc(b, bits)`
135
+ * lexicographically. Composed into an LSN of shape
136
+ * `<base32-time>_<session>_<seq>` (where both `<base32-time>` and
137
+ * `<seq>` use this encoder), a forward `Storage.list(prefix)`
138
+ * returns log entries in reverse-causal order — newer entries first.
139
+ *
140
+ * This is the structural property the read path leans on:
141
+ * `ListObjectsV2` is forward-only on S3, but the descending encoding
142
+ * makes "fetch the K newest entries" a single bounded LIST with
143
+ * `maxKeys=K` instead of a full-population LIST + in-memory reverse.
144
+ *
145
+ * Behaviourally verified across randomized populations in
146
+ * `packages/protocol/src/lsn-reverse-list.test.ts`. Quantified
147
+ * bytes-listed reduction is in
148
+ * `docs/spec/attachments/lsn-reverse-walk-baseline.json`
149
+ * (run `pnpm bench:lsn-reverse-walk` to reproduce). Spec rationale:
150
+ * `docs/spec/sync-protocol.md` §"Subtleties of the manifest key".
151
+ */
152
+ const uint2strDesc = (num, bits) => {
153
+ return uint2str(Math.pow(2, bits) - 1 - num, bits);
154
+ };
155
+ //#endregion
156
+ //#region ../protocol/src/time.ts
157
+ const timestamp = (epoch = 0) => uint2strDesc(epoch, 42);
158
+ /**
159
+ * Delay for `ms` milliseconds, with optional cancellation. If
160
+ * `signal` aborts before the delay elapses, the returned promise
161
+ * rejects with `signal.reason`. Used by `S3HttpStorage`'s retry
162
+ * loop so shutdown can interrupt an in-flight backoff instead of
163
+ * waiting for it to complete.
164
+ */
165
+ const delay = (ms, signal) => new Promise((resolve, reject) => {
166
+ if (signal?.aborted) {
167
+ reject(signal.reason);
168
+ return;
169
+ }
170
+ const timer = setTimeout(resolve, ms);
171
+ signal?.addEventListener("abort", () => {
172
+ clearTimeout(timer);
173
+ reject(signal.reason);
174
+ }, { once: true });
175
+ });
176
+ //#endregion
177
+ //#region ../dev/src/local-fs.ts
178
+ /**
179
+ * `Storage` backed by a directory tree. Keys may contain `/` and map
180
+ * to nested directories on disk so `ls`/`cat` work as expected.
181
+ *
182
+ * ETags are content-addressed: `"<sha-256-hex>"` (the surrounding
183
+ * double-quotes match S3's wire format for non-multipart objects).
184
+ * Identical bodies share an ETag across runs — the property that
185
+ * makes this adapter useful for fixture-based tests.
186
+ *
187
+ * Writes are atomic via `writeFile(temp) + rename(final)`; readers
188
+ * never see a partially-written file. The adapter does NOT coordinate
189
+ * cross-process `ifMatch`/`ifNoneMatch` checks (a TOCTOU race is
190
+ * possible if two processes write the same key concurrently).
191
+ * Single-process `baerlyDev()` is the design center; multi-process
192
+ * scenarios use the S3 / Minio path.
193
+ *
194
+ * Node-only — imports `node:fs`, `node:path`, `node:crypto`. Lives in
195
+ * `@baerly/dev` because the protocol kernel is pure-modules / no I/O
196
+ * and must remain Worker-bundleable.
197
+ */
198
+ var LocalFsStorage = class {
199
+ #root;
200
+ constructor(opts) {
201
+ this.#root = resolve(opts.root);
202
+ }
203
+ async get(key, opts) {
204
+ opts?.signal?.throwIfAborted();
205
+ const path = this.#pathFor(key);
206
+ let body;
207
+ try {
208
+ body = await readFile(path);
209
+ } catch (error) {
210
+ if (isErrnoException(error) && error.code === "ENOENT") return null;
211
+ throw new BaerlyError("InvalidResponse", `LocalFsStorage.get(${key}): ${error.message}`, error);
212
+ }
213
+ const etag = etagOf(body);
214
+ if (opts?.ifNoneMatch !== void 0 && opts.ifNoneMatch === etag) return null;
215
+ return {
216
+ body: toUint8Array(body),
217
+ etag
218
+ };
219
+ }
220
+ async put(key, body, opts) {
221
+ opts?.signal?.throwIfAborted();
222
+ const path = this.#pathFor(key);
223
+ const newEtag = etagOf(body);
224
+ if (opts?.ifMatch !== void 0 || opts?.ifNoneMatch === "*") {
225
+ const existing = await readExisting(path);
226
+ if (opts?.ifNoneMatch === "*" && existing !== null) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifNoneMatch="*" but key exists)`);
227
+ if (opts?.ifMatch !== void 0) {
228
+ if (existing === null) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`);
229
+ const currentEtag = etagOf(existing);
230
+ if (currentEtag !== opts.ifMatch) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${currentEtag})`);
231
+ }
232
+ }
233
+ await mkdir(dirname(path), { recursive: true });
234
+ const tmp = join(tmpdir(), `baerly-localfs-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`);
235
+ await writeFile(tmp, body);
236
+ try {
237
+ await rename(tmp, path);
238
+ } catch (error) {
239
+ await rm(tmp, { force: true }).catch(() => {});
240
+ throw new BaerlyError("InvalidResponse", `LocalFsStorage.put(${key}): ${error.message}`, error);
241
+ }
242
+ return {
243
+ etag: newEtag,
244
+ serverDate: /* @__PURE__ */ new Date()
245
+ };
246
+ }
247
+ async delete(key, opts) {
248
+ opts?.signal?.throwIfAborted();
249
+ const path = this.#pathFor(key);
250
+ try {
251
+ await rm(path);
252
+ } catch (error) {
253
+ if (isErrnoException(error) && error.code === "ENOENT") return;
254
+ throw new BaerlyError("InvalidResponse", `LocalFsStorage.delete(${key}): ${error.message}`, error);
255
+ }
256
+ }
257
+ async *list(prefix, opts) {
258
+ opts?.signal?.throwIfAborted();
259
+ const startAfter = opts?.startAfter ?? "";
260
+ const maxKeys = opts?.maxKeys ?? Infinity;
261
+ const keys = [];
262
+ await walk(this.#root, keys);
263
+ keys.sort();
264
+ let yielded = 0;
265
+ for (const key of keys) {
266
+ if (!key.startsWith(prefix)) continue;
267
+ if (key <= startAfter) continue;
268
+ if (yielded >= maxKeys) return;
269
+ opts?.signal?.throwIfAborted();
270
+ yield {
271
+ key,
272
+ etag: etagOf(await readFile(this.#pathFor(key)))
273
+ };
274
+ yielded += 1;
275
+ }
276
+ }
277
+ /**
278
+ * Map an S3-style key to a filesystem path under `#root`, rejecting
279
+ * anything that could escape the root (path traversal, absolute
280
+ * paths, empty segments, backslashes). All rejections throw
281
+ * `BaerlyError("InvalidConfig", …)`.
282
+ */
283
+ #pathFor(key) {
284
+ if (key.length === 0) throw new BaerlyError("InvalidConfig", "LocalFsStorage: empty key");
285
+ if (key.startsWith("/")) throw new BaerlyError("InvalidConfig", `LocalFsStorage: leading "/" in key: ${key}`);
286
+ if (key.includes("\\")) throw new BaerlyError("InvalidConfig", `LocalFsStorage: backslash in key: ${key}`);
287
+ const segments = key.split("/");
288
+ if (segments.some((s) => s === "" || s === "." || s === "..")) throw new BaerlyError("InvalidConfig", `LocalFsStorage: illegal segment in key: ${key}`);
289
+ const path = join(this.#root, ...segments);
290
+ if (path !== this.#root && !path.startsWith(this.#root + sep)) throw new BaerlyError("InvalidConfig", `LocalFsStorage: resolved path escapes root: ${key}`);
291
+ return path;
292
+ }
293
+ };
294
+ const etagOf = (body) => {
295
+ return `"${createHash("sha256").update(body).digest("hex")}"`;
296
+ };
297
+ const toUint8Array = (buf) => new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
298
+ const isErrnoException = (e) => typeof e === "object" && e !== null && "code" in e;
299
+ const readExisting = async (path) => {
300
+ try {
301
+ return await readFile(path);
302
+ } catch (error) {
303
+ if (isErrnoException(error) && error.code === "ENOENT") return null;
304
+ throw error;
305
+ }
306
+ };
307
+ /**
308
+ * Recursive directory walk. Yields filesystem-relative paths in
309
+ * forward-slash form so callers can use them as S3-style keys
310
+ * regardless of the host's path separator.
311
+ */
312
+ const walk = async (root, out) => {
313
+ const stack = [root];
314
+ while (stack.length > 0) {
315
+ const dir = stack.pop();
316
+ let entries;
317
+ try {
318
+ entries = await readdir(dir, { withFileTypes: true });
319
+ } catch (error) {
320
+ if (isErrnoException(error) && error.code === "ENOENT") continue;
321
+ throw error;
322
+ }
323
+ for (const entry of entries) {
324
+ const full = join(dir, entry.name);
325
+ if (entry.isDirectory()) stack.push(full);
326
+ else if (entry.isFile()) out.push(relative(root, full).split(sep).join(posix.sep));
327
+ }
328
+ }
329
+ };
330
+ //#endregion
331
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/util.js
332
+ const regexName = /* @__PURE__ */ new RegExp("^[:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");
333
+ function getAllMatches(string, regex) {
334
+ const matches = [];
335
+ let match = regex.exec(string);
336
+ while (match) {
337
+ const allmatches = [];
338
+ allmatches.startIndex = regex.lastIndex - match[0].length;
339
+ const len = match.length;
340
+ for (let index = 0; index < len; index++) allmatches.push(match[index]);
341
+ matches.push(allmatches);
342
+ match = regex.exec(string);
343
+ }
344
+ return matches;
345
+ }
346
+ const isName = function(string) {
347
+ const match = regexName.exec(string);
348
+ return !(match === null || typeof match === "undefined");
349
+ };
350
+ function isExist(v) {
351
+ return typeof v !== "undefined";
352
+ }
353
+ /**
354
+ * Dangerous property names that could lead to prototype pollution or security issues
355
+ */
356
+ const DANGEROUS_PROPERTY_NAMES = [
357
+ "hasOwnProperty",
358
+ "toString",
359
+ "valueOf",
360
+ "__defineGetter__",
361
+ "__defineSetter__",
362
+ "__lookupGetter__",
363
+ "__lookupSetter__"
364
+ ];
365
+ const criticalProperties = [
366
+ "__proto__",
367
+ "constructor",
368
+ "prototype"
369
+ ];
370
+ //#endregion
371
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/validator.js
372
+ const defaultOptions$1 = {
373
+ allowBooleanAttributes: false,
374
+ unpairedTags: []
375
+ };
376
+ function validate(xmlData, options) {
377
+ options = Object.assign({}, defaultOptions$1, options);
378
+ const tags = [];
379
+ let tagFound = false;
380
+ let reachedRoot = false;
381
+ if (xmlData[0] === "") xmlData = xmlData.substr(1);
382
+ for (let i = 0; i < xmlData.length; i++) if (xmlData[i] === "<" && xmlData[i + 1] === "?") {
383
+ i += 2;
384
+ i = readPI(xmlData, i);
385
+ if (i.err) return i;
386
+ } else if (xmlData[i] === "<") {
387
+ let tagStartPos = i;
388
+ i++;
389
+ if (xmlData[i] === "!") {
390
+ i = readCommentAndCDATA(xmlData, i);
391
+ continue;
392
+ } else {
393
+ let closingTag = false;
394
+ if (xmlData[i] === "/") {
395
+ closingTag = true;
396
+ i++;
397
+ }
398
+ let tagName = "";
399
+ for (; i < xmlData.length && xmlData[i] !== ">" && xmlData[i] !== " " && xmlData[i] !== " " && xmlData[i] !== "\n" && xmlData[i] !== "\r"; i++) tagName += xmlData[i];
400
+ tagName = tagName.trim();
401
+ if (tagName[tagName.length - 1] === "/") {
402
+ tagName = tagName.substring(0, tagName.length - 1);
403
+ i--;
404
+ }
405
+ if (!validateTagName(tagName)) {
406
+ let msg;
407
+ if (tagName.trim().length === 0) msg = "Invalid space after '<'.";
408
+ else msg = "Tag '" + tagName + "' is an invalid name.";
409
+ return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i));
410
+ }
411
+ const result = readAttributeStr(xmlData, i);
412
+ if (result === false) return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i));
413
+ let attrStr = result.value;
414
+ i = result.index;
415
+ if (attrStr[attrStr.length - 1] === "/") {
416
+ const attrStrStart = i - attrStr.length;
417
+ attrStr = attrStr.substring(0, attrStr.length - 1);
418
+ const isValid = validateAttributeString(attrStr, options);
419
+ if (isValid === true) tagFound = true;
420
+ else return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));
421
+ } else if (closingTag) if (!result.tagClosed) return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i));
422
+ else if (attrStr.trim().length > 0) return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
423
+ else if (tags.length === 0) return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
424
+ else {
425
+ const otg = tags.pop();
426
+ if (tagName !== otg.tagName) {
427
+ let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
428
+ return getErrorObject("InvalidTag", "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.", getLineNumberForPosition(xmlData, tagStartPos));
429
+ }
430
+ if (tags.length == 0) reachedRoot = true;
431
+ }
432
+ else {
433
+ const isValid = validateAttributeString(attrStr, options);
434
+ if (isValid !== true) return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));
435
+ if (reachedRoot === true) return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i));
436
+ else if (options.unpairedTags.indexOf(tagName) !== -1) {} else tags.push({
437
+ tagName,
438
+ tagStartPos
439
+ });
440
+ tagFound = true;
441
+ }
442
+ for (i++; i < xmlData.length; i++) if (xmlData[i] === "<") if (xmlData[i + 1] === "!") {
443
+ i++;
444
+ i = readCommentAndCDATA(xmlData, i);
445
+ continue;
446
+ } else if (xmlData[i + 1] === "?") {
447
+ i = readPI(xmlData, ++i);
448
+ if (i.err) return i;
449
+ } else break;
450
+ else if (xmlData[i] === "&") {
451
+ const afterAmp = validateAmpersand(xmlData, i);
452
+ if (afterAmp == -1) return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i));
453
+ i = afterAmp;
454
+ } else if (reachedRoot === true && !isWhiteSpace(xmlData[i])) return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i));
455
+ if (xmlData[i] === "<") i--;
456
+ }
457
+ } else {
458
+ if (isWhiteSpace(xmlData[i])) continue;
459
+ return getErrorObject("InvalidChar", "char '" + xmlData[i] + "' is not expected.", getLineNumberForPosition(xmlData, i));
460
+ }
461
+ if (!tagFound) return getErrorObject("InvalidXml", "Start tag expected.", 1);
462
+ else if (tags.length == 1) return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
463
+ else if (tags.length > 0) return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t) => t.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", {
464
+ line: 1,
465
+ col: 1
466
+ });
467
+ return true;
468
+ }
469
+ function isWhiteSpace(char) {
470
+ return char === " " || char === " " || char === "\n" || char === "\r";
471
+ }
472
+ /**
473
+ * Read Processing insstructions and skip
474
+ * @param {*} xmlData
475
+ * @param {*} i
476
+ */
477
+ function readPI(xmlData, i) {
478
+ const start = i;
479
+ for (; i < xmlData.length; i++) if (xmlData[i] == "?" || xmlData[i] == " ") {
480
+ const tagname = xmlData.substr(start, i - start);
481
+ if (i > 5 && tagname === "xml") return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i));
482
+ else if (xmlData[i] == "?" && xmlData[i + 1] == ">") {
483
+ i++;
484
+ break;
485
+ } else continue;
486
+ }
487
+ return i;
488
+ }
489
+ function readCommentAndCDATA(xmlData, i) {
490
+ if (xmlData.length > i + 5 && xmlData[i + 1] === "-" && xmlData[i + 2] === "-") {
491
+ for (i += 3; i < xmlData.length; i++) if (xmlData[i] === "-" && xmlData[i + 1] === "-" && xmlData[i + 2] === ">") {
492
+ i += 2;
493
+ break;
494
+ }
495
+ } 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") {
496
+ let angleBracketsCount = 1;
497
+ for (i += 8; i < xmlData.length; i++) if (xmlData[i] === "<") angleBracketsCount++;
498
+ else if (xmlData[i] === ">") {
499
+ angleBracketsCount--;
500
+ if (angleBracketsCount === 0) break;
501
+ }
502
+ } 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] === "[") {
503
+ for (i += 8; i < xmlData.length; i++) if (xmlData[i] === "]" && xmlData[i + 1] === "]" && xmlData[i + 2] === ">") {
504
+ i += 2;
505
+ break;
506
+ }
507
+ }
508
+ return i;
509
+ }
510
+ const doubleQuote = "\"";
511
+ const singleQuote = "'";
512
+ /**
513
+ * Keep reading xmlData until '<' is found outside the attribute value.
514
+ * @param {string} xmlData
515
+ * @param {number} i
516
+ */
517
+ function readAttributeStr(xmlData, i) {
518
+ let attrStr = "";
519
+ let startChar = "";
520
+ let tagClosed = false;
521
+ for (; i < xmlData.length; i++) {
522
+ if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) if (startChar === "") startChar = xmlData[i];
523
+ else if (startChar !== xmlData[i]) {} else startChar = "";
524
+ else if (xmlData[i] === ">") {
525
+ if (startChar === "") {
526
+ tagClosed = true;
527
+ break;
528
+ }
529
+ }
530
+ attrStr += xmlData[i];
531
+ }
532
+ if (startChar !== "") return false;
533
+ return {
534
+ value: attrStr,
535
+ index: i,
536
+ tagClosed
537
+ };
538
+ }
539
+ /**
540
+ * Select all the attributes whether valid or invalid.
541
+ */
542
+ const validAttrStrRegxp = /* @__PURE__ */ new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?", "g");
543
+ function validateAttributeString(attrStr, options) {
544
+ const matches = getAllMatches(attrStr, validAttrStrRegxp);
545
+ const attrNames = {};
546
+ for (let i = 0; i < matches.length; i++) {
547
+ if (matches[i][1].length === 0) return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' has no space in starting.", getPositionFromMatch(matches[i]));
548
+ 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]));
549
+ else if (matches[i][3] === void 0 && !options.allowBooleanAttributes) return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i][2] + "' is not allowed.", getPositionFromMatch(matches[i]));
550
+ const attrName = matches[i][2];
551
+ if (!validateAttrName(attrName)) return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i]));
552
+ if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) attrNames[attrName] = 1;
553
+ else return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i]));
554
+ }
555
+ return true;
556
+ }
557
+ function validateNumberAmpersand(xmlData, i) {
558
+ let re = /\d/;
559
+ if (xmlData[i] === "x") {
560
+ i++;
561
+ re = /[\da-fA-F]/;
562
+ }
563
+ for (; i < xmlData.length; i++) {
564
+ if (xmlData[i] === ";") return i;
565
+ if (!xmlData[i].match(re)) break;
566
+ }
567
+ return -1;
568
+ }
569
+ function validateAmpersand(xmlData, i) {
570
+ i++;
571
+ if (xmlData[i] === ";") return -1;
572
+ if (xmlData[i] === "#") {
573
+ i++;
574
+ return validateNumberAmpersand(xmlData, i);
575
+ }
576
+ let count = 0;
577
+ for (; i < xmlData.length; i++, count++) {
578
+ if (xmlData[i].match(/\w/) && count < 20) continue;
579
+ if (xmlData[i] === ";") break;
580
+ return -1;
581
+ }
582
+ return i;
583
+ }
584
+ function getErrorObject(code, message, lineNumber) {
585
+ return { err: {
586
+ code,
587
+ msg: message,
588
+ line: lineNumber.line || lineNumber,
589
+ col: lineNumber.col
590
+ } };
591
+ }
592
+ function validateAttrName(attrName) {
593
+ return isName(attrName);
594
+ }
595
+ function validateTagName(tagname) {
596
+ return isName(tagname);
597
+ }
598
+ function getLineNumberForPosition(xmlData, index) {
599
+ const lines = xmlData.substring(0, index).split(/\r?\n/);
600
+ return {
601
+ line: lines.length,
602
+ col: lines[lines.length - 1].length + 1
603
+ };
604
+ }
605
+ function getPositionFromMatch(match) {
606
+ return match.startIndex + match[1].length;
607
+ }
608
+ //#endregion
609
+ //#region ../../node_modules/.pnpm/@nodable+entities@2.1.0/node_modules/@nodable/entities/src/entities.js
610
+ /**
611
+ * Basic Latin & Special Characters
612
+ * @type {Record<string, string>}
613
+ */
614
+ const BASIC_LATIN = {
615
+ amp: "&",
616
+ AMP: "&",
617
+ lt: "<",
618
+ LT: "<",
619
+ gt: ">",
620
+ GT: ">",
621
+ quot: "\"",
622
+ QUOT: "\"",
623
+ apos: "'",
624
+ lsquo: "‘",
625
+ rsquo: "’",
626
+ ldquo: "“",
627
+ rdquo: "”",
628
+ lsquor: "‚",
629
+ rsquor: "’",
630
+ ldquor: "„",
631
+ bdquo: "„",
632
+ comma: ",",
633
+ period: ".",
634
+ colon: ":",
635
+ semi: ";",
636
+ excl: "!",
637
+ quest: "?",
638
+ num: "#",
639
+ dollar: "$",
640
+ percent: "%",
641
+ amp: "&",
642
+ ast: "*",
643
+ commat: "@",
644
+ lowbar: "_",
645
+ verbar: "|",
646
+ vert: "|",
647
+ sol: "/",
648
+ bsol: "\\",
649
+ lbrace: "{",
650
+ rbrace: "}",
651
+ lbrack: "[",
652
+ rbrack: "]",
653
+ lpar: "(",
654
+ rpar: ")",
655
+ nbsp: "\xA0",
656
+ iexcl: "¡",
657
+ cent: "¢",
658
+ pound: "£",
659
+ curren: "¤",
660
+ yen: "¥",
661
+ brvbar: "¦",
662
+ sect: "§",
663
+ uml: "¨",
664
+ copy: "©",
665
+ COPY: "©",
666
+ ordf: "ª",
667
+ laquo: "«",
668
+ not: "¬",
669
+ shy: "­",
670
+ reg: "®",
671
+ REG: "®",
672
+ macr: "¯",
673
+ deg: "°",
674
+ plusmn: "±",
675
+ sup2: "²",
676
+ sup3: "³",
677
+ acute: "´",
678
+ micro: "µ",
679
+ para: "¶",
680
+ middot: "·",
681
+ cedil: "¸",
682
+ sup1: "¹",
683
+ ordm: "º",
684
+ raquo: "»",
685
+ frac14: "¼",
686
+ frac12: "½",
687
+ half: "½",
688
+ frac34: "¾",
689
+ iquest: "¿",
690
+ times: "×",
691
+ div: "÷",
692
+ divide: "÷"
693
+ };
694
+ /**
695
+ * Latin Extended & Accented Letters (A-Z)
696
+ * @type {Record<string, string>}
697
+ */
698
+ const LATIN_ACCENTS = {
699
+ Agrave: "À",
700
+ agrave: "à",
701
+ Aacute: "Á",
702
+ aacute: "á",
703
+ Acirc: "Â",
704
+ acirc: "â",
705
+ Atilde: "Ã",
706
+ atilde: "ã",
707
+ Auml: "Ä",
708
+ auml: "ä",
709
+ Aring: "Å",
710
+ aring: "å",
711
+ AElig: "Æ",
712
+ aelig: "æ",
713
+ Ccedil: "Ç",
714
+ ccedil: "ç",
715
+ Egrave: "È",
716
+ egrave: "è",
717
+ Eacute: "É",
718
+ eacute: "é",
719
+ Ecirc: "Ê",
720
+ ecirc: "ê",
721
+ Euml: "Ë",
722
+ euml: "ë",
723
+ Igrave: "Ì",
724
+ igrave: "ì",
725
+ Iacute: "Í",
726
+ iacute: "í",
727
+ Icirc: "Î",
728
+ icirc: "î",
729
+ Iuml: "Ï",
730
+ iuml: "ï",
731
+ ETH: "Ð",
732
+ eth: "ð",
733
+ Ntilde: "Ñ",
734
+ ntilde: "ñ",
735
+ Ograve: "Ò",
736
+ ograve: "ò",
737
+ Oacute: "Ó",
738
+ oacute: "ó",
739
+ Ocirc: "Ô",
740
+ ocirc: "ô",
741
+ Otilde: "Õ",
742
+ otilde: "õ",
743
+ Ouml: "Ö",
744
+ ouml: "ö",
745
+ Oslash: "Ø",
746
+ oslash: "ø",
747
+ Ugrave: "Ù",
748
+ ugrave: "ù",
749
+ Uacute: "Ú",
750
+ uacute: "ú",
751
+ Ucirc: "Û",
752
+ ucirc: "û",
753
+ Uuml: "Ü",
754
+ uuml: "ü",
755
+ Yacute: "Ý",
756
+ yacute: "ý",
757
+ THORN: "Þ",
758
+ thorn: "þ",
759
+ szlig: "ß",
760
+ yuml: "ÿ",
761
+ Yuml: "Ÿ"
762
+ };
763
+ /**
764
+ * Latin Extended (Letters with diacritics)
765
+ * @type {Record<string, string>}
766
+ */
767
+ const LATIN_EXTENDED = {
768
+ Amacr: "Ā",
769
+ amacr: "ā",
770
+ Abreve: "Ă",
771
+ abreve: "ă",
772
+ Aogon: "Ą",
773
+ aogon: "ą",
774
+ Cacute: "Ć",
775
+ cacute: "ć",
776
+ Ccirc: "Ĉ",
777
+ ccirc: "ĉ",
778
+ Cdot: "Ċ",
779
+ cdot: "ċ",
780
+ Ccaron: "Č",
781
+ ccaron: "č",
782
+ Dcaron: "Ď",
783
+ dcaron: "ď",
784
+ Dstrok: "Đ",
785
+ dstrok: "đ",
786
+ Emacr: "Ē",
787
+ emacr: "ē",
788
+ Ecaron: "Ě",
789
+ ecaron: "ě",
790
+ Edot: "Ė",
791
+ edot: "ė",
792
+ Eogon: "Ę",
793
+ eogon: "ę",
794
+ Gcirc: "Ĝ",
795
+ gcirc: "ĝ",
796
+ Gbreve: "Ğ",
797
+ gbreve: "ğ",
798
+ Gdot: "Ġ",
799
+ gdot: "ġ",
800
+ Gcedil: "Ģ",
801
+ Hcirc: "Ĥ",
802
+ hcirc: "ĥ",
803
+ Hstrok: "Ħ",
804
+ hstrok: "ħ",
805
+ Itilde: "Ĩ",
806
+ itilde: "ĩ",
807
+ Imacr: "Ī",
808
+ imacr: "ī",
809
+ Iogon: "Į",
810
+ iogon: "į",
811
+ Idot: "İ",
812
+ IJlig: "IJ",
813
+ ijlig: "ij",
814
+ Jcirc: "Ĵ",
815
+ jcirc: "ĵ",
816
+ Kcedil: "Ķ",
817
+ kcedil: "ķ",
818
+ kgreen: "ĸ",
819
+ Lacute: "Ĺ",
820
+ lacute: "ĺ",
821
+ Lcedil: "Ļ",
822
+ lcedil: "ļ",
823
+ Lcaron: "Ľ",
824
+ lcaron: "ľ",
825
+ Lmidot: "Ŀ",
826
+ lmidot: "ŀ",
827
+ Lstrok: "Ł",
828
+ lstrok: "ł",
829
+ Nacute: "Ń",
830
+ nacute: "ń",
831
+ Ncaron: "Ň",
832
+ ncaron: "ň",
833
+ Ncedil: "Ņ",
834
+ ncedil: "ņ",
835
+ ENG: "Ŋ",
836
+ eng: "ŋ",
837
+ Omacr: "Ō",
838
+ omacr: "ō",
839
+ Odblac: "Ő",
840
+ odblac: "ő",
841
+ OElig: "Œ",
842
+ oelig: "œ",
843
+ Racute: "Ŕ",
844
+ racute: "ŕ",
845
+ Rcaron: "Ř",
846
+ rcaron: "ř",
847
+ Rcedil: "Ŗ",
848
+ rcedil: "ŗ",
849
+ Sacute: "Ś",
850
+ sacute: "ś",
851
+ Scirc: "Ŝ",
852
+ scirc: "ŝ",
853
+ Scedil: "Ş",
854
+ scedil: "ş",
855
+ Scaron: "Š",
856
+ scaron: "š",
857
+ Tcedil: "Ţ",
858
+ tcedil: "ţ",
859
+ Tcaron: "Ť",
860
+ tcaron: "ť",
861
+ Tstrok: "Ŧ",
862
+ tstrok: "ŧ",
863
+ Utilde: "Ũ",
864
+ utilde: "ũ",
865
+ Umacr: "Ū",
866
+ umacr: "ū",
867
+ Ubreve: "Ŭ",
868
+ ubreve: "ŭ",
869
+ Uring: "Ů",
870
+ uring: "ů",
871
+ Udblac: "Ű",
872
+ udblac: "ű",
873
+ Uogon: "Ų",
874
+ uogon: "ų",
875
+ Wcirc: "Ŵ",
876
+ wcirc: "ŵ",
877
+ Ycirc: "Ŷ",
878
+ ycirc: "ŷ",
879
+ Zacute: "Ź",
880
+ zacute: "ź",
881
+ Zdot: "Ż",
882
+ zdot: "ż",
883
+ Zcaron: "Ž",
884
+ zcaron: "ž"
885
+ };
886
+ /**
887
+ * Greek Letters
888
+ * @type {Record<string, string>}
889
+ */
890
+ const GREEK = {
891
+ Alpha: "Α",
892
+ alpha: "α",
893
+ Beta: "Β",
894
+ beta: "β",
895
+ Gamma: "Γ",
896
+ gamma: "γ",
897
+ Delta: "Δ",
898
+ delta: "δ",
899
+ Epsilon: "Ε",
900
+ epsilon: "ε",
901
+ epsiv: "ϵ",
902
+ varepsilon: "ϵ",
903
+ Zeta: "Ζ",
904
+ zeta: "ζ",
905
+ Eta: "Η",
906
+ eta: "η",
907
+ Theta: "Θ",
908
+ theta: "θ",
909
+ thetasym: "ϑ",
910
+ vartheta: "ϑ",
911
+ Iota: "Ι",
912
+ iota: "ι",
913
+ Kappa: "Κ",
914
+ kappa: "κ",
915
+ kappav: "ϰ",
916
+ varkappa: "ϰ",
917
+ Lambda: "Λ",
918
+ lambda: "λ",
919
+ Mu: "Μ",
920
+ mu: "μ",
921
+ Nu: "Ν",
922
+ nu: "ν",
923
+ Xi: "Ξ",
924
+ xi: "ξ",
925
+ Omicron: "Ο",
926
+ omicron: "ο",
927
+ Pi: "Π",
928
+ pi: "π",
929
+ piv: "ϖ",
930
+ varpi: "ϖ",
931
+ Rho: "Ρ",
932
+ rho: "ρ",
933
+ rhov: "ϱ",
934
+ varrho: "ϱ",
935
+ Sigma: "Σ",
936
+ sigma: "σ",
937
+ sigmaf: "ς",
938
+ sigmav: "ς",
939
+ varsigma: "ς",
940
+ Tau: "Τ",
941
+ tau: "τ",
942
+ Upsilon: "Υ",
943
+ upsilon: "υ",
944
+ upsi: "υ",
945
+ Upsi: "ϒ",
946
+ upsih: "ϒ",
947
+ Phi: "Φ",
948
+ phi: "φ",
949
+ phiv: "ϕ",
950
+ varphi: "ϕ",
951
+ Chi: "Χ",
952
+ chi: "χ",
953
+ Psi: "Ψ",
954
+ psi: "ψ",
955
+ Omega: "Ω",
956
+ omega: "ω",
957
+ ohm: "Ω",
958
+ Gammad: "Ϝ",
959
+ gammad: "ϝ",
960
+ digamma: "ϝ"
961
+ };
962
+ /**
963
+ * Cyrillic Letters
964
+ * @type {Record<string, string>}
965
+ */
966
+ const CYRILLIC = {
967
+ Afr: "𝔄",
968
+ afr: "𝔞",
969
+ Acy: "А",
970
+ acy: "а",
971
+ Bcy: "Б",
972
+ bcy: "б",
973
+ Vcy: "В",
974
+ vcy: "в",
975
+ Gcy: "Г",
976
+ gcy: "г",
977
+ Dcy: "Д",
978
+ dcy: "д",
979
+ IEcy: "Е",
980
+ iecy: "е",
981
+ IOcy: "Ё",
982
+ iocy: "ё",
983
+ ZHcy: "Ж",
984
+ zhcy: "ж",
985
+ Zcy: "З",
986
+ zcy: "з",
987
+ Icy: "И",
988
+ icy: "и",
989
+ Jcy: "Й",
990
+ jcy: "й",
991
+ Kcy: "К",
992
+ kcy: "к",
993
+ Lcy: "Л",
994
+ lcy: "л",
995
+ Mcy: "М",
996
+ mcy: "м",
997
+ Ncy: "Н",
998
+ ncy: "н",
999
+ Ocy: "О",
1000
+ ocy: "о",
1001
+ Pcy: "П",
1002
+ pcy: "п",
1003
+ Rcy: "Р",
1004
+ rcy: "р",
1005
+ Scy: "С",
1006
+ scy: "с",
1007
+ Tcy: "Т",
1008
+ tcy: "т",
1009
+ Ucy: "У",
1010
+ ucy: "у",
1011
+ Fcy: "Ф",
1012
+ fcy: "ф",
1013
+ KHcy: "Х",
1014
+ khcy: "х",
1015
+ TScy: "Ц",
1016
+ tscy: "ц",
1017
+ CHcy: "Ч",
1018
+ chcy: "ч",
1019
+ SHcy: "Ш",
1020
+ shcy: "ш",
1021
+ SHCHcy: "Щ",
1022
+ shchcy: "щ",
1023
+ HARDcy: "Ъ",
1024
+ hardcy: "ъ",
1025
+ Ycy: "Ы",
1026
+ ycy: "ы",
1027
+ SOFTcy: "Ь",
1028
+ softcy: "ь",
1029
+ Ecy: "Э",
1030
+ ecy: "э",
1031
+ YUcy: "Ю",
1032
+ yucy: "ю",
1033
+ YAcy: "Я",
1034
+ yacy: "я",
1035
+ DJcy: "Ђ",
1036
+ djcy: "ђ",
1037
+ GJcy: "Ѓ",
1038
+ gjcy: "ѓ",
1039
+ Jukcy: "Є",
1040
+ jukcy: "є",
1041
+ DScy: "Ѕ",
1042
+ dscy: "ѕ",
1043
+ Iukcy: "І",
1044
+ iukcy: "і",
1045
+ YIcy: "Ї",
1046
+ yicy: "ї",
1047
+ Jsercy: "Ј",
1048
+ jsercy: "ј",
1049
+ LJcy: "Љ",
1050
+ ljcy: "љ",
1051
+ NJcy: "Њ",
1052
+ njcy: "њ",
1053
+ TSHcy: "Ћ",
1054
+ tshcy: "ћ",
1055
+ KJcy: "Ќ",
1056
+ kjcy: "ќ",
1057
+ Ubrcy: "Ў",
1058
+ ubrcy: "ў",
1059
+ DZcy: "Џ",
1060
+ dzcy: "џ"
1061
+ };
1062
+ /**
1063
+ * Mathematical Operators & Relations
1064
+ * @type {Record<string, string>}
1065
+ */
1066
+ const MATH = {
1067
+ plus: "+",
1068
+ minus: "−",
1069
+ mnplus: "∓",
1070
+ mp: "∓",
1071
+ pm: "±",
1072
+ times: "×",
1073
+ div: "÷",
1074
+ divide: "÷",
1075
+ sdot: "⋅",
1076
+ star: "☆",
1077
+ starf: "★",
1078
+ bigstar: "★",
1079
+ lowast: "∗",
1080
+ ast: "*",
1081
+ midast: "*",
1082
+ compfn: "∘",
1083
+ smallcircle: "∘",
1084
+ bullet: "•",
1085
+ bull: "•",
1086
+ nbsp: "\xA0",
1087
+ hellip: "…",
1088
+ mldr: "…",
1089
+ prime: "′",
1090
+ Prime: "″",
1091
+ tprime: "‴",
1092
+ bprime: "‵",
1093
+ backprime: "‵",
1094
+ minus: "−",
1095
+ minusd: "∸",
1096
+ dotminus: "∸",
1097
+ plusdo: "∔",
1098
+ dotplus: "∔",
1099
+ plusmn: "±",
1100
+ minusplus: "∓",
1101
+ mnplus: "∓",
1102
+ mp: "∓",
1103
+ setminus: "∖",
1104
+ smallsetminus: "∖",
1105
+ Backslash: "∖",
1106
+ setmn: "∖",
1107
+ ssetmn: "∖",
1108
+ lowbar: "_",
1109
+ verbar: "|",
1110
+ vert: "|",
1111
+ VerticalLine: "|",
1112
+ colon: ":",
1113
+ Colon: "∷",
1114
+ Proportion: "∷",
1115
+ ratio: "∶",
1116
+ equals: "=",
1117
+ ne: "≠",
1118
+ nequiv: "≢",
1119
+ equiv: "≡",
1120
+ Congruent: "≡",
1121
+ sim: "∼",
1122
+ thicksim: "∼",
1123
+ thksim: "∼",
1124
+ sime: "≃",
1125
+ simeq: "≃",
1126
+ TildeEqual: "≃",
1127
+ asymp: "≈",
1128
+ approx: "≈",
1129
+ thickapprox: "≈",
1130
+ thkap: "≈",
1131
+ TildeTilde: "≈",
1132
+ ncong: "≇",
1133
+ cong: "≅",
1134
+ TildeFullEqual: "≅",
1135
+ asympeq: "≍",
1136
+ CupCap: "≍",
1137
+ bump: "≎",
1138
+ Bumpeq: "≎",
1139
+ HumpDownHump: "≎",
1140
+ bumpe: "≏",
1141
+ bumpeq: "≏",
1142
+ HumpEqual: "≏",
1143
+ dotminus: "∸",
1144
+ minusd: "∸",
1145
+ plusdo: "∔",
1146
+ dotplus: "∔",
1147
+ le: "≤",
1148
+ LessEqual: "≤",
1149
+ ge: "≥",
1150
+ GreaterEqual: "≥",
1151
+ lesseqgtr: "⋚",
1152
+ lesseqqgtr: "⪋",
1153
+ greater: ">",
1154
+ less: "<"
1155
+ };
1156
+ /**
1157
+ * Mathematical Operators (Advanced)
1158
+ * @type {Record<string, string>}
1159
+ */
1160
+ const MATH_ADVANCED = {
1161
+ alefsym: "ℵ",
1162
+ aleph: "ℵ",
1163
+ beth: "ℶ",
1164
+ gimel: "ℷ",
1165
+ daleth: "ℸ",
1166
+ forall: "∀",
1167
+ ForAll: "∀",
1168
+ part: "∂",
1169
+ PartialD: "∂",
1170
+ exist: "∃",
1171
+ Exists: "∃",
1172
+ nexist: "∄",
1173
+ nexists: "∄",
1174
+ empty: "∅",
1175
+ emptyset: "∅",
1176
+ emptyv: "∅",
1177
+ varnothing: "∅",
1178
+ nabla: "∇",
1179
+ Del: "∇",
1180
+ isin: "∈",
1181
+ isinv: "∈",
1182
+ in: "∈",
1183
+ Element: "∈",
1184
+ notin: "∉",
1185
+ notinva: "∉",
1186
+ ni: "∋",
1187
+ niv: "∋",
1188
+ SuchThat: "∋",
1189
+ ReverseElement: "∋",
1190
+ notni: "∌",
1191
+ notniva: "∌",
1192
+ prod: "∏",
1193
+ Product: "∏",
1194
+ coprod: "∐",
1195
+ Coproduct: "∐",
1196
+ sum: "∑",
1197
+ Sum: "∑",
1198
+ minus: "−",
1199
+ mp: "∓",
1200
+ plusdo: "∔",
1201
+ dotplus: "∔",
1202
+ setminus: "∖",
1203
+ lowast: "∗",
1204
+ radic: "√",
1205
+ Sqrt: "√",
1206
+ prop: "∝",
1207
+ propto: "∝",
1208
+ Proportional: "∝",
1209
+ varpropto: "∝",
1210
+ infin: "∞",
1211
+ infintie: "⧝",
1212
+ ang: "∠",
1213
+ angle: "∠",
1214
+ angmsd: "∡",
1215
+ measuredangle: "∡",
1216
+ angsph: "∢",
1217
+ mid: "∣",
1218
+ VerticalBar: "∣",
1219
+ nmid: "∤",
1220
+ nsmid: "∤",
1221
+ npar: "∦",
1222
+ parallel: "∥",
1223
+ spar: "∥",
1224
+ nparallel: "∦",
1225
+ nspar: "∦",
1226
+ and: "∧",
1227
+ wedge: "∧",
1228
+ or: "∨",
1229
+ vee: "∨",
1230
+ cap: "∩",
1231
+ cup: "∪",
1232
+ int: "∫",
1233
+ Integral: "∫",
1234
+ conint: "∮",
1235
+ ContourIntegral: "∮",
1236
+ Conint: "∯",
1237
+ DoubleContourIntegral: "∯",
1238
+ Cconint: "∰",
1239
+ there4: "∴",
1240
+ therefore: "∴",
1241
+ Therefore: "∴",
1242
+ becaus: "∵",
1243
+ because: "∵",
1244
+ Because: "∵",
1245
+ ratio: "∶",
1246
+ Proportion: "∷",
1247
+ minusd: "∸",
1248
+ dotminus: "∸",
1249
+ mDDot: "∺",
1250
+ homtht: "∻",
1251
+ sim: "∼",
1252
+ bsimg: "∽",
1253
+ backsim: "∽",
1254
+ ac: "∾",
1255
+ mstpos: "∾",
1256
+ acd: "∿",
1257
+ VerticalTilde: "≀",
1258
+ wr: "≀",
1259
+ wreath: "≀",
1260
+ nsime: "≄",
1261
+ nsimeq: "≄",
1262
+ nsimeq: "≄",
1263
+ ncong: "≇",
1264
+ simne: "≆",
1265
+ ncongdot: "⩭̸",
1266
+ ngsim: "≵",
1267
+ nsim: "≁",
1268
+ napprox: "≉",
1269
+ nap: "≉",
1270
+ ngeq: "≱",
1271
+ nge: "≱",
1272
+ nleq: "≰",
1273
+ nle: "≰",
1274
+ ngtr: "≯",
1275
+ ngt: "≯",
1276
+ nless: "≮",
1277
+ nlt: "≮",
1278
+ nprec: "⊀",
1279
+ npr: "⊀",
1280
+ nsucc: "⊁",
1281
+ nsc: "⊁"
1282
+ };
1283
+ /**
1284
+ * Arrows
1285
+ * @type {Record<string, string>}
1286
+ */
1287
+ const ARROWS = {
1288
+ larr: "←",
1289
+ leftarrow: "←",
1290
+ LeftArrow: "←",
1291
+ uarr: "↑",
1292
+ uparrow: "↑",
1293
+ UpArrow: "↑",
1294
+ rarr: "→",
1295
+ rightarrow: "→",
1296
+ RightArrow: "→",
1297
+ darr: "↓",
1298
+ downarrow: "↓",
1299
+ DownArrow: "↓",
1300
+ harr: "↔",
1301
+ leftrightarrow: "↔",
1302
+ LeftRightArrow: "↔",
1303
+ varr: "↕",
1304
+ updownarrow: "↕",
1305
+ UpDownArrow: "↕",
1306
+ nwarr: "↖",
1307
+ nwarrow: "↖",
1308
+ UpperLeftArrow: "↖",
1309
+ nearr: "↗",
1310
+ nearrow: "↗",
1311
+ UpperRightArrow: "↗",
1312
+ searr: "↘",
1313
+ searrow: "↘",
1314
+ LowerRightArrow: "↘",
1315
+ swarr: "↙",
1316
+ swarrow: "↙",
1317
+ LowerLeftArrow: "↙",
1318
+ lArr: "⇐",
1319
+ Leftarrow: "⇐",
1320
+ uArr: "⇑",
1321
+ Uparrow: "⇑",
1322
+ rArr: "⇒",
1323
+ Rightarrow: "⇒",
1324
+ dArr: "⇓",
1325
+ Downarrow: "⇓",
1326
+ hArr: "⇔",
1327
+ Leftrightarrow: "⇔",
1328
+ iff: "⇔",
1329
+ vArr: "⇕",
1330
+ Updownarrow: "⇕",
1331
+ lAarr: "⇚",
1332
+ Lleftarrow: "⇚",
1333
+ rAarr: "⇛",
1334
+ Rrightarrow: "⇛",
1335
+ lrarr: "⇆",
1336
+ leftrightarrows: "⇆",
1337
+ rlarr: "⇄",
1338
+ rightleftarrows: "⇄",
1339
+ lrhar: "⇋",
1340
+ leftrightharpoons: "⇋",
1341
+ ReverseEquilibrium: "⇋",
1342
+ rlhar: "⇌",
1343
+ rightleftharpoons: "⇌",
1344
+ Equilibrium: "⇌",
1345
+ udarr: "⇅",
1346
+ UpArrowDownArrow: "⇅",
1347
+ duarr: "⇵",
1348
+ DownArrowUpArrow: "⇵",
1349
+ llarr: "⇇",
1350
+ leftleftarrows: "⇇",
1351
+ rrarr: "⇉",
1352
+ rightrightarrows: "⇉",
1353
+ ddarr: "⇊",
1354
+ downdownarrows: "⇊",
1355
+ har: "↽",
1356
+ lhard: "↽",
1357
+ leftharpoondown: "↽",
1358
+ lharu: "↼",
1359
+ leftharpoonup: "↼",
1360
+ rhard: "⇁",
1361
+ rightharpoondown: "⇁",
1362
+ rharu: "⇀",
1363
+ rightharpoonup: "⇀",
1364
+ lsh: "↰",
1365
+ Lsh: "↰",
1366
+ rsh: "↱",
1367
+ Rsh: "↱",
1368
+ ldsh: "↲",
1369
+ rdsh: "↳",
1370
+ hookleftarrow: "↩",
1371
+ hookrightarrow: "↪",
1372
+ mapstoleft: "↤",
1373
+ mapstoup: "↥",
1374
+ map: "↦",
1375
+ mapsto: "↦",
1376
+ mapstodown: "↧",
1377
+ crarr: "↵",
1378
+ nwarrow: "↖",
1379
+ nearrow: "↗",
1380
+ searrow: "↘",
1381
+ swarrow: "↙",
1382
+ nleftarrow: "↚",
1383
+ nleftrightarrow: "↮",
1384
+ nrightarrow: "↛",
1385
+ nrarr: "↛",
1386
+ larrtl: "↢",
1387
+ rarrtl: "↣",
1388
+ leftarrowtail: "↢",
1389
+ rightarrowtail: "↣",
1390
+ twoheadleftarrow: "↞",
1391
+ twoheadrightarrow: "↠",
1392
+ Larr: "↞",
1393
+ Rarr: "↠",
1394
+ larrhk: "↩",
1395
+ rarrhk: "↪",
1396
+ larrlp: "↫",
1397
+ looparrowleft: "↫",
1398
+ rarrlp: "↬",
1399
+ looparrowright: "↬",
1400
+ harrw: "↭",
1401
+ leftrightsquigarrow: "↭",
1402
+ nrarrw: "↝̸",
1403
+ rarrw: "↝",
1404
+ rightsquigarrow: "↝",
1405
+ larrbfs: "⤟",
1406
+ rarrbfs: "⤠",
1407
+ nvHarr: "⤄",
1408
+ nvlArr: "⤂",
1409
+ nvrArr: "⤃",
1410
+ larrfs: "⤝",
1411
+ rarrfs: "⤞",
1412
+ Map: "⤅",
1413
+ larrsim: "⥳",
1414
+ rarrsim: "⥴",
1415
+ harrcir: "⥈",
1416
+ Uarrocir: "⥉",
1417
+ lurdshar: "⥊",
1418
+ ldrdhar: "⥧",
1419
+ ldrushar: "⥋",
1420
+ rdldhar: "⥩",
1421
+ lrhard: "⥭",
1422
+ rlhar: "⇌",
1423
+ uharr: "↾",
1424
+ uharl: "↿",
1425
+ dharr: "⇂",
1426
+ dharl: "⇃",
1427
+ Uarr: "↟",
1428
+ Darr: "↡",
1429
+ zigrarr: "⇝",
1430
+ nwArr: "⇖",
1431
+ neArr: "⇗",
1432
+ seArr: "⇘",
1433
+ swArr: "⇙",
1434
+ nharr: "↮",
1435
+ nhArr: "⇎",
1436
+ nlarr: "↚",
1437
+ nlArr: "⇍",
1438
+ nrarr: "↛",
1439
+ nrArr: "⇏",
1440
+ larrb: "⇤",
1441
+ LeftArrowBar: "⇤",
1442
+ rarrb: "⇥",
1443
+ RightArrowBar: "⇥"
1444
+ };
1445
+ /**
1446
+ * Geometric Shapes
1447
+ * @type {Record<string, string>}
1448
+ */
1449
+ const SHAPES = {
1450
+ square: "□",
1451
+ Square: "□",
1452
+ squ: "□",
1453
+ squf: "▪",
1454
+ squarf: "▪",
1455
+ blacksquar: "▪",
1456
+ blacksquare: "▪",
1457
+ FilledVerySmallSquare: "▪",
1458
+ blk34: "▓",
1459
+ blk12: "▒",
1460
+ blk14: "░",
1461
+ block: "█",
1462
+ srect: "▭",
1463
+ rect: "▭",
1464
+ sdot: "⋅",
1465
+ sdotb: "⊡",
1466
+ dotsquare: "⊡",
1467
+ triangle: "▵",
1468
+ tri: "▵",
1469
+ trine: "▵",
1470
+ utri: "▵",
1471
+ triangledown: "▿",
1472
+ dtri: "▿",
1473
+ tridown: "▿",
1474
+ triangleleft: "◃",
1475
+ ltri: "◃",
1476
+ triangleright: "▹",
1477
+ rtri: "▹",
1478
+ blacktriangle: "▴",
1479
+ utrif: "▴",
1480
+ blacktriangledown: "▾",
1481
+ dtrif: "▾",
1482
+ blacktriangleleft: "◂",
1483
+ ltrif: "◂",
1484
+ blacktriangleright: "▸",
1485
+ rtrif: "▸",
1486
+ loz: "◊",
1487
+ lozenge: "◊",
1488
+ blacklozenge: "⧫",
1489
+ lozf: "⧫",
1490
+ bigcirc: "◯",
1491
+ xcirc: "◯",
1492
+ circ: "ˆ",
1493
+ Circle: "○",
1494
+ cir: "○",
1495
+ o: "○",
1496
+ bullet: "•",
1497
+ bull: "•",
1498
+ hellip: "…",
1499
+ mldr: "…",
1500
+ nldr: "‥",
1501
+ boxh: "─",
1502
+ HorizontalLine: "─",
1503
+ boxv: "│",
1504
+ boxdr: "┌",
1505
+ boxdl: "┐",
1506
+ boxur: "└",
1507
+ boxul: "┘",
1508
+ boxvr: "├",
1509
+ boxvl: "┤",
1510
+ boxhd: "┬",
1511
+ boxhu: "┴",
1512
+ boxvh: "┼",
1513
+ boxH: "═",
1514
+ boxV: "║",
1515
+ boxdR: "╒",
1516
+ boxDr: "╓",
1517
+ boxDR: "╔",
1518
+ boxDl: "╕",
1519
+ boxdL: "╖",
1520
+ boxDL: "╗",
1521
+ boxuR: "╘",
1522
+ boxUr: "╙",
1523
+ boxUR: "╚",
1524
+ boxUl: "╜",
1525
+ boxuL: "╛",
1526
+ boxUL: "╝",
1527
+ boxvR: "╞",
1528
+ boxVr: "╟",
1529
+ boxVR: "╠",
1530
+ boxVl: "╢",
1531
+ boxvL: "╡",
1532
+ boxVL: "╣",
1533
+ boxHd: "╤",
1534
+ boxhD: "╥",
1535
+ boxHD: "╦",
1536
+ boxHu: "╧",
1537
+ boxhU: "╨",
1538
+ boxHU: "╩",
1539
+ boxvH: "╪",
1540
+ boxVh: "╫",
1541
+ boxVH: "╬"
1542
+ };
1543
+ /**
1544
+ * Punctuation & Diacritics
1545
+ * @type {Record<string, string>}
1546
+ */
1547
+ const PUNCTUATION = {
1548
+ excl: "!",
1549
+ iexcl: "¡",
1550
+ brvbar: "¦",
1551
+ sect: "§",
1552
+ uml: "¨",
1553
+ copy: "©",
1554
+ ordf: "ª",
1555
+ laquo: "«",
1556
+ not: "¬",
1557
+ shy: "­",
1558
+ reg: "®",
1559
+ macr: "¯",
1560
+ deg: "°",
1561
+ plusmn: "±",
1562
+ sup2: "²",
1563
+ sup3: "³",
1564
+ acute: "´",
1565
+ micro: "µ",
1566
+ para: "¶",
1567
+ middot: "·",
1568
+ cedil: "¸",
1569
+ sup1: "¹",
1570
+ ordm: "º",
1571
+ raquo: "»",
1572
+ frac14: "¼",
1573
+ frac12: "½",
1574
+ frac34: "¾",
1575
+ iquest: "¿",
1576
+ nbsp: "\xA0",
1577
+ comma: ",",
1578
+ period: ".",
1579
+ colon: ":",
1580
+ semi: ";",
1581
+ vert: "|",
1582
+ Verbar: "‖",
1583
+ verbar: "|",
1584
+ dblac: "˝",
1585
+ circ: "ˆ",
1586
+ caron: "ˇ",
1587
+ breve: "˘",
1588
+ dot: "˙",
1589
+ ring: "˚",
1590
+ ogon: "˛",
1591
+ tilde: "˜",
1592
+ DiacriticalGrave: "`",
1593
+ DiacriticalAcute: "´",
1594
+ DiacriticalTilde: "˜",
1595
+ DiacriticalDot: "˙",
1596
+ DiacriticalDoubleAcute: "˝",
1597
+ grave: "`",
1598
+ acute: "´"
1599
+ };
1600
+ /**
1601
+ * Currency Symbols
1602
+ * @type {Record<string, string>}
1603
+ */
1604
+ const CURRENCY = {
1605
+ cent: "¢",
1606
+ pound: "£",
1607
+ curren: "¤",
1608
+ yen: "¥",
1609
+ euro: "€",
1610
+ dollar: "$",
1611
+ euro: "€",
1612
+ fnof: "ƒ",
1613
+ inr: "₹",
1614
+ af: "؋",
1615
+ birr: "ብር",
1616
+ peso: "₱",
1617
+ rub: "₽",
1618
+ won: "₩",
1619
+ yuan: "¥",
1620
+ cedil: "¸"
1621
+ };
1622
+ /**
1623
+ * Fractions
1624
+ * @type {Record<string, string>}
1625
+ */
1626
+ const FRACTIONS = {
1627
+ frac12: "½",
1628
+ half: "½",
1629
+ frac13: "⅓",
1630
+ frac14: "¼",
1631
+ frac15: "⅕",
1632
+ frac16: "⅙",
1633
+ frac18: "⅛",
1634
+ frac23: "⅔",
1635
+ frac25: "⅖",
1636
+ frac34: "¾",
1637
+ frac35: "⅗",
1638
+ frac38: "⅜",
1639
+ frac45: "⅘",
1640
+ frac56: "⅚",
1641
+ frac58: "⅝",
1642
+ frac78: "⅞",
1643
+ frasl: "⁄"
1644
+ };
1645
+ /**
1646
+ * Miscellaneous Symbols
1647
+ * @type {Record<string, string>}
1648
+ */
1649
+ const MISC_SYMBOLS = {
1650
+ trade: "™",
1651
+ TRADE: "™",
1652
+ telrec: "⌕",
1653
+ target: "⌖",
1654
+ ulcorn: "⌜",
1655
+ ulcorner: "⌜",
1656
+ urcorn: "⌝",
1657
+ urcorner: "⌝",
1658
+ dlcorn: "⌞",
1659
+ llcorner: "⌞",
1660
+ drcorn: "⌟",
1661
+ lrcorner: "⌟",
1662
+ intercal: "⊺",
1663
+ intcal: "⊺",
1664
+ oplus: "⊕",
1665
+ CirclePlus: "⊕",
1666
+ ominus: "⊖",
1667
+ CircleMinus: "⊖",
1668
+ otimes: "⊗",
1669
+ CircleTimes: "⊗",
1670
+ osol: "⊘",
1671
+ odot: "⊙",
1672
+ CircleDot: "⊙",
1673
+ oast: "⊛",
1674
+ circledast: "⊛",
1675
+ odash: "⊝",
1676
+ circleddash: "⊝",
1677
+ ocirc: "⊚",
1678
+ circledcirc: "⊚",
1679
+ boxplus: "⊞",
1680
+ plusb: "⊞",
1681
+ boxminus: "⊟",
1682
+ minusb: "⊟",
1683
+ boxtimes: "⊠",
1684
+ timesb: "⊠",
1685
+ boxdot: "⊡",
1686
+ sdotb: "⊡",
1687
+ veebar: "⊻",
1688
+ vee: "∨",
1689
+ barvee: "⊽",
1690
+ and: "∧",
1691
+ wedge: "∧",
1692
+ Cap: "⋒",
1693
+ Cup: "⋓",
1694
+ Fork: "⋔",
1695
+ pitchfork: "⋔",
1696
+ epar: "⋕",
1697
+ ltlarr: "⥶",
1698
+ nvap: "≍⃒",
1699
+ nvsim: "∼⃒",
1700
+ nvge: "≥⃒",
1701
+ nvle: "≤⃒",
1702
+ nvlt: "<⃒",
1703
+ nvgt: ">⃒",
1704
+ nvltrie: "⊴⃒",
1705
+ nvrtrie: "⊵⃒",
1706
+ Vdash: "⊩",
1707
+ dashv: "⊣",
1708
+ vDash: "⊨",
1709
+ Vdash: "⊩",
1710
+ Vvdash: "⊪",
1711
+ nvdash: "⊬",
1712
+ nvDash: "⊭",
1713
+ nVdash: "⊮",
1714
+ nVDash: "⊯"
1715
+ };
1716
+ ({
1717
+ ...BASIC_LATIN,
1718
+ ...LATIN_ACCENTS,
1719
+ ...LATIN_EXTENDED,
1720
+ ...GREEK,
1721
+ ...CYRILLIC,
1722
+ ...MATH,
1723
+ ...MATH_ADVANCED,
1724
+ ...ARROWS,
1725
+ ...SHAPES,
1726
+ ...PUNCTUATION,
1727
+ ...CURRENCY,
1728
+ ...FRACTIONS,
1729
+ ...MISC_SYMBOLS
1730
+ });
1731
+ const XML = {
1732
+ amp: "&",
1733
+ apos: "'",
1734
+ gt: ">",
1735
+ lt: "<",
1736
+ quot: "\""
1737
+ };
1738
+ const COMMON_HTML = {
1739
+ nbsp: "\xA0",
1740
+ copy: "©",
1741
+ reg: "®",
1742
+ trade: "™",
1743
+ mdash: "—",
1744
+ ndash: "–",
1745
+ hellip: "…",
1746
+ laquo: "«",
1747
+ raquo: "»",
1748
+ lsquo: "‘",
1749
+ rsquo: "’",
1750
+ ldquo: "“",
1751
+ rdquo: "”",
1752
+ bull: "•",
1753
+ para: "¶",
1754
+ sect: "§",
1755
+ deg: "°",
1756
+ frac12: "½",
1757
+ frac14: "¼",
1758
+ frac34: "¾"
1759
+ };
1760
+ //#endregion
1761
+ //#region ../../node_modules/.pnpm/@nodable+entities@2.1.0/node_modules/@nodable/entities/src/EntityDecoder.js
1762
+ const SPECIAL_CHARS = /* @__PURE__ */ new Set("!?\\\\/[]$%{}^&*()<>|+");
1763
+ /**
1764
+ * Validate that an entity name contains no dangerous characters.
1765
+ * @param {string} name
1766
+ * @returns {string} the name, unchanged
1767
+ * @throws {Error} on invalid characters
1768
+ */
1769
+ function validateEntityName$1(name) {
1770
+ if (name[0] === "#") throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${name}"`);
1771
+ for (const ch of name) if (SPECIAL_CHARS.has(ch)) throw new Error(`[EntityReplacer] Invalid character '${ch}' in entity name: "${name}"`);
1772
+ return name;
1773
+ }
1774
+ /**
1775
+ * Merge one or more entity maps into a flat name→string map.
1776
+ * Accepts either:
1777
+ * - plain string values: { amp: '&' }
1778
+ * - legacy {regex,val} / {regx,val}: { lt: { regex: /.../, val: '<' } }
1779
+ *
1780
+ * Values containing '&' are skipped (recursive expansion risk).
1781
+ *
1782
+ * @param {...object} maps
1783
+ * @returns {Record<string, string>}
1784
+ */
1785
+ function mergeEntityMaps(...maps) {
1786
+ const out = Object.create(null);
1787
+ for (const map of maps) {
1788
+ if (!map) continue;
1789
+ for (const key of Object.keys(map)) {
1790
+ const raw = map[key];
1791
+ if (typeof raw === "string") out[key] = raw;
1792
+ else if (raw && typeof raw === "object" && raw.val !== void 0) {
1793
+ const val = raw.val;
1794
+ if (typeof val === "string") out[key] = val;
1795
+ }
1796
+ }
1797
+ }
1798
+ return out;
1799
+ }
1800
+ const LIMIT_TIER_EXTERNAL = "external";
1801
+ const LIMIT_TIER_BASE = "base";
1802
+ const LIMIT_TIER_ALL = "all";
1803
+ /**
1804
+ * Resolve `applyLimitsTo` option into a normalised Set of tier strings.
1805
+ * Accepted values: 'external' | 'base' | 'all' | string[]
1806
+ * Default: 'external' (only untrusted injected entities are counted).
1807
+ * @param {string|string[]|undefined} raw
1808
+ * @returns {Set<string>}
1809
+ */
1810
+ function parseLimitTiers(raw) {
1811
+ if (!raw || raw === LIMIT_TIER_EXTERNAL) return new Set([LIMIT_TIER_EXTERNAL]);
1812
+ if (raw === LIMIT_TIER_ALL) return new Set([LIMIT_TIER_ALL]);
1813
+ if (raw === LIMIT_TIER_BASE) return new Set([LIMIT_TIER_BASE]);
1814
+ if (Array.isArray(raw)) return new Set(raw);
1815
+ return new Set([LIMIT_TIER_EXTERNAL]);
1816
+ }
1817
+ const NCR_LEVEL = Object.freeze({
1818
+ allow: 0,
1819
+ leave: 1,
1820
+ remove: 2,
1821
+ throw: 3
1822
+ });
1823
+ const XML10_ALLOWED_C0 = new Set([
1824
+ 9,
1825
+ 10,
1826
+ 13
1827
+ ]);
1828
+ /**
1829
+ * Parse the `ncr` constructor option into flat, hot-path-friendly fields.
1830
+ * @param {object|undefined} ncr
1831
+ * @returns {{ xmlVersion: number, onLevel: number, nullLevel: number }}
1832
+ */
1833
+ function parseNCRConfig(ncr) {
1834
+ if (!ncr) return {
1835
+ xmlVersion: 1,
1836
+ onLevel: NCR_LEVEL.allow,
1837
+ nullLevel: NCR_LEVEL.remove
1838
+ };
1839
+ const xmlVersion = ncr.xmlVersion === 1.1 ? 1.1 : 1;
1840
+ const onLevel = NCR_LEVEL[ncr.onNCR] ?? NCR_LEVEL.allow;
1841
+ const nullLevel = NCR_LEVEL[ncr.nullNCR] ?? NCR_LEVEL.remove;
1842
+ return {
1843
+ xmlVersion,
1844
+ onLevel,
1845
+ nullLevel: Math.max(nullLevel, NCR_LEVEL.remove)
1846
+ };
1847
+ }
1848
+ /**
1849
+ * Single-pass, zero-regex entity replacer for XML/HTML content.
1850
+ *
1851
+ * Algorithm: scan the string once for '&', read to ';', resolve via map
1852
+ * or direct codepoint conversion, build output chunks, join once at the end.
1853
+ *
1854
+ * Entity lookup priority (highest → lowest):
1855
+ * 1. input / runtime (DOCTYPE entities for current document)
1856
+ * 2. persistent external (survive across documents)
1857
+ * 3. base named map (DEFAULT_XML_ENTITIES + user-supplied namedEntities)
1858
+ *
1859
+ * Both input and external resolve as the 'external' tier for limit purposes.
1860
+ * Base map entities resolve as the 'base' tier.
1861
+ *
1862
+ * Numeric / hex references (&#NNN; / &#xHH;) are resolved directly via
1863
+ * String.fromCodePoint() — no map needed. They count as 'base' tier.
1864
+ *
1865
+ * @example
1866
+ * const replacer = new EntityReplacer({ namedEntities: COMMON_HTML });
1867
+ * replacer.setExternalEntities({ brand: 'Acme' });
1868
+ *
1869
+ * const instance = replacer.reset();
1870
+ * instance.addInputEntities({ version: '1.0' });
1871
+ * instance.encode('&brand; v&version; &lt;'); // 'Acme v1.0 <'
1872
+ */
1873
+ var EntityDecoder = class {
1874
+ /**
1875
+ * @param {object} [options]
1876
+ * @param {object|null} [options.namedEntities] — extra named entities merged into base map
1877
+ * @param {object} [options.limit] — security limits
1878
+ * @param {number} [options.limit.maxTotalExpansions=0] — 0 = unlimited
1879
+ * @param {number} [options.limit.maxExpandedLength=0] — 0 = unlimited
1880
+ * @param {'external'|'base'|'all'|string[]} [options.limit.applyLimitsTo='external']
1881
+ * Which entity tiers count against the security limits:
1882
+ * - 'external' (default) — only input/runtime + persistent external entities
1883
+ * - 'base' — only DEFAULT_XML_ENTITIES + namedEntities
1884
+ * - 'all' — every entity regardless of tier
1885
+ * - string[] — explicit combination, e.g. ['external', 'base']
1886
+ * @param {((resolved: string, original: string) => string)|null} [options.postCheck=null]
1887
+ * @param {string[]} [options.remove=[]] — entity names (e.g. ['nbsp', '#13']) to delete (replace with empty string)
1888
+ * @param {string[]} [options.leave=[]] — entity names to keep as literal (unchanged in output)
1889
+ * @param {object} [options.ncr] — Numeric Character Reference controls
1890
+ * @param {1.0|1.1} [options.ncr.xmlVersion=1.0]
1891
+ * XML version governing which codepoint ranges are restricted:
1892
+ * - 1.0 — C0 controls U+0001–U+001F (except U+0009/000A/000D) are prohibited
1893
+ * - 1.1 — C0 controls are allowed when written as NCRs; C1 (U+007F–U+009F) decoded as-is
1894
+ * @param {'allow'|'leave'|'remove'|'throw'} [options.ncr.onNCR='allow']
1895
+ * Base action for numeric references. Severity order: allow < leave < remove < throw.
1896
+ * For codepoint ranges that carry a minimum level (surrogates → remove, XML 1.0 C0 → remove),
1897
+ * the effective action is max(onNCR, rangeMinimum).
1898
+ * @param {'remove'|'throw'} [options.ncr.nullNCR='remove']
1899
+ * Action for U+0000 (null). 'allow' and 'leave' are clamped to 'remove' since null is never safe.
1900
+ */
1901
+ constructor(options = {}) {
1902
+ this._limit = options.limit || {};
1903
+ this._maxTotalExpansions = this._limit.maxTotalExpansions || 0;
1904
+ this._maxExpandedLength = this._limit.maxExpandedLength || 0;
1905
+ this._postCheck = typeof options.postCheck === "function" ? options.postCheck : (r) => r;
1906
+ this._limitTiers = parseLimitTiers(this._limit.applyLimitsTo ?? LIMIT_TIER_EXTERNAL);
1907
+ this._numericAllowed = options.numericAllowed ?? true;
1908
+ this._baseMap = mergeEntityMaps(XML, options.namedEntities || null);
1909
+ /** @type {Record<string, string>} */
1910
+ this._externalMap = Object.create(null);
1911
+ /** @type {Record<string, string>} */
1912
+ this._inputMap = Object.create(null);
1913
+ this._totalExpansions = 0;
1914
+ this._expandedLength = 0;
1915
+ /** @type {Set<string>} */
1916
+ this._removeSet = new Set(options.remove && Array.isArray(options.remove) ? options.remove : []);
1917
+ /** @type {Set<string>} */
1918
+ this._leaveSet = new Set(options.leave && Array.isArray(options.leave) ? options.leave : []);
1919
+ const ncrCfg = parseNCRConfig(options.ncr);
1920
+ this._ncrXmlVersion = ncrCfg.xmlVersion;
1921
+ this._ncrOnLevel = ncrCfg.onLevel;
1922
+ this._ncrNullLevel = ncrCfg.nullLevel;
1923
+ }
1924
+ /**
1925
+ * Replace the full set of persistent external entities.
1926
+ * All keys are validated — throws on invalid characters.
1927
+ * @param {Record<string, string | { regex?: RegExp, val: string }>} map
1928
+ */
1929
+ setExternalEntities(map) {
1930
+ if (map) for (const key of Object.keys(map)) validateEntityName$1(key);
1931
+ this._externalMap = mergeEntityMaps(map);
1932
+ }
1933
+ /**
1934
+ * Add a single persistent external entity.
1935
+ * @param {string} key
1936
+ * @param {string} value
1937
+ */
1938
+ addExternalEntity(key, value) {
1939
+ validateEntityName$1(key);
1940
+ if (typeof value === "string" && value.indexOf("&") === -1) this._externalMap[key] = value;
1941
+ }
1942
+ /**
1943
+ * Inject DOCTYPE entities for the current document.
1944
+ * Also resets per-document expansion counters.
1945
+ * @param {Record<string, string | { regx?: RegExp, regex?: RegExp, val: string }>} map
1946
+ */
1947
+ addInputEntities(map) {
1948
+ this._totalExpansions = 0;
1949
+ this._expandedLength = 0;
1950
+ this._inputMap = mergeEntityMaps(map);
1951
+ }
1952
+ /**
1953
+ * Wipe input/runtime entities and reset counters.
1954
+ * Call this before processing each new document.
1955
+ * @returns {this}
1956
+ */
1957
+ reset() {
1958
+ this._inputMap = Object.create(null);
1959
+ this._totalExpansions = 0;
1960
+ this._expandedLength = 0;
1961
+ return this;
1962
+ }
1963
+ /**
1964
+ * Update the XML version used for NCR classification.
1965
+ * Call this as soon as the document's `<?xml version="...">` declaration is parsed.
1966
+ * @param {1.0|1.1|number} version
1967
+ */
1968
+ setXmlVersion(version) {
1969
+ this._ncrXmlVersion = version === 1.1 ? 1.1 : 1;
1970
+ }
1971
+ /**
1972
+ * Replace all entity references in `str` in a single pass.
1973
+ *
1974
+ * @param {string} str
1975
+ * @returns {string}
1976
+ */
1977
+ decode(str) {
1978
+ if (typeof str !== "string" || str.length === 0) return str;
1979
+ const original = str;
1980
+ const chunks = [];
1981
+ const len = str.length;
1982
+ let last = 0;
1983
+ let i = 0;
1984
+ const limitExpansions = this._maxTotalExpansions > 0;
1985
+ const limitLength = this._maxExpandedLength > 0;
1986
+ const checkLimits = limitExpansions || limitLength;
1987
+ while (i < len) {
1988
+ if (str.charCodeAt(i) !== 38) {
1989
+ i++;
1990
+ continue;
1991
+ }
1992
+ let j = i + 1;
1993
+ while (j < len && str.charCodeAt(j) !== 59 && j - i <= 32) j++;
1994
+ if (j >= len || str.charCodeAt(j) !== 59) {
1995
+ i++;
1996
+ continue;
1997
+ }
1998
+ const token = str.slice(i + 1, j);
1999
+ if (token.length === 0) {
2000
+ i++;
2001
+ continue;
2002
+ }
2003
+ let replacement;
2004
+ let tier;
2005
+ if (this._removeSet.has(token)) {
2006
+ replacement = "";
2007
+ if (tier === void 0) tier = LIMIT_TIER_EXTERNAL;
2008
+ } else if (this._leaveSet.has(token)) {
2009
+ i++;
2010
+ continue;
2011
+ } else if (token.charCodeAt(0) === 35) {
2012
+ const ncrResult = this._resolveNCR(token);
2013
+ if (ncrResult === void 0) {
2014
+ i++;
2015
+ continue;
2016
+ }
2017
+ replacement = ncrResult;
2018
+ tier = LIMIT_TIER_BASE;
2019
+ } else {
2020
+ const resolved = this._resolveName(token);
2021
+ replacement = resolved?.value;
2022
+ tier = resolved?.tier;
2023
+ }
2024
+ if (replacement === void 0) {
2025
+ i++;
2026
+ continue;
2027
+ }
2028
+ if (i > last) chunks.push(str.slice(last, i));
2029
+ chunks.push(replacement);
2030
+ last = j + 1;
2031
+ i = last;
2032
+ if (checkLimits && this._tierCounts(tier)) {
2033
+ if (limitExpansions) {
2034
+ this._totalExpansions++;
2035
+ if (this._totalExpansions > this._maxTotalExpansions) throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);
2036
+ }
2037
+ if (limitLength) {
2038
+ const delta = replacement.length - (token.length + 2);
2039
+ if (delta > 0) {
2040
+ this._expandedLength += delta;
2041
+ if (this._expandedLength > this._maxExpandedLength) throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`);
2042
+ }
2043
+ }
2044
+ }
2045
+ }
2046
+ if (last < len) chunks.push(str.slice(last));
2047
+ const result = chunks.length === 0 ? str : chunks.join("");
2048
+ return this._postCheck(result, original);
2049
+ }
2050
+ /**
2051
+ * Returns true if a resolved entity of the given tier should count
2052
+ * against the expansion/length limits.
2053
+ * @param {string} tier — LIMIT_TIER_EXTERNAL | LIMIT_TIER_BASE
2054
+ * @returns {boolean}
2055
+ */
2056
+ _tierCounts(tier) {
2057
+ if (this._limitTiers.has(LIMIT_TIER_ALL)) return true;
2058
+ return this._limitTiers.has(tier);
2059
+ }
2060
+ /**
2061
+ * Resolve a named entity token (without & and ;).
2062
+ * Priority: inputMap > externalMap > baseMap
2063
+ * Returns the resolved value tagged with its limit tier.
2064
+ *
2065
+ * @param {string} name
2066
+ * @returns {{ value: string, tier: string }|undefined}
2067
+ */
2068
+ _resolveName(name) {
2069
+ if (name in this._inputMap) return {
2070
+ value: this._inputMap[name],
2071
+ tier: LIMIT_TIER_EXTERNAL
2072
+ };
2073
+ if (name in this._externalMap) return {
2074
+ value: this._externalMap[name],
2075
+ tier: LIMIT_TIER_EXTERNAL
2076
+ };
2077
+ if (name in this._baseMap) return {
2078
+ value: this._baseMap[name],
2079
+ tier: LIMIT_TIER_BASE
2080
+ };
2081
+ }
2082
+ /**
2083
+ * Classify a codepoint and return the minimum action level that must be applied.
2084
+ * Returns -1 when no minimum is imposed (normal allow path).
2085
+ *
2086
+ * Ranges checked (in priority order):
2087
+ * 1. U+0000 — null, governed by nullNCR (always ≥ remove)
2088
+ * 2. U+D800–U+DFFF — surrogates, always prohibited (min: remove)
2089
+ * 3. U+0001–U+001F \ {0x09,0x0A,0x0D} — XML 1.0 restricted C0 (min: remove)
2090
+ * (skipped in XML 1.1 — C0 controls are allowed when written as NCRs)
2091
+ *
2092
+ * @param {number} cp — codepoint
2093
+ * @returns {number} — minimum NCR_LEVEL value, or -1 for no restriction
2094
+ */
2095
+ _classifyNCR(cp) {
2096
+ if (cp === 0) return this._ncrNullLevel;
2097
+ if (cp >= 55296 && cp <= 57343) return NCR_LEVEL.remove;
2098
+ if (this._ncrXmlVersion === 1) {
2099
+ if (cp >= 1 && cp <= 31 && !XML10_ALLOWED_C0.has(cp)) return NCR_LEVEL.remove;
2100
+ }
2101
+ return -1;
2102
+ }
2103
+ /**
2104
+ * Execute a resolved NCR action.
2105
+ *
2106
+ * @param {number} action — NCR_LEVEL value
2107
+ * @param {string} token — raw token (e.g. '#38') for error messages
2108
+ * @param {number} cp — codepoint, used only for error messages
2109
+ * @returns {string|undefined}
2110
+ * - decoded character string → 'allow'
2111
+ * - '' → 'remove'
2112
+ * - undefined → 'leave' (caller must skip past '&' only)
2113
+ * - throws Error → 'throw'
2114
+ */
2115
+ _applyNCRAction(action, token, cp) {
2116
+ switch (action) {
2117
+ case NCR_LEVEL.allow: return String.fromCodePoint(cp);
2118
+ case NCR_LEVEL.remove: return "";
2119
+ case NCR_LEVEL.leave: return;
2120
+ case NCR_LEVEL.throw: throw new Error(`[EntityDecoder] Prohibited numeric character reference &${token}; (U+${cp.toString(16).toUpperCase().padStart(4, "0")})`);
2121
+ default: return String.fromCodePoint(cp);
2122
+ }
2123
+ }
2124
+ /**
2125
+ * Full NCR resolution pipeline for a numeric token.
2126
+ *
2127
+ * Steps:
2128
+ * 1. Parse the codepoint (decimal or hex).
2129
+ * 2. Validate the raw codepoint range (NaN, <0, >0x10FFFF).
2130
+ * 3. If numericAllowed is false and no minimum restriction applies → leave as-is.
2131
+ * 4. Classify the codepoint to find the minimum required action level.
2132
+ * 5. Resolve effective action = max(onNCR, minimum).
2133
+ * 6. Apply and return.
2134
+ *
2135
+ * @param {string} token — e.g. '#38', '#x26', '#X26'
2136
+ * @returns {string|undefined}
2137
+ * - string (incl. '') — replacement ('' = remove)
2138
+ * - undefined — leave original &token; as-is
2139
+ */
2140
+ _resolveNCR(token) {
2141
+ const second = token.charCodeAt(1);
2142
+ let cp;
2143
+ if (second === 120 || second === 88) cp = parseInt(token.slice(2), 16);
2144
+ else cp = parseInt(token.slice(1), 10);
2145
+ if (Number.isNaN(cp) || cp < 0 || cp > 1114111) return void 0;
2146
+ const minimum = this._classifyNCR(cp);
2147
+ if (!this._numericAllowed && minimum < NCR_LEVEL.remove) return void 0;
2148
+ const effective = minimum === -1 ? this._ncrOnLevel : Math.max(this._ncrOnLevel, minimum);
2149
+ return this._applyNCRAction(effective, token, cp);
2150
+ }
2151
+ };
2152
+ //#endregion
2153
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js
2154
+ const defaultOnDangerousProperty = (name) => {
2155
+ if (DANGEROUS_PROPERTY_NAMES.includes(name)) return "__" + name;
2156
+ return name;
2157
+ };
2158
+ const defaultOptions = {
2159
+ preserveOrder: false,
2160
+ attributeNamePrefix: "@_",
2161
+ attributesGroupName: false,
2162
+ textNodeName: "#text",
2163
+ ignoreAttributes: true,
2164
+ removeNSPrefix: false,
2165
+ allowBooleanAttributes: false,
2166
+ parseTagValue: true,
2167
+ parseAttributeValue: false,
2168
+ trimValues: true,
2169
+ cdataPropName: false,
2170
+ numberParseOptions: {
2171
+ hex: true,
2172
+ leadingZeros: true,
2173
+ eNotation: true
2174
+ },
2175
+ tagValueProcessor: function(tagName, val) {
2176
+ return val;
2177
+ },
2178
+ attributeValueProcessor: function(attrName, val) {
2179
+ return val;
2180
+ },
2181
+ stopNodes: [],
2182
+ alwaysCreateTextNode: false,
2183
+ isArray: () => false,
2184
+ commentPropName: false,
2185
+ unpairedTags: [],
2186
+ processEntities: true,
2187
+ htmlEntities: false,
2188
+ entityDecoder: null,
2189
+ ignoreDeclaration: false,
2190
+ ignorePiTags: false,
2191
+ transformTagName: false,
2192
+ transformAttributeName: false,
2193
+ updateTag: function(tagName, jPath, attrs) {
2194
+ return tagName;
2195
+ },
2196
+ captureMetaData: false,
2197
+ maxNestedTags: 100,
2198
+ strictReservedNames: true,
2199
+ jPath: true,
2200
+ onDangerousProperty: defaultOnDangerousProperty
2201
+ };
2202
+ /**
2203
+ * Validates that a property name is safe to use
2204
+ * @param {string} propertyName - The property name to validate
2205
+ * @param {string} optionName - The option field name (for error message)
2206
+ * @throws {Error} If property name is dangerous
2207
+ */
2208
+ function validatePropertyName(propertyName, optionName) {
2209
+ if (typeof propertyName !== "string") return;
2210
+ const normalized = propertyName.toLowerCase();
2211
+ if (DANGEROUS_PROPERTY_NAMES.some((dangerous) => normalized === dangerous.toLowerCase())) throw new Error(`[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution`);
2212
+ if (criticalProperties.some((dangerous) => normalized === dangerous.toLowerCase())) throw new Error(`[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution`);
2213
+ }
2214
+ /**
2215
+ * Normalizes processEntities option for backward compatibility
2216
+ * @param {boolean|object} value
2217
+ * @returns {object} Always returns normalized object
2218
+ */
2219
+ function normalizeProcessEntities(value, htmlEntities) {
2220
+ if (typeof value === "boolean") return {
2221
+ enabled: value,
2222
+ maxEntitySize: 1e4,
2223
+ maxExpansionDepth: 1e4,
2224
+ maxTotalExpansions: Infinity,
2225
+ maxExpandedLength: 1e5,
2226
+ maxEntityCount: 1e3,
2227
+ allowedTags: null,
2228
+ tagFilter: null,
2229
+ appliesTo: "all"
2230
+ };
2231
+ if (typeof value === "object" && value !== null) return {
2232
+ enabled: value.enabled !== false,
2233
+ maxEntitySize: Math.max(1, value.maxEntitySize ?? 1e4),
2234
+ maxExpansionDepth: Math.max(1, value.maxExpansionDepth ?? 1e4),
2235
+ maxTotalExpansions: Math.max(1, value.maxTotalExpansions ?? Infinity),
2236
+ maxExpandedLength: Math.max(1, value.maxExpandedLength ?? 1e5),
2237
+ maxEntityCount: Math.max(1, value.maxEntityCount ?? 1e3),
2238
+ allowedTags: value.allowedTags ?? null,
2239
+ tagFilter: value.tagFilter ?? null,
2240
+ appliesTo: value.appliesTo ?? "all"
2241
+ };
2242
+ return normalizeProcessEntities(true);
2243
+ }
2244
+ const buildOptions = function(options) {
2245
+ const built = Object.assign({}, defaultOptions, options);
2246
+ const propertyNameOptions = [
2247
+ {
2248
+ value: built.attributeNamePrefix,
2249
+ name: "attributeNamePrefix"
2250
+ },
2251
+ {
2252
+ value: built.attributesGroupName,
2253
+ name: "attributesGroupName"
2254
+ },
2255
+ {
2256
+ value: built.textNodeName,
2257
+ name: "textNodeName"
2258
+ },
2259
+ {
2260
+ value: built.cdataPropName,
2261
+ name: "cdataPropName"
2262
+ },
2263
+ {
2264
+ value: built.commentPropName,
2265
+ name: "commentPropName"
2266
+ }
2267
+ ];
2268
+ for (const { value, name } of propertyNameOptions) if (value) validatePropertyName(value, name);
2269
+ if (built.onDangerousProperty === null) built.onDangerousProperty = defaultOnDangerousProperty;
2270
+ built.processEntities = normalizeProcessEntities(built.processEntities, built.htmlEntities);
2271
+ built.unpairedTagsSet = new Set(built.unpairedTags);
2272
+ if (built.stopNodes && Array.isArray(built.stopNodes)) built.stopNodes = built.stopNodes.map((node) => {
2273
+ if (typeof node === "string" && node.startsWith("*.")) return ".." + node.substring(2);
2274
+ return node;
2275
+ });
2276
+ return built;
2277
+ };
2278
+ //#endregion
2279
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js
2280
+ let METADATA_SYMBOL$1;
2281
+ if (typeof Symbol !== "function") METADATA_SYMBOL$1 = "@@xmlMetadata";
2282
+ else METADATA_SYMBOL$1 = Symbol("XML Node Metadata");
2283
+ var XmlNode = class {
2284
+ constructor(tagname) {
2285
+ this.tagname = tagname;
2286
+ this.child = [];
2287
+ this[":@"] = Object.create(null);
2288
+ }
2289
+ add(key, val) {
2290
+ if (key === "__proto__") key = "#__proto__";
2291
+ this.child.push({ [key]: val });
2292
+ }
2293
+ addChild(node, startIndex) {
2294
+ if (node.tagname === "__proto__") node.tagname = "#__proto__";
2295
+ if (node[":@"] && Object.keys(node[":@"]).length > 0) this.child.push({
2296
+ [node.tagname]: node.child,
2297
+ [":@"]: node[":@"]
2298
+ });
2299
+ else this.child.push({ [node.tagname]: node.child });
2300
+ if (startIndex !== void 0) this.child[this.child.length - 1][METADATA_SYMBOL$1] = { startIndex };
2301
+ }
2302
+ /** symbol used for metadata */
2303
+ static getMetaDataSymbol() {
2304
+ return METADATA_SYMBOL$1;
2305
+ }
2306
+ };
2307
+ //#endregion
2308
+ //#region ../../node_modules/.pnpm/xml-naming@0.1.0/node_modules/xml-naming/src/index.js
2309
+ /**
2310
+ * xml-naming
2311
+ * Validates XML Name productions as defined in the XML 1.0 and 1.1 specifications.
2312
+ * Covers: Name, NCName, QName, NMToken, NMTokens
2313
+ *
2314
+ * XML 1.0 spec: https://www.w3.org/TR/xml/#NT-Name
2315
+ * XML 1.1 spec: https://www.w3.org/TR/xml11/#NT-NameStartChar
2316
+ * XML NS spec: https://www.w3.org/TR/xml-names/#NT-NCName
2317
+ */
2318
+ const nameStartChar10 = ":A-Za-z_À-ÖØ-öø-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�";
2319
+ const nameChar10 = ":A-Za-z_À-ÖØ-öø-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\\-\\.\\d·̀-ͯ‿-⁀";
2320
+ const nameStartChar11 = ":A-Za-z_À-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿";
2321
+ const nameChar11 = ":A-Za-z_À-˿Ͱ-ͽͿ-҆҈-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�𐀀-󯿿\\-\\.\\d·̀-ͯ҇‿-⁀";
2322
+ const buildRegexes = (startChar, char, flags = "") => {
2323
+ const ncNamePat = `[${startChar.replace(":", "")}][${char.replace(":", "")}]*`;
2324
+ return {
2325
+ name: new RegExp(`^[${startChar}][${char}]*$`, flags),
2326
+ ncName: new RegExp(`^${ncNamePat}$`, flags),
2327
+ qName: new RegExp(`^${ncNamePat}(?::${ncNamePat})?$`, flags),
2328
+ nmToken: new RegExp(`^[${char}]+$`, flags),
2329
+ nmTokens: new RegExp(`^[${char}]+(?:\\s+[${char}]+)*$`, flags)
2330
+ };
2331
+ };
2332
+ const regexes10 = buildRegexes(nameStartChar10, nameChar10);
2333
+ const regexes11 = buildRegexes(nameStartChar11, nameChar11, "u");
2334
+ const getRegexes = (xmlVersion = "1.0") => xmlVersion === "1.1" ? regexes11 : regexes10;
2335
+ /**
2336
+ * Returns true if the string is a valid QName (Qualified Name).
2337
+ * Allows exactly one colon as a prefix separator: prefix:localName.
2338
+ * Used for: element and attribute names in namespace-aware XML/SVG.
2339
+ */
2340
+ const qName = (str, { xmlVersion = "1.0" } = {}) => getRegexes(xmlVersion).qName.test(str);
2341
+ //#endregion
2342
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js
2343
+ var DocTypeReader = class {
2344
+ constructor(options, xmlVersion) {
2345
+ this.suppressValidationErr = !options;
2346
+ this.options = options;
2347
+ this.xmlVersion = xmlVersion || 1;
2348
+ }
2349
+ setXmlVersion(xmlVersion = 1) {
2350
+ this.xmlVersion = xmlVersion;
2351
+ }
2352
+ readDocType(xmlData, i) {
2353
+ const entities = Object.create(null);
2354
+ let entityCount = 0;
2355
+ if (xmlData[i + 3] === "O" && xmlData[i + 4] === "C" && xmlData[i + 5] === "T" && xmlData[i + 6] === "Y" && xmlData[i + 7] === "P" && xmlData[i + 8] === "E") {
2356
+ i = i + 9;
2357
+ let angleBracketsCount = 1;
2358
+ let hasBody = false, comment = false;
2359
+ let exp = "";
2360
+ for (; i < xmlData.length; i++) if (xmlData[i] === "<" && !comment) {
2361
+ if (hasBody && hasSeq(xmlData, "!ENTITY", i)) {
2362
+ i += 7;
2363
+ let entityName, val;
2364
+ [entityName, val, i] = this.readEntityExp(xmlData, i + 1, this.suppressValidationErr);
2365
+ if (val.indexOf("&") === -1) {
2366
+ if (this.options.enabled !== false && this.options.maxEntityCount != null && entityCount >= this.options.maxEntityCount) throw new Error(`Entity count (${entityCount + 1}) exceeds maximum allowed (${this.options.maxEntityCount})`);
2367
+ entities[entityName] = val;
2368
+ entityCount++;
2369
+ }
2370
+ } else if (hasBody && hasSeq(xmlData, "!ELEMENT", i)) {
2371
+ i += 8;
2372
+ const { index } = this.readElementExp(xmlData, i + 1);
2373
+ i = index;
2374
+ } else if (hasBody && hasSeq(xmlData, "!ATTLIST", i)) i += 8;
2375
+ else if (hasBody && hasSeq(xmlData, "!NOTATION", i)) {
2376
+ i += 9;
2377
+ const { index } = this.readNotationExp(xmlData, i + 1, this.suppressValidationErr);
2378
+ i = index;
2379
+ } else if (hasSeq(xmlData, "!--", i)) comment = true;
2380
+ else throw new Error(`Invalid DOCTYPE`);
2381
+ angleBracketsCount++;
2382
+ exp = "";
2383
+ } else if (xmlData[i] === ">") {
2384
+ if (comment) {
2385
+ if (xmlData[i - 1] === "-" && xmlData[i - 2] === "-") {
2386
+ comment = false;
2387
+ angleBracketsCount--;
2388
+ }
2389
+ } else angleBracketsCount--;
2390
+ if (angleBracketsCount === 0) break;
2391
+ } else if (xmlData[i] === "[") hasBody = true;
2392
+ else exp += xmlData[i];
2393
+ if (angleBracketsCount !== 0) throw new Error(`Unclosed DOCTYPE`);
2394
+ } else throw new Error(`Invalid Tag instead of DOCTYPE`);
2395
+ return {
2396
+ entities,
2397
+ i
2398
+ };
2399
+ }
2400
+ readEntityExp(xmlData, i) {
2401
+ i = skipWhitespace(xmlData, i);
2402
+ const startIndex = i;
2403
+ while (i < xmlData.length && !/\s/.test(xmlData[i]) && xmlData[i] !== "\"" && xmlData[i] !== "'") i++;
2404
+ let entityName = xmlData.substring(startIndex, i);
2405
+ validateEntityName(entityName, { xmlVersion: this.xmlVersion });
2406
+ i = skipWhitespace(xmlData, i);
2407
+ if (!this.suppressValidationErr) {
2408
+ if (xmlData.substring(i, i + 6).toUpperCase() === "SYSTEM") throw new Error("External entities are not supported");
2409
+ else if (xmlData[i] === "%") throw new Error("Parameter entities are not supported");
2410
+ }
2411
+ let entityValue = "";
2412
+ [i, entityValue] = this.readIdentifierVal(xmlData, i, "entity");
2413
+ if (this.options.enabled !== false && this.options.maxEntitySize != null && entityValue.length > this.options.maxEntitySize) throw new Error(`Entity "${entityName}" size (${entityValue.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);
2414
+ i--;
2415
+ return [
2416
+ entityName,
2417
+ entityValue,
2418
+ i
2419
+ ];
2420
+ }
2421
+ readNotationExp(xmlData, i) {
2422
+ i = skipWhitespace(xmlData, i);
2423
+ const startIndex = i;
2424
+ while (i < xmlData.length && !/\s/.test(xmlData[i])) i++;
2425
+ let notationName = xmlData.substring(startIndex, i);
2426
+ !this.suppressValidationErr && validateEntityName(notationName, { xmlVersion: this.xmlVersion });
2427
+ i = skipWhitespace(xmlData, i);
2428
+ const identifierType = xmlData.substring(i, i + 6).toUpperCase();
2429
+ if (!this.suppressValidationErr && identifierType !== "SYSTEM" && identifierType !== "PUBLIC") throw new Error(`Expected SYSTEM or PUBLIC, found "${identifierType}"`);
2430
+ i += identifierType.length;
2431
+ i = skipWhitespace(xmlData, i);
2432
+ let publicIdentifier = null;
2433
+ let systemIdentifier = null;
2434
+ if (identifierType === "PUBLIC") {
2435
+ [i, publicIdentifier] = this.readIdentifierVal(xmlData, i, "publicIdentifier");
2436
+ i = skipWhitespace(xmlData, i);
2437
+ if (xmlData[i] === "\"" || xmlData[i] === "'") [i, systemIdentifier] = this.readIdentifierVal(xmlData, i, "systemIdentifier");
2438
+ } else if (identifierType === "SYSTEM") {
2439
+ [i, systemIdentifier] = this.readIdentifierVal(xmlData, i, "systemIdentifier");
2440
+ if (!this.suppressValidationErr && !systemIdentifier) throw new Error("Missing mandatory system identifier for SYSTEM notation");
2441
+ }
2442
+ return {
2443
+ notationName,
2444
+ publicIdentifier,
2445
+ systemIdentifier,
2446
+ index: --i
2447
+ };
2448
+ }
2449
+ readIdentifierVal(xmlData, i, type) {
2450
+ let identifierVal = "";
2451
+ const startChar = xmlData[i];
2452
+ if (startChar !== "\"" && startChar !== "'") throw new Error(`Expected quoted string, found "${startChar}"`);
2453
+ i++;
2454
+ const startIndex = i;
2455
+ while (i < xmlData.length && xmlData[i] !== startChar) i++;
2456
+ identifierVal = xmlData.substring(startIndex, i);
2457
+ if (xmlData[i] !== startChar) throw new Error(`Unterminated ${type} value`);
2458
+ i++;
2459
+ return [i, identifierVal];
2460
+ }
2461
+ readElementExp(xmlData, i) {
2462
+ i = skipWhitespace(xmlData, i);
2463
+ const startIndex = i;
2464
+ while (i < xmlData.length && !/\s/.test(xmlData[i])) i++;
2465
+ let elementName = xmlData.substring(startIndex, i);
2466
+ if (!this.suppressValidationErr && !qName(elementName, { xmlVersion: this.xmlVersion })) throw new Error(`Invalid element name: "${elementName}"`);
2467
+ i = skipWhitespace(xmlData, i);
2468
+ let contentModel = "";
2469
+ if (xmlData[i] === "E" && hasSeq(xmlData, "MPTY", i)) i += 4;
2470
+ else if (xmlData[i] === "A" && hasSeq(xmlData, "NY", i)) i += 2;
2471
+ else if (xmlData[i] === "(") {
2472
+ i++;
2473
+ const startIndex = i;
2474
+ while (i < xmlData.length && xmlData[i] !== ")") i++;
2475
+ contentModel = xmlData.substring(startIndex, i);
2476
+ if (xmlData[i] !== ")") throw new Error("Unterminated content model");
2477
+ } else if (!this.suppressValidationErr) throw new Error(`Invalid Element Expression, found "${xmlData[i]}"`);
2478
+ return {
2479
+ elementName,
2480
+ contentModel: contentModel.trim(),
2481
+ index: i
2482
+ };
2483
+ }
2484
+ readAttlistExp(xmlData, i) {
2485
+ i = skipWhitespace(xmlData, i);
2486
+ let startIndex = i;
2487
+ while (i < xmlData.length && !/\s/.test(xmlData[i])) i++;
2488
+ let elementName = xmlData.substring(startIndex, i);
2489
+ validateEntityName(elementName, { xmlVersion: this.xmlVersion });
2490
+ i = skipWhitespace(xmlData, i);
2491
+ startIndex = i;
2492
+ while (i < xmlData.length && !/\s/.test(xmlData[i])) i++;
2493
+ let attributeName = xmlData.substring(startIndex, i);
2494
+ if (!validateEntityName(attributeName, { xmlVersion: this.xmlVersion })) throw new Error(`Invalid attribute name: "${attributeName}"`);
2495
+ i = skipWhitespace(xmlData, i);
2496
+ let attributeType = "";
2497
+ if (xmlData.substring(i, i + 8).toUpperCase() === "NOTATION") {
2498
+ attributeType = "NOTATION";
2499
+ i += 8;
2500
+ i = skipWhitespace(xmlData, i);
2501
+ if (xmlData[i] !== "(") throw new Error(`Expected '(', found "${xmlData[i]}"`);
2502
+ i++;
2503
+ let allowedNotations = [];
2504
+ while (i < xmlData.length && xmlData[i] !== ")") {
2505
+ const startIndex = i;
2506
+ while (i < xmlData.length && xmlData[i] !== "|" && xmlData[i] !== ")") i++;
2507
+ let notation = xmlData.substring(startIndex, i);
2508
+ notation = notation.trim();
2509
+ if (!validateEntityName(notation, { xmlVersion: this.xmlVersion })) throw new Error(`Invalid notation name: "${notation}"`);
2510
+ allowedNotations.push(notation);
2511
+ if (xmlData[i] === "|") {
2512
+ i++;
2513
+ i = skipWhitespace(xmlData, i);
2514
+ }
2515
+ }
2516
+ if (xmlData[i] !== ")") throw new Error("Unterminated list of notations");
2517
+ i++;
2518
+ attributeType += " (" + allowedNotations.join("|") + ")";
2519
+ } else {
2520
+ const startIndex = i;
2521
+ while (i < xmlData.length && !/\s/.test(xmlData[i])) i++;
2522
+ attributeType += xmlData.substring(startIndex, i);
2523
+ if (!this.suppressValidationErr && ![
2524
+ "CDATA",
2525
+ "ID",
2526
+ "IDREF",
2527
+ "IDREFS",
2528
+ "ENTITY",
2529
+ "ENTITIES",
2530
+ "NMTOKEN",
2531
+ "NMTOKENS"
2532
+ ].includes(attributeType.toUpperCase())) throw new Error(`Invalid attribute type: "${attributeType}"`);
2533
+ }
2534
+ i = skipWhitespace(xmlData, i);
2535
+ let defaultValue = "";
2536
+ if (xmlData.substring(i, i + 8).toUpperCase() === "#REQUIRED") {
2537
+ defaultValue = "#REQUIRED";
2538
+ i += 8;
2539
+ } else if (xmlData.substring(i, i + 7).toUpperCase() === "#IMPLIED") {
2540
+ defaultValue = "#IMPLIED";
2541
+ i += 7;
2542
+ } else [i, defaultValue] = this.readIdentifierVal(xmlData, i, "ATTLIST");
2543
+ return {
2544
+ elementName,
2545
+ attributeName,
2546
+ attributeType,
2547
+ defaultValue,
2548
+ index: i
2549
+ };
2550
+ }
2551
+ };
2552
+ const skipWhitespace = (data, index) => {
2553
+ while (index < data.length && /\s/.test(data[index])) index++;
2554
+ return index;
2555
+ };
2556
+ function hasSeq(data, seq, i) {
2557
+ for (let j = 0; j < seq.length; j++) if (seq[j] !== data[i + j + 1]) return false;
2558
+ return true;
2559
+ }
2560
+ function validateEntityName(name, xmlVersion) {
2561
+ if (qName(name, { xmlVersion })) return name;
2562
+ else throw new Error(`Invalid entity name ${name}`);
2563
+ }
2564
+ //#endregion
2565
+ //#region ../../node_modules/.pnpm/strnum@2.3.0/node_modules/strnum/strnum.js
2566
+ const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;
2567
+ const binRegex = /^0b[01]+$/;
2568
+ const octRegex = /^0o[0-7]+$/;
2569
+ const numRegex = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/;
2570
+ const consider = {
2571
+ hex: true,
2572
+ binary: false,
2573
+ octal: false,
2574
+ leadingZeros: true,
2575
+ decimalPoint: ".",
2576
+ eNotation: true,
2577
+ infinity: "original"
2578
+ };
2579
+ function toNumber(str, options = {}) {
2580
+ options = Object.assign({}, consider, options);
2581
+ if (!str || typeof str !== "string") return str;
2582
+ let trimmedStr = str.trim();
2583
+ if (trimmedStr.length === 0) return str;
2584
+ else if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr)) return str;
2585
+ else if (trimmedStr === "0") return 0;
2586
+ else if (options.hex && hexRegex.test(trimmedStr)) return parse_int(trimmedStr, 16);
2587
+ else if (options.binary && binRegex.test(trimmedStr)) return parse_int(trimmedStr, 2);
2588
+ else if (options.octal && octRegex.test(trimmedStr)) return parse_int(trimmedStr, 8);
2589
+ else if (!isFinite(trimmedStr)) return handleInfinity(str, Number(trimmedStr), options);
2590
+ else if (trimmedStr.includes("e") || trimmedStr.includes("E")) return resolveEnotation(str, trimmedStr, options);
2591
+ else {
2592
+ const match = numRegex.exec(trimmedStr);
2593
+ if (match) {
2594
+ const sign = match[1] || "";
2595
+ const leadingZeros = match[2];
2596
+ let numTrimmedByZeros = trimZeros(match[3]);
2597
+ const decimalAdjacentToLeadingZeros = sign ? str[leadingZeros.length + 1] === "." : str[leadingZeros.length] === ".";
2598
+ if (!options.leadingZeros && (leadingZeros.length > 1 || leadingZeros.length === 1 && !decimalAdjacentToLeadingZeros)) return str;
2599
+ else {
2600
+ const num = Number(trimmedStr);
2601
+ const parsedStr = String(num);
2602
+ if (num === 0) return num;
2603
+ if (parsedStr.search(/[eE]/) !== -1) if (options.eNotation) return num;
2604
+ else return str;
2605
+ else if (trimmedStr.indexOf(".") !== -1) if (parsedStr === "0") return num;
2606
+ else if (parsedStr === numTrimmedByZeros) return num;
2607
+ else if (parsedStr === `${sign}${numTrimmedByZeros}`) return num;
2608
+ else return str;
2609
+ let n = leadingZeros ? numTrimmedByZeros : trimmedStr;
2610
+ if (leadingZeros) return n === parsedStr || sign + n === parsedStr ? num : str;
2611
+ else return n === parsedStr || n === sign + parsedStr ? num : str;
2612
+ }
2613
+ } else return str;
2614
+ }
2615
+ }
2616
+ const eNotationRegx = /^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;
2617
+ function resolveEnotation(str, trimmedStr, options) {
2618
+ if (!options.eNotation) return str;
2619
+ const notation = trimmedStr.match(eNotationRegx);
2620
+ if (notation) {
2621
+ let sign = notation[1] || "";
2622
+ const eChar = notation[3].indexOf("e") === -1 ? "E" : "e";
2623
+ const leadingZeros = notation[2];
2624
+ const eAdjacentToLeadingZeros = sign ? str[leadingZeros.length + 1] === eChar : str[leadingZeros.length] === eChar;
2625
+ if (leadingZeros.length > 1 && eAdjacentToLeadingZeros) return str;
2626
+ else if (leadingZeros.length === 1 && (notation[3].startsWith(`.${eChar}`) || notation[3][0] === eChar)) return Number(trimmedStr);
2627
+ else if (leadingZeros.length > 0) if (options.leadingZeros && !eAdjacentToLeadingZeros) {
2628
+ trimmedStr = (notation[1] || "") + notation[3];
2629
+ return Number(trimmedStr);
2630
+ } else return str;
2631
+ else return Number(trimmedStr);
2632
+ } else return str;
2633
+ }
2634
+ /**
2635
+ *
2636
+ * @param {string} numStr without leading zeros
2637
+ * @returns
2638
+ */
2639
+ function trimZeros(numStr) {
2640
+ if (numStr && numStr.indexOf(".") !== -1) {
2641
+ numStr = numStr.replace(/0+$/, "");
2642
+ if (numStr === ".") numStr = "0";
2643
+ else if (numStr[0] === ".") numStr = "0" + numStr;
2644
+ else if (numStr[numStr.length - 1] === ".") numStr = numStr.substring(0, numStr.length - 1);
2645
+ return numStr;
2646
+ }
2647
+ return numStr;
2648
+ }
2649
+ function parse_int(numStr, base) {
2650
+ const str = numStr.trim();
2651
+ if (base === 2 || base === 8) numStr = str.substring(2);
2652
+ if (parseInt) return parseInt(numStr, base);
2653
+ else if (Number.parseInt) return Number.parseInt(numStr, base);
2654
+ else if (window && window.parseInt) return window.parseInt(numStr, base);
2655
+ else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported");
2656
+ }
2657
+ /**
2658
+ * Handle infinite values based on user option
2659
+ * @param {string} str - original input string
2660
+ * @param {number} num - parsed number (Infinity or -Infinity)
2661
+ * @param {object} options - user options
2662
+ * @returns {string|number|null} based on infinity option
2663
+ */
2664
+ function handleInfinity(str, num, options) {
2665
+ const isPositive = num === Infinity;
2666
+ switch (options.infinity.toLowerCase()) {
2667
+ case "null": return null;
2668
+ case "infinity": return num;
2669
+ case "string": return isPositive ? "Infinity" : "-Infinity";
2670
+ default: return str;
2671
+ }
2672
+ }
2673
+ //#endregion
2674
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/ignoreAttributes.js
2675
+ function getIgnoreAttributesFn(ignoreAttributes) {
2676
+ if (typeof ignoreAttributes === "function") return ignoreAttributes;
2677
+ if (Array.isArray(ignoreAttributes)) return (attrName) => {
2678
+ for (const pattern of ignoreAttributes) {
2679
+ if (typeof pattern === "string" && attrName === pattern) return true;
2680
+ if (pattern instanceof RegExp && pattern.test(attrName)) return true;
2681
+ }
2682
+ };
2683
+ return () => false;
2684
+ }
2685
+ //#endregion
2686
+ //#region ../../node_modules/.pnpm/path-expression-matcher@1.5.0/node_modules/path-expression-matcher/src/Expression.js
2687
+ /**
2688
+ * Expression - Parses and stores a tag pattern expression
2689
+ *
2690
+ * Patterns are parsed once and stored in an optimized structure for fast matching.
2691
+ *
2692
+ * @example
2693
+ * const expr = new Expression("root.users.user");
2694
+ * const expr2 = new Expression("..user[id]:first");
2695
+ * const expr3 = new Expression("root/users/user", { separator: '/' });
2696
+ */
2697
+ var Expression = class {
2698
+ /**
2699
+ * Create a new Expression
2700
+ * @param {string} pattern - Pattern string (e.g., "root.users.user", "..user[id]")
2701
+ * @param {Object} options - Configuration options
2702
+ * @param {string} options.separator - Path separator (default: '.')
2703
+ */
2704
+ constructor(pattern, options = {}, data) {
2705
+ this.pattern = pattern;
2706
+ this.separator = options.separator || ".";
2707
+ this.segments = this._parse(pattern);
2708
+ this.data = data;
2709
+ this._hasDeepWildcard = this.segments.some((seg) => seg.type === "deep-wildcard");
2710
+ this._hasAttributeCondition = this.segments.some((seg) => seg.attrName !== void 0);
2711
+ this._hasPositionSelector = this.segments.some((seg) => seg.position !== void 0);
2712
+ }
2713
+ /**
2714
+ * Parse pattern string into segments
2715
+ * @private
2716
+ * @param {string} pattern - Pattern to parse
2717
+ * @returns {Array} Array of segment objects
2718
+ */
2719
+ _parse(pattern) {
2720
+ const segments = [];
2721
+ let i = 0;
2722
+ let currentPart = "";
2723
+ while (i < pattern.length) if (pattern[i] === this.separator) if (i + 1 < pattern.length && pattern[i + 1] === this.separator) {
2724
+ if (currentPart.trim()) {
2725
+ segments.push(this._parseSegment(currentPart.trim()));
2726
+ currentPart = "";
2727
+ }
2728
+ segments.push({ type: "deep-wildcard" });
2729
+ i += 2;
2730
+ } else {
2731
+ if (currentPart.trim()) segments.push(this._parseSegment(currentPart.trim()));
2732
+ currentPart = "";
2733
+ i++;
2734
+ }
2735
+ else {
2736
+ currentPart += pattern[i];
2737
+ i++;
2738
+ }
2739
+ if (currentPart.trim()) segments.push(this._parseSegment(currentPart.trim()));
2740
+ return segments;
2741
+ }
2742
+ /**
2743
+ * Parse a single segment
2744
+ * @private
2745
+ * @param {string} part - Segment string (e.g., "user", "ns::user", "user[id]", "ns::user:first")
2746
+ * @returns {Object} Segment object
2747
+ */
2748
+ _parseSegment(part) {
2749
+ const segment = { type: "tag" };
2750
+ let bracketContent = null;
2751
+ let withoutBrackets = part;
2752
+ const bracketMatch = part.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);
2753
+ if (bracketMatch) {
2754
+ withoutBrackets = bracketMatch[1] + bracketMatch[3];
2755
+ if (bracketMatch[2]) {
2756
+ const content = bracketMatch[2].slice(1, -1);
2757
+ if (content) bracketContent = content;
2758
+ }
2759
+ }
2760
+ let namespace = void 0;
2761
+ let tagAndPosition = withoutBrackets;
2762
+ if (withoutBrackets.includes("::")) {
2763
+ const nsIndex = withoutBrackets.indexOf("::");
2764
+ namespace = withoutBrackets.substring(0, nsIndex).trim();
2765
+ tagAndPosition = withoutBrackets.substring(nsIndex + 2).trim();
2766
+ if (!namespace) throw new Error(`Invalid namespace in pattern: ${part}`);
2767
+ }
2768
+ let tag = void 0;
2769
+ let positionMatch = null;
2770
+ if (tagAndPosition.includes(":")) {
2771
+ const colonIndex = tagAndPosition.lastIndexOf(":");
2772
+ const tagPart = tagAndPosition.substring(0, colonIndex).trim();
2773
+ const posPart = tagAndPosition.substring(colonIndex + 1).trim();
2774
+ if ([
2775
+ "first",
2776
+ "last",
2777
+ "odd",
2778
+ "even"
2779
+ ].includes(posPart) || /^nth\(\d+\)$/.test(posPart)) {
2780
+ tag = tagPart;
2781
+ positionMatch = posPart;
2782
+ } else tag = tagAndPosition;
2783
+ } else tag = tagAndPosition;
2784
+ if (!tag) throw new Error(`Invalid segment pattern: ${part}`);
2785
+ segment.tag = tag;
2786
+ if (namespace) segment.namespace = namespace;
2787
+ if (bracketContent) if (bracketContent.includes("=")) {
2788
+ const eqIndex = bracketContent.indexOf("=");
2789
+ segment.attrName = bracketContent.substring(0, eqIndex).trim();
2790
+ segment.attrValue = bracketContent.substring(eqIndex + 1).trim();
2791
+ } else segment.attrName = bracketContent.trim();
2792
+ if (positionMatch) {
2793
+ const nthMatch = positionMatch.match(/^nth\((\d+)\)$/);
2794
+ if (nthMatch) {
2795
+ segment.position = "nth";
2796
+ segment.positionValue = parseInt(nthMatch[1], 10);
2797
+ } else segment.position = positionMatch;
2798
+ }
2799
+ return segment;
2800
+ }
2801
+ /**
2802
+ * Get the number of segments
2803
+ * @returns {number}
2804
+ */
2805
+ get length() {
2806
+ return this.segments.length;
2807
+ }
2808
+ /**
2809
+ * Check if expression contains deep wildcard
2810
+ * @returns {boolean}
2811
+ */
2812
+ hasDeepWildcard() {
2813
+ return this._hasDeepWildcard;
2814
+ }
2815
+ /**
2816
+ * Check if expression has attribute conditions
2817
+ * @returns {boolean}
2818
+ */
2819
+ hasAttributeCondition() {
2820
+ return this._hasAttributeCondition;
2821
+ }
2822
+ /**
2823
+ * Check if expression has position selectors
2824
+ * @returns {boolean}
2825
+ */
2826
+ hasPositionSelector() {
2827
+ return this._hasPositionSelector;
2828
+ }
2829
+ /**
2830
+ * Get string representation
2831
+ * @returns {string}
2832
+ */
2833
+ toString() {
2834
+ return this.pattern;
2835
+ }
2836
+ };
2837
+ //#endregion
2838
+ //#region ../../node_modules/.pnpm/path-expression-matcher@1.5.0/node_modules/path-expression-matcher/src/ExpressionSet.js
2839
+ /**
2840
+ * ExpressionSet - An indexed collection of Expressions for efficient bulk matching
2841
+ *
2842
+ * Instead of iterating all expressions on every tag, ExpressionSet pre-indexes
2843
+ * them at insertion time by depth and terminal tag name. At match time, only
2844
+ * the relevant bucket is evaluated — typically reducing checks from O(E) to O(1)
2845
+ * lookup plus O(small bucket) matches.
2846
+ *
2847
+ * Three buckets are maintained:
2848
+ * - `_byDepthAndTag` — exact depth + exact tag name (tightest, used first)
2849
+ * - `_wildcardByDepth` — exact depth + wildcard tag `*` (depth-matched only)
2850
+ * - `_deepWildcards` — expressions containing `..` (cannot be depth-indexed)
2851
+ *
2852
+ * @example
2853
+ * import { Expression, ExpressionSet } from 'fast-xml-tagger';
2854
+ *
2855
+ * // Build once at config time
2856
+ * const stopNodes = new ExpressionSet();
2857
+ * stopNodes.add(new Expression('root.users.user'));
2858
+ * stopNodes.add(new Expression('root.config.setting'));
2859
+ * stopNodes.add(new Expression('..script'));
2860
+ *
2861
+ * // Query on every tag — hot path
2862
+ * if (stopNodes.matchesAny(matcher)) { ... }
2863
+ */
2864
+ var ExpressionSet = class {
2865
+ constructor() {
2866
+ /** @type {Map<string, import('./Expression.js').default[]>} depth:tag → expressions */
2867
+ this._byDepthAndTag = /* @__PURE__ */ new Map();
2868
+ /** @type {Map<number, import('./Expression.js').default[]>} depth → wildcard-tag expressions */
2869
+ this._wildcardByDepth = /* @__PURE__ */ new Map();
2870
+ /** @type {import('./Expression.js').default[]} expressions containing deep wildcard (..) */
2871
+ this._deepWildcards = [];
2872
+ /** @type {Set<string>} pattern strings already added — used for deduplication */
2873
+ this._patterns = /* @__PURE__ */ new Set();
2874
+ /** @type {boolean} whether the set is sealed against further additions */
2875
+ this._sealed = false;
2876
+ }
2877
+ /**
2878
+ * Add an Expression to the set.
2879
+ * Duplicate patterns (same pattern string) are silently ignored.
2880
+ *
2881
+ * @param {import('./Expression.js').default} expression - A pre-constructed Expression instance
2882
+ * @returns {this} for chaining
2883
+ * @throws {TypeError} if called after seal()
2884
+ *
2885
+ * @example
2886
+ * set.add(new Expression('root.users.user'));
2887
+ * set.add(new Expression('..script'));
2888
+ */
2889
+ add(expression) {
2890
+ if (this._sealed) throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.");
2891
+ if (this._patterns.has(expression.pattern)) return this;
2892
+ this._patterns.add(expression.pattern);
2893
+ if (expression.hasDeepWildcard()) {
2894
+ this._deepWildcards.push(expression);
2895
+ return this;
2896
+ }
2897
+ const depth = expression.length;
2898
+ const tag = expression.segments[expression.segments.length - 1]?.tag;
2899
+ if (!tag || tag === "*") {
2900
+ if (!this._wildcardByDepth.has(depth)) this._wildcardByDepth.set(depth, []);
2901
+ this._wildcardByDepth.get(depth).push(expression);
2902
+ } else {
2903
+ const key = `${depth}:${tag}`;
2904
+ if (!this._byDepthAndTag.has(key)) this._byDepthAndTag.set(key, []);
2905
+ this._byDepthAndTag.get(key).push(expression);
2906
+ }
2907
+ return this;
2908
+ }
2909
+ /**
2910
+ * Add multiple expressions at once.
2911
+ *
2912
+ * @param {import('./Expression.js').default[]} expressions - Array of Expression instances
2913
+ * @returns {this} for chaining
2914
+ *
2915
+ * @example
2916
+ * set.addAll([
2917
+ * new Expression('root.users.user'),
2918
+ * new Expression('root.config.setting'),
2919
+ * ]);
2920
+ */
2921
+ addAll(expressions) {
2922
+ for (const expr of expressions) this.add(expr);
2923
+ return this;
2924
+ }
2925
+ /**
2926
+ * Check whether a pattern string is already present in the set.
2927
+ *
2928
+ * @param {import('./Expression.js').default} expression
2929
+ * @returns {boolean}
2930
+ */
2931
+ has(expression) {
2932
+ return this._patterns.has(expression.pattern);
2933
+ }
2934
+ /**
2935
+ * Number of expressions in the set.
2936
+ * @type {number}
2937
+ */
2938
+ get size() {
2939
+ return this._patterns.size;
2940
+ }
2941
+ /**
2942
+ * Seal the set against further modifications.
2943
+ * Useful to prevent accidental mutations after config is built.
2944
+ * Calling add() or addAll() on a sealed set throws a TypeError.
2945
+ *
2946
+ * @returns {this}
2947
+ */
2948
+ seal() {
2949
+ this._sealed = true;
2950
+ return this;
2951
+ }
2952
+ /**
2953
+ * Whether the set has been sealed.
2954
+ * @type {boolean}
2955
+ */
2956
+ get isSealed() {
2957
+ return this._sealed;
2958
+ }
2959
+ /**
2960
+ * Test whether the matcher's current path matches any expression in the set.
2961
+ *
2962
+ * Evaluation order (cheapest → most expensive):
2963
+ * 1. Exact depth + tag bucket — O(1) lookup, typically 0–2 expressions
2964
+ * 2. Depth-only wildcard bucket — O(1) lookup, rare
2965
+ * 3. Deep-wildcard list — always checked, but usually small
2966
+ *
2967
+ * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view)
2968
+ * @returns {boolean} true if any expression matches the current path
2969
+ *
2970
+ * @example
2971
+ * if (stopNodes.matchesAny(matcher)) {
2972
+ * // handle stop node
2973
+ * }
2974
+ */
2975
+ matchesAny(matcher) {
2976
+ return this.findMatch(matcher) !== null;
2977
+ }
2978
+ /**
2979
+ * Find and return the first Expression that matches the matcher's current path.
2980
+ *
2981
+ * Uses the same evaluation order as matchesAny (cheapest → most expensive):
2982
+ * 1. Exact depth + tag bucket
2983
+ * 2. Depth-only wildcard bucket
2984
+ * 3. Deep-wildcard list
2985
+ *
2986
+ * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view)
2987
+ * @returns {import('./Expression.js').default | null} the first matching Expression, or null
2988
+ *
2989
+ * @example
2990
+ * const expr = stopNodes.findMatch(matcher);
2991
+ * if (expr) {
2992
+ * // access expr.config, expr.pattern, etc.
2993
+ * }
2994
+ */
2995
+ findMatch(matcher) {
2996
+ const depth = matcher.getDepth();
2997
+ const exactKey = `${depth}:${matcher.getCurrentTag()}`;
2998
+ const exactBucket = this._byDepthAndTag.get(exactKey);
2999
+ if (exactBucket) {
3000
+ for (let i = 0; i < exactBucket.length; i++) if (matcher.matches(exactBucket[i])) return exactBucket[i];
3001
+ }
3002
+ const wildcardBucket = this._wildcardByDepth.get(depth);
3003
+ if (wildcardBucket) {
3004
+ for (let i = 0; i < wildcardBucket.length; i++) if (matcher.matches(wildcardBucket[i])) return wildcardBucket[i];
3005
+ }
3006
+ for (let i = 0; i < this._deepWildcards.length; i++) if (matcher.matches(this._deepWildcards[i])) return this._deepWildcards[i];
3007
+ return null;
3008
+ }
3009
+ };
3010
+ //#endregion
3011
+ //#region ../../node_modules/.pnpm/path-expression-matcher@1.5.0/node_modules/path-expression-matcher/src/Matcher.js
3012
+ /**
3013
+ * MatcherView - A lightweight read-only view over a Matcher's internal state.
3014
+ *
3015
+ * Created once by Matcher and reused across all callbacks. Holds a direct
3016
+ * reference to the parent Matcher so it always reflects current parser state
3017
+ * with zero copying or freezing overhead.
3018
+ *
3019
+ * Users receive this via {@link Matcher#readOnly} or directly from parser
3020
+ * callbacks. It exposes all query and matching methods but has no mutation
3021
+ * methods — misuse is caught at the TypeScript level rather than at runtime.
3022
+ *
3023
+ * @example
3024
+ * const matcher = new Matcher();
3025
+ * const view = matcher.readOnly();
3026
+ *
3027
+ * matcher.push("root", {});
3028
+ * view.getCurrentTag(); // "root"
3029
+ * view.getDepth(); // 1
3030
+ */
3031
+ var MatcherView = class {
3032
+ /**
3033
+ * @param {Matcher} matcher - The parent Matcher instance to read from.
3034
+ */
3035
+ constructor(matcher) {
3036
+ this._matcher = matcher;
3037
+ }
3038
+ /**
3039
+ * Get the path separator used by the parent matcher.
3040
+ * @returns {string}
3041
+ */
3042
+ get separator() {
3043
+ return this._matcher.separator;
3044
+ }
3045
+ /**
3046
+ * Get current tag name.
3047
+ * @returns {string|undefined}
3048
+ */
3049
+ getCurrentTag() {
3050
+ const path = this._matcher.path;
3051
+ return path.length > 0 ? path[path.length - 1].tag : void 0;
3052
+ }
3053
+ /**
3054
+ * Get current namespace.
3055
+ * @returns {string|undefined}
3056
+ */
3057
+ getCurrentNamespace() {
3058
+ const path = this._matcher.path;
3059
+ return path.length > 0 ? path[path.length - 1].namespace : void 0;
3060
+ }
3061
+ /**
3062
+ * Get current node's attribute value.
3063
+ * @param {string} attrName
3064
+ * @returns {*}
3065
+ */
3066
+ getAttrValue(attrName) {
3067
+ const path = this._matcher.path;
3068
+ if (path.length === 0) return void 0;
3069
+ return path[path.length - 1].values?.[attrName];
3070
+ }
3071
+ /**
3072
+ * Check if current node has an attribute.
3073
+ * @param {string} attrName
3074
+ * @returns {boolean}
3075
+ */
3076
+ hasAttr(attrName) {
3077
+ const path = this._matcher.path;
3078
+ if (path.length === 0) return false;
3079
+ const current = path[path.length - 1];
3080
+ return current.values !== void 0 && attrName in current.values;
3081
+ }
3082
+ /**
3083
+ * Get current node's sibling position (child index in parent).
3084
+ * @returns {number}
3085
+ */
3086
+ getPosition() {
3087
+ const path = this._matcher.path;
3088
+ if (path.length === 0) return -1;
3089
+ return path[path.length - 1].position ?? 0;
3090
+ }
3091
+ /**
3092
+ * Get current node's repeat counter (occurrence count of this tag name).
3093
+ * @returns {number}
3094
+ */
3095
+ getCounter() {
3096
+ const path = this._matcher.path;
3097
+ if (path.length === 0) return -1;
3098
+ return path[path.length - 1].counter ?? 0;
3099
+ }
3100
+ /**
3101
+ * Get current node's sibling index (alias for getPosition).
3102
+ * @returns {number}
3103
+ * @deprecated Use getPosition() or getCounter() instead
3104
+ */
3105
+ getIndex() {
3106
+ return this.getPosition();
3107
+ }
3108
+ /**
3109
+ * Get current path depth.
3110
+ * @returns {number}
3111
+ */
3112
+ getDepth() {
3113
+ return this._matcher.path.length;
3114
+ }
3115
+ /**
3116
+ * Get path as string.
3117
+ * @param {string} [separator] - Optional separator (uses default if not provided)
3118
+ * @param {boolean} [includeNamespace=true]
3119
+ * @returns {string}
3120
+ */
3121
+ toString(separator, includeNamespace = true) {
3122
+ return this._matcher.toString(separator, includeNamespace);
3123
+ }
3124
+ /**
3125
+ * Get path as array of tag names.
3126
+ * @returns {string[]}
3127
+ */
3128
+ toArray() {
3129
+ return this._matcher.path.map((n) => n.tag);
3130
+ }
3131
+ /**
3132
+ * Match current path against an Expression.
3133
+ * @param {Expression} expression
3134
+ * @returns {boolean}
3135
+ */
3136
+ matches(expression) {
3137
+ return this._matcher.matches(expression);
3138
+ }
3139
+ /**
3140
+ * Match any expression in the given set against the current path.
3141
+ * @param {ExpressionSet} exprSet
3142
+ * @returns {boolean}
3143
+ */
3144
+ matchesAny(exprSet) {
3145
+ return exprSet.matchesAny(this._matcher);
3146
+ }
3147
+ };
3148
+ /**
3149
+ * Matcher - Tracks current path in XML/JSON tree and matches against Expressions.
3150
+ *
3151
+ * The matcher maintains a stack of nodes representing the current path from root to
3152
+ * current tag. It only stores attribute values for the current (top) node to minimize
3153
+ * memory usage. Sibling tracking is used to auto-calculate position and counter.
3154
+ *
3155
+ * Use {@link Matcher#readOnly} to obtain a {@link MatcherView} safe to pass to
3156
+ * user callbacks — it always reflects current state with no Proxy overhead.
3157
+ *
3158
+ * @example
3159
+ * const matcher = new Matcher();
3160
+ * matcher.push("root", {});
3161
+ * matcher.push("users", {});
3162
+ * matcher.push("user", { id: "123", type: "admin" });
3163
+ *
3164
+ * const expr = new Expression("root.users.user");
3165
+ * matcher.matches(expr); // true
3166
+ */
3167
+ var Matcher = class {
3168
+ /**
3169
+ * Create a new Matcher.
3170
+ * @param {Object} [options={}]
3171
+ * @param {string} [options.separator='.'] - Default path separator
3172
+ */
3173
+ constructor(options = {}) {
3174
+ this.separator = options.separator || ".";
3175
+ this.path = [];
3176
+ this.siblingStacks = [];
3177
+ this._pathStringCache = null;
3178
+ this._view = new MatcherView(this);
3179
+ }
3180
+ /**
3181
+ * Push a new tag onto the path.
3182
+ * @param {string} tagName
3183
+ * @param {Object|null} [attrValues=null]
3184
+ * @param {string|null} [namespace=null]
3185
+ */
3186
+ push(tagName, attrValues = null, namespace = null) {
3187
+ this._pathStringCache = null;
3188
+ if (this.path.length > 0) this.path[this.path.length - 1].values = void 0;
3189
+ const currentLevel = this.path.length;
3190
+ if (!this.siblingStacks[currentLevel]) this.siblingStacks[currentLevel] = /* @__PURE__ */ new Map();
3191
+ const siblings = this.siblingStacks[currentLevel];
3192
+ const siblingKey = namespace ? `${namespace}:${tagName}` : tagName;
3193
+ const counter = siblings.get(siblingKey) || 0;
3194
+ let position = 0;
3195
+ for (const count of siblings.values()) position += count;
3196
+ siblings.set(siblingKey, counter + 1);
3197
+ const node = {
3198
+ tag: tagName,
3199
+ position,
3200
+ counter
3201
+ };
3202
+ if (namespace !== null && namespace !== void 0) node.namespace = namespace;
3203
+ if (attrValues !== null && attrValues !== void 0) node.values = attrValues;
3204
+ this.path.push(node);
3205
+ }
3206
+ /**
3207
+ * Pop the last tag from the path.
3208
+ * @returns {Object|undefined} The popped node
3209
+ */
3210
+ pop() {
3211
+ if (this.path.length === 0) return void 0;
3212
+ this._pathStringCache = null;
3213
+ const node = this.path.pop();
3214
+ if (this.siblingStacks.length > this.path.length + 1) this.siblingStacks.length = this.path.length + 1;
3215
+ return node;
3216
+ }
3217
+ /**
3218
+ * Update current node's attribute values.
3219
+ * Useful when attributes are parsed after push.
3220
+ * @param {Object} attrValues
3221
+ */
3222
+ updateCurrent(attrValues) {
3223
+ if (this.path.length > 0) {
3224
+ const current = this.path[this.path.length - 1];
3225
+ if (attrValues !== null && attrValues !== void 0) current.values = attrValues;
3226
+ }
3227
+ }
3228
+ /**
3229
+ * Get current tag name.
3230
+ * @returns {string|undefined}
3231
+ */
3232
+ getCurrentTag() {
3233
+ return this.path.length > 0 ? this.path[this.path.length - 1].tag : void 0;
3234
+ }
3235
+ /**
3236
+ * Get current namespace.
3237
+ * @returns {string|undefined}
3238
+ */
3239
+ getCurrentNamespace() {
3240
+ return this.path.length > 0 ? this.path[this.path.length - 1].namespace : void 0;
3241
+ }
3242
+ /**
3243
+ * Get current node's attribute value.
3244
+ * @param {string} attrName
3245
+ * @returns {*}
3246
+ */
3247
+ getAttrValue(attrName) {
3248
+ if (this.path.length === 0) return void 0;
3249
+ return this.path[this.path.length - 1].values?.[attrName];
3250
+ }
3251
+ /**
3252
+ * Check if current node has an attribute.
3253
+ * @param {string} attrName
3254
+ * @returns {boolean}
3255
+ */
3256
+ hasAttr(attrName) {
3257
+ if (this.path.length === 0) return false;
3258
+ const current = this.path[this.path.length - 1];
3259
+ return current.values !== void 0 && attrName in current.values;
3260
+ }
3261
+ /**
3262
+ * Get current node's sibling position (child index in parent).
3263
+ * @returns {number}
3264
+ */
3265
+ getPosition() {
3266
+ if (this.path.length === 0) return -1;
3267
+ return this.path[this.path.length - 1].position ?? 0;
3268
+ }
3269
+ /**
3270
+ * Get current node's repeat counter (occurrence count of this tag name).
3271
+ * @returns {number}
3272
+ */
3273
+ getCounter() {
3274
+ if (this.path.length === 0) return -1;
3275
+ return this.path[this.path.length - 1].counter ?? 0;
3276
+ }
3277
+ /**
3278
+ * Get current node's sibling index (alias for getPosition).
3279
+ * @returns {number}
3280
+ * @deprecated Use getPosition() or getCounter() instead
3281
+ */
3282
+ getIndex() {
3283
+ return this.getPosition();
3284
+ }
3285
+ /**
3286
+ * Get current path depth.
3287
+ * @returns {number}
3288
+ */
3289
+ getDepth() {
3290
+ return this.path.length;
3291
+ }
3292
+ /**
3293
+ * Get path as string.
3294
+ * @param {string} [separator] - Optional separator (uses default if not provided)
3295
+ * @param {boolean} [includeNamespace=true]
3296
+ * @returns {string}
3297
+ */
3298
+ toString(separator, includeNamespace = true) {
3299
+ const sep = separator || this.separator;
3300
+ if (sep === this.separator && includeNamespace === true) {
3301
+ if (this._pathStringCache !== null) return this._pathStringCache;
3302
+ const result = this.path.map((n) => n.namespace ? `${n.namespace}:${n.tag}` : n.tag).join(sep);
3303
+ this._pathStringCache = result;
3304
+ return result;
3305
+ }
3306
+ return this.path.map((n) => includeNamespace && n.namespace ? `${n.namespace}:${n.tag}` : n.tag).join(sep);
3307
+ }
3308
+ /**
3309
+ * Get path as array of tag names.
3310
+ * @returns {string[]}
3311
+ */
3312
+ toArray() {
3313
+ return this.path.map((n) => n.tag);
3314
+ }
3315
+ /**
3316
+ * Reset the path to empty.
3317
+ */
3318
+ reset() {
3319
+ this._pathStringCache = null;
3320
+ this.path = [];
3321
+ this.siblingStacks = [];
3322
+ }
3323
+ /**
3324
+ * Match current path against an Expression.
3325
+ * @param {Expression} expression
3326
+ * @returns {boolean}
3327
+ */
3328
+ matches(expression) {
3329
+ const segments = expression.segments;
3330
+ if (segments.length === 0) return false;
3331
+ if (expression.hasDeepWildcard()) return this._matchWithDeepWildcard(segments);
3332
+ return this._matchSimple(segments);
3333
+ }
3334
+ /**
3335
+ * @private
3336
+ */
3337
+ _matchSimple(segments) {
3338
+ if (this.path.length !== segments.length) return false;
3339
+ for (let i = 0; i < segments.length; i++) if (!this._matchSegment(segments[i], this.path[i], i === this.path.length - 1)) return false;
3340
+ return true;
3341
+ }
3342
+ /**
3343
+ * @private
3344
+ */
3345
+ _matchWithDeepWildcard(segments) {
3346
+ let pathIdx = this.path.length - 1;
3347
+ let segIdx = segments.length - 1;
3348
+ while (segIdx >= 0 && pathIdx >= 0) {
3349
+ const segment = segments[segIdx];
3350
+ if (segment.type === "deep-wildcard") {
3351
+ segIdx--;
3352
+ if (segIdx < 0) return true;
3353
+ const nextSeg = segments[segIdx];
3354
+ let found = false;
3355
+ for (let i = pathIdx; i >= 0; i--) if (this._matchSegment(nextSeg, this.path[i], i === this.path.length - 1)) {
3356
+ pathIdx = i - 1;
3357
+ segIdx--;
3358
+ found = true;
3359
+ break;
3360
+ }
3361
+ if (!found) return false;
3362
+ } else {
3363
+ if (!this._matchSegment(segment, this.path[pathIdx], pathIdx === this.path.length - 1)) return false;
3364
+ pathIdx--;
3365
+ segIdx--;
3366
+ }
3367
+ }
3368
+ return segIdx < 0;
3369
+ }
3370
+ /**
3371
+ * @private
3372
+ */
3373
+ _matchSegment(segment, node, isCurrentNode) {
3374
+ if (segment.tag !== "*" && segment.tag !== node.tag) return false;
3375
+ if (segment.namespace !== void 0) {
3376
+ if (segment.namespace !== "*" && segment.namespace !== node.namespace) return false;
3377
+ }
3378
+ if (segment.attrName !== void 0) {
3379
+ if (!isCurrentNode) return false;
3380
+ if (!node.values || !(segment.attrName in node.values)) return false;
3381
+ if (segment.attrValue !== void 0) {
3382
+ if (String(node.values[segment.attrName]) !== String(segment.attrValue)) return false;
3383
+ }
3384
+ }
3385
+ if (segment.position !== void 0) {
3386
+ if (!isCurrentNode) return false;
3387
+ const counter = node.counter ?? 0;
3388
+ if (segment.position === "first" && counter !== 0) return false;
3389
+ else if (segment.position === "odd" && counter % 2 !== 1) return false;
3390
+ else if (segment.position === "even" && counter % 2 !== 0) return false;
3391
+ else if (segment.position === "nth" && counter !== segment.positionValue) return false;
3392
+ }
3393
+ return true;
3394
+ }
3395
+ /**
3396
+ * Match any expression in the given set against the current path.
3397
+ * @param {ExpressionSet} exprSet
3398
+ * @returns {boolean}
3399
+ */
3400
+ matchesAny(exprSet) {
3401
+ return exprSet.matchesAny(this);
3402
+ }
3403
+ /**
3404
+ * Create a snapshot of current state.
3405
+ * @returns {Object}
3406
+ */
3407
+ snapshot() {
3408
+ return {
3409
+ path: this.path.map((node) => ({ ...node })),
3410
+ siblingStacks: this.siblingStacks.map((map) => new Map(map))
3411
+ };
3412
+ }
3413
+ /**
3414
+ * Restore state from snapshot.
3415
+ * @param {Object} snapshot
3416
+ */
3417
+ restore(snapshot) {
3418
+ this._pathStringCache = null;
3419
+ this.path = snapshot.path.map((node) => ({ ...node }));
3420
+ this.siblingStacks = snapshot.siblingStacks.map((map) => new Map(map));
3421
+ }
3422
+ /**
3423
+ * Return the read-only {@link MatcherView} for this matcher.
3424
+ *
3425
+ * The same instance is returned on every call — no allocation occurs.
3426
+ * It always reflects the current parser state and is safe to pass to
3427
+ * user callbacks without risk of accidental mutation.
3428
+ *
3429
+ * @returns {MatcherView}
3430
+ *
3431
+ * @example
3432
+ * const view = matcher.readOnly();
3433
+ * // pass view to callbacks — it stays in sync automatically
3434
+ * view.matches(expr); // ✓
3435
+ * view.getCurrentTag(); // ✓
3436
+ * // view.push(...) // ✗ method does not exist — caught by TypeScript
3437
+ */
3438
+ readOnly() {
3439
+ return this._view;
3440
+ }
3441
+ };
3442
+ //#endregion
3443
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js
3444
+ /**
3445
+ * Extract raw attributes (without prefix) from prefixed attribute map
3446
+ * @param {object} prefixedAttrs - Attributes with prefix from buildAttributesMap
3447
+ * @param {object} options - Parser options containing attributeNamePrefix
3448
+ * @returns {object} Raw attributes for matcher
3449
+ */
3450
+ function extractRawAttributes(prefixedAttrs, options) {
3451
+ if (!prefixedAttrs) return {};
3452
+ const attrs = options.attributesGroupName ? prefixedAttrs[options.attributesGroupName] : prefixedAttrs;
3453
+ if (!attrs) return {};
3454
+ const rawAttrs = {};
3455
+ for (const key in attrs) if (key.startsWith(options.attributeNamePrefix)) {
3456
+ const rawName = key.substring(options.attributeNamePrefix.length);
3457
+ rawAttrs[rawName] = attrs[key];
3458
+ } else rawAttrs[key] = attrs[key];
3459
+ return rawAttrs;
3460
+ }
3461
+ /**
3462
+ * Extract namespace from raw tag name
3463
+ * @param {string} rawTagName - Tag name possibly with namespace (e.g., "soap:Envelope")
3464
+ * @returns {string|undefined} Namespace or undefined
3465
+ */
3466
+ function extractNamespace(rawTagName) {
3467
+ if (!rawTagName || typeof rawTagName !== "string") return void 0;
3468
+ const colonIndex = rawTagName.indexOf(":");
3469
+ if (colonIndex !== -1 && colonIndex > 0) {
3470
+ const ns = rawTagName.substring(0, colonIndex);
3471
+ if (ns !== "xmlns") return ns;
3472
+ }
3473
+ }
3474
+ var OrderedObjParser = class {
3475
+ constructor(options, externalEntities) {
3476
+ this.options = options;
3477
+ this.currentNode = null;
3478
+ this.tagsNodeStack = [];
3479
+ this.parseXml = parseXml;
3480
+ this.parseTextData = parseTextData;
3481
+ this.resolveNameSpace = resolveNameSpace;
3482
+ this.buildAttributesMap = buildAttributesMap;
3483
+ this.isItStopNode = isItStopNode;
3484
+ this.replaceEntitiesValue = replaceEntitiesValue;
3485
+ this.readStopNodeData = readStopNodeData;
3486
+ this.saveTextToParentTag = saveTextToParentTag;
3487
+ this.addChild = addChild;
3488
+ this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes);
3489
+ this.entityExpansionCount = 0;
3490
+ this.currentExpandedLength = 0;
3491
+ let namedEntities = { ...XML };
3492
+ if (this.options.entityDecoder) this.entityDecoder = this.options.entityDecoder;
3493
+ else {
3494
+ if (typeof this.options.htmlEntities === "object") namedEntities = this.options.htmlEntities;
3495
+ else if (this.options.htmlEntities === true) namedEntities = {
3496
+ ...COMMON_HTML,
3497
+ ...CURRENCY
3498
+ };
3499
+ this.entityDecoder = new EntityDecoder({
3500
+ namedEntities: {
3501
+ ...namedEntities,
3502
+ ...externalEntities
3503
+ },
3504
+ numericAllowed: this.options.htmlEntities,
3505
+ limit: {
3506
+ maxTotalExpansions: this.options.processEntities.maxTotalExpansions,
3507
+ maxExpandedLength: this.options.processEntities.maxExpandedLength,
3508
+ applyLimitsTo: this.options.processEntities.appliesTo
3509
+ }
3510
+ });
3511
+ }
3512
+ this.matcher = new Matcher();
3513
+ this.readonlyMatcher = this.matcher.readOnly();
3514
+ this.isCurrentNodeStopNode = false;
3515
+ this.stopNodeExpressionsSet = new ExpressionSet();
3516
+ const stopNodesOpts = this.options.stopNodes;
3517
+ if (stopNodesOpts && stopNodesOpts.length > 0) {
3518
+ for (let i = 0; i < stopNodesOpts.length; i++) {
3519
+ const stopNodeExp = stopNodesOpts[i];
3520
+ if (typeof stopNodeExp === "string") this.stopNodeExpressionsSet.add(new Expression(stopNodeExp));
3521
+ else if (stopNodeExp instanceof Expression) this.stopNodeExpressionsSet.add(stopNodeExp);
3522
+ }
3523
+ this.stopNodeExpressionsSet.seal();
3524
+ }
3525
+ }
3526
+ };
3527
+ /**
3528
+ * @param {string} val
3529
+ * @param {string} tagName
3530
+ * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath
3531
+ * @param {boolean} dontTrim
3532
+ * @param {boolean} hasAttributes
3533
+ * @param {boolean} isLeafNode
3534
+ * @param {boolean} escapeEntities
3535
+ */
3536
+ function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
3537
+ const options = this.options;
3538
+ if (val !== void 0) {
3539
+ if (options.trimValues && !dontTrim) val = val.trim();
3540
+ if (val.length > 0) {
3541
+ if (!escapeEntities) val = this.replaceEntitiesValue(val, tagName, jPath);
3542
+ const jPathOrMatcher = options.jPath ? jPath.toString() : jPath;
3543
+ const newval = options.tagValueProcessor(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode);
3544
+ if (newval === null || newval === void 0) return val;
3545
+ else if (typeof newval !== typeof val || newval !== val) return newval;
3546
+ else if (options.trimValues) return parseValue(val, options.parseTagValue, options.numberParseOptions);
3547
+ else if (val.trim() === val) return parseValue(val, options.parseTagValue, options.numberParseOptions);
3548
+ else return val;
3549
+ }
3550
+ }
3551
+ }
3552
+ function resolveNameSpace(tagname) {
3553
+ if (this.options.removeNSPrefix) {
3554
+ const tags = tagname.split(":");
3555
+ const prefix = tagname.charAt(0) === "/" ? "/" : "";
3556
+ if (tags[0] === "xmlns") return "";
3557
+ if (tags.length === 2) tagname = prefix + tags[1];
3558
+ }
3559
+ return tagname;
3560
+ }
3561
+ const attrsRegx = /* @__PURE__ */ new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?", "gm");
3562
+ function buildAttributesMap(attrStr, jPath, tagName, force = false) {
3563
+ const options = this.options;
3564
+ if (force === true || options.ignoreAttributes !== true && typeof attrStr === "string") {
3565
+ const matches = getAllMatches(attrStr, attrsRegx);
3566
+ const len = matches.length;
3567
+ const attrs = {};
3568
+ const processedVals = new Array(len);
3569
+ let hasRawAttrs = false;
3570
+ const rawAttrsForMatcher = {};
3571
+ for (let i = 0; i < len; i++) {
3572
+ const attrName = this.resolveNameSpace(matches[i][1]);
3573
+ const oldVal = matches[i][4];
3574
+ if (attrName.length && oldVal !== void 0) {
3575
+ let val = oldVal;
3576
+ if (options.trimValues) val = val.trim();
3577
+ val = this.replaceEntitiesValue(val, tagName, this.readonlyMatcher);
3578
+ processedVals[i] = val;
3579
+ rawAttrsForMatcher[attrName] = val;
3580
+ hasRawAttrs = true;
3581
+ }
3582
+ }
3583
+ if (hasRawAttrs && typeof jPath === "object" && jPath.updateCurrent) jPath.updateCurrent(rawAttrsForMatcher);
3584
+ const jPathStr = options.jPath ? jPath.toString() : this.readonlyMatcher;
3585
+ let hasAttrs = false;
3586
+ for (let i = 0; i < len; i++) {
3587
+ const attrName = this.resolveNameSpace(matches[i][1]);
3588
+ if (this.ignoreAttributesFn(attrName, jPathStr)) continue;
3589
+ let aName = options.attributeNamePrefix + attrName;
3590
+ if (attrName.length) {
3591
+ if (options.transformAttributeName) aName = options.transformAttributeName(aName);
3592
+ aName = sanitizeName(aName, options);
3593
+ if (matches[i][4] !== void 0) {
3594
+ const oldVal = processedVals[i];
3595
+ const newVal = options.attributeValueProcessor(attrName, oldVal, jPathStr);
3596
+ if (newVal === null || newVal === void 0) attrs[aName] = oldVal;
3597
+ else if (typeof newVal !== typeof oldVal || newVal !== oldVal) attrs[aName] = newVal;
3598
+ else attrs[aName] = parseValue(oldVal, options.parseAttributeValue, options.numberParseOptions);
3599
+ hasAttrs = true;
3600
+ } else if (options.allowBooleanAttributes) {
3601
+ attrs[aName] = true;
3602
+ hasAttrs = true;
3603
+ }
3604
+ }
3605
+ }
3606
+ if (!hasAttrs) return;
3607
+ if (options.attributesGroupName && !options.preserveOrder) {
3608
+ const attrCollection = {};
3609
+ attrCollection[options.attributesGroupName] = attrs;
3610
+ return attrCollection;
3611
+ }
3612
+ return attrs;
3613
+ }
3614
+ }
3615
+ const parseXml = function(xmlData) {
3616
+ xmlData = xmlData.replace(/\r\n?/g, "\n");
3617
+ const xmlObj = new XmlNode("!xml");
3618
+ let currentNode = xmlObj;
3619
+ let textData = "";
3620
+ this.matcher.reset();
3621
+ this.entityDecoder.reset();
3622
+ this.entityExpansionCount = 0;
3623
+ this.currentExpandedLength = 0;
3624
+ const options = this.options;
3625
+ const docTypeReader = new DocTypeReader(options.processEntities);
3626
+ const xmlLen = xmlData.length;
3627
+ for (let i = 0; i < xmlLen; i++) if (xmlData[i] === "<") {
3628
+ const c1 = xmlData.charCodeAt(i + 1);
3629
+ if (c1 === 47) {
3630
+ const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.");
3631
+ let tagName = xmlData.substring(i + 2, closeIndex).trim();
3632
+ if (options.removeNSPrefix) {
3633
+ const colonIndex = tagName.indexOf(":");
3634
+ if (colonIndex !== -1) tagName = tagName.substr(colonIndex + 1);
3635
+ }
3636
+ tagName = transformTagName(options.transformTagName, tagName, "", options).tagName;
3637
+ if (currentNode) textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
3638
+ const lastTagName = this.matcher.getCurrentTag();
3639
+ if (tagName && options.unpairedTagsSet.has(tagName)) throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
3640
+ if (lastTagName && options.unpairedTagsSet.has(lastTagName)) {
3641
+ this.matcher.pop();
3642
+ this.tagsNodeStack.pop();
3643
+ }
3644
+ this.matcher.pop();
3645
+ this.isCurrentNodeStopNode = false;
3646
+ currentNode = this.tagsNodeStack.pop();
3647
+ textData = "";
3648
+ i = closeIndex;
3649
+ } else if (c1 === 63) {
3650
+ let tagData = readTagExp(xmlData, i, false, "?>");
3651
+ if (!tagData) throw new Error("Pi Tag is not closed.");
3652
+ textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
3653
+ const attsMap = this.buildAttributesMap(tagData.tagExp, this.matcher, tagData.tagName, true);
3654
+ if (attsMap) {
3655
+ const ver = attsMap[this.options.attributeNamePrefix + "version"];
3656
+ this.entityDecoder.setXmlVersion(Number(ver) || 1);
3657
+ docTypeReader.setXmlVersion(Number(ver) || 1);
3658
+ }
3659
+ if (options.ignoreDeclaration && tagData.tagName === "?xml" || options.ignorePiTags) {} else {
3660
+ const childNode = new XmlNode(tagData.tagName);
3661
+ childNode.add(options.textNodeName, "");
3662
+ if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent && options.ignoreAttributes !== true) childNode[":@"] = attsMap;
3663
+ this.addChild(currentNode, childNode, this.readonlyMatcher, i);
3664
+ }
3665
+ i = tagData.closeIndex + 1;
3666
+ } else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 45 && xmlData.charCodeAt(i + 3) === 45) {
3667
+ const endIndex = findClosingIndex(xmlData, "-->", i + 4, "Comment is not closed.");
3668
+ if (options.commentPropName) {
3669
+ const comment = xmlData.substring(i + 4, endIndex - 2);
3670
+ textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
3671
+ currentNode.add(options.commentPropName, [{ [options.textNodeName]: comment }]);
3672
+ }
3673
+ i = endIndex;
3674
+ } else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 68) {
3675
+ const result = docTypeReader.readDocType(xmlData, i);
3676
+ this.entityDecoder.addInputEntities(result.entities);
3677
+ i = result.i;
3678
+ } else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 91) {
3679
+ const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2;
3680
+ const tagExp = xmlData.substring(i + 9, closeIndex);
3681
+ textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
3682
+ let val = this.parseTextData(tagExp, currentNode.tagname, this.readonlyMatcher, true, false, true, true);
3683
+ if (val == void 0) val = "";
3684
+ if (options.cdataPropName) currentNode.add(options.cdataPropName, [{ [options.textNodeName]: tagExp }]);
3685
+ else currentNode.add(options.textNodeName, val);
3686
+ i = closeIndex + 2;
3687
+ } else {
3688
+ let result = readTagExp(xmlData, i, options.removeNSPrefix);
3689
+ if (!result) {
3690
+ const context = xmlData.substring(Math.max(0, i - 50), Math.min(xmlLen, i + 50));
3691
+ throw new Error(`readTagExp returned undefined at position ${i}. Context: "${context}"`);
3692
+ }
3693
+ let tagName = result.tagName;
3694
+ const rawTagName = result.rawTagName;
3695
+ let tagExp = result.tagExp;
3696
+ let attrExpPresent = result.attrExpPresent;
3697
+ let closeIndex = result.closeIndex;
3698
+ ({tagName, tagExp} = transformTagName(options.transformTagName, tagName, tagExp, options));
3699
+ if (options.strictReservedNames && (tagName === options.commentPropName || tagName === options.cdataPropName || tagName === options.textNodeName || tagName === options.attributesGroupName)) throw new Error(`Invalid tag name: ${tagName}`);
3700
+ if (currentNode && textData) {
3701
+ if (currentNode.tagname !== "!xml") textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher, false);
3702
+ }
3703
+ const lastTag = currentNode;
3704
+ if (lastTag && options.unpairedTagsSet.has(lastTag.tagname)) {
3705
+ currentNode = this.tagsNodeStack.pop();
3706
+ this.matcher.pop();
3707
+ }
3708
+ let isSelfClosing = false;
3709
+ if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
3710
+ isSelfClosing = true;
3711
+ if (tagName[tagName.length - 1] === "/") {
3712
+ tagName = tagName.substr(0, tagName.length - 1);
3713
+ tagExp = tagName;
3714
+ } else tagExp = tagExp.substr(0, tagExp.length - 1);
3715
+ attrExpPresent = tagName !== tagExp;
3716
+ }
3717
+ let prefixedAttrs = null;
3718
+ let namespace = void 0;
3719
+ namespace = extractNamespace(rawTagName);
3720
+ if (tagName !== xmlObj.tagname) this.matcher.push(tagName, {}, namespace);
3721
+ if (tagName !== tagExp && attrExpPresent) {
3722
+ prefixedAttrs = this.buildAttributesMap(tagExp, this.matcher, tagName);
3723
+ if (prefixedAttrs) extractRawAttributes(prefixedAttrs, options);
3724
+ }
3725
+ if (tagName !== xmlObj.tagname) this.isCurrentNodeStopNode = this.isItStopNode();
3726
+ const startIndex = i;
3727
+ if (this.isCurrentNodeStopNode) {
3728
+ let tagContent = "";
3729
+ if (isSelfClosing) i = result.closeIndex;
3730
+ else if (options.unpairedTagsSet.has(tagName)) i = result.closeIndex;
3731
+ else {
3732
+ const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
3733
+ if (!result) throw new Error(`Unexpected end of ${rawTagName}`);
3734
+ i = result.i;
3735
+ tagContent = result.tagContent;
3736
+ }
3737
+ const childNode = new XmlNode(tagName);
3738
+ if (prefixedAttrs) childNode[":@"] = prefixedAttrs;
3739
+ childNode.add(options.textNodeName, tagContent);
3740
+ this.matcher.pop();
3741
+ this.isCurrentNodeStopNode = false;
3742
+ this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
3743
+ } else {
3744
+ if (isSelfClosing) {
3745
+ ({tagName, tagExp} = transformTagName(options.transformTagName, tagName, tagExp, options));
3746
+ const childNode = new XmlNode(tagName);
3747
+ if (prefixedAttrs) childNode[":@"] = prefixedAttrs;
3748
+ this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
3749
+ this.matcher.pop();
3750
+ this.isCurrentNodeStopNode = false;
3751
+ } else if (options.unpairedTagsSet.has(tagName)) {
3752
+ const childNode = new XmlNode(tagName);
3753
+ if (prefixedAttrs) childNode[":@"] = prefixedAttrs;
3754
+ this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
3755
+ this.matcher.pop();
3756
+ this.isCurrentNodeStopNode = false;
3757
+ i = result.closeIndex;
3758
+ continue;
3759
+ } else {
3760
+ const childNode = new XmlNode(tagName);
3761
+ if (this.tagsNodeStack.length > options.maxNestedTags) throw new Error("Maximum nested tags exceeded");
3762
+ this.tagsNodeStack.push(currentNode);
3763
+ if (prefixedAttrs) childNode[":@"] = prefixedAttrs;
3764
+ this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
3765
+ currentNode = childNode;
3766
+ }
3767
+ textData = "";
3768
+ i = closeIndex;
3769
+ }
3770
+ }
3771
+ } else textData += xmlData[i];
3772
+ return xmlObj.child;
3773
+ };
3774
+ function addChild(currentNode, childNode, matcher, startIndex) {
3775
+ if (!this.options.captureMetaData) startIndex = void 0;
3776
+ const jPathOrMatcher = this.options.jPath ? matcher.toString() : matcher;
3777
+ const result = this.options.updateTag(childNode.tagname, jPathOrMatcher, childNode[":@"]);
3778
+ if (result === false) {} else if (typeof result === "string") {
3779
+ childNode.tagname = result;
3780
+ currentNode.addChild(childNode, startIndex);
3781
+ } else currentNode.addChild(childNode, startIndex);
3782
+ }
3783
+ /**
3784
+ * @param {object} val - Entity object with regex and val properties
3785
+ * @param {string} tagName - Tag name
3786
+ * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath
3787
+ */
3788
+ function replaceEntitiesValue(val, tagName, jPath) {
3789
+ const entityConfig = this.options.processEntities;
3790
+ if (!entityConfig || !entityConfig.enabled) return val;
3791
+ if (entityConfig.allowedTags) {
3792
+ const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;
3793
+ if (!(Array.isArray(entityConfig.allowedTags) ? entityConfig.allowedTags.includes(tagName) : entityConfig.allowedTags(tagName, jPathOrMatcher))) return val;
3794
+ }
3795
+ if (entityConfig.tagFilter) {
3796
+ const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;
3797
+ if (!entityConfig.tagFilter(tagName, jPathOrMatcher)) return val;
3798
+ }
3799
+ return this.entityDecoder.decode(val);
3800
+ }
3801
+ function saveTextToParentTag(textData, parentNode, matcher, isLeafNode) {
3802
+ if (textData) {
3803
+ if (isLeafNode === void 0) isLeafNode = parentNode.child.length === 0;
3804
+ textData = this.parseTextData(textData, parentNode.tagname, matcher, false, parentNode[":@"] ? Object.keys(parentNode[":@"]).length !== 0 : false, isLeafNode);
3805
+ if (textData !== void 0 && textData !== "") parentNode.add(this.options.textNodeName, textData);
3806
+ textData = "";
3807
+ }
3808
+ return textData;
3809
+ }
3810
+ /**
3811
+ * @param {Array<Expression>} stopNodeExpressions - Array of compiled Expression objects
3812
+ * @param {Matcher} matcher - Current path matcher
3813
+ */
3814
+ function isItStopNode() {
3815
+ if (this.stopNodeExpressionsSet.size === 0) return false;
3816
+ return this.matcher.matchesAny(this.stopNodeExpressionsSet);
3817
+ }
3818
+ /**
3819
+ * Returns the tag Expression and where it is ending handling single-double quotes situation
3820
+ * @param {string} xmlData
3821
+ * @param {number} i starting index
3822
+ * @returns
3823
+ */
3824
+ function tagExpWithClosingIndex(xmlData, i, closingChar = ">") {
3825
+ let attrBoundary = 0;
3826
+ const len = xmlData.length;
3827
+ const closeCode0 = closingChar.charCodeAt(0);
3828
+ const closeCode1 = closingChar.length > 1 ? closingChar.charCodeAt(1) : -1;
3829
+ let result = "";
3830
+ let segmentStart = i;
3831
+ for (let index = i; index < len; index++) {
3832
+ const code = xmlData.charCodeAt(index);
3833
+ if (attrBoundary) {
3834
+ if (code === attrBoundary) attrBoundary = 0;
3835
+ } else if (code === 34 || code === 39) attrBoundary = code;
3836
+ else if (code === closeCode0) if (closeCode1 !== -1) {
3837
+ if (xmlData.charCodeAt(index + 1) === closeCode1) {
3838
+ result += xmlData.substring(segmentStart, index);
3839
+ return {
3840
+ data: result,
3841
+ index
3842
+ };
3843
+ }
3844
+ } else {
3845
+ result += xmlData.substring(segmentStart, index);
3846
+ return {
3847
+ data: result,
3848
+ index
3849
+ };
3850
+ }
3851
+ else if (code === 9 && !attrBoundary) {
3852
+ result += xmlData.substring(segmentStart, index) + " ";
3853
+ segmentStart = index + 1;
3854
+ }
3855
+ }
3856
+ }
3857
+ function findClosingIndex(xmlData, str, i, errMsg) {
3858
+ const closingIndex = xmlData.indexOf(str, i);
3859
+ if (closingIndex === -1) throw new Error(errMsg);
3860
+ else return closingIndex + str.length - 1;
3861
+ }
3862
+ function findClosingChar(xmlData, char, i, errMsg) {
3863
+ const closingIndex = xmlData.indexOf(char, i);
3864
+ if (closingIndex === -1) throw new Error(errMsg);
3865
+ return closingIndex;
3866
+ }
3867
+ function readTagExp(xmlData, i, removeNSPrefix, closingChar = ">") {
3868
+ const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar);
3869
+ if (!result) return;
3870
+ let tagExp = result.data;
3871
+ const closeIndex = result.index;
3872
+ const separatorIndex = tagExp.search(/\s/);
3873
+ let tagName = tagExp;
3874
+ let attrExpPresent = true;
3875
+ if (separatorIndex !== -1) {
3876
+ tagName = tagExp.substring(0, separatorIndex);
3877
+ tagExp = tagExp.substring(separatorIndex + 1).trimStart();
3878
+ }
3879
+ const rawTagName = tagName;
3880
+ if (removeNSPrefix) {
3881
+ const colonIndex = tagName.indexOf(":");
3882
+ if (colonIndex !== -1) {
3883
+ tagName = tagName.substr(colonIndex + 1);
3884
+ attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
3885
+ }
3886
+ }
3887
+ return {
3888
+ tagName,
3889
+ tagExp,
3890
+ closeIndex,
3891
+ attrExpPresent,
3892
+ rawTagName
3893
+ };
3894
+ }
3895
+ /**
3896
+ * find paired tag for a stop node
3897
+ * @param {string} xmlData
3898
+ * @param {string} tagName
3899
+ * @param {number} i
3900
+ */
3901
+ function readStopNodeData(xmlData, tagName, i) {
3902
+ const startIndex = i;
3903
+ let openTagCount = 1;
3904
+ const xmllen = xmlData.length;
3905
+ for (; i < xmllen; i++) if (xmlData[i] === "<") {
3906
+ const c1 = xmlData.charCodeAt(i + 1);
3907
+ if (c1 === 47) {
3908
+ const closeIndex = findClosingChar(xmlData, ">", i, `${tagName} is not closed`);
3909
+ if (xmlData.substring(i + 2, closeIndex).trim() === tagName) {
3910
+ openTagCount--;
3911
+ if (openTagCount === 0) return {
3912
+ tagContent: xmlData.substring(startIndex, i),
3913
+ i: closeIndex
3914
+ };
3915
+ }
3916
+ i = closeIndex;
3917
+ } else if (c1 === 63) i = findClosingIndex(xmlData, "?>", i + 1, "StopNode is not closed.");
3918
+ else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 45 && xmlData.charCodeAt(i + 3) === 45) i = findClosingIndex(xmlData, "-->", i + 3, "StopNode is not closed.");
3919
+ else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 91) i = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2;
3920
+ else {
3921
+ const tagData = readTagExp(xmlData, i, false);
3922
+ if (tagData) {
3923
+ if ((tagData && tagData.tagName) === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") openTagCount++;
3924
+ i = tagData.closeIndex;
3925
+ }
3926
+ }
3927
+ }
3928
+ }
3929
+ function parseValue(val, shouldParse, options) {
3930
+ if (shouldParse && typeof val === "string") {
3931
+ const newval = val.trim();
3932
+ if (newval === "true") return true;
3933
+ else if (newval === "false") return false;
3934
+ else return toNumber(val, options);
3935
+ } else if (isExist(val)) return val;
3936
+ else return "";
3937
+ }
3938
+ function transformTagName(fn, tagName, tagExp, options) {
3939
+ if (fn) {
3940
+ const newTagName = fn(tagName);
3941
+ if (tagExp === tagName) tagExp = newTagName;
3942
+ tagName = newTagName;
3943
+ }
3944
+ tagName = sanitizeName(tagName, options);
3945
+ return {
3946
+ tagName,
3947
+ tagExp
3948
+ };
3949
+ }
3950
+ function sanitizeName(name, options) {
3951
+ if (criticalProperties.includes(name)) throw new Error(`[SECURITY] Invalid name: "${name}" is a reserved JavaScript keyword that could cause prototype pollution`);
3952
+ else if (DANGEROUS_PROPERTY_NAMES.includes(name)) return options.onDangerousProperty(name);
3953
+ return name;
3954
+ }
3955
+ //#endregion
3956
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/node2json.js
3957
+ const METADATA_SYMBOL = XmlNode.getMetaDataSymbol();
3958
+ /**
3959
+ * Helper function to strip attribute prefix from attribute map
3960
+ * @param {object} attrs - Attributes with prefix (e.g., {"@_class": "code"})
3961
+ * @param {string} prefix - Attribute prefix to remove (e.g., "@_")
3962
+ * @returns {object} Attributes without prefix (e.g., {"class": "code"})
3963
+ */
3964
+ function stripAttributePrefix(attrs, prefix) {
3965
+ if (!attrs || typeof attrs !== "object") return {};
3966
+ if (!prefix) return attrs;
3967
+ const rawAttrs = {};
3968
+ for (const key in attrs) if (key.startsWith(prefix)) {
3969
+ const rawName = key.substring(prefix.length);
3970
+ rawAttrs[rawName] = attrs[key];
3971
+ } else rawAttrs[key] = attrs[key];
3972
+ return rawAttrs;
3973
+ }
3974
+ /**
3975
+ *
3976
+ * @param {array} node
3977
+ * @param {any} options
3978
+ * @param {Matcher} matcher - Path matcher instance
3979
+ * @returns
3980
+ */
3981
+ function prettify(node, options, matcher, readonlyMatcher) {
3982
+ return compress(node, options, matcher, readonlyMatcher);
3983
+ }
3984
+ /**
3985
+ * @param {array} arr
3986
+ * @param {object} options
3987
+ * @param {Matcher} matcher - Path matcher instance
3988
+ * @returns object
3989
+ */
3990
+ function compress(arr, options, matcher, readonlyMatcher) {
3991
+ let text;
3992
+ const compressedObj = {};
3993
+ for (let i = 0; i < arr.length; i++) {
3994
+ const tagObj = arr[i];
3995
+ const property = propName(tagObj);
3996
+ if (property !== void 0 && property !== options.textNodeName) {
3997
+ const rawAttrs = stripAttributePrefix(tagObj[":@"] || {}, options.attributeNamePrefix);
3998
+ matcher.push(property, rawAttrs);
3999
+ }
4000
+ if (property === options.textNodeName) if (text === void 0) text = tagObj[property];
4001
+ else text += "" + tagObj[property];
4002
+ else if (property === void 0) continue;
4003
+ else if (tagObj[property]) {
4004
+ let val = compress(tagObj[property], options, matcher, readonlyMatcher);
4005
+ const isLeaf = isLeafTag(val, options);
4006
+ if (Object.keys(val).length === 0 && options.alwaysCreateTextNode) val[options.textNodeName] = "";
4007
+ if (tagObj[":@"]) assignAttributes(val, tagObj[":@"], readonlyMatcher, options);
4008
+ else if (Object.keys(val).length === 1 && val[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode) val = val[options.textNodeName];
4009
+ else if (Object.keys(val).length === 0) if (options.alwaysCreateTextNode) val[options.textNodeName] = "";
4010
+ else val = "";
4011
+ if (tagObj[METADATA_SYMBOL] !== void 0 && typeof val === "object" && val !== null) val[METADATA_SYMBOL] = tagObj[METADATA_SYMBOL];
4012
+ if (compressedObj[property] !== void 0 && Object.prototype.hasOwnProperty.call(compressedObj, property)) {
4013
+ if (!Array.isArray(compressedObj[property])) compressedObj[property] = [compressedObj[property]];
4014
+ compressedObj[property].push(val);
4015
+ } else {
4016
+ const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() : readonlyMatcher;
4017
+ if (options.isArray(property, jPathOrMatcher, isLeaf)) compressedObj[property] = [val];
4018
+ else compressedObj[property] = val;
4019
+ }
4020
+ if (property !== void 0 && property !== options.textNodeName) matcher.pop();
4021
+ }
4022
+ }
4023
+ if (typeof text === "string") {
4024
+ if (text.length > 0) compressedObj[options.textNodeName] = text;
4025
+ } else if (text !== void 0) compressedObj[options.textNodeName] = text;
4026
+ return compressedObj;
4027
+ }
4028
+ function propName(obj) {
4029
+ const keys = Object.keys(obj);
4030
+ for (let i = 0; i < keys.length; i++) {
4031
+ const key = keys[i];
4032
+ if (key !== ":@") return key;
4033
+ }
4034
+ }
4035
+ function assignAttributes(obj, attrMap, readonlyMatcher, options) {
4036
+ if (attrMap) {
4037
+ const keys = Object.keys(attrMap);
4038
+ const len = keys.length;
4039
+ for (let i = 0; i < len; i++) {
4040
+ const atrrName = keys[i];
4041
+ const rawAttrName = atrrName.startsWith(options.attributeNamePrefix) ? atrrName.substring(options.attributeNamePrefix.length) : atrrName;
4042
+ const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() + "." + rawAttrName : readonlyMatcher;
4043
+ if (options.isArray(atrrName, jPathOrMatcher, true, true)) obj[atrrName] = [attrMap[atrrName]];
4044
+ else obj[atrrName] = attrMap[atrrName];
4045
+ }
4046
+ }
4047
+ }
4048
+ function isLeafTag(obj, options) {
4049
+ const { textNodeName } = options;
4050
+ const propCount = Object.keys(obj).length;
4051
+ if (propCount === 0) return true;
4052
+ if (propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)) return true;
4053
+ return false;
4054
+ }
4055
+ //#endregion
4056
+ //#region ../../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js
4057
+ var XMLParser = class {
4058
+ constructor(options) {
4059
+ this.externalEntities = {};
4060
+ this.options = buildOptions(options);
4061
+ }
4062
+ /**
4063
+ * Parse XML dats to JS object
4064
+ * @param {string|Uint8Array} xmlData
4065
+ * @param {boolean|Object} validationOption
4066
+ */
4067
+ parse(xmlData, validationOption) {
4068
+ if (typeof xmlData !== "string" && xmlData.toString) xmlData = xmlData.toString();
4069
+ else if (typeof xmlData !== "string") throw new Error("XML data is accepted in String or Bytes[] form.");
4070
+ if (validationOption) {
4071
+ if (validationOption === true) validationOption = {};
4072
+ const result = validate(xmlData, validationOption);
4073
+ if (result !== true) throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`);
4074
+ }
4075
+ const orderedObjParser = new OrderedObjParser(this.options, this.externalEntities);
4076
+ const orderedResult = orderedObjParser.parseXml(xmlData);
4077
+ if (this.options.preserveOrder || orderedResult === void 0) return orderedResult;
4078
+ else return prettify(orderedResult, this.options, orderedObjParser.matcher, orderedObjParser.readonlyMatcher);
4079
+ }
4080
+ /**
4081
+ * Add Entity which is not by default supported by this library
4082
+ * @param {string} key
4083
+ * @param {string} value
4084
+ */
4085
+ addEntity(key, value) {
4086
+ if (value.indexOf("&") !== -1) throw new Error("Entity value can't have '&'");
4087
+ else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");
4088
+ else if (value === "&") throw new Error("An entity with value '&' is not permitted");
4089
+ else this.externalEntities[key] = value;
4090
+ }
4091
+ /**
4092
+ * Returns a Symbol that can be used to access the metadata
4093
+ * property on a node.
4094
+ *
4095
+ * If Symbol is not available in the environment, an ordinary property is used
4096
+ * and the name of the property is here returned.
4097
+ *
4098
+ * The XMLMetaData property is only present when `captureMetaData`
4099
+ * is true in the options.
4100
+ */
4101
+ static getMetaDataSymbol() {
4102
+ return XmlNode.getMetaDataSymbol();
4103
+ }
4104
+ };
4105
+ //#endregion
4106
+ //#region ../adapter-node/src/xml.ts
4107
+ const xmlParser = new XMLParser({
4108
+ ignoreAttributes: true,
4109
+ parseTagValue: false,
4110
+ isArray: (name) => name === "Contents",
4111
+ htmlEntities: true
4112
+ });
4113
+ const xmlVal = (obj, name) => {
4114
+ const v = obj[name];
4115
+ if (typeof v !== "string" || v === "") return;
4116
+ return decodeURIComponent(v.replace(/\+/g, " "));
4117
+ };
4118
+ const parseListObjectsV2CommandOutput = (xml) => {
4119
+ if (/<!DOCTYPE\b/i.test(xml)) throw new BaerlyError("InvalidResponse", "DTD not allowed in S3 XML responses");
4120
+ let result;
4121
+ try {
4122
+ result = xmlParser.parse(xml);
4123
+ } catch {
4124
+ throw new BaerlyError("InvalidResponse", `Invalid XML: ${xml}`);
4125
+ }
4126
+ const root = result.ListBucketResult ?? {};
4127
+ return {
4128
+ Contents: (root["Contents"] ?? []).map((content) => {
4129
+ const lm = xmlVal(content, "LastModified");
4130
+ return {
4131
+ ETag: xmlVal(content, "ETag"),
4132
+ Key: xmlVal(content, "Key"),
4133
+ LastModified: lm ? new Date(lm) : void 0
4134
+ };
4135
+ }),
4136
+ NextContinuationToken: xmlVal(root, "NextContinuationToken")
4137
+ };
4138
+ };
4139
+ //#endregion
4140
+ //#region ../adapter-node/src/s3-http.ts
4141
+ /**
4142
+ * Permanent {@link BaerlyError} codes that must short-circuit `retry`.
4143
+ * These represent caller- or environment-level faults where retrying
4144
+ * cannot succeed: `AccessDenied` (403 — credentials/policy),
4145
+ * `InvalidConfig` (bad bucket / unsupported credential type),
4146
+ * `InvalidResponse` (server returned unparseable data), and
4147
+ * `Conflict` (CAS guard lost — retrying would just re-lose against
4148
+ * the same state). `NetworkError` is intentionally absent — it covers
4149
+ * transient transport faults and stays retryable.
4150
+ */
4151
+ const PERMANENT_ERROR_CODES = new Set([
4152
+ "AccessDenied",
4153
+ "InvalidConfig",
4154
+ "InvalidResponse",
4155
+ "Conflict"
4156
+ ]);
4157
+ /**
4158
+ * Parse an HTTP `Retry-After` header into a non-negative seconds value,
4159
+ * clamped to {@link RETRY_AFTER_MAX_SECONDS}. Returns `undefined` if
4160
+ * the header is absent, malformed, or whitespace.
4161
+ *
4162
+ * RFC 7231 §7.1.3 admits two forms: delta-seconds (non-negative
4163
+ * integer) and HTTP-date. Both are accepted; dates in the past return
4164
+ * `0`. Fractional seconds, negatives, and arbitrary strings reject.
4165
+ *
4166
+ * The `now` injection point exists for the unit test; production
4167
+ * callers should pass nothing.
4168
+ */
4169
+ function parseRetryAfter(header, now = Date.now) {
4170
+ if (header === null) return;
4171
+ const trimmed = header.trim();
4172
+ if (trimmed === "") return;
4173
+ if (/^\d+$/.test(trimmed)) {
4174
+ const n = Number.parseInt(trimmed, 10);
4175
+ return Number.isFinite(n) ? Math.min(n, 60) : void 0;
4176
+ }
4177
+ if (!/[a-z]/i.test(trimmed)) return;
4178
+ const t = Date.parse(trimmed);
4179
+ if (Number.isNaN(t)) return;
4180
+ const seconds = Math.max(0, Math.ceil((t - now()) / 1e3));
4181
+ return Math.min(seconds, 60);
4182
+ }
4183
+ const retryAfterCause = (res) => {
4184
+ const hint = parseRetryAfter(res.headers.get("Retry-After"));
4185
+ return hint !== void 0 ? { retryAfterSeconds: hint } : {};
4186
+ };
4187
+ const retry = async (fn, { retries = 8, backoffMs = 100, maxDelayMs = 1e4 } = {}) => {
4188
+ let wait = backoffMs;
4189
+ for (let attempt = 0; attempt <= retries; attempt++) try {
4190
+ return await fn();
4191
+ } catch (error) {
4192
+ if (error instanceof BaerlyError && PERMANENT_ERROR_CODES.has(error.code)) throw error;
4193
+ if (attempt === retries) throw error;
4194
+ const hintMs = retryAfterHintMs(error, maxDelayMs);
4195
+ await delay(hintMs ?? wait);
4196
+ if (hintMs === void 0) wait = Math.min(wait * 1.5, maxDelayMs);
4197
+ else wait = backoffMs;
4198
+ }
4199
+ throw new BaerlyError("Internal", "s3-http retry loop exited without returning or throwing");
4200
+ };
4201
+ const retryAfterHintMs = (e, maxDelayMs) => {
4202
+ if (!(e instanceof BaerlyError)) return;
4203
+ const cause = e.cause;
4204
+ if (cause?.retryAfterSeconds === void 0) return;
4205
+ return Math.min(cause.retryAfterSeconds * 1e3, maxDelayMs);
4206
+ };
4207
+ /**
4208
+ * `Storage` impl that speaks the S3 REST API directly. Works against
4209
+ * any S3-compatible endpoint — AWS S3, R2 (S3-compat), GCS (S3-compat),
4210
+ * Minio. Does not depend on any AWS SDK.
4211
+ *
4212
+ * Authentication is plugged in via the `sign` callback; this class
4213
+ * itself does no SigV4. For Cloudflare Workers, the R2 binding fast
4214
+ * path lives in `@baerly/adapter-cloudflare`.
4215
+ */
4216
+ var S3HttpStorage = class {
4217
+ #endpoint;
4218
+ #bucket;
4219
+ #fetch;
4220
+ #sign;
4221
+ #retries;
4222
+ #backoffMs;
4223
+ constructor(options) {
4224
+ this.#endpoint = options.endpoint.replace(/\/+$/, "");
4225
+ this.#bucket = options.bucket;
4226
+ this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
4227
+ this.#sign = options.sign;
4228
+ this.#retries = options.retries ?? 8;
4229
+ this.#backoffMs = options.backoffMs ?? 100;
4230
+ }
4231
+ #objectUrl(key, versionId) {
4232
+ const base = `${this.#endpoint}/${this.#bucket}/${encodeURIComponent(key)}`;
4233
+ return versionId !== void 0 ? `${base}?versionId=${encodeURIComponent(versionId)}` : base;
4234
+ }
4235
+ async #dispatch(req) {
4236
+ const signed = this.#sign ? await this.#sign(req) : req;
4237
+ return this.#fetch(signed);
4238
+ }
4239
+ #retry(fn) {
4240
+ return retry(fn, {
4241
+ retries: this.#retries,
4242
+ backoffMs: this.#backoffMs
4243
+ });
4244
+ }
4245
+ async get(key, opts) {
4246
+ opts?.signal?.throwIfAborted();
4247
+ const url = this.#objectUrl(key, opts?.versionId);
4248
+ const headers = new Headers();
4249
+ if (opts?.ifNoneMatch !== void 0) headers.set("If-None-Match", opts.ifNoneMatch);
4250
+ return this.#retry(async () => {
4251
+ const res = await this.#dispatch(new Request(url, {
4252
+ method: "GET",
4253
+ headers,
4254
+ signal: opts?.signal ?? null
4255
+ }));
4256
+ switch (res.status) {
4257
+ case 200: {
4258
+ const etag = res.headers.get("ETag");
4259
+ if (etag === null) throw new BaerlyError("InvalidResponse", `GET ${key}: missing ETag`);
4260
+ const body = new Uint8Array(await res.arrayBuffer());
4261
+ const versionId = res.headers.get("x-amz-version-id") ?? void 0;
4262
+ return versionId !== void 0 ? {
4263
+ body,
4264
+ etag,
4265
+ versionId
4266
+ } : {
4267
+ body,
4268
+ etag
4269
+ };
4270
+ }
4271
+ case 304:
4272
+ case 404: return null;
4273
+ case 403: throw new BaerlyError("AccessDenied", `GET ${key}: 403`);
4274
+ default:
4275
+ if (res.status === 429 || res.status >= 500) throw new BaerlyError("NetworkError", `GET ${key}: ${res.status} ${await res.text()}`, {
4276
+ status: res.status,
4277
+ ...retryAfterCause(res)
4278
+ });
4279
+ throw new BaerlyError("InvalidResponse", `GET ${key}: ${res.status} ${await res.text()}`);
4280
+ }
4281
+ });
4282
+ }
4283
+ async put(key, body, opts) {
4284
+ opts?.signal?.throwIfAborted();
4285
+ const url = this.#objectUrl(key);
4286
+ const headers = new Headers();
4287
+ headers.set("Content-Type", opts?.contentType ?? "application/octet-stream");
4288
+ if (opts?.ifMatch !== void 0) headers.set("If-Match", opts.ifMatch);
4289
+ if (opts?.ifNoneMatch === "*") headers.set("If-None-Match", "*");
4290
+ return this.#retry(async () => {
4291
+ const res = await this.#dispatch(new Request(url, {
4292
+ method: "PUT",
4293
+ headers,
4294
+ body,
4295
+ signal: opts?.signal ?? null
4296
+ }));
4297
+ if (res.status === 412) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed`);
4298
+ if (res.status === 404 && opts?.ifMatch !== void 0) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`);
4299
+ if (res.status === 403) throw new BaerlyError("AccessDenied", `PUT ${key}: 403`);
4300
+ if (res.status === 429 || res.status >= 500) throw new BaerlyError("NetworkError", `PUT ${key}: ${res.status} ${await res.text()}`, {
4301
+ status: res.status,
4302
+ ...retryAfterCause(res)
4303
+ });
4304
+ if (res.status !== 200 && res.status !== 204) throw new BaerlyError("InvalidResponse", `PUT ${key}: ${res.status} ${await res.text()}`);
4305
+ const etag = res.headers.get("ETag");
4306
+ if (etag === null) throw new BaerlyError("InvalidResponse", `PUT ${key}: missing ETag`);
4307
+ const dateStr = res.headers.get("Date");
4308
+ const versionId = res.headers.get("x-amz-version-id") ?? void 0;
4309
+ const result = { etag };
4310
+ if (dateStr !== null) result.serverDate = new Date(dateStr);
4311
+ if (versionId !== void 0) result.versionId = versionId;
4312
+ return result;
4313
+ });
4314
+ }
4315
+ async delete(key, opts) {
4316
+ opts?.signal?.throwIfAborted();
4317
+ const url = this.#objectUrl(key);
4318
+ await this.#retry(async () => {
4319
+ const res = await this.#dispatch(new Request(url, {
4320
+ method: "DELETE",
4321
+ signal: opts?.signal ?? null
4322
+ }));
4323
+ if (res.status === 403) throw new BaerlyError("AccessDenied", `DELETE ${key}: 403`);
4324
+ if (res.status === 429 || res.status >= 500) throw new BaerlyError("NetworkError", `DELETE ${key}: ${res.status} ${await res.text()}`, {
4325
+ status: res.status,
4326
+ ...retryAfterCause(res)
4327
+ });
4328
+ });
4329
+ }
4330
+ async *list(prefix, opts) {
4331
+ opts?.signal?.throwIfAborted();
4332
+ let yielded = 0;
4333
+ let continuationToken;
4334
+ const startAfter = opts?.startAfter ?? "";
4335
+ while (true) {
4336
+ opts?.signal?.throwIfAborted();
4337
+ const params = new URLSearchParams();
4338
+ params.set("list-type", "2");
4339
+ params.set("prefix", prefix);
4340
+ if (continuationToken !== void 0) params.set("continuation-token", continuationToken);
4341
+ else if (startAfter !== "") params.set("start-after", startAfter);
4342
+ if (opts?.maxKeys !== void 0) {
4343
+ const remaining = opts.maxKeys - yielded;
4344
+ params.set("max-keys", String(Math.min(remaining, 1e3)));
4345
+ }
4346
+ const url = `${this.#endpoint}/${this.#bucket}/?${params.toString()}`;
4347
+ let parsed;
4348
+ let lastHint;
4349
+ for (let attempt = 0; attempt < 10; attempt++) {
4350
+ const outcome = await this.#retry(async () => {
4351
+ const res = await this.#dispatch(new Request(url, {
4352
+ method: "GET",
4353
+ signal: opts?.signal ?? null
4354
+ }));
4355
+ if (res.status === 200) return {
4356
+ kind: "ok",
4357
+ body: await res.text()
4358
+ };
4359
+ if (res.status === 429) return {
4360
+ kind: "ratelimited",
4361
+ retryAfterSeconds: parseRetryAfter(res.headers.get("Retry-After"))
4362
+ };
4363
+ if (res.status === 403) throw new BaerlyError("AccessDenied", `LIST ${prefix}: 403`);
4364
+ if (res.status >= 500) throw new BaerlyError("NetworkError", `LIST ${prefix}: ${res.status} ${await res.text()}`, {
4365
+ status: res.status,
4366
+ ...retryAfterCause(res)
4367
+ });
4368
+ throw new BaerlyError("InvalidResponse", `LIST ${prefix}: ${res.status} ${await res.text()}`);
4369
+ });
4370
+ if (outcome.kind === "ok") {
4371
+ parsed = parseListObjectsV2CommandOutput(outcome.body);
4372
+ break;
4373
+ }
4374
+ lastHint = outcome.retryAfterSeconds;
4375
+ const hintMs = outcome.retryAfterSeconds !== void 0 ? outcome.retryAfterSeconds * 1e3 : 0;
4376
+ await delay(Math.max(hintMs, RATE_LIMIT_BACKOFF_MILLIS));
4377
+ }
4378
+ if (parsed === void 0) throw new BaerlyError("NetworkError", `LIST ${prefix}: rate-limited`, {
4379
+ status: 429,
4380
+ ...lastHint !== void 0 ? { retryAfterSeconds: lastHint } : {}
4381
+ });
4382
+ for (const entry of parsed.Contents ?? []) {
4383
+ if (entry.Key === void 0) continue;
4384
+ yield {
4385
+ key: entry.Key,
4386
+ etag: entry.ETag ?? "",
4387
+ ...entry.LastModified !== void 0 && { lastModified: entry.LastModified }
4388
+ };
4389
+ yielded += 1;
4390
+ if (opts?.maxKeys !== void 0 && yielded >= opts.maxKeys) return;
4391
+ }
4392
+ continuationToken = parsed.NextContinuationToken;
4393
+ if (continuationToken === void 0 || continuationToken === "") return;
4394
+ }
4395
+ }
4396
+ };
4397
+ //#endregion
4398
+ //#region ../../node_modules/.pnpm/aws4fetch@1.0.20/node_modules/aws4fetch/dist/aws4fetch.esm.mjs
4399
+ /**
4400
+ * @license MIT <https://opensource.org/licenses/MIT>
4401
+ * @copyright Michael Hart 2024
4402
+ */
4403
+ const encoder = new TextEncoder();
4404
+ const HOST_SERVICES = {
4405
+ appstream2: "appstream",
4406
+ cloudhsmv2: "cloudhsm",
4407
+ email: "ses",
4408
+ marketplace: "aws-marketplace",
4409
+ mobile: "AWSMobileHubService",
4410
+ pinpoint: "mobiletargeting",
4411
+ queue: "sqs",
4412
+ "git-codecommit": "codecommit",
4413
+ "mturk-requester-sandbox": "mturk-requester",
4414
+ "personalize-runtime": "personalize"
4415
+ };
4416
+ const UNSIGNABLE_HEADERS = new Set([
4417
+ "authorization",
4418
+ "content-type",
4419
+ "content-length",
4420
+ "user-agent",
4421
+ "presigned-expires",
4422
+ "expect",
4423
+ "x-amzn-trace-id",
4424
+ "range",
4425
+ "connection"
4426
+ ]);
4427
+ var AwsClient = class {
4428
+ constructor({ accessKeyId, secretAccessKey, sessionToken, service, region, cache, retries, initRetryMs }) {
4429
+ if (accessKeyId == null) throw new TypeError("accessKeyId is a required option");
4430
+ if (secretAccessKey == null) throw new TypeError("secretAccessKey is a required option");
4431
+ this.accessKeyId = accessKeyId;
4432
+ this.secretAccessKey = secretAccessKey;
4433
+ this.sessionToken = sessionToken;
4434
+ this.service = service;
4435
+ this.region = region;
4436
+ this.cache = cache || /* @__PURE__ */ new Map();
4437
+ this.retries = retries != null ? retries : 10;
4438
+ this.initRetryMs = initRetryMs || 50;
4439
+ }
4440
+ async sign(input, init) {
4441
+ if (input instanceof Request) {
4442
+ const { method, url, headers, body } = input;
4443
+ init = Object.assign({
4444
+ method,
4445
+ url,
4446
+ headers
4447
+ }, init);
4448
+ if (init.body == null && headers.has("Content-Type")) init.body = body != null && headers.has("X-Amz-Content-Sha256") ? body : await input.clone().arrayBuffer();
4449
+ input = url;
4450
+ }
4451
+ const signer = new AwsV4Signer(Object.assign({ url: input.toString() }, init, this, init && init.aws));
4452
+ const signed = Object.assign({}, init, await signer.sign());
4453
+ delete signed.aws;
4454
+ try {
4455
+ return new Request(signed.url.toString(), signed);
4456
+ } catch (e) {
4457
+ if (e instanceof TypeError) return new Request(signed.url.toString(), Object.assign({ duplex: "half" }, signed));
4458
+ throw e;
4459
+ }
4460
+ }
4461
+ async fetch(input, init) {
4462
+ for (let i = 0; i <= this.retries; i++) {
4463
+ const fetched = fetch(await this.sign(input, init));
4464
+ if (i === this.retries) return fetched;
4465
+ const res = await fetched;
4466
+ if (res.status < 500 && res.status !== 429) return res;
4467
+ await new Promise((resolve) => setTimeout(resolve, Math.random() * this.initRetryMs * Math.pow(2, i)));
4468
+ }
4469
+ throw new Error("An unknown error occurred, ensure retries is not negative");
4470
+ }
4471
+ };
4472
+ var AwsV4Signer = class {
4473
+ constructor({ method, url, headers, body, accessKeyId, secretAccessKey, sessionToken, service, region, cache, datetime, signQuery, appendSessionToken, allHeaders, singleEncode }) {
4474
+ if (url == null) throw new TypeError("url is a required option");
4475
+ if (accessKeyId == null) throw new TypeError("accessKeyId is a required option");
4476
+ if (secretAccessKey == null) throw new TypeError("secretAccessKey is a required option");
4477
+ this.method = method || (body ? "POST" : "GET");
4478
+ this.url = new URL(url);
4479
+ this.headers = new Headers(headers || {});
4480
+ this.body = body;
4481
+ this.accessKeyId = accessKeyId;
4482
+ this.secretAccessKey = secretAccessKey;
4483
+ this.sessionToken = sessionToken;
4484
+ let guessedService, guessedRegion;
4485
+ if (!service || !region) [guessedService, guessedRegion] = guessServiceRegion(this.url, this.headers);
4486
+ this.service = service || guessedService || "";
4487
+ this.region = region || guessedRegion || "us-east-1";
4488
+ this.cache = cache || /* @__PURE__ */ new Map();
4489
+ this.datetime = datetime || (/* @__PURE__ */ new Date()).toISOString().replace(/[:-]|\.\d{3}/g, "");
4490
+ this.signQuery = signQuery;
4491
+ this.appendSessionToken = appendSessionToken || this.service === "iotdevicegateway";
4492
+ this.headers.delete("Host");
4493
+ if (this.service === "s3" && !this.signQuery && !this.headers.has("X-Amz-Content-Sha256")) this.headers.set("X-Amz-Content-Sha256", "UNSIGNED-PAYLOAD");
4494
+ const params = this.signQuery ? this.url.searchParams : this.headers;
4495
+ params.set("X-Amz-Date", this.datetime);
4496
+ if (this.sessionToken && !this.appendSessionToken) params.set("X-Amz-Security-Token", this.sessionToken);
4497
+ this.signableHeaders = ["host", ...this.headers.keys()].filter((header) => allHeaders || !UNSIGNABLE_HEADERS.has(header)).sort();
4498
+ this.signedHeaders = this.signableHeaders.join(";");
4499
+ this.canonicalHeaders = this.signableHeaders.map((header) => header + ":" + (header === "host" ? this.url.host : (this.headers.get(header) || "").replace(/\s+/g, " "))).join("\n");
4500
+ this.credentialString = [
4501
+ this.datetime.slice(0, 8),
4502
+ this.region,
4503
+ this.service,
4504
+ "aws4_request"
4505
+ ].join("/");
4506
+ if (this.signQuery) {
4507
+ if (this.service === "s3" && !params.has("X-Amz-Expires")) params.set("X-Amz-Expires", "86400");
4508
+ params.set("X-Amz-Algorithm", "AWS4-HMAC-SHA256");
4509
+ params.set("X-Amz-Credential", this.accessKeyId + "/" + this.credentialString);
4510
+ params.set("X-Amz-SignedHeaders", this.signedHeaders);
4511
+ }
4512
+ if (this.service === "s3") try {
4513
+ this.encodedPath = decodeURIComponent(this.url.pathname.replace(/\+/g, " "));
4514
+ } catch (e) {
4515
+ this.encodedPath = this.url.pathname;
4516
+ }
4517
+ else this.encodedPath = this.url.pathname.replace(/\/+/g, "/");
4518
+ if (!singleEncode) this.encodedPath = encodeURIComponent(this.encodedPath).replace(/%2F/g, "/");
4519
+ this.encodedPath = encodeRfc3986(this.encodedPath);
4520
+ const seenKeys = /* @__PURE__ */ new Set();
4521
+ this.encodedSearch = [...this.url.searchParams].filter(([k]) => {
4522
+ if (!k) return false;
4523
+ if (this.service === "s3") {
4524
+ if (seenKeys.has(k)) return false;
4525
+ seenKeys.add(k);
4526
+ }
4527
+ return true;
4528
+ }).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("&");
4529
+ }
4530
+ async sign() {
4531
+ if (this.signQuery) {
4532
+ this.url.searchParams.set("X-Amz-Signature", await this.signature());
4533
+ if (this.sessionToken && this.appendSessionToken) this.url.searchParams.set("X-Amz-Security-Token", this.sessionToken);
4534
+ } else this.headers.set("Authorization", await this.authHeader());
4535
+ return {
4536
+ method: this.method,
4537
+ url: this.url,
4538
+ headers: this.headers,
4539
+ body: this.body
4540
+ };
4541
+ }
4542
+ async authHeader() {
4543
+ return [
4544
+ "AWS4-HMAC-SHA256 Credential=" + this.accessKeyId + "/" + this.credentialString,
4545
+ "SignedHeaders=" + this.signedHeaders,
4546
+ "Signature=" + await this.signature()
4547
+ ].join(", ");
4548
+ }
4549
+ async signature() {
4550
+ const date = this.datetime.slice(0, 8);
4551
+ const cacheKey = [
4552
+ this.secretAccessKey,
4553
+ date,
4554
+ this.region,
4555
+ this.service
4556
+ ].join();
4557
+ let kCredentials = this.cache.get(cacheKey);
4558
+ if (!kCredentials) {
4559
+ kCredentials = await hmac(await hmac(await hmac(await hmac("AWS4" + this.secretAccessKey, date), this.region), this.service), "aws4_request");
4560
+ this.cache.set(cacheKey, kCredentials);
4561
+ }
4562
+ return buf2hex(await hmac(kCredentials, await this.stringToSign()));
4563
+ }
4564
+ async stringToSign() {
4565
+ return [
4566
+ "AWS4-HMAC-SHA256",
4567
+ this.datetime,
4568
+ this.credentialString,
4569
+ buf2hex(await hash(await this.canonicalString()))
4570
+ ].join("\n");
4571
+ }
4572
+ async canonicalString() {
4573
+ return [
4574
+ this.method.toUpperCase(),
4575
+ this.encodedPath,
4576
+ this.encodedSearch,
4577
+ this.canonicalHeaders + "\n",
4578
+ this.signedHeaders,
4579
+ await this.hexBodyHash()
4580
+ ].join("\n");
4581
+ }
4582
+ async hexBodyHash() {
4583
+ let hashHeader = this.headers.get("X-Amz-Content-Sha256") || (this.service === "s3" && this.signQuery ? "UNSIGNED-PAYLOAD" : null);
4584
+ if (hashHeader == null) {
4585
+ 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");
4586
+ hashHeader = buf2hex(await hash(this.body || ""));
4587
+ }
4588
+ return hashHeader;
4589
+ }
4590
+ };
4591
+ async function hmac(key, string) {
4592
+ const cryptoKey = await crypto.subtle.importKey("raw", typeof key === "string" ? encoder.encode(key) : key, {
4593
+ name: "HMAC",
4594
+ hash: { name: "SHA-256" }
4595
+ }, false, ["sign"]);
4596
+ return crypto.subtle.sign("HMAC", cryptoKey, encoder.encode(string));
4597
+ }
4598
+ async function hash(content) {
4599
+ return crypto.subtle.digest("SHA-256", typeof content === "string" ? encoder.encode(content) : content);
4600
+ }
4601
+ const HEX_CHARS = [
4602
+ "0",
4603
+ "1",
4604
+ "2",
4605
+ "3",
4606
+ "4",
4607
+ "5",
4608
+ "6",
4609
+ "7",
4610
+ "8",
4611
+ "9",
4612
+ "a",
4613
+ "b",
4614
+ "c",
4615
+ "d",
4616
+ "e",
4617
+ "f"
4618
+ ];
4619
+ function buf2hex(arrayBuffer) {
4620
+ const buffer = new Uint8Array(arrayBuffer);
4621
+ let out = "";
4622
+ for (let idx = 0; idx < buffer.length; idx++) {
4623
+ const n = buffer[idx];
4624
+ out += HEX_CHARS[n >>> 4 & 15];
4625
+ out += HEX_CHARS[n & 15];
4626
+ }
4627
+ return out;
4628
+ }
4629
+ function encodeRfc3986(urlEncodedStr) {
4630
+ return urlEncodedStr.replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());
4631
+ }
4632
+ function guessServiceRegion(url, headers) {
4633
+ const { hostname, pathname } = url;
4634
+ if (hostname.endsWith(".on.aws")) {
4635
+ const match = hostname.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);
4636
+ return match != null ? ["lambda", match[1] || ""] : ["", ""];
4637
+ }
4638
+ if (hostname.endsWith(".r2.cloudflarestorage.com")) return ["s3", "auto"];
4639
+ if (hostname.endsWith(".backblazeb2.com")) {
4640
+ const match = hostname.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);
4641
+ return match != null ? ["s3", match[1] || ""] : ["", ""];
4642
+ }
4643
+ const match = hostname.replace("dualstack.", "").match(/([^.]{1,63})\.(?:([^.]{0,63})\.)?amazonaws\.com(?:\.cn)?$/);
4644
+ let service = match && match[1] || "";
4645
+ let region = match && match[2];
4646
+ if (region === "us-gov") region = "us-gov-west-1";
4647
+ else if (region === "s3" || region === "s3-accelerate") {
4648
+ region = "us-east-1";
4649
+ service = "s3";
4650
+ } else if (service === "iot") if (hostname.startsWith("iot.")) service = "execute-api";
4651
+ else if (hostname.startsWith("data.jobs.iot.")) service = "iot-jobs-data";
4652
+ else service = pathname === "/mqtt" ? "iotdevicegateway" : "iotdata";
4653
+ else if (service === "autoscaling") {
4654
+ const targetPrefix = (headers.get("X-Amz-Target") || "").split(".")[0];
4655
+ if (targetPrefix === "AnyScaleFrontendService") service = "application-autoscaling";
4656
+ else if (targetPrefix === "AnyScaleScalingPlannerFrontendService") service = "autoscaling-plans";
4657
+ } else if (region == null && service.startsWith("s3-")) {
4658
+ region = service.slice(3).replace(/^fips-|^external-1/, "");
4659
+ service = "s3";
4660
+ } else if (service.endsWith("-fips")) service = service.slice(0, -5);
4661
+ else if (region && /-\d$/.test(service) && !/-\d$/.test(region)) [service, region] = [region, service];
4662
+ return [HOST_SERVICES[service] || service, region || ""];
4663
+ }
4664
+ //#endregion
4665
+ //#region ../adapter-node/src/credentials/signer.ts
4666
+ const REFRESH_BUFFER_MS = 300 * 1e3;
4667
+ function buildAwsClient(creds, region) {
4668
+ return new AwsClient({
4669
+ accessKeyId: creds.accessKeyId,
4670
+ secretAccessKey: creds.secretAccessKey,
4671
+ sessionToken: creds.sessionToken,
4672
+ region,
4673
+ service: "s3"
4674
+ });
4675
+ }
4676
+ function refreshingSigner(opts) {
4677
+ const region = opts.region;
4678
+ const now = opts.now ?? (() => Date.now());
4679
+ if (typeof opts.credentials !== "function") {
4680
+ const aws = buildAwsClient(opts.credentials, region);
4681
+ return (req) => aws.sign(req);
4682
+ }
4683
+ const provider = opts.credentials;
4684
+ let cached = null;
4685
+ let inFlight = null;
4686
+ const resolve = async () => {
4687
+ if (cached !== null && cached.expiresAt - REFRESH_BUFFER_MS > now()) return cached.aws;
4688
+ if (inFlight !== null) return inFlight;
4689
+ inFlight = (async () => {
4690
+ try {
4691
+ const creds = await provider();
4692
+ const aws = buildAwsClient(creds, region);
4693
+ cached = {
4694
+ aws,
4695
+ expiresAt: creds.expiration?.getTime() ?? Number.POSITIVE_INFINITY
4696
+ };
4697
+ return aws;
4698
+ } finally {
4699
+ inFlight = null;
4700
+ }
4701
+ })();
4702
+ return inFlight;
4703
+ };
4704
+ return async (req) => {
4705
+ return (await resolve()).sign(req);
4706
+ };
4707
+ }
4708
+ //#endregion
4709
+ //#region ../adapter-node/src/storage-factories.ts
4710
+ function buildS3Storage(opts) {
4711
+ const sign = refreshingSigner({
4712
+ region: opts.region,
4713
+ credentials: opts.credentials
4714
+ });
4715
+ return new S3HttpStorage({
4716
+ endpoint: opts.endpoint,
4717
+ bucket: opts.bucket,
4718
+ sign
4719
+ });
4720
+ }
4721
+ /**
4722
+ * AWS S3 `Storage` factory. Wraps `S3HttpStorage` with the standard
4723
+ * `aws4fetch` SigV4 signer. The endpoint is derived from the region as
4724
+ * `https://s3.<region>.amazonaws.com`.
4725
+ *
4726
+ * @example Static credentials
4727
+ * ```ts
4728
+ * import { s3Storage } from "@gusto/baerly-storage/node";
4729
+ *
4730
+ * const storage = s3Storage({
4731
+ * region: process.env["AWS_REGION"] ?? "us-east-1",
4732
+ * bucket: process.env["BUCKET"]!,
4733
+ * credentials: {
4734
+ * accessKeyId: process.env["AWS_ACCESS_KEY_ID"]!,
4735
+ * secretAccessKey: process.env["AWS_SECRET_ACCESS_KEY"]!,
4736
+ * },
4737
+ * });
4738
+ * ```
4739
+ *
4740
+ * @example EKS Pod Identity (refreshing)
4741
+ * ```ts
4742
+ * import { s3Storage, fromEksPodIdentity } from "@gusto/baerly-storage/node";
4743
+ *
4744
+ * const storage = s3Storage({
4745
+ * region: process.env["AWS_REGION"] ?? "us-east-1",
4746
+ * bucket: process.env["BUCKET"]!,
4747
+ * credentials: fromEksPodIdentity(),
4748
+ * });
4749
+ * ```
4750
+ */
4751
+ function s3Storage(opts) {
4752
+ return buildS3Storage({
4753
+ endpoint: `https://s3.${opts.region}.amazonaws.com`,
4754
+ region: opts.region,
4755
+ bucket: opts.bucket,
4756
+ credentials: opts.credentials
4757
+ });
4758
+ }
4759
+ /**
4760
+ * Cloudflare R2 `Storage` factory (S3-compat endpoint). Derives the
4761
+ * endpoint from `accountId` as
4762
+ * `https://<accountId>.r2.cloudflarestorage.com` and pins region
4763
+ * `"auto"` — R2 ignores region but `aws4fetch`'s signer requires
4764
+ * the field to be set.
4765
+ *
4766
+ * For Workers that have a native R2 binding (no HTTP hop), see
4767
+ * `r2BindingStorage` in `@baerly/adapter-cloudflare`. This factory
4768
+ * is for Node hosts that talk to R2 over its public S3-compat URL.
4769
+ *
4770
+ * @example
4771
+ * ```ts
4772
+ * import { r2Storage } from "@gusto/baerly-storage/node";
4773
+ *
4774
+ * const storage = r2Storage({
4775
+ * accountId: process.env["R2_ACCOUNT_ID"]!,
4776
+ * bucket: process.env["BUCKET"]!,
4777
+ * credentials: {
4778
+ * accessKeyId: process.env["AWS_ACCESS_KEY_ID"]!,
4779
+ * secretAccessKey: process.env["AWS_SECRET_ACCESS_KEY"]!,
4780
+ * },
4781
+ * });
4782
+ * ```
4783
+ */
4784
+ function r2Storage(opts) {
4785
+ return buildS3Storage({
4786
+ endpoint: `https://${opts.accountId}.r2.cloudflarestorage.com`,
4787
+ region: "auto",
4788
+ bucket: opts.bucket,
4789
+ credentials: opts.credentials
4790
+ });
4791
+ }
4792
+ /**
4793
+ * Minio `Storage` factory — for local-dev / self-hosted S3-compat.
4794
+ * Endpoint is fully caller-supplied (e.g. `http://localhost:9102`)
4795
+ * because Minio deployments don't follow a URL template. Region is
4796
+ * pinned to `"us-east-1"`; Minio ignores it but `aws4fetch` requires
4797
+ * a value.
4798
+ *
4799
+ * @example
4800
+ * ```ts
4801
+ * import { minioStorage } from "@gusto/baerly-storage/node";
4802
+ *
4803
+ * const storage = minioStorage({
4804
+ * endpoint: process.env["BAERLY_S3_ENDPOINT"] ?? "http://localhost:9102",
4805
+ * bucket: "baerly",
4806
+ * credentials: {
4807
+ * accessKeyId: process.env["MINIO_ACCESS_KEY"]!,
4808
+ * secretAccessKey: process.env["MINIO_SECRET_KEY"]!,
4809
+ * },
4810
+ * });
4811
+ * ```
4812
+ */
4813
+ function minioStorage(opts) {
4814
+ return buildS3Storage({
4815
+ endpoint: opts.endpoint,
4816
+ region: "us-east-1",
4817
+ bucket: opts.bucket,
4818
+ credentials: opts.credentials
4819
+ });
4820
+ }
4821
+ //#endregion
4822
+ //#region src/bucket-uri.ts
4823
+ /**
4824
+ * Bucket URI parsing for the CLI surface. Consumed by every
4825
+ * `baerly admin <cmd>`, `baerly inspect`, and `baerly export`.
4826
+ *
4827
+ * Grammar:
4828
+ * - `s3://<bucket>[/<prefix>]` — S3-compatible HTTP. Creds via env
4829
+ * vars (`BAERLY_S3_ENDPOINT`, `BAERLY_S3_ACCESS_KEY_ID`,
4830
+ * `BAERLY_S3_SECRET_ACCESS_KEY`, `BAERLY_S3_REGION` — region
4831
+ * defaults to `us-east-1`).
4832
+ * - `file:///<absolute-path>` — `LocalFsStorage` rooted at the path.
4833
+ * Relative paths are rejected by the three-slash prefix.
4834
+ * - `memory://<bucket>` — `MemoryStorage` keyed via
4835
+ * `getOrCreateMemoryStorageForBucket`. Test-only.
4836
+ */
4837
+ /**
4838
+ * Parse a bucket URI into a constructed `Storage` handle + optional
4839
+ * key prefix.
4840
+ *
4841
+ * @throws BaerlyError code="InvalidConfig" — unsupported scheme, or an
4842
+ * `s3://` URI with a missing env var.
4843
+ */
4844
+ const parseBucketUri = async (uri) => {
4845
+ if (uri.startsWith("s3://")) {
4846
+ const rest = uri.slice(5);
4847
+ const slash = rest.indexOf("/");
4848
+ const bucket = slash === -1 ? rest : rest.slice(0, slash);
4849
+ const prefix = slash === -1 ? "" : rest.slice(slash + 1);
4850
+ if (bucket.length === 0) throw new BaerlyError("InvalidConfig", `bucket URI: s3:// URI requires a bucket name (got ${JSON.stringify(uri)})`);
4851
+ const accessKeyId = requireEnv("BAERLY_S3_ACCESS_KEY_ID");
4852
+ const secretAccessKey = requireEnv("BAERLY_S3_SECRET_ACCESS_KEY");
4853
+ const region = process.env["BAERLY_S3_REGION"] ?? "us-east-1";
4854
+ const endpoint = requireEnv("BAERLY_S3_ENDPOINT");
4855
+ return {
4856
+ storage: pickS3Storage({
4857
+ r2Host: endpoint.match(/^https?:\/\/([^./]+)\.r2\.cloudflarestorage\.com\b/i),
4858
+ isAws: /^https?:\/\/s3(\.[^.]+)?\.amazonaws\.com\b/i.test(endpoint),
4859
+ endpoint,
4860
+ bucket,
4861
+ accessKeyId,
4862
+ secretAccessKey,
4863
+ region
4864
+ }),
4865
+ keyPrefix: normalizeKeyPrefix(prefix)
4866
+ };
4867
+ }
4868
+ if (uri.startsWith("file:///")) return {
4869
+ storage: new LocalFsStorage({ root: uri.slice(7) }),
4870
+ keyPrefix: ""
4871
+ };
4872
+ if (uri.startsWith("memory://")) {
4873
+ const bucket = uri.slice(9);
4874
+ if (bucket.length === 0) throw new BaerlyError("InvalidConfig", `bucket URI: memory:// URI requires a bucket name (got ${JSON.stringify(uri)})`);
4875
+ return {
4876
+ storage: getOrCreateMemoryStorageForBucket(bucket),
4877
+ keyPrefix: ""
4878
+ };
4879
+ }
4880
+ throw new BaerlyError("InvalidConfig", `bucket URI: unsupported URI ${JSON.stringify(uri)}`);
4881
+ };
4882
+ const requireEnv = (name) => {
4883
+ const v = process.env[name];
4884
+ if (v === void 0 || v === "") throw new BaerlyError("InvalidConfig", `bucket URI: env var ${name} unset`);
4885
+ return v;
4886
+ };
4887
+ const pickS3Storage = (opts) => {
4888
+ const { r2Host, isAws, endpoint, bucket, accessKeyId, secretAccessKey, region } = opts;
4889
+ if (r2Host !== null) return r2Storage({
4890
+ accountId: r2Host[1],
4891
+ bucket,
4892
+ credentials: {
4893
+ accessKeyId,
4894
+ secretAccessKey
4895
+ }
4896
+ });
4897
+ if (isAws) return s3Storage({
4898
+ region,
4899
+ bucket,
4900
+ credentials: {
4901
+ accessKeyId,
4902
+ secretAccessKey
4903
+ }
4904
+ });
4905
+ return minioStorage({
4906
+ endpoint,
4907
+ bucket,
4908
+ credentials: {
4909
+ accessKeyId,
4910
+ secretAccessKey
4911
+ }
4912
+ });
4913
+ };
4914
+ const normalizeKeyPrefix = (prefix) => {
4915
+ if (prefix === "") return "";
4916
+ if (prefix.endsWith("/")) return prefix;
4917
+ return `${prefix}/`;
4918
+ };
4919
+ //#endregion
4920
+ export { decodeJsonBytes as a, uuid as i, timestamp as n, encodeJsonBytes as o, countKey as r, parseBucketUri as t };
4921
+
4922
+ //# sourceMappingURL=bucket-uri-BrDEYvzy.js.map