@o3co/ts.hocon 1.12.0 → 1.14.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 (43) hide show
  1. package/README.ja.md +256 -32
  2. package/README.md +166 -32
  3. package/dist/adapters/env.cjs +26 -1678
  4. package/dist/adapters/env.d.cts +1 -1
  5. package/dist/adapters/env.d.ts +1 -1
  6. package/dist/adapters/env.js +11 -1625
  7. package/dist/adapters/json5.cjs +496 -0
  8. package/dist/adapters/json5.d.cts +47 -0
  9. package/dist/adapters/json5.d.ts +47 -0
  10. package/dist/adapters/json5.js +496 -0
  11. package/dist/adapters/jsonc.cjs +17 -1632
  12. package/dist/adapters/jsonc.d.cts +1 -1
  13. package/dist/adapters/jsonc.d.ts +1 -1
  14. package/dist/adapters/jsonc.js +9 -1586
  15. package/dist/adapters/properties.cjs +7 -1773
  16. package/dist/adapters/properties.d.cts +1 -1
  17. package/dist/adapters/properties.d.ts +1 -1
  18. package/dist/adapters/properties.js +6 -1735
  19. package/dist/adapters/toml.cjs +12 -1626
  20. package/dist/adapters/toml.d.cts +1 -1
  21. package/dist/adapters/toml.d.ts +1 -1
  22. package/dist/adapters/toml.js +10 -1589
  23. package/dist/adapters/yaml.cjs +20 -1635
  24. package/dist/adapters/yaml.d.cts +1 -1
  25. package/dist/adapters/yaml.d.ts +1 -1
  26. package/dist/adapters/yaml.js +10 -1589
  27. package/dist/chunk-GBNQADHT.cjs +83 -0
  28. package/dist/chunk-IMJ7QHIK.cjs +158 -0
  29. package/dist/chunk-QY7ECGS6.js +83 -0
  30. package/dist/chunk-RO4D6BH7.cjs +3792 -0
  31. package/dist/chunk-WTXULUZS.js +3792 -0
  32. package/dist/chunk-XWKO4JM3.js +158 -0
  33. package/dist/{config-Dlq6rF3w.d.cts → config-OccaKqXu.d.cts} +148 -4
  34. package/dist/{config-Dlq6rF3w.d.ts → config-OccaKqXu.d.ts} +148 -4
  35. package/dist/index.cjs +35 -3449
  36. package/dist/index.d.cts +2 -2
  37. package/dist/index.d.ts +2 -2
  38. package/dist/index.js +25 -3383
  39. package/dist/zod.cjs +107 -3291
  40. package/dist/zod.d.cts +83 -3
  41. package/dist/zod.d.ts +83 -3
  42. package/dist/zod.js +95 -3245
  43. package/package.json +12 -2
