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