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