package/dist/zod.cjs CHANGED
@@ -1,3322 +1,138 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/zod.ts
31
- var zod_exports = {};
32
- __export(zod_exports, {
33
- getValidated: () => getValidated,
34
- parseFileWithSchema: () => parseFileWithSchema,
35
- parseWithSchema: () => parseWithSchema,
36
- validate: () => validate
37
- });
38
- module.exports = __toCommonJS(zod_exports);
39
-
40
- // src/coerce.ts
41
- var DECIMAL_NUMBER_RE = /^-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
42
- function isHoconWs(cp) {
43
- if (cp === 9 || cp === 10 || cp === 11 || cp === 12 || cp === 13) return true;
44
- if (cp >= 28 && cp <= 31) return true;
45
- if (cp === 32 || cp === 160 || cp === 65279) return true;
46
- if (cp === 5760) return true;
47
- if (cp >= 8192 && cp <= 8202) return true;
48
- if (cp === 8232 || cp === 8233 || cp === 8239 || cp === 8287) return true;
49
- if (cp === 12288) return true;
50
- return false;
51
- }
52
- function trimHoconWs(s) {
53
- let start = 0;
54
- let end = s.length;
55
- while (start < end && isHoconWs(s.charCodeAt(start))) {
56
- start++;
57
- }
58
- while (end > start && isHoconWs(s.charCodeAt(end - 1))) {
59
- end--;
60
- }
61
- return s.slice(start, end);
62
- }
63
- var TRUTHY = /* @__PURE__ */ new Set(["true", "yes", "on"]);
64
- var FALSY = /* @__PURE__ */ new Set(["false", "no", "off"]);
65
- function coerceBoolean(value) {
66
- const lower = value.toLowerCase();
67
- if (TRUTHY.has(lower)) return true;
68
- if (FALSY.has(lower)) return false;
69
- return void 0;
70
- }
71
- function coerceNumber(value) {
72
- if (!DECIMAL_NUMBER_RE.test(value)) return void 0;
73
- return Number(value);
74
- }
75
- var DURATION_UNITS = {
76
- ns: 1e-6,
77
- nanosecond: 1e-6,
78
- nanoseconds: 1e-6,
79
- us: 1e-3,
80
- microsecond: 1e-3,
81
- microseconds: 1e-3,
82
- ms: 1,
83
- millisecond: 1,
84
- milliseconds: 1,
85
- s: 1e3,
86
- second: 1e3,
87
- seconds: 1e3,
88
- m: 6e4,
89
- minute: 6e4,
90
- minutes: 6e4,
91
- h: 36e5,
92
- hour: 36e5,
93
- hours: 36e5,
94
- d: 864e5,
95
- day: 864e5,
96
- days: 864e5
97
- };
98
- var OUTPUT_DURATION_UNITS = {
99
- ns: 1e-6,
100
- us: 1e-3,
101
- ms: 1,
102
- s: 1e3,
103
- m: 6e4,
104
- h: 36e5,
105
- d: 864e5
106
- };
107
- function parseDuration(value, outputUnit = "ms") {
108
- const trimmed = trimHoconWs(value);
109
- let i = 0;
110
- while (i < trimmed.length) {
111
- const ch = trimmed[i];
112
- if (i === 0 && (ch === "-" || ch === "+")) {
113
- i++;
114
- continue;
115
- }
116
- if (ch !== "." && (ch < "0" || ch > "9")) break;
117
- i++;
118
- }
119
- if (i === 0) return NaN;
120
- const num = Number(trimmed.slice(0, i));
121
- if (Number.isNaN(num)) return NaN;
122
- const unit = trimHoconWs(trimmed.slice(i));
123
- const divisor = OUTPUT_DURATION_UNITS[outputUnit];
124
- if (divisor === void 0) return NaN;
125
- if (unit === "") {
126
- return num / divisor;
127
- }
128
- const mult = DURATION_UNITS[unit];
129
- if (mult === void 0) return NaN;
130
- const ms = num * mult;
131
- return ms / divisor;
132
- }
133
- var BYTE_UNITS = {
134
- B: 1,
135
- byte: 1,
136
- bytes: 1,
137
- KB: 1e3,
138
- kilobyte: 1e3,
139
- kilobytes: 1e3,
140
- KiB: 1024,
141
- kibibyte: 1024,
142
- kibibytes: 1024,
143
- MB: 1e6,
144
- megabyte: 1e6,
145
- megabytes: 1e6,
146
- MiB: 1048576,
147
- mebibyte: 1048576,
148
- mebibytes: 1048576,
149
- GB: 1e9,
150
- gigabyte: 1e9,
151
- gigabytes: 1e9,
152
- GiB: 1073741824,
153
- gibibyte: 1073741824,
154
- gibibytes: 1073741824,
155
- TB: 1e12,
156
- terabyte: 1e12,
157
- terabytes: 1e12,
158
- TiB: 1099511627776,
159
- tebibyte: 1099511627776,
160
- tebibytes: 1099511627776,
161
- // S21.4 — HOCON.md L1385: single-letter abbreviations → powers of two (java -Xmx convention).
162
- // Lightbend typesafe-config 1.4.3 verified: 1K=1024, 1M=1048576, etc.
163
- // Both upper- and lowercase accepted per Lightbend behaviour.
164
- // Z/Y (2^70/2^80) are deferred — they overflow MAX_SAFE_INTEGER and require BigInt accessor.
165
- K: 1024,
166
- k: 1024,
167
- M: 1024 ** 2,
168
- m: 1024 ** 2,
169
- G: 1024 ** 3,
170
- g: 1024 ** 3,
171
- T: 1024 ** 4,
172
- t: 1024 ** 4,
173
- P: 1024 ** 5,
174
- p: 1024 ** 5,
175
- E: 1024 ** 6,
176
- e: 1024 ** 6,
177
- // lowercase short-form aliases
178
- b: 1,
179
- kb: 1e3,
180
- kib: 1024,
181
- mb: 1e6,
182
- mib: 1048576,
183
- gb: 1e9,
184
- gib: 1073741824,
185
- tb: 1e12,
186
- tib: 1099511627776
187
- };
188
- var OUTPUT_BYTE_UNITS = {
189
- B: 1,
190
- KB: 1e3,
191
- KiB: 1024,
192
- MB: 1e6,
193
- MiB: 1048576,
194
- GB: 1e9,
195
- GiB: 1073741824,
196
- TB: 1e12,
197
- TiB: 1099511627776
198
- };
199
- function parseBytes(value, outputUnit = "B") {
200
- const trimmed = trimHoconWs(value);
201
- let i = 0;
202
- while (i < trimmed.length) {
203
- const ch = trimmed[i];
204
- if (i === 0 && (ch === "-" || ch === "+")) {
205
- i++;
206
- continue;
207
- }
208
- if (ch !== "." && (ch < "0" || ch > "9")) break;
209
- i++;
210
- }
211
- if (i === 0) return NaN;
212
- const num = Number(trimmed.slice(0, i));
213
- if (Number.isNaN(num)) return NaN;
214
- const unit = trimHoconWs(trimmed.slice(i));
215
- const divisor = OUTPUT_BYTE_UNITS[outputUnit];
216
- if (divisor === void 0) return NaN;
217
- if (unit === "") {
218
- const bytes2 = Math.trunc(num);
219
- if (Math.abs(bytes2) > Number.MAX_SAFE_INTEGER) {
220
- throw new RangeError("byte size overflows representable range (max 2^53-1 bytes)");
221
- }
222
- return bytes2 / divisor;
223
- }
224
- let mult = BYTE_UNITS[unit];
225
- if (mult === void 0) {
226
- mult = BYTE_UNITS[unit.toLowerCase()];
227
- }
228
- if (mult === void 0) return NaN;
229
- const bytes = num * mult;
230
- if (Math.abs(bytes) > Number.MAX_SAFE_INTEGER) {
231
- throw new RangeError("byte size overflows representable range (max 2^53-1 bytes)");
232
- }
233
- const result = bytes / divisor;
234
- return outputUnit === "B" ? Math.round(result) : result;
235
- }
236
-
237
- // src/parse.ts
238
- var fs = __toESM(require("fs"), 1);
239
- var path = __toESM(require("path"), 1);
240
-
241
- // src/errors.ts
242
- var ParseError = class extends Error {
243
- constructor(message, line, col, file) {
244
- super(message);
245
- this.line = line;
246
- this.col = col;
247
- this.file = file;
248
- this.name = "ParseError";
249
- }
250
- };
251
- var ResolveError = class extends Error {
252
- constructor(message, path2, line, col, file) {
253
- super(message);
254
- this.path = path2;
255
- this.line = line;
256
- this.col = col;
257
- this.file = file;
258
- this.name = "ResolveError";
259
- }
260
- };
261
- var PackageLookupError = class extends ResolveError {
262
- constructor(message, identifier, packageFile, line, col) {
263
- super(message, `${identifier}/${packageFile}`, line, col);
264
- this.identifier = identifier;
265
- this.packageFile = packageFile;
266
- this.name = "PackageLookupError";
267
- }
268
- };
269
- var ConfigError = class extends Error {
270
- constructor(message, path2) {
271
- super(message);
272
- this.path = path2;
273
- this.name = "ConfigError";
274
- }
275
- };
276
- var NotResolvedError = class extends ConfigError {
277
- constructor(path2) {
278
- super(`value at path "${path2}" is not resolved (call resolve() first)`, path2);
279
- this.name = "NotResolvedError";
280
- }
281
- };
282
-
283
- // src/internal/resolver/fold-self-ref.ts
284
- function substFullKey(s) {
285
- return stringSegmentsToKey(s.segments.map((seg) => seg.text));
286
- }
287
- function stringSegmentsToKey(segments) {
288
- return segments.map((t) => {
289
- if (t === "" || /[^a-zA-Z0-9\-_]/.test(t)) {
290
- return `"${t.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
291
- }
292
- return t;
293
- }).join(".");
294
- }
295
- function containsSelfRef(v, fullKey) {
296
- if (isSubst(v)) return !v.knownAbsent && substFullKey(v) === fullKey;
297
- if (isConcat(v)) return v.nodes.some((n) => containsSelfRef(n, fullKey));
298
- if (isResObj(v)) {
299
- for (const f of v.fields.values()) {
300
- if (containsSelfRef(f, fullKey)) return true;
301
- }
302
- return false;
303
- }
304
- const hv = v;
305
- if (hv.kind === "array") {
306
- return hv.items.some((item) => containsSelfRef(item, fullKey));
307
- }
308
- if (hv.kind === "object") {
309
- for (const f of hv.fields.values()) {
310
- if (containsSelfRef(f, fullKey)) return true;
311
- }
312
- return false;
313
- }
314
- return false;
315
- }
316
- function foldSelfRef(v, fullKey, replacement) {
317
- if (isSubst(v)) {
318
- return substFullKey(v) === fullKey ? replacement : v;
319
- }
320
- if (isConcat(v)) {
321
- return {
322
- _kind: "concat-placeholder",
323
- nodes: v.nodes.map((n) => foldSelfRef(n, fullKey, replacement)),
324
- line: v.line,
325
- col: v.col
326
- };
327
- }
328
- if (isResObj(v)) {
329
- const newFields = /* @__PURE__ */ new Map();
330
- for (const [k, val] of v.fields) {
331
- newFields.set(k, foldSelfRef(val, fullKey, replacement));
332
- }
333
- return { _kind: "res-obj", fields: newFields, priorValues: new Map(v.priorValues), resetKeys: new Set(v.resetKeys) };
334
- }
335
- const hv = v;
336
- if (hv.kind === "array") {
337
- return {
338
- kind: "array",
339
- items: hv.items.map((item) => foldSelfRef(item, fullKey, replacement))
340
- };
341
- }
342
- if (hv.kind === "object") {
343
- const newFields = /* @__PURE__ */ new Map();
344
- for (const [k, val] of hv.fields) {
345
- newFields.set(k, foldSelfRef(val, fullKey, replacement));
346
- }
347
- return { kind: "object", fields: newFields };
348
- }
349
- return v;
350
- }
351
- function foldKnownAbsentSelfRef(v, fullKey, replacement) {
352
- if (isSubst(v)) {
353
- return v.knownAbsent && substFullKey(v) === fullKey ? replacement : v;
354
- }
355
- if (isConcat(v)) {
356
- return {
357
- _kind: "concat-placeholder",
358
- nodes: v.nodes.map((n) => foldKnownAbsentSelfRef(n, fullKey, replacement)),
359
- line: v.line,
360
- col: v.col
361
- };
362
- }
363
- if (isResObj(v)) {
364
- const newFields = /* @__PURE__ */ new Map();
365
- for (const [k, val] of v.fields) {
366
- newFields.set(k, foldKnownAbsentSelfRef(val, fullKey, replacement));
367
- }
368
- return { _kind: "res-obj", fields: newFields, priorValues: new Map(v.priorValues), resetKeys: new Set(v.resetKeys) };
369
- }
370
- const hv = v;
371
- if (hv.kind === "array") {
372
- return {
373
- kind: "array",
374
- items: hv.items.map((item) => foldKnownAbsentSelfRef(item, fullKey, replacement))
375
- };
376
- }
377
- if (hv.kind === "object") {
378
- const newFields = /* @__PURE__ */ new Map();
379
- for (const [k, val] of hv.fields) {
380
- newFields.set(k, foldKnownAbsentSelfRef(val, fullKey, replacement));
381
- }
382
- return { kind: "object", fields: newFields };
383
- }
384
- return v;
385
- }
386
- function foldOrSkipPrior(prior, fullKey, old) {
387
- if (!containsSelfRef(prior, fullKey)) return cloneResolverValue(prior);
388
- if (old === void 0) return foldOptionalSelfRefAbsent(prior, fullKey);
389
- return foldSelfRef(prior, fullKey, old);
390
- }
391
- function foldOptionalSelfRefAbsent(v, fullKey) {
392
- if (isSubst(v) && substFullKey(v) === fullKey) {
393
- if (!v.optional) return void 0;
394
- return {
395
- _kind: "subst-placeholder",
396
- segments: v.segments.map((seg) => ({ text: seg.text, line: seg.line, col: seg.col })),
397
- optional: v.optional,
398
- knownAbsent: true,
399
- listSuffix: v.listSuffix,
400
- line: v.line,
401
- col: v.col,
402
- prefixLen: v.prefixLen
403
- };
404
- }
405
- if (isConcat(v)) {
406
- const nodes = [];
407
- for (const node of v.nodes) {
408
- const folded = foldOptionalSelfRefAbsent(node, fullKey);
409
- if (folded === void 0) return void 0;
410
- nodes.push(folded);
411
- }
412
- return { _kind: "concat-placeholder", nodes, line: v.line, col: v.col };
413
- }
414
- if (isResObj(v)) {
415
- const fields = /* @__PURE__ */ new Map();
416
- for (const [key, value] of v.fields) {
417
- const folded = foldOptionalSelfRefAbsent(value, fullKey);
418
- if (folded === void 0) return void 0;
419
- fields.set(key, folded);
420
- }
421
- return { _kind: "res-obj", fields, priorValues: new Map(v.priorValues), resetKeys: new Set(v.resetKeys) };
422
- }
423
- const hv = v;
424
- if (hv.kind === "array") {
425
- const items = [];
426
- for (const item of hv.items) {
427
- const folded = foldOptionalSelfRefAbsent(item, fullKey);
428
- if (folded === void 0) return void 0;
429
- items.push(folded);
430
- }
431
- return { kind: "array", items };
432
- }
433
- if (hv.kind === "object") {
434
- const fields = /* @__PURE__ */ new Map();
435
- for (const [key, value] of hv.fields) {
436
- const folded = foldOptionalSelfRefAbsent(value, fullKey);
437
- if (folded === void 0) return void 0;
438
- fields.set(key, folded);
439
- }
440
- return { kind: "object", fields };
441
- }
442
- return cloneResolverValue(v);
443
- }
444
- function cloneResolverValue(v) {
445
- if (isSubst(v)) {
446
- return {
447
- _kind: "subst-placeholder",
448
- segments: v.segments.map((seg) => ({ text: seg.text, line: seg.line, col: seg.col })),
449
- optional: v.optional,
450
- knownAbsent: v.knownAbsent,
451
- listSuffix: v.listSuffix,
452
- line: v.line,
453
- col: v.col,
454
- prefixLen: v.prefixLen
455
- };
456
- }
457
- if (isConcat(v)) {
458
- return {
459
- _kind: "concat-placeholder",
460
- nodes: v.nodes.map((n) => cloneResolverValue(n)),
461
- line: v.line,
462
- col: v.col
463
- };
464
- }
465
- if (isResObj(v)) {
466
- const newFields = /* @__PURE__ */ new Map();
467
- for (const [k, val] of v.fields) newFields.set(k, cloneResolverValue(val));
468
- const newPriors = /* @__PURE__ */ new Map();
469
- for (const [k, val] of v.priorValues) newPriors.set(k, cloneResolverValue(val));
470
- return { _kind: "res-obj", fields: newFields, priorValues: newPriors, resetKeys: new Set(v.resetKeys) };
471
- }
472
- const hv = v;
473
- if (hv.kind === "array") {
474
- return {
475
- kind: "array",
476
- items: hv.items.map((item) => cloneResolverValue(item))
477
- };
478
- }
479
- if (hv.kind === "object") {
480
- const newFields = /* @__PURE__ */ new Map();
481
- for (const [k, val] of hv.fields) {
482
- newFields.set(k, cloneResolverValue(val));
483
- }
484
- return { kind: "object", fields: newFields };
485
- }
486
- return hv;
487
- }
488
- function foldNestedSelfRefs(v, pathPrefix) {
489
- if (!isResObj(v)) return v;
490
- const newFields = /* @__PURE__ */ new Map();
491
- for (const [k, fieldVal] of v.fields) {
492
- const childPath = [...pathPrefix, k];
493
- const fullKey = stringSegmentsToKey(childPath);
494
- const folded = foldNestedSelfRefs(fieldVal, childPath);
495
- let finalVal = folded;
496
- if (containsSelfRef(folded, fullKey)) {
497
- const leafPrior = v.priorValues.get(k);
498
- if (leafPrior !== void 0) {
499
- const leafPriorFolded = foldNestedSelfRefs(leafPrior, childPath);
500
- finalVal = foldSelfRef(folded, fullKey, leafPriorFolded);
501
- }
502
- }
503
- newFields.set(k, finalVal);
504
- }
505
- return { _kind: "res-obj", fields: newFields, priorValues: new Map(v.priorValues), resetKeys: new Set(v.resetKeys) };
506
- }
507
- function containsSubstByPath(v, target) {
508
- if (isSubst(v)) return !v.knownAbsent && segmentsTextEqual(v.segments, target);
509
- if (isConcat(v)) return v.nodes.some((n) => containsSubstByPath(n, target));
510
- if (isResObj(v)) {
511
- for (const f of v.fields.values()) {
512
- if (containsSubstByPath(f, target)) return true;
513
- }
514
- return false;
515
- }
516
- const hv = v;
517
- if (hv.kind === "array") {
518
- return hv.items.some((item) => containsSubstByPath(item, target));
519
- }
520
- if (hv.kind === "object") {
521
- for (const f of hv.fields.values()) {
522
- if (containsSubstByPath(f, target)) return true;
523
- }
524
- return false;
525
- }
526
- return false;
527
- }
528
- function segmentsTextEqual(a, b) {
529
- if (a.length !== b.length) return false;
530
- for (let i = 0; i < a.length; i++) {
531
- const ai = a[i];
532
- const bi = b[i];
533
- if (ai === void 0 || bi === void 0 || ai.text !== bi.text) return false;
534
- }
535
- return true;
536
- }
537
-
538
- // src/internal/resolver/types.ts
539
- var separatorValues = /* @__PURE__ */ new WeakSet();
540
- function isSubst(v) {
541
- return v._kind === "subst-placeholder";
542
- }
543
- function isConcat(v) {
544
- return v._kind === "concat-placeholder";
545
- }
546
- function isResObj(v) {
547
- return v._kind === "res-obj";
548
- }
549
- function makeResObj() {
550
- return { _kind: "res-obj", fields: /* @__PURE__ */ new Map(), priorValues: /* @__PURE__ */ new Map(), resetKeys: /* @__PURE__ */ new Set() };
551
- }
552
- function mergeUnresolved(receiver, fallback) {
553
- const result = makeResObj();
554
- for (const [k, v] of fallback.fields) {
555
- result.fields.set(k, v);
556
- }
557
- for (const [k, v] of fallback.priorValues) {
558
- result.priorValues.set(k, v);
559
- }
560
- for (const [k, rv] of receiver.fields) {
561
- const existing = result.fields.get(k);
562
- if (existing !== void 0) {
563
- const recPrior = receiver.priorValues.get(k);
564
- if (recPrior !== void 0 && !isResObj(recPrior)) {
565
- result.fields.set(k, rv);
566
- continue;
567
- }
568
- if (isResObj(rv) && isResObj(existing)) {
569
- result.fields.set(k, mergeUnresolved(rv, existing));
570
- continue;
571
- }
572
- const foldedPrior = foldOrSkipPrior(existing, k, void 0);
573
- if (foldedPrior !== void 0) result.priorValues.set(k, foldedPrior);
574
- }
575
- result.fields.set(k, rv);
576
- }
577
- for (const [k, v] of receiver.priorValues) {
578
- if (receiver.fields.has(k)) {
579
- result.priorValues.set(k, v);
580
- }
581
- }
582
- return result;
583
- }
584
-
585
- // src/internal/resolver/utils.ts
586
- function segmentsToKey(segments) {
587
- return segments.map((s) => {
588
- const t = s.text;
589
- if (t === "" || /[^a-zA-Z0-9\-_]/.test(t)) {
590
- return `"${t.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
591
- }
592
- return t;
593
- }).join(".");
594
- }
595
- function lookupPath(root, segments) {
596
- const [head, ...tail] = segments;
597
- if (head === void 0) return void 0;
598
- const key = head.text;
599
- const val = root.fields.get(key);
600
- if (val === void 0) return void 0;
601
- if (tail.length === 0) return val;
602
- if (isResObj(val)) return lookupPath(val, tail);
603
- return void 0;
604
- }
605
- function lookupResObj(root, segments) {
606
- let cur = root;
607
- for (const seg of segments) {
608
- const val = cur.fields.get(seg.text);
609
- if (val === void 0 || !isResObj(val)) return void 0;
610
- cur = val;
611
- }
612
- return cur;
613
- }
614
- function deepMergeHoconValues(base, overlay) {
615
- const merged = new Map(base.fields);
616
- for (const [k, v] of overlay.fields) {
617
- const existing = merged.get(k);
618
- if (existing?.kind === "object" && v.kind === "object") {
619
- merged.set(k, deepMergeHoconValues(existing, v));
620
- } else {
621
- merged.set(k, v);
622
- }
623
- }
624
- return { kind: "object", fields: merged };
625
- }
626
- function deepMergeResObjInto(dst, src, pathPrefix = []) {
627
- for (const [k, srcVal] of src.fields) {
628
- const childPrefix = [...pathPrefix, k];
629
- const fullKey = stringSegmentsToKey(childPrefix);
630
- const dstVal = dst.fields.get(k);
631
- if (dstVal !== void 0 && isResObj(dstVal) && isResObj(srcVal)) {
632
- const priorExisting = dst.priorValues.get(k);
633
- const prior = foldOrSkipPrior(dstVal, fullKey, priorExisting);
634
- if (prior !== void 0) dst.priorValues.set(k, prior);
635
- deepMergeResObjInto(dstVal, srcVal, childPrefix);
636
- } else {
637
- if (dstVal !== void 0) {
638
- if (src.resetKeys.has(k)) {
639
- dst.priorValues.delete(k);
640
- } else {
641
- const dstFolded = foldOrSkipPrior(dstVal, fullKey, dst.priorValues.get(k));
642
- if (dstFolded !== void 0) {
643
- const srcPrior = src.priorValues.get(k);
644
- if (srcPrior !== void 0) {
645
- dst.priorValues.set(k, foldKnownAbsentSelfRef(srcPrior, fullKey, dstFolded));
646
- } else {
647
- dst.priorValues.set(k, dstFolded);
648
- }
649
- }
650
- }
651
- }
652
- dst.fields.set(k, srcVal);
653
- }
654
- }
655
- for (const [k, srcPrior] of src.priorValues) {
656
- if (!dst.priorValues.has(k)) {
657
- dst.priorValues.set(k, srcPrior);
658
- }
659
- }
660
- for (const k of src.resetKeys) dst.resetKeys.add(k);
661
- }
662
- function hoconValueToResObj(hv) {
663
- const obj = makeResObj();
664
- if (hv.kind !== "object") return obj;
665
- for (const [key, val] of hv.fields) {
666
- if (val.kind === "object") {
667
- obj.fields.set(key, hoconValueToResObj(val));
668
- } else {
669
- obj.fields.set(key, val);
670
- }
671
- }
672
- return obj;
673
- }
674
- function isFileNotFoundError(e) {
675
- if (!(e instanceof Error)) return false;
676
- const code = e.code;
677
- if (code === "ENOENT" || code === "MODULE_NOT_FOUND") return true;
678
- const msg = e.message.toLowerCase();
679
- return msg.includes("not found") || msg.includes("no such file") || msg.includes("enoent");
680
- }
681
-
682
- // src/internal/resolver/include-loader.ts
683
- var import_node_module = require("module");
684
- var nodePath = __toESM(require("path"), 1);
685
- var import_node_url = require("url");
686
-
687
- // src/internal/lexer/lexer.ts
688
- function isHoconWhitespace(ch) {
689
- const cp = ch.codePointAt(0) ?? -1;
690
- if (cp === 9 || cp === 10 || cp === 11 || cp === 12 || cp === 13) return true;
691
- if (cp >= 28 && cp <= 31) return true;
692
- if (cp === 32 || cp === 160 || cp === 65279) return true;
693
- if (cp === 5760) return true;
694
- if (cp >= 8192 && cp <= 8202) return true;
695
- if (cp === 8232 || cp === 8233 || cp === 8239 || cp === 8287) return true;
696
- if (cp === 12288) return true;
697
- return false;
698
- }
699
- function isHoconNewline(ch) {
700
- return ch === "\n";
701
- }
702
- var SINGLE_CHAR_TOKENS = {
703
- "{": "lbrace",
704
- "}": "rbrace",
705
- "[": "lbracket",
706
- "]": "rbracket",
707
- ",": "comma",
708
- ":": "colon"
709
- };
710
- var Lexer = class {
711
- constructor(input) {
712
- this.input = input;
713
- this.pos = 0;
714
- this.line = 1;
715
- this.col = 1;
716
- this.hadSpace = false;
717
- // Accumulates literal whitespace chars consumed between tokens. Reset on every
718
- // token push. Used so the parser can preserve path-expression whitespace
719
- // (xx.hocon#42, E13) — e.g. tab vs space adjacent to dots in key paths.
720
- // Comment text is NOT accumulated; only the actual WS chars.
721
- this.whitespaceBuffer = "";
722
- this.tokens = [];
723
- if (input.charCodeAt(0) === 65279) this.input = input.slice(1);
724
- }
725
- tokenize() {
726
- while (this.pos < this.input.length) {
727
- const sl = this.line, sc = this.col;
728
- const ch = this.peek();
729
- if (isHoconNewline(ch)) {
730
- this.advance();
731
- if (this.tokens[this.tokens.length - 1]?.kind !== "newline") {
732
- this.push("newline", "\n", sl, sc);
733
- }
734
- continue;
735
- }
736
- if (isHoconWhitespace(ch)) {
737
- this.whitespaceBuffer += ch;
738
- this.advance();
739
- this.hadSpace = true;
740
- continue;
741
- }
742
- if (ch === "/" && this.peek(1) === "/") {
743
- while (this.pos < this.input.length && this.peek() !== "\n") this.advance();
744
- this.hadSpace = true;
745
- continue;
746
- }
747
- if (ch === "#") {
748
- while (this.pos < this.input.length && this.peek() !== "\n") this.advance();
749
- this.hadSpace = true;
750
- continue;
751
- }
752
- if (ch in SINGLE_CHAR_TOKENS) {
753
- this.advance();
754
- this.push(SINGLE_CHAR_TOKENS[ch], ch, sl, sc);
755
- continue;
756
- }
757
- if (ch === "=") {
758
- this.advance();
759
- this.push("equals", "=", sl, sc);
760
- continue;
761
- }
762
- if (ch === "+" && this.peek(1) === "=") {
763
- this.advance();
764
- this.advance();
765
- this.push("plus_equals", "+=", sl, sc);
766
- continue;
767
- }
768
- if (ch === "$" && this.peek(1) === "{") {
769
- this.advance();
770
- this.advance();
771
- const payload = this.parseSubstBody(sl, sc);
772
- const value = payload.segments.map((s) => {
773
- const t = s.text;
774
- if (t === "" || t.includes(".") || t.includes(" ") || t.includes(" ") || t.includes('"') || t.includes("\\") || t !== t.trim()) {
775
- const escaped = t.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
776
- return `"${escaped}"`;
777
- }
778
- return t;
779
- }).join(".");
780
- this.pushSubst(payload, value, sl, sc);
781
- continue;
782
- }
783
- if (ch === '"' && this.peek(1) === '"' && this.peek(2) === '"') {
784
- this.advance();
785
- this.advance();
786
- this.advance();
787
- let value = "";
788
- let closed = false;
789
- while (this.pos < this.input.length) {
790
- if (this.peek() === '"') {
791
- let quoteCount = 0;
792
- while (this.pos < this.input.length && this.peek() === '"') {
793
- quoteCount++;
794
- this.advance();
795
- }
796
- if (quoteCount >= 3) {
797
- for (let i = 0; i < quoteCount - 3; i++) value += '"';
798
- closed = true;
799
- break;
800
- }
801
- for (let i = 0; i < quoteCount; i++) value += '"';
802
- continue;
803
- }
804
- value += this.advance();
805
- }
806
- if (!closed) {
807
- throw new ParseError("unterminated triple-quoted string", sl, sc);
808
- }
809
- if (value.startsWith("\n")) value = value.slice(1);
810
- this.push("triple_string", value, sl, sc, true);
811
- continue;
812
- }
813
- if (ch === '"') {
814
- this.advance();
815
- const value = this.readQuotedStringBody(sl, sc);
816
- this.push("string", value, sl, sc, true);
817
- continue;
818
- }
819
- if (isUnquotedStart(ch)) {
820
- let value = "";
821
- while (this.pos < this.input.length && isUnquotedContinue(this.peek(), () => this.peek(1))) {
822
- value += this.advance();
823
- }
824
- this.push("unquoted", value.trimEnd(), sl, sc);
825
- continue;
826
- }
827
- throw new ParseError(`unexpected character: ${JSON.stringify(ch)}`, sl, sc);
828
- }
829
- this.tokens.push({ kind: "eof", value: "", line: this.line, col: this.col, isQuoted: false, precedingSpace: false, precedingWhitespace: "" });
830
- return this.tokens;
831
- }
832
- peek(offset = 0) {
833
- return this.input[this.pos + offset] ?? "";
834
- }
835
- advance() {
836
- const ch = this.input[this.pos++] ?? "";
837
- if (ch === "\n") {
838
- this.line++;
839
- this.col = 1;
840
- } else {
841
- this.col++;
842
- }
843
- return ch;
844
- }
845
- push(kind, value, l, c, isQuoted = false) {
846
- this.tokens.push({ kind, value, line: l, col: c, isQuoted, precedingSpace: this.hadSpace, precedingWhitespace: this.whitespaceBuffer });
847
- this.hadSpace = false;
848
- this.whitespaceBuffer = "";
849
- }
850
- pushSubst(payload, value, l, c) {
851
- this.tokens.push({ kind: "subst", value, line: l, col: c, isQuoted: false, precedingSpace: this.hadSpace, precedingWhitespace: this.whitespaceBuffer, subst: payload });
852
- this.hadSpace = false;
853
- this.whitespaceBuffer = "";
854
- }
855
- /**
856
- * Read body of a quoted string. Opening `"` must already be consumed.
857
- * Returns decoded string. Throws ParseError on unterminated/invalid-escape.
858
- * openLine/openCol are the position of the opening `"` for error reporting.
859
- */
860
- readQuotedStringBody(openLine, openCol) {
861
- let value = "";
862
- while (this.pos < this.input.length && this.peek() !== '"') {
863
- if (this.peek() === "\n") throw new ParseError("unterminated string", openLine, openCol);
864
- if (this.peek() === "\\") {
865
- const escCol = this.col;
866
- this.advance();
867
- if (this.pos >= this.input.length) {
868
- throw new ParseError("unterminated string", openLine, openCol);
869
- }
870
- const esc = this.advance();
871
- switch (esc) {
872
- case "n":
873
- value += "\n";
874
- break;
875
- case "t":
876
- value += " ";
877
- break;
878
- case "r":
879
- value += "\r";
880
- break;
881
- case '"':
882
- value += '"';
883
- break;
884
- case "\\":
885
- value += "\\";
886
- break;
887
- case "/":
888
- value += "/";
889
- break;
890
- case "b":
891
- value += "\b";
892
- break;
893
- case "f":
894
- value += "\f";
895
- break;
896
- case "u": {
897
- if (this.pos + 4 > this.input.length) {
898
- throw new ParseError("invalid unicode escape", openLine, escCol);
899
- }
900
- const hex = this.input.slice(this.pos, this.pos + 4);
901
- if (!/^[0-9a-fA-F]{4}$/.test(hex)) {
902
- throw new ParseError("invalid unicode escape", openLine, escCol);
903
- }
904
- const code = parseInt(hex, 16);
905
- value += String.fromCharCode(code);
906
- for (let i = 0; i < 4; i++) this.advance();
907
- break;
908
- }
909
- default:
910
- throw new ParseError(`unknown escape sequence: \\${esc}`, openLine, escCol);
911
- }
912
- } else {
913
- value += this.advance();
914
- }
915
- }
916
- if (this.pos >= this.input.length || this.peek() !== '"') {
917
- throw new ParseError("unterminated string", openLine, openCol);
918
- }
919
- this.advance();
920
- return value;
921
- }
922
- /**
923
- * Parse the body of a `${...}` substitution (called after `${` has been consumed).
924
- * Implements Appendix A state machine from the cross-language spec.
925
- *
926
- * S13c extension: if the segment-collection loop encounters `[`, it delegates to
927
- * `parseListSuffix()` which consumes the literal `[]` and sets `listSuffix=true`.
928
- * ASCII space/tab before `[` is buffered in `pendingWs` and discarded (E7).
929
- */
930
- parseSubstBody(startLine, startCol) {
931
- let optional = false;
932
- if (this.peek() === "?") {
933
- this.advance();
934
- optional = true;
935
- }
936
- let curText = "";
937
- let curStarted = false;
938
- let curLine = 0;
939
- let curCol = 0;
940
- let pendingWs = "";
941
- const segments = [];
942
- let lastDot = null;
943
- let listSuffix = false;
944
- while (true) {
945
- if (this.pos >= this.input.length) {
946
- throw new ParseError("unterminated substitution", startLine, startCol);
947
- }
948
- const ch = this.peek();
949
- if (ch === "}") {
950
- this.advance();
951
- pendingWs = "";
952
- break;
953
- } else if (ch === "[") {
954
- if (!curStarted) {
955
- throw new ParseError("empty segment before '[]' suffix in substitution path", startLine, this.col);
956
- }
957
- for (const w of pendingWs) {
958
- if (w !== " " && w !== " ") {
959
- throw new ParseError(
960
- `only ASCII space or tab allowed between substitution path and '[]' suffix (got ${JSON.stringify(w)}, HOCON extra-spec E7)`,
961
- startLine,
962
- this.col
963
- );
964
- }
965
- }
966
- segments.push({ text: curText, line: curLine, col: curCol });
967
- pendingWs = "";
968
- listSuffix = this.parseListSuffix(startLine);
969
- break;
970
- } else if (ch === '"') {
971
- const qLine = startLine;
972
- const qCol = this.col;
973
- if (curStarted) {
974
- curText += pendingWs;
975
- }
976
- pendingWs = "";
977
- this.advance();
978
- const decoded = this.readQuotedStringBody(qLine, qCol);
979
- curText += decoded;
980
- if (!curStarted) {
981
- curLine = qLine;
982
- curCol = qCol;
983
- curStarted = true;
984
- }
985
- } else if (isUnquotedSubstChar(ch)) {
986
- if (ch === "-" && !curStarted && !isDecimalDigit(this.peek(1))) {
987
- const after = this.peek(1) === "" ? "EOF" : JSON.stringify(this.peek(1));
988
- throw new ParseError(
989
- `unquoted path segment cannot begin with '-' unless followed by a digit (got '-' then ${after}, HOCON.md L270-276)`,
990
- startLine,
991
- this.col
992
- );
993
- }
994
- const uCol = this.col;
995
- if (curStarted) {
996
- curText += pendingWs;
997
- }
998
- pendingWs = "";
999
- if (!curStarted) {
1000
- curLine = startLine;
1001
- curCol = uCol;
1002
- curStarted = true;
1003
- }
1004
- while (this.pos < this.input.length && isUnquotedSubstChar(this.peek())) {
1005
- curText += this.advance();
1006
- }
1007
- } else if (ch === ".") {
1008
- const dotCol = this.col;
1009
- pendingWs = "";
1010
- if (!curStarted) {
1011
- throw new ParseError("empty segment in path", startLine, dotCol);
1012
- }
1013
- segments.push({ text: curText, line: curLine, col: curCol });
1014
- curText = "";
1015
- curStarted = false;
1016
- curLine = 0;
1017
- curCol = 0;
1018
- lastDot = [startLine, dotCol];
1019
- this.advance();
1020
- } else if (isHoconNewline(ch)) {
1021
- throw new ParseError("unterminated substitution", startLine, startCol);
1022
- } else if (isHoconWhitespace(ch)) {
1023
- pendingWs += ch;
1024
- this.advance();
1025
- } else {
1026
- throw new ParseError(`unexpected character in substitution path: ${JSON.stringify(ch)}`, startLine, this.col);
1027
- }
1028
- }
1029
- if (!listSuffix) {
1030
- if (curStarted) {
1031
- segments.push({ text: curText, line: curLine, col: curCol });
1032
- } else if (segments.length === 0) {
1033
- throw new ParseError("empty substitution path", startLine, startCol);
1034
- } else {
1035
- const [errLine, errCol] = lastDot ?? [startLine, startCol];
1036
- throw new ParseError("empty segment in path", errLine, errCol);
1037
- }
1038
- }
1039
- return { segments, optional, listSuffix };
1040
- }
1041
- /**
1042
- * Consume the literal `[]` suffix inside a substitution body.
1043
- * Called after the `[` has been detected (but not yet consumed).
1044
- * Requires the next character to be `[`, then exactly `]`, then `}`.
1045
- * Whitespace inside `[]` is not permitted (per spec Decision §1).
1046
- * Returns true (always — only called when listSuffix path is taken).
1047
- */
1048
- parseListSuffix(startLine) {
1049
- this.advance();
1050
- const afterBracket = this.peek();
1051
- if (afterBracket !== "]") {
1052
- const desc = afterBracket === "" ? "EOF" : JSON.stringify(afterBracket);
1053
- throw new ParseError(
1054
- `expected ']' after '[' in substitution list suffix (got ${desc})`,
1055
- startLine,
1056
- this.col
1057
- );
1058
- }
1059
- this.advance();
1060
- if (this.peek() !== "}") {
1061
- const desc = this.peek() === "" ? "EOF" : JSON.stringify(this.peek());
1062
- throw new ParseError(
1063
- `expected '}' after '[]' in substitution list suffix (got ${desc})`,
1064
- startLine,
1065
- this.col
1066
- );
1067
- }
1068
- this.advance();
1069
- return true;
1070
- }
1071
- };
1072
- function tokenize(input) {
1073
- return new Lexer(input).tokenize();
1074
- }
1075
- function isUnquotedSubstChar(ch) {
1076
- if (ch === "" || isHoconWhitespace(ch)) return false;
1077
- if ('"\\'.includes(ch)) return false;
1078
- if ("{}[]".includes(ch)) return false;
1079
- if (":=,+#`^?!@*&$.".includes(ch)) return false;
1080
- return true;
1081
- }
1082
- function isDecimalDigit(ch) {
1083
- return ch >= "0" && ch <= "9";
1084
- }
1085
- function isUnquotedStart(ch) {
1086
- if (ch === "" || isHoconWhitespace(ch)) return false;
1087
- if ('{}[],:=+#"$?!@*&^`\\'.includes(ch)) return false;
1088
- return true;
1089
- }
1090
- function isUnquotedContinue(ch, nextFn) {
1091
- if (ch === "" || isHoconWhitespace(ch)) return false;
1092
- if ('{}[],:=#"$?!@*&^`\\'.includes(ch)) return false;
1093
- if (ch === "+" && nextFn() === "=") return false;
1094
- if (ch === "/" && nextFn() === "/") return false;
1095
- return true;
1096
- }
1097
-
1098
- // src/internal/parser/parser.ts
1099
- var EOF_TOKEN = { kind: "eof", value: "", line: 0, col: 0, isQuoted: false, precedingSpace: false, precedingWhitespace: "", subst: void 0 };
1100
- var Parser = class {
1101
- constructor(tokens) {
1102
- this.tokens = tokens;
1103
- this.pos = 0;
1104
- }
1105
- parse() {
1106
- this.skip("newline");
1107
- const t = this.peek();
1108
- if (t.kind === "lbrace") {
1109
- this.advance();
1110
- const first = this.parseObject(true);
1111
- const allFields = first.kind === "object" ? [...first.fields] : [];
1112
- while (true) {
1113
- this.skip("newline");
1114
- if (this.peek().kind === "eof") break;
1115
- if (this.peek().kind === "lbrace") {
1116
- this.advance();
1117
- const extra = this.parseObject(true);
1118
- if (extra.kind === "object") allFields.push(...extra.fields);
1119
- } else {
1120
- const rest = this.parseObject(false);
1121
- if (rest.kind === "object") allFields.push(...rest.fields);
1122
- break;
1123
- }
1124
- }
1125
- this.skip("newline");
1126
- const remaining = this.peek();
1127
- if (remaining.kind !== "eof") {
1128
- throw new ParseError(`Unexpected token '${remaining.value}' after closing brace`, remaining.line, remaining.col);
1129
- }
1130
- return { kind: "object", fields: allFields, pos: first.pos };
1131
- }
1132
- if (t.kind === "lbracket") {
1133
- this.advance();
1134
- const arr = this.parseArray();
1135
- this.skip("newline");
1136
- const remaining = this.peek();
1137
- if (remaining.kind !== "eof") {
1138
- throw new ParseError(`Unexpected token '${remaining.value}' after root array`, remaining.line, remaining.col);
1139
- }
1140
- return { ...arr, pos: { line: t.line, col: t.col } };
1141
- }
1142
- return this.parseObject(false);
1143
- }
1144
- peek(offset = 0) {
1145
- return this.tokens[this.pos + offset] ?? EOF_TOKEN;
1146
- }
1147
- advance() {
1148
- const t = this.tokens[this.pos];
1149
- if (this.pos < this.tokens.length) this.pos++;
1150
- return t ?? EOF_TOKEN;
1151
- }
1152
- skip(...kinds) {
1153
- while (kinds.includes(this.peek().kind)) this.advance();
1154
- }
1155
- currentPos() {
1156
- const t = this.peek();
1157
- return { line: t.line, col: t.col };
1158
- }
1159
- parseObject(expectClosingBrace) {
1160
- const p = this.currentPos();
1161
- const fields = [];
1162
- while (true) {
1163
- this.skip("newline");
1164
- const t = this.peek();
1165
- if (t.kind === "eof" || t.kind === "rbrace") break;
1166
- if (t.kind === "unquoted" && t.value === "include") {
1167
- const next = this.peek(1);
1168
- if (next.kind === "equals" || next.kind === "colon" || next.kind === "plus_equals" || next.kind === "lbrace") {
1169
- throw new ParseError(
1170
- `'include' is reserved at the start of a key path expression; use "include" (quoted) to use it as a key`,
1171
- t.line,
1172
- t.col
1173
- );
1174
- }
1175
- this.advance();
1176
- fields.push(this.parseInclude());
1177
- this.skip("newline");
1178
- if (this.peek().kind === "comma") this.advance();
1179
- this.skip("newline");
1180
- continue;
1181
- }
1182
- const keyPos = this.currentPos();
1183
- const { segments: key, firstWasQuoted } = this.parseKey();
1184
- if (key[0] === "include" && !firstWasQuoted) {
1185
- throw new ParseError(
1186
- `'include' is reserved at the start of a key path expression; use "include".foo (quoted) or rename the key`,
1187
- keyPos.line,
1188
- keyPos.col
1189
- );
1190
- }
1191
- this.skip("newline");
1192
- let append = false;
1193
- const sep = this.peek();
1194
- if (sep.kind === "equals") this.advance();
1195
- else if (sep.kind === "plus_equals") {
1196
- this.advance();
1197
- append = true;
1198
- } else if (sep.kind === "colon") this.advance();
1199
- else if (sep.kind === "lbrace") {
1200
- } else if (sep.kind !== "newline" && sep.kind !== "eof") {
1201
- throw new ParseError(`unexpected token after key: ${sep.kind}`, sep.line, sep.col);
1202
- }
1203
- this.skip("newline");
1204
- const value = this.parseValue();
1205
- fields.push({ key, value, append, pos: keyPos });
1206
- this.skip("newline");
1207
- if (this.peek().kind === "comma") this.advance();
1208
- this.skip("newline");
1209
- }
1210
- if (expectClosingBrace) {
1211
- const t = this.peek();
1212
- if (t.kind !== "rbrace") throw new ParseError("expected }", t.line, t.col);
1213
- this.advance();
1214
- }
1215
- return { kind: "object", fields, pos: p };
1216
- }
1217
- parseKey() {
1218
- const segments = [];
1219
- let trailingDot = false;
1220
- let firstWasQuoted = false;
1221
- let spaceConcat = false;
1222
- let postDotPrefix = "";
1223
- while (true) {
1224
- const t = this.peek();
1225
- if (t.kind === "string") {
1226
- this.advance();
1227
- if (segments.length === 0) firstWasQuoted = true;
1228
- if (spaceConcat) {
1229
- segments[segments.length - 1] = `${segments[segments.length - 1]}${t.precedingWhitespace}${t.value}`;
1230
- } else if (postDotPrefix !== "") {
1231
- segments.push(`${postDotPrefix}${t.value}`);
1232
- postDotPrefix = "";
1233
- } else {
1234
- segments.push(t.value);
1235
- }
1236
- trailingDot = false;
1237
- } else if (t.kind === "unquoted") {
1238
- this.advance();
1239
- const raw = t.value.startsWith(".") && segments.length > 0 && !t.precedingSpace ? t.value.slice(1) : t.value;
1240
- const parts = raw.split(".");
1241
- const leadingDotIsSeparator = spaceConcat || postDotPrefix !== "";
1242
- for (let i = 0; i < parts.length; i++) {
1243
- if (parts[i] !== "") continue;
1244
- if (i === parts.length - 1) continue;
1245
- if (i === 0 && leadingDotIsSeparator) continue;
1246
- throw new ParseError(
1247
- `path has ${i === 0 ? "a leading period '.'" : "two adjacent periods '.'"} \u2014 empty key segment not allowed, use quoted "" (HOCON.md path rules)`,
1248
- t.line,
1249
- t.col
1250
- );
1251
- }
1252
- const filtered = parts.filter((s) => s.length > 0);
1253
- if (spaceConcat) {
1254
- segments[segments.length - 1] = `${segments[segments.length - 1]}${t.precedingWhitespace}`;
1255
- if (raw.startsWith(".")) {
1256
- segments.push(...filtered);
1257
- } else if (filtered.length > 0) {
1258
- const [head, ...tail] = filtered;
1259
- segments[segments.length - 1] = `${segments[segments.length - 1]}${head}`;
1260
- segments.push(...tail);
1261
- }
1262
- } else if (postDotPrefix !== "" && raw.startsWith(".")) {
1263
- segments.push(postDotPrefix);
1264
- postDotPrefix = "";
1265
- segments.push(...filtered);
1266
- } else if (postDotPrefix !== "" && filtered.length > 0) {
1267
- const [head, ...tail] = filtered;
1268
- segments.push(`${postDotPrefix}${head}`, ...tail);
1269
- postDotPrefix = "";
1270
- } else {
1271
- segments.push(...filtered);
1272
- }
1273
- trailingDot = raw.endsWith(".");
1274
- } else {
1275
- if (segments.length === 0) throw new ParseError(`expected key, got ${t.kind}`, t.line, t.col);
1276
- break;
1277
- }
1278
- spaceConcat = false;
1279
- if (trailingDot) {
1280
- const next2 = this.peek();
1281
- if ((next2.kind === "unquoted" || next2.kind === "string") && next2.precedingWhitespace.length > 0) {
1282
- postDotPrefix = next2.precedingWhitespace;
1283
- } else {
1284
- postDotPrefix = "";
1285
- }
1286
- continue;
1287
- }
1288
- const next = this.peek();
1289
- if (next.kind === "unquoted" && next.value === "." && !next.precedingSpace) {
1290
- this.advance();
1291
- trailingDot = true;
1292
- const afterDot = this.peek();
1293
- if ((afterDot.kind === "unquoted" || afterDot.kind === "string") && afterDot.precedingWhitespace.length > 0) {
1294
- postDotPrefix = afterDot.precedingWhitespace;
1295
- }
1296
- continue;
1297
- }
1298
- if (next.kind === "unquoted" && next.value.startsWith(".") && !next.precedingSpace) {
1299
- trailingDot = true;
1300
- continue;
1301
- }
1302
- if ((next.kind === "unquoted" || next.kind === "string") && next.precedingSpace) {
1303
- spaceConcat = true;
1304
- continue;
1305
- }
1306
- break;
1307
- }
1308
- if (trailingDot) {
1309
- const here = this.peek();
1310
- throw new ParseError(
1311
- `path has a trailing period '.' \u2014 empty key segment not allowed (HOCON.md path rules)`,
1312
- here.line,
1313
- here.col
1314
- );
1315
- }
1316
- return { segments, firstWasQuoted };
1317
- }
1318
- parseInclude() {
1319
- const p = this.currentPos();
1320
- this.skip("newline");
1321
- const t = this.peek();
1322
- if (t.kind === "unquoted" && (t.value === "required(" || t.value === "required" || t.value.startsWith("required("))) {
1323
- if (t.value === "required") {
1324
- const next = this.peek(1);
1325
- if (next.kind !== "unquoted" || !next.value.startsWith("(")) {
1326
- throw new ParseError("include required must be followed by (", t.line, t.col);
1327
- }
1328
- }
1329
- this.advance();
1330
- const innerPrefix = t.value.startsWith("required(") ? t.value.slice("required(".length) : "";
1331
- if (innerPrefix === "url" || innerPrefix.startsWith("url(") || innerPrefix === "classpath" || innerPrefix.startsWith("classpath(")) {
1332
- throw new ParseError("include url(...) and classpath(...) are not supported", t.line, t.col);
1333
- }
1334
- const nextTok = this.peek();
1335
- if (innerPrefix === "package" || innerPrefix.startsWith("package(") || innerPrefix === "" && nextTok.kind === "unquoted" && (nextTok.value === "package(" || nextTok.value.startsWith("package("))) {
1336
- const consumePackageToken = innerPrefix === "";
1337
- const { qualifier, path: path3 } = this.parsePackageArgs(consumePackageToken);
1338
- return this.makeIncludeField(qualifier, path3, true, p);
1339
- }
1340
- if (innerPrefix === "file" || innerPrefix.startsWith("file(") || innerPrefix === "" && nextTok.kind === "unquoted" && (nextTok.value === "file(" || nextTok.value === "file")) {
1341
- if (innerPrefix === "") {
1342
- this.advance();
1343
- }
1344
- const path3 = this.parseQuotedPathSkipWrapper(t);
1345
- return this.makeIncludeField({ kind: "file" }, path3, true, p);
1346
- }
1347
- if (innerPrefix === "" && nextTok.kind === "unquoted" && (nextTok.value === "url" || nextTok.value.startsWith("url(") || nextTok.value === "classpath" || nextTok.value.startsWith("classpath("))) {
1348
- throw new ParseError("include url(...) and classpath(...) are not supported", nextTok.line, nextTok.col);
1349
- }
1350
- if (innerPrefix !== "") {
1351
- if (innerPrefix === ")") {
1352
- throw new ParseError("include required(...) must contain a path", t.line, t.col);
1353
- }
1354
- const name = innerPrefix.replace(/\(.*$/, "").replace(/\).*$/, "");
1355
- throw new ParseError(`unknown include qualifier inside required(): "${name}"`, t.line, t.col);
1356
- }
1357
- const path2 = this.parseQuotedPathSkipWrapper(t);
1358
- return this.makeIncludeField({ kind: "bare" }, path2, true, p);
1359
- }
1360
- if (t.kind === "string") {
1361
- const path2 = this.advance().value;
1362
- return this.makeIncludeField({ kind: "bare" }, path2, false, p);
1363
- }
1364
- if (t.kind === "unquoted" && (t.value === "file(" || t.value === "file")) {
1365
- this.advance();
1366
- const path2 = this.parseQuotedPathSkipWrapper(t);
1367
- return this.makeIncludeField({ kind: "file" }, path2, false, p);
1368
- }
1369
- if (t.kind === "unquoted" && (t.value === "package(" || t.value.startsWith("package("))) {
1370
- const { qualifier, path: path2 } = this.parsePackageArgs();
1371
- return this.makeIncludeField(qualifier, path2, false, p);
1372
- }
1373
- if (t.kind === "unquoted" && (t.value === "url" || t.value.startsWith("url("))) {
1374
- throw new ParseError("include url(...) is not supported", t.line, t.col);
1375
- }
1376
- if (t.kind === "unquoted" && (t.value === "classpath" || t.value.startsWith("classpath("))) {
1377
- throw new ParseError("include classpath(...) is not supported", t.line, t.col);
1378
- }
1379
- throw new ParseError(`expected include path, got ${t.kind}`, t.line, t.col);
1380
- }
1381
- makeIncludeField(qualifier, path2, required, pos) {
1382
- return { key: [], value: { kind: "include", qualifier, path: path2, required, pos }, append: false, pos };
1383
- }
1384
- /**
1385
- * Skip past include-syntax wrapper tokens to find the quoted path string.
1386
- * Strict: only allows `(`, `)`, and bare qualifier keywords (file / file( /
1387
- * package / package( / url / url( / classpath / classpath() between the
1388
- * directive and the quoted path. Anything else is a parse error rather than
1389
- * silently swallowed (see ts#113).
1390
- */
1391
- parseQuotedPathSkipWrapper(errTok) {
1392
- while (this.isIncludeWrapperToken(this.peek())) this.advance();
1393
- if (this.peek().kind !== "string") {
1394
- const tok = this.peek();
1395
- if (tok.kind === "eof") throw new ParseError("expected include path", errTok.line, errTok.col);
1396
- const desc = tok.kind === "unquoted" ? `unquoted "${tok.value}"` : tok.kind;
1397
- throw new ParseError(`expected quoted include path, got ${desc}`, tok.line, tok.col);
1398
- }
1399
- const path2 = this.advance().value;
1400
- while (this.peek().kind === "unquoted" && (this.peek().value === ")" || this.peek().value === "))")) {
1401
- this.advance();
1402
- }
1403
- const after = this.peek();
1404
- if (after.kind !== "newline" && after.kind !== "rbrace" && after.kind !== "eof" && after.kind !== "comma") {
1405
- const desc = after.kind === "unquoted" ? `unquoted "${after.value}"` : after.kind;
1406
- throw new ParseError(`unexpected token after include path: ${desc}`, after.line, after.col);
1407
- }
1408
- return path2;
1409
- }
1410
- isIncludeWrapperToken(tok) {
1411
- return tok.kind === "unquoted" && tok.value === "(";
1412
- }
1413
- /**
1414
- * Parse the body of `package("identifier", "file")`.
1415
- *
1416
- * @param consumePackageToken - When true (default), the current token is `package(` and
1417
- * must be consumed first. When false, the lexer already bundled `package(` into the
1418
- * preceding token (e.g. `required(package("`), so we are already positioned at the
1419
- * first string argument.
1420
- */
1421
- parsePackageArgs(consumePackageToken = true) {
1422
- const pkgTok = consumePackageToken ? this.advance() : this.peek();
1423
- this.skip("newline");
1424
- const idTok = this.peek();
1425
- if (idTok.kind !== "string") {
1426
- throw new ParseError("include package: expected quoted identifier as first argument", pkgTok.line, pkgTok.col);
1427
- }
1428
- const identifier = this.advance().value;
1429
- this.skip("newline");
1430
- if (this.peek().kind !== "comma") {
1431
- const after = this.peek();
1432
- throw new ParseError(
1433
- after.kind === "string" ? "include package: missing comma between identifier and file arguments" : "include package: requires exactly two arguments (identifier, file) \u2014 one-arg form is not supported",
1434
- pkgTok.line,
1435
- pkgTok.col
1436
- );
1437
- }
1438
- this.advance();
1439
- this.skip("newline");
1440
- const fileTok = this.peek();
1441
- if (fileTok.kind !== "string") {
1442
- throw new ParseError(
1443
- "include package: requires exactly two arguments (identifier, file) \u2014 one-arg form is not supported",
1444
- pkgTok.line,
1445
- pkgTok.col
1446
- );
1447
- }
1448
- const filePath = this.advance().value;
1449
- while (this.peek().kind !== "newline" && this.peek().kind !== "rbrace" && this.peek().kind !== "eof" && this.peek().kind !== "comma") {
1450
- this.advance();
1451
- }
1452
- return { qualifier: { kind: "package", identifier }, path: filePath };
1453
- }
1454
- parseValue() {
1455
- const p = this.currentPos();
1456
- const parts = [];
1457
- while (true) {
1458
- const t = this.peek();
1459
- if (t.kind === "eof" || t.kind === "newline" || t.kind === "rbrace" || t.kind === "rbracket" || t.kind === "comma") break;
1460
- const hadSpace = t.precedingSpace && parts.length > 0;
1461
- let node;
1462
- if (t.kind === "lbrace") {
1463
- this.advance();
1464
- node = this.parseObject(true);
1465
- } else if (t.kind === "lbracket") {
1466
- this.advance();
1467
- node = this.parseArray();
1468
- } else if (t.kind === "subst") {
1469
- this.advance();
1470
- if (!t.subst) {
1471
- throw new ParseError(`internal: subst token missing payload`, t.line, t.col);
1472
- }
1473
- const payload = t.subst;
1474
- node = { kind: "subst", segments: payload.segments, optional: payload.optional, listSuffix: payload.listSuffix, pos: { line: t.line, col: t.col } };
1475
- } else if (t.kind === "string" || t.kind === "triple_string") {
1476
- this.advance();
1477
- node = { kind: "scalar", raw: t.value, valueType: "string", pos: { line: t.line, col: t.col } };
1478
- } else if (t.kind === "unquoted") {
1479
- this.advance();
1480
- node = { kind: "scalar", raw: t.value, valueType: this.scalarValueType(t.value), pos: { line: t.line, col: t.col } };
1481
- } else if ((t.kind === "colon" || t.kind === "equals") && parts.length > 0) {
1482
- this.advance();
1483
- node = { kind: "scalar", raw: t.value, valueType: "string", pos: { line: t.line, col: t.col } };
1484
- } else {
1485
- break;
1486
- }
1487
- if (hadSpace) {
1488
- const sep = t.precedingWhitespace.length > 0 ? t.precedingWhitespace : " ";
1489
- parts.push({ kind: "scalar", raw: sep, valueType: "string", pos: { line: t.line, col: t.col }, _separator: true });
1490
- }
1491
- parts.push(node);
1492
- }
1493
- if (parts.length === 0) throw new ParseError("expected value", this.peek().line, this.peek().col);
1494
- if (parts.length === 1) {
1495
- return parts[0];
1496
- }
1497
- return { kind: "concat", nodes: parts, pos: p };
1498
- }
1499
- parseArray() {
1500
- const p = this.currentPos();
1501
- const items = [];
1502
- while (true) {
1503
- this.skip("newline");
1504
- if (this.peek().kind === "rbracket" || this.peek().kind === "eof") break;
1505
- items.push(this.parseValue());
1506
- this.skip("newline");
1507
- if (this.peek().kind === "comma") this.advance();
1508
- this.skip("newline");
1509
- }
1510
- const t = this.peek();
1511
- if (t.kind !== "rbracket") throw new ParseError("expected ]", t.line, t.col);
1512
- this.advance();
1513
- return { kind: "array", items, pos: p };
1514
- }
1515
- scalarValueType(raw) {
1516
- if (raw === "true" || raw === "false") return "boolean";
1517
- if (raw === "null") return "null";
1518
- if (raw.length > 0 && (raw.charCodeAt(0) >= 48 && raw.charCodeAt(0) <= 57 || raw.charCodeAt(0) === 45)) {
1519
- if (DECIMAL_NUMBER_RE.test(raw)) return "number";
1520
- }
1521
- return "string";
1522
- }
1523
- };
1524
- function parseTokens(tokens) {
1525
- return new Parser(tokens).parse();
1526
- }
1527
-
1528
- // src/internal/strip-bom.ts
1529
- function stripBom(input) {
1530
- return input.charCodeAt(0) === 65279 ? input.slice(1) : input;
1531
- }
1532
-
1533
- // src/internal/depth.ts
1534
- var MAX_PATH_SEGMENTS = 64;
1535
- function tooDeep(segments) {
1536
- return segments > MAX_PATH_SEGMENTS;
1537
- }
1538
- function guardStackDepth(fn, wrap) {
1539
- try {
1540
- return fn();
1541
- } catch (e) {
1542
- if (!isStackOverflow(e)) throw e;
1543
- throw wrap(STACK_MESSAGE);
1544
- }
1545
- }
1546
- var STACK_MESSAGE = "input is nested too deeply for this engine's stack, or contains a cycle (flatten the document, or break the cycle)";
1547
- function isStackOverflow(e) {
1548
- if (!(e instanceof RangeError)) return false;
1549
- const m = e.message.toLowerCase();
1550
- return m.includes("call stack") || // V8: "Maximum call stack size exceeded"
1551
- m.includes("recursion") || // SpiderMonkey: "too much recursion"
1552
- m.includes("stack overflow");
1553
- }
1554
-
1555
- // src/internal/properties/properties.ts
1556
- function parseProperties(input) {
1557
- const pairs = [];
1558
- for (const { text, line } of logicalLines(stripBom(input))) {
1559
- const [rawKey, rawValue] = splitKeyValue(text);
1560
- const key = unescapeProps(rawKey, line);
1561
- if (key === "") continue;
1562
- const segments = key.split(".");
1563
- if (tooDeep(segments.length)) {
1564
- throw new ParseError(
1565
- `key maps to a path ${segments.length} segments deep, over the limit of ${MAX_PATH_SEGMENTS}`,
1566
- line,
1567
- 1
1568
- );
1569
- }
1570
- pairs.push([segments, unescapeProps(rawValue, line)]);
1571
- }
1572
- return nestPairs(pairs);
1573
- }
1574
- function nestPairs(pairs) {
1575
- const root = /* @__PURE__ */ Object.create(null);
1576
- const sorted = [...pairs].sort(([a], [b]) => compareSegments(a, b));
1577
- for (const [segments, value] of sorted) {
1578
- setNested(root, segments, value);
1579
- }
1580
- return root;
1581
- }
1582
- function compareSegments(a, b) {
1583
- const n = Math.min(a.length, b.length);
1584
- for (let i = 0; i < n; i++) {
1585
- const x = a[i];
1586
- const y = b[i];
1587
- if (x !== y) return x < y ? -1 : 1;
1588
- }
1589
- return a.length - b.length;
1590
- }
1591
- function logicalLines(input) {
1592
- const natural = input.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
1593
- const out = [];
1594
- for (let i = 0; i < natural.length; i++) {
1595
- let text = trimLeadingSpace(natural[i] ?? "");
1596
- if (text === "" || text.startsWith("#") || text.startsWith("!")) continue;
1597
- const start = i + 1;
1598
- while (endsWithContinuation(text)) {
1599
- text = text.slice(0, -1);
1600
- if (i + 1 >= natural.length) break;
1601
- i++;
1602
- text += trimLeadingSpace(natural[i] ?? "");
1603
- }
1604
- out.push({ text, line: start });
1605
- }
1606
- return out;
1607
- }
1608
- function trimLeadingSpace(s) {
1609
- return s.replace(/^[ \t\f]+/, "");
1610
- }
1611
- function endsWithContinuation(line) {
1612
- let n = 0;
1613
- for (let i = line.length - 1; i >= 0 && line[i] === "\\"; i--) n++;
1614
- return n % 2 === 1;
1615
- }
1616
- function splitKeyValue(line) {
1617
- let key = "";
1618
- let i = 0;
1619
- for (; i < line.length; i++) {
1620
- const c = line[i];
1621
- if (c === "\\" && i + 1 < line.length) {
1622
- key += c + line[i + 1];
1623
- i++;
1624
- continue;
1625
- }
1626
- if (c === "=" || c === ":" || isPropsSpace(c)) break;
1627
- key += c;
1628
- }
1629
- while (i < line.length && isPropsSpace(line[i])) i++;
1630
- if (i < line.length && (line[i] === "=" || line[i] === ":")) {
1631
- i++;
1632
- while (i < line.length && isPropsSpace(line[i])) i++;
1633
- }
1634
- return [key, line.slice(i)];
1635
- }
1636
- function isPropsSpace(c) {
1637
- return c === " " || c === " " || c === "\f";
1638
- }
1639
- function unescapeProps(s, line) {
1640
- let out = "";
1641
- for (let i = 0; i < s.length; i++) {
1642
- if (s[i] !== "\\") {
1643
- out += s[i];
1644
- continue;
1645
- }
1646
- i++;
1647
- if (i >= s.length) break;
1648
- const e = s[i];
1649
- switch (e) {
1650
- case "t":
1651
- out += " ";
1652
- break;
1653
- case "n":
1654
- out += "\n";
1655
- break;
1656
- case "r":
1657
- out += "\r";
1658
- break;
1659
- case "f":
1660
- out += "\f";
1661
- break;
1662
- case "u": {
1663
- const hex = s.slice(i + 1, i + 5);
1664
- if (!/^[0-9a-fA-F]{4}$/.test(hex)) {
1665
- throw new ParseError(`malformed \\u escape in .properties: \\u${hex}`, line, i + 1);
1666
- }
1667
- out += String.fromCharCode(parseInt(hex, 16));
1668
- i += 4;
1669
- break;
1670
- }
1671
- default:
1672
- out += e;
1673
- }
1674
- }
1675
- return out;
1676
- }
1677
- function setNested(obj, segments, value) {
1678
- let current = obj;
1679
- for (let i = 0; i < segments.length - 1; i++) {
1680
- const seg = segments[i];
1681
- if (!(seg in current) || typeof current[seg] !== "object" || current[seg] === null) {
1682
- current[seg] = /* @__PURE__ */ Object.create(null);
1683
- }
1684
- current = current[seg];
1685
- }
1686
- const last = segments[segments.length - 1];
1687
- if (typeof current[last] === "object" && current[last] !== null) return;
1688
- current[last] = value;
1689
- }
1690
- function propertiesToHoconValue(input) {
1691
- const parsed = parseProperties(input);
1692
- return recordToHoconValue(parsed);
1693
- }
1694
- function recordToHoconValue(obj) {
1695
- const fields = /* @__PURE__ */ new Map();
1696
- for (const [key, val] of Object.entries(obj)) {
1697
- if (typeof val === "string") {
1698
- fields.set(key, { kind: "scalar", raw: val, valueType: "string" });
1699
- } else if (val !== null && typeof val === "object") {
1700
- fields.set(key, recordToHoconValue(val));
1701
- }
1702
- }
1703
- return { kind: "object", fields };
1704
- }
1705
-
1706
- // src/internal/resolver/include-loader.ts
1707
- var import_meta = {};
1708
- var _require;
1709
- function getRequire() {
1710
- if (_require === void 0) {
1711
- _require = pickRequire(
1712
- typeof require === "function" ? require : void 0,
1713
- import_meta.url
1714
- );
1715
- }
1716
- return _require;
1717
- }
1718
- function pickRequire(candidate, metaUrl) {
1719
- if (typeof candidate?.resolve === "function") {
1720
- return candidate;
1721
- }
1722
- return (0, import_node_module.createRequire)(metaUrl ?? (0, import_node_url.pathToFileURL)(nodePath.join(process.cwd(), "noop.js")));
1723
- }
1724
- function isPnpPath(p) {
1725
- return p.includes(".yarn/cache") || p.includes(".pnp.cjs") || p.includes(".pnp.loader");
1726
- }
1727
- function assertObjectRootedInclude(ast, sourcePath) {
1728
- if (ast.kind === "array") {
1729
- throw new ResolveError(
1730
- `included file has array at file root \u2014 an included file must contain an object, not an array (HOCON.md L993-994): ${sourcePath}`,
1731
- sourcePath,
1732
- ast.pos.line,
1733
- ast.pos.col
1734
- );
1735
- }
1736
- }
1737
- function validatePackageFile(file, identifier) {
1738
- if (file.length === 0) {
1739
- throw new ParseError(`include package("${identifier}", ...): file argument must be non-empty`, 0, 0);
1740
- }
1741
- if (file.includes("\\")) {
1742
- throw new ParseError(
1743
- `include package("${identifier}", "${file}"): backslash not allowed in file argument (use forward slash)`,
1744
- 0,
1745
- 0
1746
- );
1747
- }
1748
- if (file.startsWith("/")) {
1749
- throw new ParseError(
1750
- `include package("${identifier}", "${file}"): absolute path not allowed in file argument`,
1751
- 0,
1752
- 0
1753
- );
1754
- }
1755
- if (/(?:^|\/)\.\.?(?:\/|$)/u.test(file)) {
1756
- throw new ParseError(
1757
- `include package("${identifier}", "${file}"): path traversal (. or ..) not allowed in file argument`,
1758
- 0,
1759
- 0
1760
- );
1761
- }
1762
- if (file.includes("//")) {
1763
- throw new ParseError(
1764
- `include package("${identifier}", "${file}"): consecutive slashes not allowed in file argument`,
1765
- 0,
1766
- 0
1767
- );
1768
- }
1769
- }
1770
- function validatePackageIdentifier(identifier) {
1771
- if (identifier.length === 0) {
1772
- throw new ParseError("include package: identifier argument must be non-empty", 0, 0);
1773
- }
1774
- }
1775
- function defaultPackageResolver(identifier, file, includingFile, baseDir, resolveFrom) {
1776
- const from = resolveFrom ? Array.isArray(resolveFrom) ? resolveFrom : [resolveFrom] : baseDir ? [baseDir] : includingFile ? [nodePath.dirname(includingFile)] : [process.cwd()];
1777
- let resolved;
1778
- try {
1779
- resolved = getRequire().resolve(`${identifier}/${file}`, { paths: from });
1780
- } catch {
1781
- throw new PackageLookupError(
1782
- `include package("${identifier}", "${file}"): module not found (starting from: ${from.join(", ")})`,
1783
- identifier,
1784
- file,
1785
- 0,
1786
- 0
1787
- );
1788
- }
1789
- if (isPnpPath(resolved)) {
1790
- throw new ResolveError(
1791
- `include package("${identifier}", "${file}"): Yarn Berry PnP store paths are not supported. Provide a custom packageResolver option to handle PnP resolution.`,
1792
- `${identifier}/${file}`,
1793
- 0,
1794
- 0
1795
- );
1796
- }
1797
- const fileParts = file.split("/");
1798
- const expectedBasename = fileParts[fileParts.length - 1] ?? file;
1799
- const resolvedBasename = nodePath.basename(resolved);
1800
- if (resolvedBasename !== expectedBasename) {
1801
- throw new PackageLookupError(
1802
- `include package("${identifier}", "${file}"): case mismatch \u2014 resolved "${resolvedBasename}" but expected "${expectedBasename}" (E11 decision 5: case-sensitive)`,
1803
- identifier,
1804
- file,
1805
- 0,
1806
- 0
1807
- );
1808
- }
1809
- return resolved;
1810
- }
1811
- var IncludeLoader = class {
1812
- constructor(opts) {
1813
- this.opts = opts;
1814
- }
1815
- /**
1816
- * Resolve an include path to an absolute path.
1817
- * - file() includes resolve relative to CWD (or as absolute paths),
1818
- * NOT relative to the including file's directory.
1819
- * - Bare includes resolve relative to the including file's directory (baseDir).
1820
- */
1821
- resolveIncludePath(includePath, baseDir, isFile) {
1822
- return isFile ? nodePath.resolve(includePath) : baseDir ? nodePath.resolve(baseDir, includePath) : nodePath.resolve(includePath);
1823
- }
1824
- load(includePath, required, isFile) {
1825
- const { baseDir, includeStack = [] } = this.opts;
1826
- const absPath = this.resolveIncludePath(includePath, baseDir, !!isFile);
1827
- if (includeStack.includes(absPath)) {
1828
- throw new ResolveError(`circular include: ${absPath}`, absPath, 0, 0);
1829
- }
1830
- if (includeStack.length >= 50) {
1831
- throw new ResolveError(`include depth limit exceeded (max 50)`, includePath, 0, 0);
1832
- }
1833
- const hasExplicitExt = absPath.endsWith(".conf") || absPath.endsWith(".json") || absPath.endsWith(".properties");
1834
- if (hasExplicitExt) {
1835
- const result = this.loadSingle(absPath);
1836
- if (result !== void 0) return result;
1837
- if (required) {
1838
- throw new ResolveError(`required include file not found: ${includePath}`, includePath, 0, 0);
1839
- }
1840
- return makeResObj();
1841
- }
1842
- const merged = makeResObj();
1843
- let foundAny = false;
1844
- const probeExts = [".properties", ".json", ".conf"];
1845
- for (const ext of probeExts) {
1846
- const obj = this.loadSingle(`${absPath}${ext}`);
1847
- if (obj !== void 0) {
1848
- deepMergeResObjInto(merged, obj, []);
1849
- foundAny = true;
1850
- }
1851
- }
1852
- if (!foundAny && required) {
1853
- throw new ResolveError(`required include file not found: ${includePath}`, includePath, 0, 0);
1854
- }
1855
- return merged;
1856
- }
1857
- async loadAsync(includePath, required, isFile) {
1858
- const { baseDir, includeStack = [] } = this.opts;
1859
- const absPath = this.resolveIncludePath(includePath, baseDir, !!isFile);
1860
- if (includeStack.includes(absPath)) {
1861
- throw new ResolveError(`circular include: ${absPath}`, absPath, 0, 0);
1862
- }
1863
- if (includeStack.length >= 50) {
1864
- throw new ResolveError(`include depth limit exceeded (max 50)`, includePath, 0, 0);
1865
- }
1866
- const hasExplicitExt = absPath.endsWith(".conf") || absPath.endsWith(".json") || absPath.endsWith(".properties");
1867
- if (hasExplicitExt) {
1868
- const result = await this.loadSingleAsync(absPath);
1869
- if (result !== void 0) return result;
1870
- if (required) {
1871
- throw new ResolveError(`required include file not found: ${includePath}`, includePath, 0, 0);
1872
- }
1873
- return makeResObj();
1874
- }
1875
- const merged = makeResObj();
1876
- let foundAny = false;
1877
- const probeExts = [".properties", ".json", ".conf"];
1878
- for (const ext of probeExts) {
1879
- const obj = await this.loadSingleAsync(`${absPath}${ext}`);
1880
- if (obj !== void 0) {
1881
- deepMergeResObjInto(merged, obj, []);
1882
- foundAny = true;
1883
- }
1884
- }
1885
- if (!foundAny && required) {
1886
- throw new ResolveError(`required include file not found: ${includePath}`, includePath, 0, 0);
1887
- }
1888
- return merged;
1889
- }
1890
- /**
1891
- * Resolve and load `include package("identifier", "file")`.
1892
- * Validates the identifier and file arguments, resolves via the package resolver,
1893
- * performs cycle detection using a JSON-serialised cycle key, and parses the content.
1894
- */
1895
- // `required` is reserved for future optional-package semantics (E11 decision 7);
1896
- // currently all package lookup failures throw regardless of this flag.
1897
- loadPackage(identifier, file, _required) {
1898
- validatePackageIdentifier(identifier);
1899
- validatePackageFile(file, identifier);
1900
- const { includeStack = [], baseDir, resolveFrom, packageResolver, readFileSync: readFileSync2 } = this.opts;
1901
- const cycleKey = JSON.stringify(["package", identifier, file]);
1902
- if (includeStack.includes(cycleKey)) {
1903
- throw new ResolveError(
1904
- `circular include: package("${identifier}", "${file}")`,
1905
- `${identifier}/${file}`,
1906
- 0,
1907
- 0
1908
- );
1909
- }
1910
- if (includeStack.length >= 50) {
1911
- throw new ResolveError(`include depth limit exceeded (max 50)`, `${identifier}/${file}`, 0, 0);
1912
- }
1913
- const resolver = packageResolver ?? ((id, f, includingFile, bDir) => defaultPackageResolver(id, f, includingFile, bDir, resolveFrom));
1914
- const resolvedPath = resolver(identifier, file, void 0, baseDir);
1915
- const content = readFileSync2(resolvedPath);
1916
- const tokens = tokenize(content);
1917
- const ast = parseTokens(tokens);
1918
- assertObjectRootedInclude(ast, resolvedPath);
1919
- return this.onBuildResObj(ast, {
1920
- ...this.opts,
1921
- baseDir: nodePath.dirname(resolvedPath),
1922
- includeStack: [...includeStack, cycleKey]
1923
- });
1924
- }
1925
- /**
1926
- * Async variant of `loadPackage`.
1927
- */
1928
- async loadPackageAsync(identifier, file, _required) {
1929
- validatePackageIdentifier(identifier);
1930
- validatePackageFile(file, identifier);
1931
- const { includeStack = [], baseDir, resolveFrom, packageResolver, readFile, readFileSync: readFileSync2 } = this.opts;
1932
- const cycleKey = JSON.stringify(["package", identifier, file]);
1933
- if (includeStack.includes(cycleKey)) {
1934
- throw new ResolveError(
1935
- `circular include: package("${identifier}", "${file}")`,
1936
- `${identifier}/${file}`,
1937
- 0,
1938
- 0
1939
- );
1940
- }
1941
- if (includeStack.length >= 50) {
1942
- throw new ResolveError(`include depth limit exceeded (max 50)`, `${identifier}/${file}`, 0, 0);
1943
- }
1944
- const resolver = packageResolver ?? ((id, f, includingFile, bDir) => defaultPackageResolver(id, f, includingFile, bDir, resolveFrom));
1945
- const resolvedPath = resolver(identifier, file, void 0, baseDir);
1946
- const read = readFile ? async (p) => readFile(p) : async (p) => readFileSync2(p);
1947
- const content = await read(resolvedPath);
1948
- const tokens = tokenize(content);
1949
- const ast = parseTokens(tokens);
1950
- assertObjectRootedInclude(ast, resolvedPath);
1951
- return this.onBuildResObjAsync(ast, {
1952
- ...this.opts,
1953
- baseDir: nodePath.dirname(resolvedPath),
1954
- includeStack: [...includeStack, cycleKey]
1955
- });
1956
- }
1957
- loadSingle(candidate) {
1958
- const { readFileSync: readFileSync2, includeStack = [] } = this.opts;
1959
- if (includeStack.includes(candidate)) {
1960
- throw new ResolveError(`circular include: ${candidate}`, candidate, 0, 0);
1961
- }
1962
- let content;
1963
- try {
1964
- content = readFileSync2(candidate);
1965
- } catch (e) {
1966
- if (isFileNotFoundError(e)) return void 0;
1967
- throw e;
1968
- }
1969
- if (candidate.endsWith(".properties")) {
1970
- return hoconValueToResObj(propertiesToHoconValue(content));
1971
- }
1972
- const tokens = tokenize(content);
1973
- const ast = parseTokens(tokens);
1974
- assertObjectRootedInclude(ast, candidate);
1975
- return this.onBuildResObj(ast, {
1976
- ...this.opts,
1977
- baseDir: nodePath.dirname(candidate),
1978
- includeStack: [...includeStack, candidate]
1979
- });
1980
- }
1981
- async loadSingleAsync(candidate) {
1982
- const { readFile, readFileSync: readFileSync2, includeStack = [] } = this.opts;
1983
- const read = readFile ? async (p) => readFile(p) : async (p) => readFileSync2(p);
1984
- if (includeStack.includes(candidate)) {
1985
- throw new ResolveError(`circular include: ${candidate}`, candidate, 0, 0);
1986
- }
1987
- let content;
1988
- try {
1989
- content = await read(candidate);
1990
- } catch (e) {
1991
- if (isFileNotFoundError(e)) return void 0;
1992
- throw e;
1993
- }
1994
- if (candidate.endsWith(".properties")) {
1995
- return hoconValueToResObj(propertiesToHoconValue(content));
1996
- }
1997
- const tokens = tokenize(content);
1998
- const ast = parseTokens(tokens);
1999
- assertObjectRootedInclude(ast, candidate);
2000
- return this.onBuildResObjAsync(ast, {
2001
- ...this.opts,
2002
- baseDir: nodePath.dirname(candidate),
2003
- includeStack: [...includeStack, candidate]
2004
- });
2005
- }
2006
- };
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2007
2
 
2008
- // src/internal/resolver/structure-builder.ts
2009
- var StructureBuilder = class _StructureBuilder {
2010
- constructor(opts) {
2011
- this.loader = new IncludeLoader(opts);
2012
- this.loader.onBuildResObj = (a, o) => new _StructureBuilder(o).build(a);
2013
- this.loader.onBuildResObjAsync = async (a, o) => new _StructureBuilder(o).buildAsync(a);
2014
- }
2015
- build(ast, pathPrefix = []) {
2016
- if (ast.kind !== "object") {
2017
- throw new ResolveError("root AST must be an object", "", ast.pos.line, ast.pos.col);
2018
- }
2019
- const obj = makeResObj();
2020
- for (const field of ast.fields) {
2021
- this.applyField(obj, field, pathPrefix);
2022
- }
2023
- return obj;
2024
- }
2025
- async buildAsync(ast, pathPrefix = []) {
2026
- if (ast.kind !== "object") {
2027
- throw new ResolveError("root AST must be an object", "", ast.pos.line, ast.pos.col);
2028
- }
2029
- const obj = makeResObj();
2030
- for (const field of ast.fields) {
2031
- await this.applyFieldAsync(obj, field, pathPrefix);
2032
- }
2033
- return obj;
2034
- }
2035
- applyField(obj, field, pathPrefix) {
2036
- if (field.key.length === 0 && field.value.kind === "include") {
2037
- const { qualifier, path: path2, required } = field.value;
2038
- let included;
2039
- if (qualifier.kind === "package") {
2040
- included = this.loader.loadPackage(qualifier.identifier, path2, required);
2041
- } else {
2042
- included = this.loader.load(path2, required, qualifier.kind === "file");
2043
- }
2044
- if (pathPrefix.length > 0) {
2045
- this.relativizeResObj(included, pathPrefix);
2046
- }
2047
- deepMergeResObjInto(obj, included, pathPrefix);
2048
- return;
2049
- }
2050
- const [head, ...tail] = field.key;
2051
- if (head === void 0) return;
2052
- if (tail.length > 0) {
2053
- const syntheticAst = {
2054
- kind: "object",
2055
- fields: [{ key: tail, value: field.value, append: field.append, pos: field.pos }],
2056
- pos: field.pos
2057
- };
2058
- this.applyField(obj, { key: [head], value: syntheticAst, append: false, pos: field.pos }, pathPrefix);
2059
- return;
2060
- }
2061
- const childPrefix = [...pathPrefix, head];
2062
- const fullKey = stringSegmentsToKey(childPrefix);
2063
- if (field.append) {
2064
- const synthetic = this.desugarAppend(field, childPrefix);
2065
- this.applyField(obj, synthetic, pathPrefix);
2066
- return;
2067
- }
2068
- const existing = obj.fields.get(head);
2069
- const newVal = this.astToResolverValue(field.value, childPrefix);
2070
- if (!containsSelfRef(newVal, fullKey)) {
2071
- obj.resetKeys.add(head);
2072
- }
2073
- if (existing !== void 0) {
2074
- const oldPrior = obj.priorValues.get(head);
2075
- const priorInput = isResObj(existing) ? foldNestedSelfRefs(existing, childPrefix) : existing;
2076
- const prior = foldOrSkipPrior(priorInput, fullKey, oldPrior);
2077
- if (prior !== void 0) obj.priorValues.set(head, prior);
2078
- }
2079
- if (existing !== void 0 && isResObj(existing) && isResObj(newVal)) {
2080
- deepMergeResObjInto(existing, newVal, childPrefix);
2081
- return;
2082
- }
2083
- obj.fields.set(head, newVal);
2084
- }
2085
- async applyFieldAsync(obj, field, pathPrefix) {
2086
- if (field.key.length === 0 && field.value.kind === "include") {
2087
- const { qualifier, path: path2, required } = field.value;
2088
- let included;
2089
- if (qualifier.kind === "package") {
2090
- included = await this.loader.loadPackageAsync(qualifier.identifier, path2, required);
2091
- } else {
2092
- included = await this.loader.loadAsync(path2, required, qualifier.kind === "file");
2093
- }
2094
- if (pathPrefix.length > 0) {
2095
- this.relativizeResObj(included, pathPrefix);
2096
- }
2097
- deepMergeResObjInto(obj, included, pathPrefix);
2098
- return;
2099
- }
2100
- const [head, ...tail] = field.key;
2101
- if (head === void 0) return;
2102
- if (tail.length > 0) {
2103
- const syntheticAst = {
2104
- kind: "object",
2105
- fields: [{ key: tail, value: field.value, append: field.append, pos: field.pos }],
2106
- pos: field.pos
2107
- };
2108
- await this.applyFieldAsync(obj, { key: [head], value: syntheticAst, append: false, pos: field.pos }, pathPrefix);
2109
- return;
2110
- }
2111
- const childPrefix = [...pathPrefix, head];
2112
- const fullKey = stringSegmentsToKey(childPrefix);
2113
- if (field.append) {
2114
- const synthetic = this.desugarAppend(field, childPrefix);
2115
- await this.applyFieldAsync(obj, synthetic, pathPrefix);
2116
- return;
2117
- }
2118
- const existing = obj.fields.get(head);
2119
- const newVal = await this.astToResolverValueAsync(field.value, childPrefix);
2120
- if (!containsSelfRef(newVal, fullKey)) {
2121
- obj.resetKeys.add(head);
2122
- }
2123
- if (existing !== void 0) {
2124
- const oldPrior = obj.priorValues.get(head);
2125
- const priorInput = isResObj(existing) ? foldNestedSelfRefs(existing, childPrefix) : existing;
2126
- const prior = foldOrSkipPrior(priorInput, fullKey, oldPrior);
2127
- if (prior !== void 0) obj.priorValues.set(head, prior);
2128
- }
2129
- if (existing !== void 0 && isResObj(existing) && isResObj(newVal)) {
2130
- deepMergeResObjInto(existing, newVal, childPrefix);
2131
- return;
2132
- }
2133
- obj.fields.set(head, newVal);
2134
- }
2135
- /** Builds the `key = ${?fullkey} [value]` field that `key += value` desugars
2136
- * to (S13b.2, HOCON.md L732). `childPrefix` is the field's fully-qualified
2137
- * path (pathPrefix + key), so a nested `srv { items += x }` references
2138
- * `${?srv.items}`; include relativization rewrites it under a mount prefix.
2139
- * `field.key` is already single-segment here (multi-segment keys are split
2140
- * into nested objects upstream). Returns a NEW AstField (append=false);
2141
- * positions inherit from the original field so resolve-time errors (the
2142
- * S13b.2 non-array check, now via the scalar+array concat) keep a location. */
2143
- desugarAppend(field, childPrefix) {
2144
- const segments = childPrefix.map((text) => ({ text, line: field.pos.line, col: field.pos.col }));
2145
- const subst = { kind: "subst", segments, optional: true, listSuffix: false, pos: field.pos };
2146
- const elemArray = { kind: "array", items: [field.value], pos: field.pos };
2147
- const synthetic = { kind: "concat", nodes: [subst, elemArray], pos: field.pos };
2148
- return { key: field.key, value: synthetic, append: false, pos: field.pos };
2149
- }
2150
- astToResolverValue(ast, pathPrefix) {
2151
- switch (ast.kind) {
2152
- case "scalar": {
2153
- const sv = { kind: "scalar", raw: ast.raw, valueType: ast.valueType };
2154
- if (ast._separator) separatorValues.add(sv);
2155
- return sv;
2156
- }
2157
- case "array":
2158
- return { kind: "array", items: ast.items.map((i) => this.astToResolverValue(i, pathPrefix)) };
2159
- case "object": {
2160
- const inner = this.build(ast, pathPrefix);
2161
- return inner;
2162
- }
2163
- case "subst":
2164
- return { _kind: "subst-placeholder", segments: ast.segments, optional: ast.optional, knownAbsent: false, listSuffix: ast.listSuffix, line: ast.pos.line, col: ast.pos.col, prefixLen: 0 };
2165
- case "concat":
2166
- return { _kind: "concat-placeholder", nodes: ast.nodes.map((n) => this.astToResolverValue(n, pathPrefix)), line: ast.pos.line, col: ast.pos.col };
2167
- case "include":
2168
- return { kind: "scalar", raw: "null", valueType: "null" };
2169
- }
2170
- }
2171
- async astToResolverValueAsync(ast, pathPrefix) {
2172
- switch (ast.kind) {
2173
- case "scalar": {
2174
- const sv = { kind: "scalar", raw: ast.raw, valueType: ast.valueType };
2175
- if (ast._separator) separatorValues.add(sv);
2176
- return sv;
2177
- }
2178
- case "array": {
2179
- const items = [];
2180
- for (const i of ast.items) {
2181
- items.push(await this.astToResolverValueAsync(i, pathPrefix));
2182
- }
2183
- return { kind: "array", items };
2184
- }
2185
- case "object":
2186
- return await this.buildAsync(ast, pathPrefix);
2187
- case "subst":
2188
- return { _kind: "subst-placeholder", segments: ast.segments, optional: ast.optional, knownAbsent: false, listSuffix: ast.listSuffix, line: ast.pos.line, col: ast.pos.col, prefixLen: 0 };
2189
- case "concat": {
2190
- const nodes = [];
2191
- for (const n of ast.nodes) {
2192
- nodes.push(await this.astToResolverValueAsync(n, pathPrefix));
2193
- }
2194
- return { _kind: "concat-placeholder", nodes, line: ast.pos.line, col: ast.pos.col };
2195
- }
2196
- case "include":
2197
- return { kind: "scalar", raw: "null", valueType: "null" };
2198
- }
2199
- }
2200
- // ---- Relativize substitution paths for nested includes ----
2201
- relativizeSubstPaths(val, prefixSegments) {
2202
- if (isSubst(val)) {
2203
- const prefixAsSegments = prefixSegments.map((text) => ({ text, line: 0, col: 0 }));
2204
- val.segments = [...prefixAsSegments, ...val.segments];
2205
- val.prefixLen += prefixSegments.length;
2206
- return;
2207
- }
2208
- if (isConcat(val)) {
2209
- for (const node of val.nodes) {
2210
- this.relativizeSubstPaths(node, prefixSegments);
2211
- }
2212
- return;
2213
- }
2214
- if (isResObj(val)) {
2215
- this.relativizeResObj(val, prefixSegments);
2216
- return;
2217
- }
2218
- const hv = val;
2219
- if (hv.kind === "array") {
2220
- for (const item of hv.items) {
2221
- this.relativizeSubstPaths(item, prefixSegments);
2222
- }
2223
- }
2224
- }
2225
- relativizeResObj(obj, prefixSegments) {
2226
- for (const val of obj.fields.values()) {
2227
- this.relativizeSubstPaths(val, prefixSegments);
2228
- }
2229
- for (const val of obj.priorValues.values()) {
2230
- this.relativizeSubstPaths(val, prefixSegments);
2231
- }
2232
- }
2233
- };
2234
3
 
2235
- // src/value/numeric-array.ts
2236
- function numericObjectToArray(value) {
2237
- if (value.kind !== "object") return null;
2238
- if (value.fields.size === 0) return null;
2239
- const canonicalInt = /^(0|[1-9][0-9]*)$/;
2240
- const eligible = [];
2241
- for (const [key, val] of value.fields) {
2242
- if (!canonicalInt.test(key)) continue;
2243
- const n = Number(key);
2244
- if (!Number.isInteger(n) || n > 2147483647) continue;
2245
- eligible.push({ n, v: val });
2246
- }
2247
- if (eligible.length === 0) return null;
2248
- eligible.sort((a, b) => a.n - b.n);
2249
- return eligible.map((e) => e.v);
2250
- }
4
+ var _chunkIMJ7QHIKcjs = require('./chunk-IMJ7QHIK.cjs');
2251
5
 
2252
- // src/internal/resolver/substitution-resolver.ts
2253
- var SubstitutionResolver = class {
2254
- constructor(root, opts) {
2255
- this.root = root;
2256
- this.opts = opts;
2257
- this.resolving = /* @__PURE__ */ new Set();
2258
- this.cache = /* @__PURE__ */ new Map();
2259
- // Tracks ConcatPlaceholder nodes currently being iterated by resolveConcat.
2260
- // Used by isSelfRef detection: fires only when found === a concat currently
2261
- // mid-iteration (i.e. we are inside found's own resolution), preventing the
2262
- // "foofoo" double-count without misfiring when an external field looks up the
2263
- // same concat via a substitution (multi-reviewer convergence fix).
2264
- //
2265
- // Spec deviation: the S13a.13 spec ★1 decision #1 specified path-equality
2266
- // preservation for self-ref detection. Round-2 multi-agent-review surfaced a
2267
- // false-positive on external lookups (`a = ${?a}foo; b = ${a}`), so the
2268
- // criterion was tightened to node-membership-in-iterating-set — strictly
2269
- // narrower than path-equality. Spec amendment deferred to a follow-up
2270
- // xx.hocon PR (see Phase 6 #3f close-out notes).
2271
- this.resolvingConcats = /* @__PURE__ */ new WeakSet();
2272
- // Path stack tracking the full dotted path of the field currently being
2273
- // assigned in `resolveResObj`. Leaf keys are pushed on entry to each
2274
- // `(key, val)` iteration and popped on exit, so nested objects build up
2275
- // the full path (e.g. `["o", "history"]` while resolving `o.history`).
2276
- //
2277
- // Used to tighten self-ref detection at the L192 found-lookup site:
2278
- // a substitution `${X}` whose looked-up value contains a Subst pointing
2279
- // at `X` is only a true self-reference when the field currently being
2280
- // assigned is `X` (or a descendant of `X`). Without this guard, an
2281
- // external lookup like `b = ${o}` (where o has a self-referential
2282
- // field) would mis-fire and short-circuit to o's prior, returning the
2283
- // wrong value for b. The is_owner gate (rfp prefix-matches s.segments)
2284
- // narrows the check to the owner case only.
2285
- //
2286
- // Cross-impl with rs.hocon v1.5.1's resolving_field_path (same purpose,
2287
- // same prefix-match semantics).
2288
- this.resolvingFieldPath = [];
2289
- }
2290
- /** Returns a prefix for error messages, including origin info when set. */
2291
- originPrefix() {
2292
- return this.opts.originDescription ? `${this.opts.originDescription}: ` : "";
2293
- }
2294
- resolve() {
2295
- return this.resolveResObj(this.root);
2296
- }
2297
- resolveResObj(obj) {
2298
- const result = /* @__PURE__ */ new Map();
2299
- for (const [key, val] of obj.fields) {
2300
- this.resolvingFieldPath.push(key);
2301
- const fullCacheKey = stringSegmentsToKey(this.resolvingFieldPath);
2302
- this.cache.delete(fullCacheKey);
2303
- let resolved;
2304
- try {
2305
- resolved = this.resolveVal(val, obj);
2306
- } finally {
2307
- this.resolvingFieldPath.pop();
2308
- }
2309
- if (resolved !== void 0) {
2310
- if (resolved.kind === "object") {
2311
- const prior = obj.priorValues.get(key);
2312
- if (prior !== void 0) {
2313
- const priorResolved = this.resolveVal(prior, obj);
2314
- if (priorResolved !== void 0 && priorResolved.kind === "object") {
2315
- const finalValue = deepMergeHoconValues(
2316
- priorResolved,
2317
- resolved
2318
- );
2319
- result.set(key, finalValue);
2320
- this.cache.set(fullCacheKey, finalValue);
2321
- this.cacheDescendants(fullCacheKey, finalValue);
2322
- continue;
2323
- }
2324
- }
2325
- }
2326
- result.set(key, resolved);
2327
- this.cache.set(fullCacheKey, resolved);
2328
- this.cacheDescendants(fullCacheKey, resolved);
2329
- } else {
2330
- const prior = obj.priorValues.get(key);
2331
- if (prior !== void 0) {
2332
- const priorResolved = this.resolveVal(prior, obj);
2333
- if (priorResolved !== void 0) {
2334
- result.set(key, priorResolved);
2335
- this.cache.set(fullCacheKey, priorResolved);
2336
- this.cacheDescendants(fullCacheKey, priorResolved);
2337
- }
2338
- }
2339
- }
2340
- }
2341
- return { kind: "object", fields: result };
2342
- }
2343
- cacheDescendants(prefix, value) {
2344
- if (value.kind !== "object") return;
2345
- for (const [key, child] of value.fields) {
2346
- const childKey = `${prefix}.${stringSegmentsToKey([key])}`;
2347
- this.cache.set(childKey, child);
2348
- this.cacheDescendants(childKey, child);
2349
- }
2350
- }
2351
- resolveVal(v, scope) {
2352
- if (isSubst(v)) return this.resolveSubst(v, scope);
2353
- if (isConcat(v)) {
2354
- this.resolvingConcats.add(v);
2355
- try {
2356
- const concatResult = this.resolveConcat(v.nodes, scope, v.line, v.col);
2357
- return concatResult;
2358
- } finally {
2359
- this.resolvingConcats.delete(v);
2360
- }
2361
- }
2362
- if (isResObj(v)) return this.resolveResObj(v);
2363
- const hv = v;
2364
- if (hv.kind === "array") {
2365
- return {
2366
- kind: "array",
2367
- items: hv.items.map(
2368
- (item) => this.resolveVal(item, scope) ?? { kind: "scalar", raw: "null", valueType: "null" }
2369
- )
2370
- };
2371
- }
2372
- return hv;
2373
- }
2374
- resolveSubst(s, scope) {
2375
- if (s.knownAbsent) return void 0;
2376
- const key = s.listSuffix ? `${segmentsToKey(s.segments)}[]` : segmentsToKey(s.segments);
2377
- if (this.cache.has(key)) return this.cache.get(key);
2378
- if (this.resolving.has(key)) {
2379
- let prior;
2380
- if (s.segments.length > 1) {
2381
- const leafSeg = s.segments[s.segments.length - 1]?.text ?? "";
2382
- const parentScope = lookupResObj(
2383
- this.root,
2384
- s.segments.slice(0, s.segments.length - 1)
2385
- );
2386
- prior = parentScope?.priorValues.get(leafSeg);
2387
- } else {
2388
- const rootSeg = s.segments[0]?.text ?? "";
2389
- prior = scope.priorValues.get(rootSeg) ?? this.root.priorValues.get(rootSeg);
2390
- }
2391
- if (prior !== void 0) {
2392
- const saved = this.resolving;
2393
- this.resolving = new Set(saved);
2394
- try {
2395
- return this.resolveVal(prior, scope);
2396
- } finally {
2397
- this.resolving = saved;
2398
- }
2399
- }
2400
- if (s.optional) return void 0;
2401
- throw new ResolveError(
2402
- this.originPrefix() + `circular substitution: ${key}`,
2403
- key,
2404
- s.line,
2405
- s.col
2406
- );
2407
- }
2408
- this.resolving.add(key);
2409
- try {
2410
- const found = lookupPath(this.root, s.segments);
2411
- if (found !== void 0) {
2412
- const rfp = this.resolvingFieldPath;
2413
- const isOwner = rfp.length >= s.segments.length && s.segments.every((seg, i) => rfp[i] === seg.text);
2414
- const isSelfRef = isConcat(found) && this.resolvingConcats.has(found) || isOwner && containsSubstByPath(found, s.segments);
2415
- if (isSelfRef) {
2416
- let prior;
2417
- if (s.segments.length > 1) {
2418
- const leafSeg = s.segments[s.segments.length - 1]?.text ?? "";
2419
- const parentScope = lookupResObj(
2420
- this.root,
2421
- s.segments.slice(0, s.segments.length - 1)
2422
- );
2423
- prior = parentScope?.priorValues.get(leafSeg);
2424
- } else {
2425
- const rootSeg = s.segments[0]?.text ?? "";
2426
- prior = scope.priorValues.get(rootSeg) ?? this.root.priorValues.get(rootSeg);
2427
- }
2428
- if (prior !== void 0) {
2429
- const result2 = this.resolveVal(prior, scope);
2430
- if (result2 !== void 0) this.cache.set(key, result2);
2431
- return result2;
2432
- }
2433
- if (s.optional) return void 0;
2434
- throw new ResolveError(
2435
- `${this.originPrefix()}could not resolve substitution: \${${key}}`,
2436
- key,
2437
- s.line,
2438
- s.col
2439
- );
2440
- }
2441
- let result = this.resolveVal(found, scope);
2442
- const effectiveLen = s.segments.length - s.prefixLen;
2443
- if (effectiveLen === 1 && result !== void 0 && result.kind === "object") {
2444
- const leafSeg = s.segments[s.segments.length - 1]?.text ?? "";
2445
- let prior;
2446
- if (s.prefixLen > 0) {
2447
- const parentScope = lookupResObj(
2448
- this.root,
2449
- s.segments.slice(0, s.segments.length - 1)
2450
- );
2451
- prior = parentScope?.priorValues.get(leafSeg);
2452
- } else {
2453
- prior = scope.priorValues.get(leafSeg) ?? this.root.priorValues.get(leafSeg);
2454
- }
2455
- if (prior !== void 0) {
2456
- const priorResolved = this.resolveVal(prior, scope);
2457
- if (priorResolved !== void 0 && priorResolved.kind === "object") {
2458
- result = deepMergeHoconValues(
2459
- priorResolved,
2460
- result
2461
- );
2462
- }
2463
- }
2464
- }
2465
- if (result !== void 0) this.cache.set(key, result);
2466
- return result;
2467
- }
2468
- if (s.prefixLen > 0 && s.segments.length > s.prefixLen) {
2469
- const originalSegments = s.segments.slice(s.prefixLen);
2470
- const fallbackFound = lookupPath(this.root, originalSegments);
2471
- if (fallbackFound !== void 0) {
2472
- let result = this.resolveVal(fallbackFound, scope);
2473
- if (originalSegments.length === 1 && result !== void 0 && result.kind === "object") {
2474
- const rootSeg = originalSegments[0]?.text ?? "";
2475
- const prior = this.root.priorValues.get(rootSeg);
2476
- if (prior !== void 0) {
2477
- const priorResolved = this.resolveVal(prior, scope);
2478
- if (priorResolved !== void 0 && priorResolved.kind === "object") {
2479
- result = deepMergeHoconValues(
2480
- priorResolved,
2481
- result
2482
- );
2483
- }
2484
- }
2485
- }
2486
- if (result !== void 0) this.cache.set(key, result);
2487
- return result;
2488
- }
2489
- }
2490
- if (s.listSuffix && this.opts.useSystemEnvironment !== false) {
2491
- const result = this.resolveEnvList(s);
2492
- if (result !== void 0) {
2493
- this.cache.set(key, result);
2494
- return result;
2495
- }
2496
- if (s.optional) return void 0;
2497
- const envBase = s.segments.map((seg) => seg.text).join(".");
2498
- throw new ResolveError(
2499
- `${this.originPrefix()}could not resolve substitution: \${${key}} (no environment variables ${envBase}_0, ${envBase}_1, \u2026 set)`,
2500
- key,
2501
- s.line,
2502
- s.col
2503
- );
2504
- } else if (s.listSuffix) {
2505
- if (s.optional) return void 0;
2506
- if (this.opts.allowUnresolved) return s;
2507
- throw new ResolveError(
2508
- `${this.originPrefix()}could not resolve substitution: \${${key}}`,
2509
- key,
2510
- s.line,
2511
- s.col
2512
- );
2513
- }
2514
- if (this.opts.useSystemEnvironment !== false) {
2515
- const envKey = s.segments.map((seg) => seg.text).join(".");
2516
- const envVal = this.opts.env[envKey] ?? (s.prefixLen > 0 ? this.opts.env[s.segments.slice(s.prefixLen).map((seg) => seg.text).join(".")] : void 0);
2517
- if (envVal !== void 0) {
2518
- const result = { kind: "scalar", raw: envVal, valueType: "string" };
2519
- this.cache.set(key, result);
2520
- return result;
2521
- }
2522
- }
2523
- if (s.optional) return void 0;
2524
- if (this.opts.allowUnresolved) {
2525
- return s;
2526
- }
2527
- throw new ResolveError(
2528
- `${this.originPrefix()}could not resolve substitution: \${${key}}`,
2529
- key,
2530
- s.line,
2531
- s.col
2532
- );
2533
- } finally {
2534
- this.resolving.delete(key);
2535
- }
2536
- }
2537
- /**
2538
- * S13c: scan environment for NAME_0, NAME_1, … and return an Array<Scalar(String)>.
2539
- *
2540
- * Candidate bases follow the same fully-qualified→bare order used by the scalar
2541
- * env fallback. The first base whose _0 key is present wins entirely — no
2542
- * cross-base merging (spec §Relativized fallback precedence rules).
2543
- *
2544
- * Returns the HoconValue Array if any candidate base has _0, or undefined if
2545
- * none do (caller applies optional/required handling).
2546
- */
2547
- resolveEnvList(s) {
2548
- const bases = this.candidateBases(s);
2549
- for (const base of bases) {
2550
- const key0 = base + "_0";
2551
- if (!(key0 in this.opts.env)) continue;
2552
- const items = [];
2553
- for (let i = 0; ; i++) {
2554
- const k = base + "_" + i;
2555
- if (!(k in this.opts.env)) break;
2556
- items.push({ kind: "scalar", raw: this.opts.env[k], valueType: "string" });
2557
- }
2558
- return { kind: "array", items };
2559
- }
2560
- return void 0;
2561
- }
2562
- /**
2563
- * Return the candidate base names for env-var-list lookup, in precedence order.
2564
- * Mirrors the fully-qualified→bare fallback used by the scalar env path.
2565
- */
2566
- candidateBases(s) {
2567
- const full = s.segments.map((seg) => seg.text).join(".");
2568
- if (s.prefixLen === 0) return [full];
2569
- const bare = s.segments.slice(s.prefixLen).map((seg) => seg.text).join(".");
2570
- return [full, bare];
2571
- }
2572
- resolveConcat(nodes, scope, line = 0, col = 0) {
2573
- const rawResolved = nodes.map((n) => this.resolveVal(n, scope));
2574
- if (this.opts.allowUnresolved) {
2575
- for (const v of rawResolved) {
2576
- if (v !== void 0 && isSubst(v)) {
2577
- return v;
2578
- }
2579
- }
2580
- }
2581
- const resolved = rawResolved.filter((v) => v !== void 0);
2582
- if (resolved.length === 0) return void 0;
2583
- if (resolved.length === 1) return resolved[0];
2584
- const nonSep = resolved.filter((v) => !separatorValues.has(v));
2585
- if (nonSep.length === 0) {
2586
- const str = resolved.map((v) => v.kind === "scalar" ? v.raw : JSON.stringify(v)).join("");
2587
- return { kind: "scalar", raw: str, valueType: "string" };
2588
- }
2589
- const joinPair = (left, right) => {
2590
- if (left.kind === "object" && right.kind === "object") {
2591
- return deepMergeHoconValues(left, right);
2592
- }
2593
- if (left.kind === "array" && right.kind === "object") {
2594
- const converted = numericObjectToArray(right);
2595
- if (converted !== null) {
2596
- return { kind: "array", items: [...left.items, ...converted] };
2597
- }
2598
- throw new ResolveError(
2599
- "cannot concatenate array with object: value concatenation requires same-kind operands (S10.4)",
2600
- "",
2601
- line,
2602
- col
2603
- );
2604
- }
2605
- if (left.kind === "object" && right.kind === "array") {
2606
- const converted = numericObjectToArray(left);
2607
- if (converted !== null) {
2608
- return { kind: "array", items: [...converted, ...right.items] };
2609
- }
2610
- throw new ResolveError(
2611
- "cannot concatenate object with array: value concatenation requires same-kind operands (S10.4)",
2612
- "",
2613
- line,
2614
- col
2615
- );
2616
- }
2617
- if (left.kind === "array" && right.kind === "array") {
2618
- return { kind: "array", items: [...left.items, ...right.items] };
2619
- }
2620
- if (left.kind === "array" || right.kind === "array") {
2621
- throw new ResolveError(
2622
- `cannot concatenate ${left.kind} with ${right.kind}: arrays and objects may not appear in string value concatenation (S10.13)`,
2623
- "",
2624
- line,
2625
- col
2626
- );
2627
- }
2628
- if (left.kind === "object" || right.kind === "object") {
2629
- throw new ResolveError(
2630
- `cannot concatenate ${left.kind} with ${right.kind}: arrays and objects may not appear in string value concatenation (S10.13)`,
2631
- "",
2632
- line,
2633
- col
2634
- );
2635
- }
2636
- return { kind: "scalar", raw: left.raw + right.raw, valueType: "string" };
2637
- };
2638
- const [head, ...tail] = nonSep;
2639
- const folded = tail.reduce(joinPair, head);
2640
- if (folded.kind === "scalar") {
2641
- const str = resolved.map((v) => v.kind === "scalar" ? v.raw : JSON.stringify(v)).join("");
2642
- return { kind: "scalar", raw: str, valueType: "string" };
2643
- }
2644
- return folded;
2645
- }
2646
- };
2647
6
 
2648
- // src/internal/resolver/resolver.ts
2649
- function buildTree(ast, opts) {
2650
- return new StructureBuilder(opts).build(ast);
2651
- }
2652
- function resolveTree(tree, opts) {
2653
- return new SubstitutionResolver(tree, opts).resolve();
2654
- }
2655
- function containsPlaceholders(tree) {
2656
- for (const val of tree.fields.values()) {
2657
- if (valContainsPlaceholders(val)) return true;
2658
- }
2659
- return false;
7
+
8
+
9
+
10
+
11
+ var _chunkRO4D6BH7cjs = require('./chunk-RO4D6BH7.cjs');
12
+
13
+ // src/zod.ts
14
+ var _zod2 = require('zod');
15
+ function validate(config, schema) {
16
+ requireResolved(config, "");
17
+ const plain = config.toObject();
18
+ refusePrototypeKeys(plain);
19
+ const coerced = coerceValue(plain, schema);
20
+ return schema.parse(coerced);
2660
21
  }
2661
- function valContainsPlaceholders(v) {
2662
- const rv = v;
2663
- if (isSubst(rv) || isConcat(rv)) return true;
2664
- if (isResObj(rv)) return containsPlaceholders(rv);
2665
- const hv = v;
2666
- if (hv?.kind === "array") {
2667
- return hv.items.some((item) => valContainsPlaceholders(item));
2668
- }
2669
- return false;
22
+ function getValidated(config, path, schema) {
23
+ requireResolved(config, path);
24
+ const val = config.get(path);
25
+ refusePrototypeKeys(val);
26
+ const coerced = coerceValue(val, schema);
27
+ return schema.parse(coerced);
2670
28
  }
2671
- function buildPartialHoconFromResObj(tree) {
2672
- const fields = /* @__PURE__ */ new Map();
2673
- for (const [k, v] of tree.fields) {
2674
- if (!isSubst(v) && !isConcat(v)) {
2675
- if (isResObj(v)) {
2676
- fields.set(k, buildPartialHoconFromResObj(v));
29
+ function requireResolved(config, path) {
30
+ config.getValue(path);
31
+ }
32
+ var PROTOTYPE_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
33
+ function refusePrototypeKeys(value) {
34
+ const issues = [];
35
+ collectPrototypeKeys(value, [], issues);
36
+ if (issues.length > 0) throw new _zod2.z.ZodError(issues);
37
+ }
38
+ function collectPrototypeKeys(value, path, issues) {
39
+ if (Array.isArray(value)) {
40
+ value.forEach((item, i) => collectPrototypeKeys(item, [...path, i], issues));
41
+ } else if (typeof value === "object" && value !== null) {
42
+ for (const [key, item] of Object.entries(value)) {
43
+ if (PROTOTYPE_KEYS.has(key)) {
44
+ issues.push({
45
+ code: "custom",
46
+ path,
47
+ message: `key ${JSON.stringify(key)} names an object's prototype`,
48
+ params: { key }
49
+ });
2677
50
  } else {
2678
- if (!valContainsPlaceholders(v)) {
2679
- fields.set(k, v);
2680
- }
51
+ collectPrototypeKeys(item, [...path, key], issues);
2681
52
  }
2682
53
  }
2683
54
  }
2684
- return { kind: "object", fields };
2685
55
  }
2686
- function hoconValueToResObj2(value) {
2687
- const obj = makeResObj();
2688
- for (const [k, v] of value.fields) {
2689
- if (v.kind === "object") {
2690
- obj.fields.set(k, hoconValueToResObj2(v));
2691
- } else {
2692
- obj.fields.set(k, v);
56
+ function unitMarker(what, read) {
57
+ return _zod2.z.transform((input, ctx) => {
58
+ if (typeof input !== "string" && typeof input !== "number") {
59
+ ctx.issues.push({ code: "custom", message: `expected ${what}, got ${describeInput(input)}`, input });
60
+ return _zod2.z.NEVER;
2693
61
  }
62
+ const text = typeof input === "string" ? input : String(input);
63
+ const reading = read(text);
64
+ if (reading.ok) return reading.value;
65
+ ctx.issues.push({ code: "custom", message: unitProblemMessage(what, reading.problem, text), input });
66
+ return _zod2.z.NEVER;
67
+ });
68
+ }
69
+ function unitProblemMessage(what, problem, text) {
70
+ switch (problem) {
71
+ case "invalid":
72
+ return `invalid ${what}: ${JSON.stringify(text)}`;
73
+ case "negative":
74
+ return `${what} must be non-negative: ${JSON.stringify(text)}`;
75
+ case "overflow":
76
+ return `${what} overflows the representable range: ${JSON.stringify(text)}`;
2694
77
  }
2695
- return obj;
2696
78
  }
2697
- function resolve2(ast, opts) {
2698
- const tree = buildTree(ast, opts);
2699
- return resolveTree(tree, { ...opts, useSystemEnvironment: true, allowUnresolved: false });
79
+ function describeInput(input) {
80
+ if (input === null) return "null";
81
+ if (Array.isArray(input)) return "array";
82
+ return typeof input;
2700
83
  }
2701
-
2702
- // src/config.ts
2703
- var Config = class _Config {
2704
- constructor(root, opts) {
2705
- this.root = root;
2706
- this._resolved = opts?.resolved ?? true;
2707
- this._parseBaseDir = opts?.parseBaseDir;
2708
- this._originDescription = opts?.originDescription;
2709
- this._resObjRoot = opts?.resObjRoot;
2710
- this._resolveOpts = opts?.resolveOpts;
2711
- }
2712
- /** Returns true when the Config's value tree contains no unresolved
2713
- * substitution placeholders. Whole-config granularity (E12 decision 11). */
2714
- isResolved() {
2715
- return this._resolved;
2716
- }
2717
- /** @internal Test-only: construct a resolved Config from a HoconValue. */
2718
- static _fromResolvedValue(root, opts) {
2719
- return new _Config(root, { resolved: true, originDescription: opts?.originDescription });
2720
- }
2721
- /** @internal Construct an unresolved Config carrying a ResObj tree.
2722
- * Used by parseStringWithOptions (deferred path) in T6. */
2723
- static _fromUnresolvedResObj(tree, opts) {
2724
- const partialRoot = buildPartialHoconFromResObj(tree);
2725
- return new _Config(partialRoot, {
2726
- resolved: opts.resolved,
2727
- parseBaseDir: opts.parseBaseDir,
2728
- originDescription: opts.originDescription,
2729
- resObjRoot: tree,
2730
- resolveOpts: opts.resolveOpts
2731
- });
2732
- }
2733
- get(path2) {
2734
- const v = this.lookupNode(path2);
2735
- if (v === void 0) return void 0;
2736
- return hoconToJs(v);
2737
- }
2738
- /**
2739
- * Returns the raw {@link HoconValue} node at `path` as a deeply-immutable
2740
- * {@link ReadonlyHoconValue} view, or `undefined` if the path is absent. Unlike
2741
- * `get` (which decodes to a plain JS value), this exposes the value tree for
2742
- * structural introspection via the `value.ts` accessors (`asString`, `asObject`,
2743
- * `isScalar`, …).
2744
- *
2745
- * `getValue('')` returns the root object node.
2746
- *
2747
- * Throws {@link NotResolvedError} when the node (or its subtree) is unresolved:
2748
- * the `HoconValue` union has no placeholder variant, so an unresolved value
2749
- * cannot be represented. This matches `getConfig` / `getList`.
2750
- */
2751
- getValue(path2) {
2752
- const v = this.lookupNode(path2);
2753
- if (v === void 0) {
2754
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path2)) {
2755
- throw new NotResolvedError(path2);
2756
- }
2757
- return void 0;
2758
- }
2759
- if (v.kind !== "scalar" && !this._resolved && this._resObjRootSubtreeHasPlaceholders(path2)) {
2760
- throw new NotResolvedError(path2);
2761
- }
2762
- return v;
2763
- }
2764
- getString(path2) {
2765
- const v = this.requireScalar(path2);
2766
- if (v.valueType === "null") {
2767
- throw new ConfigError(`expected string at ${path2}, got ${v.valueType}`, path2);
2768
- }
2769
- return v.raw;
2770
- }
2771
- getNumber(path2) {
2772
- const v = this.requireScalar(path2);
2773
- const coerced = coerceNumber(v.raw);
2774
- if (coerced !== void 0) return coerced;
2775
- throw new ConfigError(`expected number at ${path2}, got ${v.valueType}`, path2);
2776
- }
2777
- getBoolean(path2) {
2778
- const v = this.requireScalar(path2);
2779
- const coerced = coerceBoolean(v.raw);
2780
- if (coerced !== void 0) return coerced;
2781
- throw new ConfigError(`expected boolean at ${path2}, got ${v.valueType}`, path2);
2782
- }
2783
- getDuration(path2, unit) {
2784
- const v = this.requireScalar(path2);
2785
- if (v.valueType !== "string" && v.valueType !== "number") {
2786
- throw new ConfigError(`expected duration at ${path2}, got ${v.valueType}`, path2);
2787
- }
2788
- const result = parseDuration(v.raw, unit);
2789
- if (Number.isNaN(result)) throw new ConfigError(`invalid duration at ${path2}: ${JSON.stringify(v.raw)}`, path2);
2790
- return result;
2791
- }
2792
- getBytes(path2, unit) {
2793
- const v = this.requireScalar(path2);
2794
- if (v.valueType !== "string" && v.valueType !== "number") {
2795
- throw new ConfigError(`expected byte size at ${path2}, got ${v.valueType}`, path2);
2796
- }
2797
- const result = parseBytes(v.raw, unit);
2798
- if (Number.isNaN(result)) throw new ConfigError(`invalid byte size at ${path2}: ${JSON.stringify(v.raw)}`, path2);
2799
- if (result < 0) throw new ConfigError(`byte size must be non-negative at ${path2}: ${JSON.stringify(v.raw)}`, path2);
2800
- return result;
2801
- }
2802
- getConfig(path2) {
2803
- const v = this.lookupNode(path2);
2804
- if (v === void 0) {
2805
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path2)) {
2806
- throw new NotResolvedError(path2);
2807
- }
2808
- throw new ConfigError(`path not found: ${path2}`, path2);
2809
- }
2810
- if (v.kind !== "object") throw new ConfigError(`expected object at ${path2}`, path2);
2811
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path2)) {
2812
- throw new NotResolvedError(path2);
2813
- }
2814
- return new _Config(v, { resolved: this._resolved });
2815
- }
2816
- getList(path2) {
2817
- const v = this.lookupNode(path2);
2818
- if (v === void 0) {
2819
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path2)) {
2820
- throw new NotResolvedError(path2);
2821
- }
2822
- throw new ConfigError(`path not found: ${path2}`, path2);
2823
- }
2824
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path2)) {
2825
- throw new NotResolvedError(path2);
2826
- }
2827
- if (v.kind === "object") {
2828
- const converted = numericObjectToArray(v);
2829
- if (converted !== null) return converted.map((item) => hoconToJs(item));
2830
- }
2831
- if (v.kind !== "array") throw new ConfigError(`expected array at ${path2}`, path2);
2832
- return v.items.map((item) => hoconToJs(item));
2833
- }
2834
- has(path2) {
2835
- return this.lookupNode(path2) !== void 0;
2836
- }
2837
- keys() {
2838
- return [...this.root.fields.keys()];
2839
- }
2840
- withFallback(fallback) {
2841
- if (fallback == null) return this;
2842
- const selfTree = this._resObjRoot ?? hoconValueToResObj2(this.root);
2843
- const fbTree = fallback._resObjRoot ?? hoconValueToResObj2(fallback.root);
2844
- const merged = mergeUnresolved(selfTree, fbTree);
2845
- const hasPlaceholders = containsPlaceholders(merged);
2846
- const partialRoot = buildPartialHoconFromResObj(merged);
2847
- return new _Config(partialRoot, {
2848
- resolved: !hasPlaceholders,
2849
- parseBaseDir: this._parseBaseDir,
2850
- originDescription: this._originDescription,
2851
- resObjRoot: merged,
2852
- resolveOpts: this._resolveOpts ?? fallback._resolveOpts
2853
- });
2854
- }
2855
- /**
2856
- * Runs substitution resolution (phase 2) on the stored unresolved tree.
2857
- * Idempotent: calling resolve() on an already-resolved Config returns an
2858
- * equivalent resolved Config.
2859
- *
2860
- * opts.allowUnresolved (default false) — when true, leaves unresolved
2861
- * non-optional placeholders in place rather than throwing.
2862
- * opts.useSystemEnvironment (default true) — when false, env var lookups
2863
- * are suppressed (hermetic resolution).
2864
- *
2865
- * E12 decision 3.
2866
- */
2867
- resolve(opts = {}) {
2868
- if (this._resolved) {
2869
- return new _Config(this.root, {
2870
- resolved: true,
2871
- parseBaseDir: this._parseBaseDir,
2872
- originDescription: this._originDescription
2873
- });
2874
- }
2875
- const tree = this._resObjRoot;
2876
- if (!tree) {
2877
- return new _Config(this.root, { resolved: true });
2878
- }
2879
- const resolveOpts = {
2880
- ...this._resolveOpts ?? { env: {}, baseDir: void 0, readFileSync: () => {
2881
- throw new Error("no files");
2882
- } },
2883
- allowUnresolved: opts.allowUnresolved ?? false,
2884
- useSystemEnvironment: opts.useSystemEnvironment ?? true,
2885
- originDescription: this._originDescription
2886
- };
2887
- const resolved = resolveTree(tree, resolveOpts);
2888
- if (resolved.kind !== "object") throw new Error("resolve: expected object root");
2889
- if (opts.allowUnresolved) {
2890
- const { stripped, hadPlaceholders } = stripPlaceholderFields(resolved);
2891
- return new _Config(stripped, {
2892
- resolved: !hadPlaceholders,
2893
- parseBaseDir: this._parseBaseDir,
2894
- originDescription: this._originDescription,
2895
- resObjRoot: hadPlaceholders ? tree : void 0,
2896
- resolveOpts: hadPlaceholders ? resolveOpts : void 0
2897
- });
2898
- }
2899
- return new _Config(resolved, {
2900
- resolved: true,
2901
- parseBaseDir: this._parseBaseDir,
2902
- originDescription: this._originDescription
2903
- });
2904
- }
2905
- /**
2906
- * Resolves receiver substitutions using source as lookup context.
2907
- * Source's keys are NOT merged into the result — differs from
2908
- * `this.withFallback(source).resolve()` which includes source keys.
2909
- *
2910
- * Precondition (E12 decision 10): source must be resolved. If
2911
- * source.isResolved() is false, throws NotResolvedError.
2912
- *
2913
- * On an already-resolved receiver, resolveWith is a no-op (returns an
2914
- * equivalent resolved Config, source keys not included).
2915
- *
2916
- * E12 decisions 9, 10.
2917
- */
2918
- resolveWith(source, opts = {}) {
2919
- if (!source.isResolved()) {
2920
- throw new NotResolvedError("source");
2921
- }
2922
- if (this._resolved) {
2923
- return new _Config(this.root, {
2924
- resolved: true,
2925
- parseBaseDir: this._parseBaseDir,
2926
- originDescription: this._originDescription
2927
- });
2928
- }
2929
- const receiverTree = this._resObjRoot ?? hoconValueToResObj2(this.root);
2930
- const srcTree = hoconValueToResObj2(source.root);
2931
- const merged = mergeUnresolved(receiverTree, srcTree);
2932
- const resolveOpts = {
2933
- ...this._resolveOpts ?? { env: {}, baseDir: void 0, readFileSync: () => {
2934
- throw new Error("no files");
2935
- } },
2936
- allowUnresolved: opts.allowUnresolved ?? false,
2937
- useSystemEnvironment: opts.useSystemEnvironment ?? true,
2938
- originDescription: this._originDescription
2939
- };
2940
- const resolved = resolveTree(merged, resolveOpts);
2941
- if (resolved.kind !== "object") throw new Error("resolveWith: expected object root");
2942
- const receiverShapeForFilter = resObjToKeyShape(receiverTree);
2943
- const filtered = filterByReceiverShape(resolved, receiverShapeForFilter);
2944
- if (opts.allowUnresolved) {
2945
- const { stripped, hadPlaceholders } = stripPlaceholderFields(filtered);
2946
- return new _Config(stripped, {
2947
- resolved: !hadPlaceholders,
2948
- parseBaseDir: this._parseBaseDir,
2949
- originDescription: this._originDescription,
2950
- resObjRoot: hadPlaceholders ? receiverTree : void 0,
2951
- resolveOpts: hadPlaceholders ? resolveOpts : void 0
2952
- });
2953
- }
2954
- return new _Config(filtered, {
2955
- resolved: true,
2956
- parseBaseDir: this._parseBaseDir,
2957
- originDescription: this._originDescription
2958
- });
2959
- }
84
+ var hocon = {
2960
85
  /**
2961
- * The whole config as plain JS data: objects, arrays, strings, numbers,
2962
- * booleans and `null`.
2963
- *
2964
- * Keys are reproduced exactly as the config carries them, `__proto__`,
2965
- * `constructor` and `prototype` included: each is defined as an **own data
2966
- * property**, so the returned object's prototype is always
2967
- * `Object.prototype`, and this call writes nothing to the global one.
2968
- *
2969
- * ### Passing the result to other code
2970
- *
2971
- * A config file — especially a `.properties` file or an env namespace you
2972
- * merged in — can therefore hand you an own `__proto__` key, and what happens
2973
- * next depends entirely on how the consumer copies it:
2974
- *
2975
- * ```ts
2976
- * const data = cfg.toObject()
2977
- * { ...data } // safe — own properties are copied as data
2978
- * structuredClone(data) // safe
2979
- * Object.assign({}, data) // NOT safe — [[Set]] on the {} target hits
2980
- * // Object.prototype's __proto__ setter: the key
2981
- * // vanishes and config data becomes the result's
2982
- * // prototype
2983
- * deepMerge({}, data) // NOT safe — a naive recursive merge reads
2984
- * // target['__proto__'], gets Object.prototype,
2985
- * // and writes to it: global pollution
2986
- * for (const k in data) … // prefer Object.entries / Object.keys
2987
- * ```
2988
- *
2989
- * Those two hazards come from the **destination** object's prototype, so no
2990
- * option here can disarm them — copy with spread or `structuredClone` instead.
2991
- *
2992
- * What `{ nullPrototype: true }` does give you is a result that inherits
2993
- * nothing: every object comes back with a `null` prototype, so reading
2994
- * `x.__proto__`, `x.constructor` or `x.toString` yields config data or
2995
- * `undefined` rather than something from `Object.prototype`, and code that
2996
- * merges *into* this object cannot climb out of it. Keys are all still
2997
- * present. The trade-off is the usual one for prototype-less objects: not
2998
- * `instanceof Object`, and no `hasOwnProperty` of their own.
2999
- *
3000
- * Numbers follow the JS number model, so an integer wider than 2^53 rounds
3001
- * here even when the config holds it exactly — read those with
3002
- * {@link Config.getString} instead.
86
+ * A duration, read as {@link Config.getDuration} reads it (default unit `ms`),
87
+ * exponent forms included, except that a number literal with more
88
+ * significant digits than a double holds can read differently: the getter
89
+ * reads its text, the marker its JS value (`1.0000000000000001` in `us`:
90
+ * 1000.0000000000001 through the getter, 1000 here).
3003
91
  */
3004
- toObject(opts) {
3005
- return hoconToJs(this.root, opts?.nullPrototype === true);
3006
- }
92
+ duration(unit) {
93
+ return unitMarker("duration", (text) => _chunkRO4D6BH7cjs.readDuration.call(void 0, text, unit));
94
+ },
3007
95
  /**
3008
- * @internal Test-only: renders this resolved Config's value tree as canonical
3009
- * JSON (sorted keys, no whitespace). Used by Layer-2 fixture tests to compare
3010
- * against Lightbend ground truth. NOT part of the public API.
3011
- *
3012
- * Throws if the Config is unresolved (contains placeholders).
96
+ * A byte size, read as {@link Config.getBytes} reads it (default unit `B`),
97
+ * exponent forms included, except that a number literal with more
98
+ * significant digits than a double holds can read differently: the getter
99
+ * reads its text, the marker its JS value (`1.99999999999999999`: 1 through
100
+ * the getter, 2 here).
3013
101
  */
3014
- _renderJSONForTest() {
3015
- return renderHoconAsJSON(this.root);
3016
- }
3017
- lookupNode(path2) {
3018
- const segments = splitConfigPath(path2);
3019
- let current = this.root;
3020
- for (const seg of segments) {
3021
- if (current.kind !== "object") return void 0;
3022
- const next = current.fields.get(seg);
3023
- if (next === void 0) return void 0;
3024
- current = next;
3025
- }
3026
- return current;
3027
- }
102
+ bytes(unit) {
103
+ return unitMarker("byte size", (text) => _chunkRO4D6BH7cjs.readBytes.call(void 0, text, unit));
104
+ },
3028
105
  /**
3029
- * _resObjRootSubtreeHasPlaceholders — walk _resObjRoot to the given path and
3030
- * return true if the subtree there contains any unresolved placeholder.
3031
- * Used by getConfig / getList (T2) to detect transitive unresolved placeholders
3032
- * in object / array subtrees that would otherwise appear to be "resolved" in the
3033
- * partial HoconValue root (because individual leaf fields are omitted rather than
3034
- * the whole subtree when their value is a direct placeholder scalar, but object
3035
- * sub-containers are retained in the partial root with the placeholder-keyed
3036
- * fields omitted from them — so the object appears "present but empty-ish").
106
+ * A calendar period, read as {@link Config.getPeriod} reads it (a bare
107
+ * integer is days), except that a number literal with a decimal point or in
108
+ * exponent form (`7.0`, `1e2`) can read differently: the getter refuses it,
109
+ * the marker reads the JS number.
3037
110
  */
3038
- _resObjRootSubtreeHasPlaceholders(path2) {
3039
- const tree = this._resObjRoot;
3040
- if (!tree) return false;
3041
- const segments = splitConfigPath(path2);
3042
- let cur = tree;
3043
- for (const seg of segments) {
3044
- const val = cur.fields.get(seg);
3045
- if (val === void 0) return false;
3046
- if (isResObj(val)) {
3047
- cur = val;
3048
- } else {
3049
- return valContainsPlaceholders(val);
3050
- }
3051
- }
3052
- return containsPlaceholders(cur);
3053
- }
3054
- requireScalar(path2) {
3055
- const v = this.lookupNode(path2);
3056
- if (v === void 0) {
3057
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path2)) {
3058
- throw new NotResolvedError(path2);
3059
- }
3060
- throw new ConfigError(`path not found: ${path2}`, path2);
3061
- }
3062
- if (v.kind !== "scalar") throw new ConfigError(`expected scalar at ${path2}, got ${v.kind}`, path2);
3063
- return v;
111
+ period() {
112
+ return unitMarker("period", _chunkRO4D6BH7cjs.readPeriod);
3064
113
  }
3065
114
  };
3066
- function splitConfigPath(path2) {
3067
- const segments = [];
3068
- let i = 0;
3069
- while (i < path2.length) {
3070
- if (path2[i] === '"') {
3071
- i++;
3072
- let segment = "";
3073
- let closed = false;
3074
- while (i < path2.length) {
3075
- const ch = path2[i];
3076
- if (ch === "\\" && i + 1 < path2.length) {
3077
- const next = path2[i + 1];
3078
- segment += next;
3079
- i += 2;
3080
- continue;
3081
- }
3082
- if (ch === '"') {
3083
- closed = true;
3084
- i++;
3085
- break;
3086
- }
3087
- segment += ch;
3088
- i++;
3089
- }
3090
- if (!closed) throw new ConfigError(`unterminated quoted path segment: ${path2}`, path2);
3091
- segments.push(segment);
3092
- if (i < path2.length && path2[i] === ".") i++;
3093
- } else {
3094
- const dot = path2.indexOf(".", i);
3095
- if (dot === -1) {
3096
- segments.push(path2.slice(i));
3097
- break;
3098
- }
3099
- segments.push(path2.slice(i, dot));
3100
- i = dot + 1;
3101
- }
3102
- }
3103
- return segments;
3104
- }
3105
- function scalarToJs(raw, valueType) {
3106
- switch (valueType) {
3107
- case "null":
3108
- return null;
3109
- case "boolean":
3110
- return raw === "true";
3111
- case "number":
3112
- return Number(raw);
3113
- case "string":
3114
- return raw;
3115
- }
3116
- }
3117
- function hoconToJs(v, nullPrototype = false) {
3118
- switch (v.kind) {
3119
- case "scalar":
3120
- return scalarToJs(v.raw, v.valueType);
3121
- case "array":
3122
- return v.items.map((item) => hoconToJs(item, nullPrototype));
3123
- case "object": {
3124
- const entries = Array.from(v.fields, ([k, val]) => [k, hoconToJs(val, nullPrototype)]);
3125
- if (nullPrototype) {
3126
- const obj = /* @__PURE__ */ Object.create(null);
3127
- for (const [k, val] of entries) Object.defineProperty(obj, k, {
3128
- value: val,
3129
- writable: true,
3130
- enumerable: true,
3131
- configurable: true
3132
- });
3133
- return obj;
3134
- }
3135
- return Object.fromEntries(entries);
3136
- }
3137
- }
3138
- }
3139
- function resObjToKeyShape(tree) {
3140
- const fields = /* @__PURE__ */ new Map();
3141
- for (const [k, v] of tree.fields) {
3142
- if (isSubst(v) || isConcat(v)) {
3143
- fields.set(k, { kind: "scalar", raw: "", valueType: "null" });
3144
- } else if (isResObj(v)) {
3145
- fields.set(k, resObjToKeyShape(v));
3146
- } else {
3147
- fields.set(k, v);
3148
- }
3149
- }
3150
- return { kind: "object", fields };
3151
- }
3152
- function stripPlaceholderFields(v) {
3153
- const fields = /* @__PURE__ */ new Map();
3154
- let hadPlaceholders = false;
3155
- for (const [k, val] of v.fields) {
3156
- if (val._kind === "subst-placeholder" || val._kind === "concat-placeholder") {
3157
- hadPlaceholders = true;
3158
- } else if (val.kind === "object") {
3159
- const inner = stripPlaceholderFields(val);
3160
- if (inner.hadPlaceholders) hadPlaceholders = true;
3161
- fields.set(k, inner.stripped);
3162
- } else {
3163
- fields.set(k, val);
3164
- }
3165
- }
3166
- return { stripped: { kind: "object", fields }, hadPlaceholders };
3167
- }
3168
- function filterByReceiverShape(resolved, receiverShape) {
3169
- const fields = /* @__PURE__ */ new Map();
3170
- for (const [k, rv] of resolved.fields) {
3171
- if (!receiverShape.fields.has(k)) continue;
3172
- const receiverVal = receiverShape.fields.get(k);
3173
- if (rv.kind === "object" && receiverVal.kind === "object") {
3174
- fields.set(k, filterByReceiverShape(rv, receiverVal));
3175
- } else {
3176
- fields.set(k, rv);
3177
- }
3178
- }
3179
- return { kind: "object", fields };
3180
- }
3181
- function renderHoconAsJSON(v) {
3182
- switch (v.kind) {
3183
- case "scalar": {
3184
- switch (v.valueType) {
3185
- case "null":
3186
- return "null";
3187
- case "boolean":
3188
- return v.raw;
3189
- case "number": {
3190
- const norm = normalizeLeadingZeroNumber(v.raw);
3191
- return JSON_NUMBER_RE.test(norm) ? norm : JSON.stringify(v.raw);
3192
- }
3193
- case "string":
3194
- return JSON.stringify(v.raw);
3195
- }
3196
- break;
3197
- }
3198
- case "array": {
3199
- const items = v.items.map(renderHoconAsJSON);
3200
- return `[${items.join(",")}]`;
3201
- }
3202
- case "object": {
3203
- const keys = [...v.fields.keys()].sort();
3204
- const pairs = keys.map((k) => {
3205
- const val = v.fields.get(k);
3206
- return `${JSON.stringify(k)}:${renderHoconAsJSON(val)}`;
3207
- });
3208
- return `{${pairs.join(",")}}`;
3209
- }
3210
- }
3211
- throw new Error(`renderHoconAsJSON: unsupported value kind (unresolved placeholder?)`);
3212
- }
3213
- var JSON_NUMBER_RE = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
3214
- function normalizeLeadingZeroNumber(raw) {
3215
- return raw.replace(/^([+-]?)0+(\d)/, "$1$2");
3216
- }
3217
-
3218
- // src/parse.ts
3219
- function getEnv(opts) {
3220
- if (opts.env !== void 0) return opts.env;
3221
- if (typeof process !== "undefined" && process.env) return process.env;
3222
- return {};
3223
- }
3224
- function defaultReadFileSync(filePath) {
3225
- return fs.readFileSync(filePath, "utf-8");
3226
- }
3227
- function buildResolveContext(input, opts) {
3228
- const tokens = tokenize(input);
3229
- const ast = parseTokens(tokens);
3230
- if (ast.kind === "array") {
3231
- const origin = opts.originDescription ?? "input";
3232
- throw new ConfigError(
3233
- `${origin}: ${ast.pos.line}:${ast.pos.col}: document has type array rather than object at file root (HOCON.md L989-991); the Config API requires an object root`,
3234
- ""
3235
- );
3236
- }
3237
- const resolveOpts = {
3238
- env: getEnv(opts),
3239
- baseDir: opts.baseDir,
3240
- readFileSync: opts.readFileSync ?? defaultReadFileSync,
3241
- readFile: opts.readFile,
3242
- originDescription: opts.originDescription,
3243
- resolveFrom: opts.resolveFrom,
3244
- packageResolver: opts.packageResolver
3245
- };
3246
- return { ast, resolveOpts };
3247
- }
3248
- function parse(input, opts = {}) {
3249
- return parseStringWithOptions(input, opts);
3250
- }
3251
- function parseStringWithOptions(input, opts = {}) {
3252
- return guardStackDepth(
3253
- () => parseStringInner(input, opts),
3254
- (msg) => new ParseError(msg, 1, 1, opts.originDescription)
3255
- );
3256
- }
3257
- function parseStringInner(input, opts) {
3258
- const resolveSubstitutions = opts.resolveSubstitutions ?? true;
3259
- const { ast, resolveOpts } = buildResolveContext(input, opts);
3260
- if (resolveSubstitutions) {
3261
- const value = resolve2(ast, resolveOpts);
3262
- if (value.kind !== "object") throw new Error("resolved value is not an object");
3263
- return new Config(value, { resolved: true, originDescription: opts.originDescription });
3264
- }
3265
- const tree = buildTree(ast, resolveOpts);
3266
- const hasPlaceholders = containsPlaceholders(tree);
3267
- return Config._fromUnresolvedResObj(tree, {
3268
- parseBaseDir: opts.baseDir,
3269
- originDescription: opts.originDescription,
3270
- resolved: !hasPlaceholders,
3271
- resolveOpts
3272
- });
3273
- }
3274
- function parseFile(filePath, opts = {}) {
3275
- if (typeof process === "undefined" && !opts.readFileSync) {
3276
- throw new Error("parseFile is not supported in browser environments. Provide opts.readFileSync or use parse() instead.");
3277
- }
3278
- const resolvedPath = path.resolve(filePath);
3279
- const readFileSync2 = opts.readFileSync ?? defaultReadFileSync;
3280
- const input = readFileSync2(resolvedPath);
3281
- return parse(input, {
3282
- ...opts,
3283
- baseDir: opts.baseDir ?? path.dirname(resolvedPath),
3284
- readFileSync: readFileSync2
3285
- });
3286
- }
3287
-
3288
- // src/zod.ts
3289
- function validate(config, schema) {
3290
- const plain = config.toObject();
3291
- const coerced = coerceValue(plain, schema);
3292
- return schema.parse(coerced);
3293
- }
3294
- function getValidated(config, path2, schema) {
3295
- const val = config.get(path2);
3296
- const coerced = coerceValue(val, schema);
3297
- return schema.parse(coerced);
3298
- }
3299
115
  function getDefType(schema) {
3300
116
  const zod = schema._zod;
3301
- return zod?.def?.type;
117
+ return _optionalChain([zod, 'optionalAccess', _ => _.def, 'optionalAccess', _2 => _2.type]);
3302
118
  }
3303
119
  function getInnerSchema(schema) {
3304
- const def = schema._zod?.def;
3305
- return def?.innerType ?? def?.schema;
120
+ const def = _optionalChain([schema, 'access', _3 => _3._zod, 'optionalAccess', _4 => _4.def]);
121
+ return _nullishCoalesce(_optionalChain([def, 'optionalAccess', _5 => _5.innerType]), () => ( _optionalChain([def, 'optionalAccess', _6 => _6.schema])));
3306
122
  }
3307
123
  function getObjectShape(schema) {
3308
- const shape = schema._zod?.def?.shape;
124
+ const shape = _optionalChain([schema, 'access', _7 => _7._zod, 'optionalAccess', _8 => _8.def, 'optionalAccess', _9 => _9.shape]);
3309
125
  return typeof shape === "object" && shape !== null ? shape : void 0;
3310
126
  }
3311
127
  function getArrayElement(schema) {
3312
- return schema._zod?.def?.element;
128
+ return _optionalChain([schema, 'access', _10 => _10._zod, 'optionalAccess', _11 => _11.def, 'optionalAccess', _12 => _12.element]);
3313
129
  }
3314
130
  function parseWithSchema(input, schema, opts) {
3315
- const config = parse(input, opts);
131
+ const config = _chunkIMJ7QHIKcjs.parse.call(void 0, input, opts);
3316
132
  return validate(config, schema);
3317
133
  }
3318
134
  function parseFileWithSchema(filePath, schema, opts) {
3319
- const config = parseFile(filePath, opts);
135
+ const config = _chunkIMJ7QHIKcjs.parseFile.call(void 0, filePath, opts);
3320
136
  return validate(config, schema);
3321
137
  }
3322
138
  function coerceValue(value, schema) {
@@ -3326,13 +142,13 @@ function coerceValue(value, schema) {
3326
142
  switch (defType) {
3327
143
  case "boolean":
3328
144
  if (typeof value === "string") {
3329
- const coerced = coerceBoolean(value);
145
+ const coerced = _chunkRO4D6BH7cjs.coerceBoolean.call(void 0, value);
3330
146
  return coerced !== void 0 ? coerced : value;
3331
147
  }
3332
148
  return value;
3333
149
  case "number":
3334
150
  if (typeof value === "string") {
3335
- const coerced = coerceNumber(value);
151
+ const coerced = _chunkRO4D6BH7cjs.coerceNumber.call(void 0, value);
3336
152
  return coerced !== void 0 ? coerced : value;
3337
153
  }
3338
154
  return value;
@@ -3367,10 +183,10 @@ function coerceValue(value, schema) {
3367
183
  return value;
3368
184
  }
3369
185
  }
3370
- // Annotate the CommonJS export names for ESM import in node:
3371
- 0 && (module.exports = {
3372
- getValidated,
3373
- parseFileWithSchema,
3374
- parseWithSchema,
3375
- validate
3376
- });
186
+
187
+
188
+
189
+
190
+
191
+
192
+ exports.getValidated = getValidated; exports.hocon = hocon; exports.parseFileWithSchema = parseFileWithSchema; exports.parseWithSchema = parseWithSchema; exports.validate = validate;