@o3co/ts.hocon 1.12.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.ja.md +256 -32
  2. package/README.md +166 -32
  3. package/dist/adapters/env.cjs +26 -1678
  4. package/dist/adapters/env.d.cts +1 -1
  5. package/dist/adapters/env.d.ts +1 -1
  6. package/dist/adapters/env.js +11 -1625
  7. package/dist/adapters/json5.cjs +496 -0
  8. package/dist/adapters/json5.d.cts +47 -0
  9. package/dist/adapters/json5.d.ts +47 -0
  10. package/dist/adapters/json5.js +496 -0
  11. package/dist/adapters/jsonc.cjs +17 -1632
  12. package/dist/adapters/jsonc.d.cts +1 -1
  13. package/dist/adapters/jsonc.d.ts +1 -1
  14. package/dist/adapters/jsonc.js +9 -1586
  15. package/dist/adapters/properties.cjs +7 -1773
  16. package/dist/adapters/properties.d.cts +1 -1
  17. package/dist/adapters/properties.d.ts +1 -1
  18. package/dist/adapters/properties.js +6 -1735
  19. package/dist/adapters/toml.cjs +12 -1626
  20. package/dist/adapters/toml.d.cts +1 -1
  21. package/dist/adapters/toml.d.ts +1 -1
  22. package/dist/adapters/toml.js +10 -1589
  23. package/dist/adapters/yaml.cjs +20 -1635
  24. package/dist/adapters/yaml.d.cts +1 -1
  25. package/dist/adapters/yaml.d.ts +1 -1
  26. package/dist/adapters/yaml.js +10 -1589
  27. package/dist/chunk-GBNQADHT.cjs +83 -0
  28. package/dist/chunk-IMJ7QHIK.cjs +158 -0
  29. package/dist/chunk-QY7ECGS6.js +83 -0
  30. package/dist/chunk-RO4D6BH7.cjs +3792 -0
  31. package/dist/chunk-WTXULUZS.js +3792 -0
  32. package/dist/chunk-XWKO4JM3.js +158 -0
  33. package/dist/{config-Dlq6rF3w.d.cts → config-OccaKqXu.d.cts} +148 -4
  34. package/dist/{config-Dlq6rF3w.d.ts → config-OccaKqXu.d.ts} +148 -4
  35. package/dist/index.cjs +35 -3449
  36. package/dist/index.d.cts +2 -2
  37. package/dist/index.d.ts +2 -2
  38. package/dist/index.js +25 -3383
  39. package/dist/zod.cjs +107 -3291
  40. package/dist/zod.d.cts +83 -3
  41. package/dist/zod.d.ts +83 -3
  42. package/dist/zod.js +95 -3245
  43. package/package.json +12 -2
@@ -1,1589 +1,12 @@
1
- // src/coerce.ts
2
- var DECIMAL_NUMBER_RE = /^-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
3
- function isHoconWs(cp) {
4
- if (cp === 9 || cp === 10 || cp === 11 || cp === 12 || cp === 13) return true;
5
- if (cp >= 28 && cp <= 31) return true;
6
- if (cp === 32 || cp === 160 || cp === 65279) return true;
7
- if (cp === 5760) return true;
8
- if (cp >= 8192 && cp <= 8202) return true;
9
- if (cp === 8232 || cp === 8233 || cp === 8239 || cp === 8287) return true;
10
- if (cp === 12288) return true;
11
- return false;
12
- }
13
- function trimHoconWs(s) {
14
- let start = 0;
15
- let end = s.length;
16
- while (start < end && isHoconWs(s.charCodeAt(start))) {
17
- start++;
18
- }
19
- while (end > start && isHoconWs(s.charCodeAt(end - 1))) {
20
- end--;
21
- }
22
- return s.slice(start, end);
23
- }
24
- var TRUTHY = /* @__PURE__ */ new Set(["true", "yes", "on"]);
25
- var FALSY = /* @__PURE__ */ new Set(["false", "no", "off"]);
26
- function coerceBoolean(value) {
27
- const lower = value.toLowerCase();
28
- if (TRUTHY.has(lower)) return true;
29
- if (FALSY.has(lower)) return false;
30
- return void 0;
31
- }
32
- function coerceNumber(value) {
33
- if (!DECIMAL_NUMBER_RE.test(value)) return void 0;
34
- return Number(value);
35
- }
36
- var DURATION_UNITS = {
37
- ns: 1e-6,
38
- nanosecond: 1e-6,
39
- nanoseconds: 1e-6,
40
- us: 1e-3,
41
- microsecond: 1e-3,
42
- microseconds: 1e-3,
43
- ms: 1,
44
- millisecond: 1,
45
- milliseconds: 1,
46
- s: 1e3,
47
- second: 1e3,
48
- seconds: 1e3,
49
- m: 6e4,
50
- minute: 6e4,
51
- minutes: 6e4,
52
- h: 36e5,
53
- hour: 36e5,
54
- hours: 36e5,
55
- d: 864e5,
56
- day: 864e5,
57
- days: 864e5
58
- };
59
- var OUTPUT_DURATION_UNITS = {
60
- ns: 1e-6,
61
- us: 1e-3,
62
- ms: 1,
63
- s: 1e3,
64
- m: 6e4,
65
- h: 36e5,
66
- d: 864e5
67
- };
68
- function parseDuration(value, outputUnit = "ms") {
69
- const trimmed = trimHoconWs(value);
70
- let i = 0;
71
- while (i < trimmed.length) {
72
- const ch = trimmed[i];
73
- if (i === 0 && (ch === "-" || ch === "+")) {
74
- i++;
75
- continue;
76
- }
77
- if (ch !== "." && (ch < "0" || ch > "9")) break;
78
- i++;
79
- }
80
- if (i === 0) return NaN;
81
- const num = Number(trimmed.slice(0, i));
82
- if (Number.isNaN(num)) return NaN;
83
- const unit = trimHoconWs(trimmed.slice(i));
84
- const divisor = OUTPUT_DURATION_UNITS[outputUnit];
85
- if (divisor === void 0) return NaN;
86
- if (unit === "") {
87
- return num / divisor;
88
- }
89
- const mult = DURATION_UNITS[unit];
90
- if (mult === void 0) return NaN;
91
- const ms = num * mult;
92
- return ms / divisor;
93
- }
94
- var BYTE_UNITS = {
95
- B: 1,
96
- byte: 1,
97
- bytes: 1,
98
- KB: 1e3,
99
- kilobyte: 1e3,
100
- kilobytes: 1e3,
101
- KiB: 1024,
102
- kibibyte: 1024,
103
- kibibytes: 1024,
104
- MB: 1e6,
105
- megabyte: 1e6,
106
- megabytes: 1e6,
107
- MiB: 1048576,
108
- mebibyte: 1048576,
109
- mebibytes: 1048576,
110
- GB: 1e9,
111
- gigabyte: 1e9,
112
- gigabytes: 1e9,
113
- GiB: 1073741824,
114
- gibibyte: 1073741824,
115
- gibibytes: 1073741824,
116
- TB: 1e12,
117
- terabyte: 1e12,
118
- terabytes: 1e12,
119
- TiB: 1099511627776,
120
- tebibyte: 1099511627776,
121
- tebibytes: 1099511627776,
122
- // S21.4 — HOCON.md L1385: single-letter abbreviations → powers of two (java -Xmx convention).
123
- // Lightbend typesafe-config 1.4.3 verified: 1K=1024, 1M=1048576, etc.
124
- // Both upper- and lowercase accepted per Lightbend behaviour.
125
- // Z/Y (2^70/2^80) are deferred — they overflow MAX_SAFE_INTEGER and require BigInt accessor.
126
- K: 1024,
127
- k: 1024,
128
- M: 1024 ** 2,
129
- m: 1024 ** 2,
130
- G: 1024 ** 3,
131
- g: 1024 ** 3,
132
- T: 1024 ** 4,
133
- t: 1024 ** 4,
134
- P: 1024 ** 5,
135
- p: 1024 ** 5,
136
- E: 1024 ** 6,
137
- e: 1024 ** 6,
138
- // lowercase short-form aliases
139
- b: 1,
140
- kb: 1e3,
141
- kib: 1024,
142
- mb: 1e6,
143
- mib: 1048576,
144
- gb: 1e9,
145
- gib: 1073741824,
146
- tb: 1e12,
147
- tib: 1099511627776
148
- };
149
- var OUTPUT_BYTE_UNITS = {
150
- B: 1,
151
- KB: 1e3,
152
- KiB: 1024,
153
- MB: 1e6,
154
- MiB: 1048576,
155
- GB: 1e9,
156
- GiB: 1073741824,
157
- TB: 1e12,
158
- TiB: 1099511627776
159
- };
160
- function parseBytes(value, outputUnit = "B") {
161
- const trimmed = trimHoconWs(value);
162
- let i = 0;
163
- while (i < trimmed.length) {
164
- const ch = trimmed[i];
165
- if (i === 0 && (ch === "-" || ch === "+")) {
166
- i++;
167
- continue;
168
- }
169
- if (ch !== "." && (ch < "0" || ch > "9")) break;
170
- i++;
171
- }
172
- if (i === 0) return NaN;
173
- const num = Number(trimmed.slice(0, i));
174
- if (Number.isNaN(num)) return NaN;
175
- const unit = trimHoconWs(trimmed.slice(i));
176
- const divisor = OUTPUT_BYTE_UNITS[outputUnit];
177
- if (divisor === void 0) return NaN;
178
- if (unit === "") {
179
- const bytes2 = Math.trunc(num);
180
- if (Math.abs(bytes2) > Number.MAX_SAFE_INTEGER) {
181
- throw new RangeError("byte size overflows representable range (max 2^53-1 bytes)");
182
- }
183
- return bytes2 / divisor;
184
- }
185
- let mult = BYTE_UNITS[unit];
186
- if (mult === void 0) {
187
- mult = BYTE_UNITS[unit.toLowerCase()];
188
- }
189
- if (mult === void 0) return NaN;
190
- const bytes = num * mult;
191
- if (Math.abs(bytes) > Number.MAX_SAFE_INTEGER) {
192
- throw new RangeError("byte size overflows representable range (max 2^53-1 bytes)");
193
- }
194
- const result = bytes / divisor;
195
- return outputUnit === "B" ? Math.round(result) : result;
196
- }
197
-
198
- // src/errors.ts
199
- var ResolveError = class extends Error {
200
- constructor(message, path, line, col, file) {
201
- super(message);
202
- this.path = path;
203
- this.line = line;
204
- this.col = col;
205
- this.file = file;
206
- this.name = "ResolveError";
207
- }
208
- };
209
- var ConfigError = class extends Error {
210
- constructor(message, path) {
211
- super(message);
212
- this.path = path;
213
- this.name = "ConfigError";
214
- }
215
- };
216
- var NotResolvedError = class extends ConfigError {
217
- constructor(path) {
218
- super(`value at path "${path}" is not resolved (call resolve() first)`, path);
219
- this.name = "NotResolvedError";
220
- }
221
- };
222
-
223
- // src/internal/resolver/fold-self-ref.ts
224
- function substFullKey(s) {
225
- return stringSegmentsToKey(s.segments.map((seg) => seg.text));
226
- }
227
- function stringSegmentsToKey(segments) {
228
- return segments.map((t) => {
229
- if (t === "" || /[^a-zA-Z0-9\-_]/.test(t)) {
230
- return `"${t.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
231
- }
232
- return t;
233
- }).join(".");
234
- }
235
- function containsSelfRef(v, fullKey) {
236
- if (isSubst(v)) return !v.knownAbsent && substFullKey(v) === fullKey;
237
- if (isConcat(v)) return v.nodes.some((n) => containsSelfRef(n, fullKey));
238
- if (isResObj(v)) {
239
- for (const f of v.fields.values()) {
240
- if (containsSelfRef(f, fullKey)) return true;
241
- }
242
- return false;
243
- }
244
- const hv = v;
245
- if (hv.kind === "array") {
246
- return hv.items.some((item) => containsSelfRef(item, fullKey));
247
- }
248
- if (hv.kind === "object") {
249
- for (const f of hv.fields.values()) {
250
- if (containsSelfRef(f, fullKey)) return true;
251
- }
252
- return false;
253
- }
254
- return false;
255
- }
256
- function foldSelfRef(v, fullKey, replacement) {
257
- if (isSubst(v)) {
258
- return substFullKey(v) === fullKey ? replacement : v;
259
- }
260
- if (isConcat(v)) {
261
- return {
262
- _kind: "concat-placeholder",
263
- nodes: v.nodes.map((n) => foldSelfRef(n, fullKey, replacement)),
264
- line: v.line,
265
- col: v.col
266
- };
267
- }
268
- if (isResObj(v)) {
269
- const newFields = /* @__PURE__ */ new Map();
270
- for (const [k, val] of v.fields) {
271
- newFields.set(k, foldSelfRef(val, fullKey, replacement));
272
- }
273
- return { _kind: "res-obj", fields: newFields, priorValues: new Map(v.priorValues), resetKeys: new Set(v.resetKeys) };
274
- }
275
- const hv = v;
276
- if (hv.kind === "array") {
277
- return {
278
- kind: "array",
279
- items: hv.items.map((item) => foldSelfRef(item, fullKey, replacement))
280
- };
281
- }
282
- if (hv.kind === "object") {
283
- const newFields = /* @__PURE__ */ new Map();
284
- for (const [k, val] of hv.fields) {
285
- newFields.set(k, foldSelfRef(val, fullKey, replacement));
286
- }
287
- return { kind: "object", fields: newFields };
288
- }
289
- return v;
290
- }
291
- function foldOrSkipPrior(prior, fullKey, old) {
292
- if (!containsSelfRef(prior, fullKey)) return cloneResolverValue(prior);
293
- if (old === void 0) return foldOptionalSelfRefAbsent(prior, fullKey);
294
- return foldSelfRef(prior, fullKey, old);
295
- }
296
- function foldOptionalSelfRefAbsent(v, fullKey) {
297
- if (isSubst(v) && substFullKey(v) === fullKey) {
298
- if (!v.optional) return void 0;
299
- return {
300
- _kind: "subst-placeholder",
301
- segments: v.segments.map((seg) => ({ text: seg.text, line: seg.line, col: seg.col })),
302
- optional: v.optional,
303
- knownAbsent: true,
304
- listSuffix: v.listSuffix,
305
- line: v.line,
306
- col: v.col,
307
- prefixLen: v.prefixLen
308
- };
309
- }
310
- if (isConcat(v)) {
311
- const nodes = [];
312
- for (const node of v.nodes) {
313
- const folded = foldOptionalSelfRefAbsent(node, fullKey);
314
- if (folded === void 0) return void 0;
315
- nodes.push(folded);
316
- }
317
- return { _kind: "concat-placeholder", nodes, line: v.line, col: v.col };
318
- }
319
- if (isResObj(v)) {
320
- const fields = /* @__PURE__ */ new Map();
321
- for (const [key, value] of v.fields) {
322
- const folded = foldOptionalSelfRefAbsent(value, fullKey);
323
- if (folded === void 0) return void 0;
324
- fields.set(key, folded);
325
- }
326
- return { _kind: "res-obj", fields, priorValues: new Map(v.priorValues), resetKeys: new Set(v.resetKeys) };
327
- }
328
- const hv = v;
329
- if (hv.kind === "array") {
330
- const items = [];
331
- for (const item of hv.items) {
332
- const folded = foldOptionalSelfRefAbsent(item, fullKey);
333
- if (folded === void 0) return void 0;
334
- items.push(folded);
335
- }
336
- return { kind: "array", items };
337
- }
338
- if (hv.kind === "object") {
339
- const fields = /* @__PURE__ */ new Map();
340
- for (const [key, value] of hv.fields) {
341
- const folded = foldOptionalSelfRefAbsent(value, fullKey);
342
- if (folded === void 0) return void 0;
343
- fields.set(key, folded);
344
- }
345
- return { kind: "object", fields };
346
- }
347
- return cloneResolverValue(v);
348
- }
349
- function cloneResolverValue(v) {
350
- if (isSubst(v)) {
351
- return {
352
- _kind: "subst-placeholder",
353
- segments: v.segments.map((seg) => ({ text: seg.text, line: seg.line, col: seg.col })),
354
- optional: v.optional,
355
- knownAbsent: v.knownAbsent,
356
- listSuffix: v.listSuffix,
357
- line: v.line,
358
- col: v.col,
359
- prefixLen: v.prefixLen
360
- };
361
- }
362
- if (isConcat(v)) {
363
- return {
364
- _kind: "concat-placeholder",
365
- nodes: v.nodes.map((n) => cloneResolverValue(n)),
366
- line: v.line,
367
- col: v.col
368
- };
369
- }
370
- if (isResObj(v)) {
371
- const newFields = /* @__PURE__ */ new Map();
372
- for (const [k, val] of v.fields) newFields.set(k, cloneResolverValue(val));
373
- const newPriors = /* @__PURE__ */ new Map();
374
- for (const [k, val] of v.priorValues) newPriors.set(k, cloneResolverValue(val));
375
- return { _kind: "res-obj", fields: newFields, priorValues: newPriors, resetKeys: new Set(v.resetKeys) };
376
- }
377
- const hv = v;
378
- if (hv.kind === "array") {
379
- return {
380
- kind: "array",
381
- items: hv.items.map((item) => cloneResolverValue(item))
382
- };
383
- }
384
- if (hv.kind === "object") {
385
- const newFields = /* @__PURE__ */ new Map();
386
- for (const [k, val] of hv.fields) {
387
- newFields.set(k, cloneResolverValue(val));
388
- }
389
- return { kind: "object", fields: newFields };
390
- }
391
- return hv;
392
- }
393
- function containsSubstByPath(v, target) {
394
- if (isSubst(v)) return !v.knownAbsent && segmentsTextEqual(v.segments, target);
395
- if (isConcat(v)) return v.nodes.some((n) => containsSubstByPath(n, target));
396
- if (isResObj(v)) {
397
- for (const f of v.fields.values()) {
398
- if (containsSubstByPath(f, target)) return true;
399
- }
400
- return false;
401
- }
402
- const hv = v;
403
- if (hv.kind === "array") {
404
- return hv.items.some((item) => containsSubstByPath(item, target));
405
- }
406
- if (hv.kind === "object") {
407
- for (const f of hv.fields.values()) {
408
- if (containsSubstByPath(f, target)) return true;
409
- }
410
- return false;
411
- }
412
- return false;
413
- }
414
- function segmentsTextEqual(a, b) {
415
- if (a.length !== b.length) return false;
416
- for (let i = 0; i < a.length; i++) {
417
- const ai = a[i];
418
- const bi = b[i];
419
- if (ai === void 0 || bi === void 0 || ai.text !== bi.text) return false;
420
- }
421
- return true;
422
- }
423
-
424
- // src/internal/resolver/types.ts
425
- var separatorValues = /* @__PURE__ */ new WeakSet();
426
- function isSubst(v) {
427
- return v._kind === "subst-placeholder";
428
- }
429
- function isConcat(v) {
430
- return v._kind === "concat-placeholder";
431
- }
432
- function isResObj(v) {
433
- return v._kind === "res-obj";
434
- }
435
- function makeResObj() {
436
- return { _kind: "res-obj", fields: /* @__PURE__ */ new Map(), priorValues: /* @__PURE__ */ new Map(), resetKeys: /* @__PURE__ */ new Set() };
437
- }
438
- function mergeUnresolved(receiver, fallback) {
439
- const result = makeResObj();
440
- for (const [k, v] of fallback.fields) {
441
- result.fields.set(k, v);
442
- }
443
- for (const [k, v] of fallback.priorValues) {
444
- result.priorValues.set(k, v);
445
- }
446
- for (const [k, rv] of receiver.fields) {
447
- const existing = result.fields.get(k);
448
- if (existing !== void 0) {
449
- const recPrior = receiver.priorValues.get(k);
450
- if (recPrior !== void 0 && !isResObj(recPrior)) {
451
- result.fields.set(k, rv);
452
- continue;
453
- }
454
- if (isResObj(rv) && isResObj(existing)) {
455
- result.fields.set(k, mergeUnresolved(rv, existing));
456
- continue;
457
- }
458
- const foldedPrior = foldOrSkipPrior(existing, k, void 0);
459
- if (foldedPrior !== void 0) result.priorValues.set(k, foldedPrior);
460
- }
461
- result.fields.set(k, rv);
462
- }
463
- for (const [k, v] of receiver.priorValues) {
464
- if (receiver.fields.has(k)) {
465
- result.priorValues.set(k, v);
466
- }
467
- }
468
- return result;
469
- }
470
-
471
- // src/internal/resolver/utils.ts
472
- function segmentsToKey(segments) {
473
- return segments.map((s) => {
474
- const t = s.text;
475
- if (t === "" || /[^a-zA-Z0-9\-_]/.test(t)) {
476
- return `"${t.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
477
- }
478
- return t;
479
- }).join(".");
480
- }
481
- function lookupPath(root, segments) {
482
- const [head, ...tail] = segments;
483
- if (head === void 0) return void 0;
484
- const key = head.text;
485
- const val = root.fields.get(key);
486
- if (val === void 0) return void 0;
487
- if (tail.length === 0) return val;
488
- if (isResObj(val)) return lookupPath(val, tail);
489
- return void 0;
490
- }
491
- function lookupResObj(root, segments) {
492
- let cur = root;
493
- for (const seg of segments) {
494
- const val = cur.fields.get(seg.text);
495
- if (val === void 0 || !isResObj(val)) return void 0;
496
- cur = val;
497
- }
498
- return cur;
499
- }
500
- function deepMergeHoconValues(base, overlay) {
501
- const merged = new Map(base.fields);
502
- for (const [k, v] of overlay.fields) {
503
- const existing = merged.get(k);
504
- if (existing?.kind === "object" && v.kind === "object") {
505
- merged.set(k, deepMergeHoconValues(existing, v));
506
- } else {
507
- merged.set(k, v);
508
- }
509
- }
510
- return { kind: "object", fields: merged };
511
- }
512
-
513
- // src/internal/resolver/include-loader.ts
514
- import { createRequire } from "module";
515
- import * as nodePath from "path";
516
- import { pathToFileURL } from "url";
517
-
518
- // src/internal/strip-bom.ts
519
- function stripBom(input) {
520
- return input.charCodeAt(0) === 65279 ? input.slice(1) : input;
521
- }
522
-
523
- // src/internal/depth.ts
524
- function guardStackDepth(fn, wrap) {
525
- try {
526
- return fn();
527
- } catch (e) {
528
- if (!isStackOverflow(e)) throw e;
529
- throw wrap(STACK_MESSAGE);
530
- }
531
- }
532
- var STACK_MESSAGE = "input is nested too deeply for this engine's stack, or contains a cycle (flatten the document, or break the cycle)";
533
- function isStackOverflow(e) {
534
- if (!(e instanceof RangeError)) return false;
535
- const m = e.message.toLowerCase();
536
- return m.includes("call stack") || // V8: "Maximum call stack size exceeded"
537
- m.includes("recursion") || // SpiderMonkey: "too much recursion"
538
- m.includes("stack overflow");
539
- }
540
- function depthError(message) {
541
- return new ConfigError(message, "");
542
- }
543
-
544
- // src/value/numeric-array.ts
545
- function numericObjectToArray(value) {
546
- if (value.kind !== "object") return null;
547
- if (value.fields.size === 0) return null;
548
- const canonicalInt = /^(0|[1-9][0-9]*)$/;
549
- const eligible = [];
550
- for (const [key, val] of value.fields) {
551
- if (!canonicalInt.test(key)) continue;
552
- const n = Number(key);
553
- if (!Number.isInteger(n) || n > 2147483647) continue;
554
- eligible.push({ n, v: val });
555
- }
556
- if (eligible.length === 0) return null;
557
- eligible.sort((a, b) => a.n - b.n);
558
- return eligible.map((e) => e.v);
559
- }
560
-
561
- // src/internal/resolver/substitution-resolver.ts
562
- var SubstitutionResolver = class {
563
- constructor(root, opts) {
564
- this.root = root;
565
- this.opts = opts;
566
- this.resolving = /* @__PURE__ */ new Set();
567
- this.cache = /* @__PURE__ */ new Map();
568
- // Tracks ConcatPlaceholder nodes currently being iterated by resolveConcat.
569
- // Used by isSelfRef detection: fires only when found === a concat currently
570
- // mid-iteration (i.e. we are inside found's own resolution), preventing the
571
- // "foofoo" double-count without misfiring when an external field looks up the
572
- // same concat via a substitution (multi-reviewer convergence fix).
573
- //
574
- // Spec deviation: the S13a.13 spec ★1 decision #1 specified path-equality
575
- // preservation for self-ref detection. Round-2 multi-agent-review surfaced a
576
- // false-positive on external lookups (`a = ${?a}foo; b = ${a}`), so the
577
- // criterion was tightened to node-membership-in-iterating-set — strictly
578
- // narrower than path-equality. Spec amendment deferred to a follow-up
579
- // xx.hocon PR (see Phase 6 #3f close-out notes).
580
- this.resolvingConcats = /* @__PURE__ */ new WeakSet();
581
- // Path stack tracking the full dotted path of the field currently being
582
- // assigned in `resolveResObj`. Leaf keys are pushed on entry to each
583
- // `(key, val)` iteration and popped on exit, so nested objects build up
584
- // the full path (e.g. `["o", "history"]` while resolving `o.history`).
585
- //
586
- // Used to tighten self-ref detection at the L192 found-lookup site:
587
- // a substitution `${X}` whose looked-up value contains a Subst pointing
588
- // at `X` is only a true self-reference when the field currently being
589
- // assigned is `X` (or a descendant of `X`). Without this guard, an
590
- // external lookup like `b = ${o}` (where o has a self-referential
591
- // field) would mis-fire and short-circuit to o's prior, returning the
592
- // wrong value for b. The is_owner gate (rfp prefix-matches s.segments)
593
- // narrows the check to the owner case only.
594
- //
595
- // Cross-impl with rs.hocon v1.5.1's resolving_field_path (same purpose,
596
- // same prefix-match semantics).
597
- this.resolvingFieldPath = [];
598
- }
599
- /** Returns a prefix for error messages, including origin info when set. */
600
- originPrefix() {
601
- return this.opts.originDescription ? `${this.opts.originDescription}: ` : "";
602
- }
603
- resolve() {
604
- return this.resolveResObj(this.root);
605
- }
606
- resolveResObj(obj) {
607
- const result = /* @__PURE__ */ new Map();
608
- for (const [key, val] of obj.fields) {
609
- this.resolvingFieldPath.push(key);
610
- const fullCacheKey = stringSegmentsToKey(this.resolvingFieldPath);
611
- this.cache.delete(fullCacheKey);
612
- let resolved;
613
- try {
614
- resolved = this.resolveVal(val, obj);
615
- } finally {
616
- this.resolvingFieldPath.pop();
617
- }
618
- if (resolved !== void 0) {
619
- if (resolved.kind === "object") {
620
- const prior = obj.priorValues.get(key);
621
- if (prior !== void 0) {
622
- const priorResolved = this.resolveVal(prior, obj);
623
- if (priorResolved !== void 0 && priorResolved.kind === "object") {
624
- const finalValue = deepMergeHoconValues(
625
- priorResolved,
626
- resolved
627
- );
628
- result.set(key, finalValue);
629
- this.cache.set(fullCacheKey, finalValue);
630
- this.cacheDescendants(fullCacheKey, finalValue);
631
- continue;
632
- }
633
- }
634
- }
635
- result.set(key, resolved);
636
- this.cache.set(fullCacheKey, resolved);
637
- this.cacheDescendants(fullCacheKey, resolved);
638
- } else {
639
- const prior = obj.priorValues.get(key);
640
- if (prior !== void 0) {
641
- const priorResolved = this.resolveVal(prior, obj);
642
- if (priorResolved !== void 0) {
643
- result.set(key, priorResolved);
644
- this.cache.set(fullCacheKey, priorResolved);
645
- this.cacheDescendants(fullCacheKey, priorResolved);
646
- }
647
- }
648
- }
649
- }
650
- return { kind: "object", fields: result };
651
- }
652
- cacheDescendants(prefix, value) {
653
- if (value.kind !== "object") return;
654
- for (const [key, child] of value.fields) {
655
- const childKey = `${prefix}.${stringSegmentsToKey([key])}`;
656
- this.cache.set(childKey, child);
657
- this.cacheDescendants(childKey, child);
658
- }
659
- }
660
- resolveVal(v, scope) {
661
- if (isSubst(v)) return this.resolveSubst(v, scope);
662
- if (isConcat(v)) {
663
- this.resolvingConcats.add(v);
664
- try {
665
- const concatResult = this.resolveConcat(v.nodes, scope, v.line, v.col);
666
- return concatResult;
667
- } finally {
668
- this.resolvingConcats.delete(v);
669
- }
670
- }
671
- if (isResObj(v)) return this.resolveResObj(v);
672
- const hv = v;
673
- if (hv.kind === "array") {
674
- return {
675
- kind: "array",
676
- items: hv.items.map(
677
- (item) => this.resolveVal(item, scope) ?? { kind: "scalar", raw: "null", valueType: "null" }
678
- )
679
- };
680
- }
681
- return hv;
682
- }
683
- resolveSubst(s, scope) {
684
- if (s.knownAbsent) return void 0;
685
- const key = s.listSuffix ? `${segmentsToKey(s.segments)}[]` : segmentsToKey(s.segments);
686
- if (this.cache.has(key)) return this.cache.get(key);
687
- if (this.resolving.has(key)) {
688
- let prior;
689
- if (s.segments.length > 1) {
690
- const leafSeg = s.segments[s.segments.length - 1]?.text ?? "";
691
- const parentScope = lookupResObj(
692
- this.root,
693
- s.segments.slice(0, s.segments.length - 1)
694
- );
695
- prior = parentScope?.priorValues.get(leafSeg);
696
- } else {
697
- const rootSeg = s.segments[0]?.text ?? "";
698
- prior = scope.priorValues.get(rootSeg) ?? this.root.priorValues.get(rootSeg);
699
- }
700
- if (prior !== void 0) {
701
- const saved = this.resolving;
702
- this.resolving = new Set(saved);
703
- try {
704
- return this.resolveVal(prior, scope);
705
- } finally {
706
- this.resolving = saved;
707
- }
708
- }
709
- if (s.optional) return void 0;
710
- throw new ResolveError(
711
- this.originPrefix() + `circular substitution: ${key}`,
712
- key,
713
- s.line,
714
- s.col
715
- );
716
- }
717
- this.resolving.add(key);
718
- try {
719
- const found = lookupPath(this.root, s.segments);
720
- if (found !== void 0) {
721
- const rfp = this.resolvingFieldPath;
722
- const isOwner = rfp.length >= s.segments.length && s.segments.every((seg, i) => rfp[i] === seg.text);
723
- const isSelfRef = isConcat(found) && this.resolvingConcats.has(found) || isOwner && containsSubstByPath(found, s.segments);
724
- if (isSelfRef) {
725
- let prior;
726
- if (s.segments.length > 1) {
727
- const leafSeg = s.segments[s.segments.length - 1]?.text ?? "";
728
- const parentScope = lookupResObj(
729
- this.root,
730
- s.segments.slice(0, s.segments.length - 1)
731
- );
732
- prior = parentScope?.priorValues.get(leafSeg);
733
- } else {
734
- const rootSeg = s.segments[0]?.text ?? "";
735
- prior = scope.priorValues.get(rootSeg) ?? this.root.priorValues.get(rootSeg);
736
- }
737
- if (prior !== void 0) {
738
- const result2 = this.resolveVal(prior, scope);
739
- if (result2 !== void 0) this.cache.set(key, result2);
740
- return result2;
741
- }
742
- if (s.optional) return void 0;
743
- throw new ResolveError(
744
- `${this.originPrefix()}could not resolve substitution: \${${key}}`,
745
- key,
746
- s.line,
747
- s.col
748
- );
749
- }
750
- let result = this.resolveVal(found, scope);
751
- const effectiveLen = s.segments.length - s.prefixLen;
752
- if (effectiveLen === 1 && result !== void 0 && result.kind === "object") {
753
- const leafSeg = s.segments[s.segments.length - 1]?.text ?? "";
754
- let prior;
755
- if (s.prefixLen > 0) {
756
- const parentScope = lookupResObj(
757
- this.root,
758
- s.segments.slice(0, s.segments.length - 1)
759
- );
760
- prior = parentScope?.priorValues.get(leafSeg);
761
- } else {
762
- prior = scope.priorValues.get(leafSeg) ?? this.root.priorValues.get(leafSeg);
763
- }
764
- if (prior !== void 0) {
765
- const priorResolved = this.resolveVal(prior, scope);
766
- if (priorResolved !== void 0 && priorResolved.kind === "object") {
767
- result = deepMergeHoconValues(
768
- priorResolved,
769
- result
770
- );
771
- }
772
- }
773
- }
774
- if (result !== void 0) this.cache.set(key, result);
775
- return result;
776
- }
777
- if (s.prefixLen > 0 && s.segments.length > s.prefixLen) {
778
- const originalSegments = s.segments.slice(s.prefixLen);
779
- const fallbackFound = lookupPath(this.root, originalSegments);
780
- if (fallbackFound !== void 0) {
781
- let result = this.resolveVal(fallbackFound, scope);
782
- if (originalSegments.length === 1 && result !== void 0 && result.kind === "object") {
783
- const rootSeg = originalSegments[0]?.text ?? "";
784
- const prior = this.root.priorValues.get(rootSeg);
785
- if (prior !== void 0) {
786
- const priorResolved = this.resolveVal(prior, scope);
787
- if (priorResolved !== void 0 && priorResolved.kind === "object") {
788
- result = deepMergeHoconValues(
789
- priorResolved,
790
- result
791
- );
792
- }
793
- }
794
- }
795
- if (result !== void 0) this.cache.set(key, result);
796
- return result;
797
- }
798
- }
799
- if (s.listSuffix && this.opts.useSystemEnvironment !== false) {
800
- const result = this.resolveEnvList(s);
801
- if (result !== void 0) {
802
- this.cache.set(key, result);
803
- return result;
804
- }
805
- if (s.optional) return void 0;
806
- const envBase = s.segments.map((seg) => seg.text).join(".");
807
- throw new ResolveError(
808
- `${this.originPrefix()}could not resolve substitution: \${${key}} (no environment variables ${envBase}_0, ${envBase}_1, \u2026 set)`,
809
- key,
810
- s.line,
811
- s.col
812
- );
813
- } else if (s.listSuffix) {
814
- if (s.optional) return void 0;
815
- if (this.opts.allowUnresolved) return s;
816
- throw new ResolveError(
817
- `${this.originPrefix()}could not resolve substitution: \${${key}}`,
818
- key,
819
- s.line,
820
- s.col
821
- );
822
- }
823
- if (this.opts.useSystemEnvironment !== false) {
824
- const envKey = s.segments.map((seg) => seg.text).join(".");
825
- const envVal = this.opts.env[envKey] ?? (s.prefixLen > 0 ? this.opts.env[s.segments.slice(s.prefixLen).map((seg) => seg.text).join(".")] : void 0);
826
- if (envVal !== void 0) {
827
- const result = { kind: "scalar", raw: envVal, valueType: "string" };
828
- this.cache.set(key, result);
829
- return result;
830
- }
831
- }
832
- if (s.optional) return void 0;
833
- if (this.opts.allowUnresolved) {
834
- return s;
835
- }
836
- throw new ResolveError(
837
- `${this.originPrefix()}could not resolve substitution: \${${key}}`,
838
- key,
839
- s.line,
840
- s.col
841
- );
842
- } finally {
843
- this.resolving.delete(key);
844
- }
845
- }
846
- /**
847
- * S13c: scan environment for NAME_0, NAME_1, … and return an Array<Scalar(String)>.
848
- *
849
- * Candidate bases follow the same fully-qualified→bare order used by the scalar
850
- * env fallback. The first base whose _0 key is present wins entirely — no
851
- * cross-base merging (spec §Relativized fallback precedence rules).
852
- *
853
- * Returns the HoconValue Array if any candidate base has _0, or undefined if
854
- * none do (caller applies optional/required handling).
855
- */
856
- resolveEnvList(s) {
857
- const bases = this.candidateBases(s);
858
- for (const base of bases) {
859
- const key0 = base + "_0";
860
- if (!(key0 in this.opts.env)) continue;
861
- const items = [];
862
- for (let i = 0; ; i++) {
863
- const k = base + "_" + i;
864
- if (!(k in this.opts.env)) break;
865
- items.push({ kind: "scalar", raw: this.opts.env[k], valueType: "string" });
866
- }
867
- return { kind: "array", items };
868
- }
869
- return void 0;
870
- }
871
- /**
872
- * Return the candidate base names for env-var-list lookup, in precedence order.
873
- * Mirrors the fully-qualified→bare fallback used by the scalar env path.
874
- */
875
- candidateBases(s) {
876
- const full = s.segments.map((seg) => seg.text).join(".");
877
- if (s.prefixLen === 0) return [full];
878
- const bare = s.segments.slice(s.prefixLen).map((seg) => seg.text).join(".");
879
- return [full, bare];
880
- }
881
- resolveConcat(nodes, scope, line = 0, col = 0) {
882
- const rawResolved = nodes.map((n) => this.resolveVal(n, scope));
883
- if (this.opts.allowUnresolved) {
884
- for (const v of rawResolved) {
885
- if (v !== void 0 && isSubst(v)) {
886
- return v;
887
- }
888
- }
889
- }
890
- const resolved = rawResolved.filter((v) => v !== void 0);
891
- if (resolved.length === 0) return void 0;
892
- if (resolved.length === 1) return resolved[0];
893
- const nonSep = resolved.filter((v) => !separatorValues.has(v));
894
- if (nonSep.length === 0) {
895
- const str = resolved.map((v) => v.kind === "scalar" ? v.raw : JSON.stringify(v)).join("");
896
- return { kind: "scalar", raw: str, valueType: "string" };
897
- }
898
- const joinPair = (left, right) => {
899
- if (left.kind === "object" && right.kind === "object") {
900
- return deepMergeHoconValues(left, right);
901
- }
902
- if (left.kind === "array" && right.kind === "object") {
903
- const converted = numericObjectToArray(right);
904
- if (converted !== null) {
905
- return { kind: "array", items: [...left.items, ...converted] };
906
- }
907
- throw new ResolveError(
908
- "cannot concatenate array with object: value concatenation requires same-kind operands (S10.4)",
909
- "",
910
- line,
911
- col
912
- );
913
- }
914
- if (left.kind === "object" && right.kind === "array") {
915
- const converted = numericObjectToArray(left);
916
- if (converted !== null) {
917
- return { kind: "array", items: [...converted, ...right.items] };
918
- }
919
- throw new ResolveError(
920
- "cannot concatenate object with array: value concatenation requires same-kind operands (S10.4)",
921
- "",
922
- line,
923
- col
924
- );
925
- }
926
- if (left.kind === "array" && right.kind === "array") {
927
- return { kind: "array", items: [...left.items, ...right.items] };
928
- }
929
- if (left.kind === "array" || right.kind === "array") {
930
- throw new ResolveError(
931
- `cannot concatenate ${left.kind} with ${right.kind}: arrays and objects may not appear in string value concatenation (S10.13)`,
932
- "",
933
- line,
934
- col
935
- );
936
- }
937
- if (left.kind === "object" || right.kind === "object") {
938
- throw new ResolveError(
939
- `cannot concatenate ${left.kind} with ${right.kind}: arrays and objects may not appear in string value concatenation (S10.13)`,
940
- "",
941
- line,
942
- col
943
- );
944
- }
945
- return { kind: "scalar", raw: left.raw + right.raw, valueType: "string" };
946
- };
947
- const [head, ...tail] = nonSep;
948
- const folded = tail.reduce(joinPair, head);
949
- if (folded.kind === "scalar") {
950
- const str = resolved.map((v) => v.kind === "scalar" ? v.raw : JSON.stringify(v)).join("");
951
- return { kind: "scalar", raw: str, valueType: "string" };
952
- }
953
- return folded;
954
- }
955
- };
956
-
957
- // src/internal/resolver/resolver.ts
958
- function resolveTree(tree, opts) {
959
- return new SubstitutionResolver(tree, opts).resolve();
960
- }
961
- function containsPlaceholders(tree) {
962
- for (const val of tree.fields.values()) {
963
- if (valContainsPlaceholders(val)) return true;
964
- }
965
- return false;
966
- }
967
- function valContainsPlaceholders(v) {
968
- const rv = v;
969
- if (isSubst(rv) || isConcat(rv)) return true;
970
- if (isResObj(rv)) return containsPlaceholders(rv);
971
- const hv = v;
972
- if (hv?.kind === "array") {
973
- return hv.items.some((item) => valContainsPlaceholders(item));
974
- }
975
- return false;
976
- }
977
- function buildPartialHoconFromResObj(tree) {
978
- const fields = /* @__PURE__ */ new Map();
979
- for (const [k, v] of tree.fields) {
980
- if (!isSubst(v) && !isConcat(v)) {
981
- if (isResObj(v)) {
982
- fields.set(k, buildPartialHoconFromResObj(v));
983
- } else {
984
- if (!valContainsPlaceholders(v)) {
985
- fields.set(k, v);
986
- }
987
- }
988
- }
989
- }
990
- return { kind: "object", fields };
991
- }
992
- function hoconValueToResObj2(value) {
993
- const obj = makeResObj();
994
- for (const [k, v] of value.fields) {
995
- if (v.kind === "object") {
996
- obj.fields.set(k, hoconValueToResObj2(v));
997
- } else {
998
- obj.fields.set(k, v);
999
- }
1000
- }
1001
- return obj;
1002
- }
1003
-
1004
- // src/config.ts
1005
- var Config = class _Config {
1006
- constructor(root, opts) {
1007
- this.root = root;
1008
- this._resolved = opts?.resolved ?? true;
1009
- this._parseBaseDir = opts?.parseBaseDir;
1010
- this._originDescription = opts?.originDescription;
1011
- this._resObjRoot = opts?.resObjRoot;
1012
- this._resolveOpts = opts?.resolveOpts;
1013
- }
1014
- /** Returns true when the Config's value tree contains no unresolved
1015
- * substitution placeholders. Whole-config granularity (E12 decision 11). */
1016
- isResolved() {
1017
- return this._resolved;
1018
- }
1019
- /** @internal Test-only: construct a resolved Config from a HoconValue. */
1020
- static _fromResolvedValue(root, opts) {
1021
- return new _Config(root, { resolved: true, originDescription: opts?.originDescription });
1022
- }
1023
- /** @internal Construct an unresolved Config carrying a ResObj tree.
1024
- * Used by parseStringWithOptions (deferred path) in T6. */
1025
- static _fromUnresolvedResObj(tree, opts) {
1026
- const partialRoot = buildPartialHoconFromResObj(tree);
1027
- return new _Config(partialRoot, {
1028
- resolved: opts.resolved,
1029
- parseBaseDir: opts.parseBaseDir,
1030
- originDescription: opts.originDescription,
1031
- resObjRoot: tree,
1032
- resolveOpts: opts.resolveOpts
1033
- });
1034
- }
1035
- get(path) {
1036
- const v = this.lookupNode(path);
1037
- if (v === void 0) return void 0;
1038
- return hoconToJs(v);
1039
- }
1040
- /**
1041
- * Returns the raw {@link HoconValue} node at `path` as a deeply-immutable
1042
- * {@link ReadonlyHoconValue} view, or `undefined` if the path is absent. Unlike
1043
- * `get` (which decodes to a plain JS value), this exposes the value tree for
1044
- * structural introspection via the `value.ts` accessors (`asString`, `asObject`,
1045
- * `isScalar`, …).
1046
- *
1047
- * `getValue('')` returns the root object node.
1048
- *
1049
- * Throws {@link NotResolvedError} when the node (or its subtree) is unresolved:
1050
- * the `HoconValue` union has no placeholder variant, so an unresolved value
1051
- * cannot be represented. This matches `getConfig` / `getList`.
1052
- */
1053
- getValue(path) {
1054
- const v = this.lookupNode(path);
1055
- if (v === void 0) {
1056
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1057
- throw new NotResolvedError(path);
1058
- }
1059
- return void 0;
1060
- }
1061
- if (v.kind !== "scalar" && !this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1062
- throw new NotResolvedError(path);
1063
- }
1064
- return v;
1065
- }
1066
- getString(path) {
1067
- const v = this.requireScalar(path);
1068
- if (v.valueType === "null") {
1069
- throw new ConfigError(`expected string at ${path}, got ${v.valueType}`, path);
1070
- }
1071
- return v.raw;
1072
- }
1073
- getNumber(path) {
1074
- const v = this.requireScalar(path);
1075
- const coerced = coerceNumber(v.raw);
1076
- if (coerced !== void 0) return coerced;
1077
- throw new ConfigError(`expected number at ${path}, got ${v.valueType}`, path);
1078
- }
1079
- getBoolean(path) {
1080
- const v = this.requireScalar(path);
1081
- const coerced = coerceBoolean(v.raw);
1082
- if (coerced !== void 0) return coerced;
1083
- throw new ConfigError(`expected boolean at ${path}, got ${v.valueType}`, path);
1084
- }
1085
- getDuration(path, unit) {
1086
- const v = this.requireScalar(path);
1087
- if (v.valueType !== "string" && v.valueType !== "number") {
1088
- throw new ConfigError(`expected duration at ${path}, got ${v.valueType}`, path);
1089
- }
1090
- const result = parseDuration(v.raw, unit);
1091
- if (Number.isNaN(result)) throw new ConfigError(`invalid duration at ${path}: ${JSON.stringify(v.raw)}`, path);
1092
- return result;
1093
- }
1094
- getBytes(path, unit) {
1095
- const v = this.requireScalar(path);
1096
- if (v.valueType !== "string" && v.valueType !== "number") {
1097
- throw new ConfigError(`expected byte size at ${path}, got ${v.valueType}`, path);
1098
- }
1099
- const result = parseBytes(v.raw, unit);
1100
- if (Number.isNaN(result)) throw new ConfigError(`invalid byte size at ${path}: ${JSON.stringify(v.raw)}`, path);
1101
- if (result < 0) throw new ConfigError(`byte size must be non-negative at ${path}: ${JSON.stringify(v.raw)}`, path);
1102
- return result;
1103
- }
1104
- getConfig(path) {
1105
- const v = this.lookupNode(path);
1106
- if (v === void 0) {
1107
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1108
- throw new NotResolvedError(path);
1109
- }
1110
- throw new ConfigError(`path not found: ${path}`, path);
1111
- }
1112
- if (v.kind !== "object") throw new ConfigError(`expected object at ${path}`, path);
1113
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1114
- throw new NotResolvedError(path);
1115
- }
1116
- return new _Config(v, { resolved: this._resolved });
1117
- }
1118
- getList(path) {
1119
- const v = this.lookupNode(path);
1120
- if (v === void 0) {
1121
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1122
- throw new NotResolvedError(path);
1123
- }
1124
- throw new ConfigError(`path not found: ${path}`, path);
1125
- }
1126
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1127
- throw new NotResolvedError(path);
1128
- }
1129
- if (v.kind === "object") {
1130
- const converted = numericObjectToArray(v);
1131
- if (converted !== null) return converted.map((item) => hoconToJs(item));
1132
- }
1133
- if (v.kind !== "array") throw new ConfigError(`expected array at ${path}`, path);
1134
- return v.items.map((item) => hoconToJs(item));
1135
- }
1136
- has(path) {
1137
- return this.lookupNode(path) !== void 0;
1138
- }
1139
- keys() {
1140
- return [...this.root.fields.keys()];
1141
- }
1142
- withFallback(fallback) {
1143
- if (fallback == null) return this;
1144
- const selfTree = this._resObjRoot ?? hoconValueToResObj2(this.root);
1145
- const fbTree = fallback._resObjRoot ?? hoconValueToResObj2(fallback.root);
1146
- const merged = mergeUnresolved(selfTree, fbTree);
1147
- const hasPlaceholders = containsPlaceholders(merged);
1148
- const partialRoot = buildPartialHoconFromResObj(merged);
1149
- return new _Config(partialRoot, {
1150
- resolved: !hasPlaceholders,
1151
- parseBaseDir: this._parseBaseDir,
1152
- originDescription: this._originDescription,
1153
- resObjRoot: merged,
1154
- resolveOpts: this._resolveOpts ?? fallback._resolveOpts
1155
- });
1156
- }
1157
- /**
1158
- * Runs substitution resolution (phase 2) on the stored unresolved tree.
1159
- * Idempotent: calling resolve() on an already-resolved Config returns an
1160
- * equivalent resolved Config.
1161
- *
1162
- * opts.allowUnresolved (default false) — when true, leaves unresolved
1163
- * non-optional placeholders in place rather than throwing.
1164
- * opts.useSystemEnvironment (default true) — when false, env var lookups
1165
- * are suppressed (hermetic resolution).
1166
- *
1167
- * E12 decision 3.
1168
- */
1169
- resolve(opts = {}) {
1170
- if (this._resolved) {
1171
- return new _Config(this.root, {
1172
- resolved: true,
1173
- parseBaseDir: this._parseBaseDir,
1174
- originDescription: this._originDescription
1175
- });
1176
- }
1177
- const tree = this._resObjRoot;
1178
- if (!tree) {
1179
- return new _Config(this.root, { resolved: true });
1180
- }
1181
- const resolveOpts = {
1182
- ...this._resolveOpts ?? { env: {}, baseDir: void 0, readFileSync: () => {
1183
- throw new Error("no files");
1184
- } },
1185
- allowUnresolved: opts.allowUnresolved ?? false,
1186
- useSystemEnvironment: opts.useSystemEnvironment ?? true,
1187
- originDescription: this._originDescription
1188
- };
1189
- const resolved = resolveTree(tree, resolveOpts);
1190
- if (resolved.kind !== "object") throw new Error("resolve: expected object root");
1191
- if (opts.allowUnresolved) {
1192
- const { stripped, hadPlaceholders } = stripPlaceholderFields(resolved);
1193
- return new _Config(stripped, {
1194
- resolved: !hadPlaceholders,
1195
- parseBaseDir: this._parseBaseDir,
1196
- originDescription: this._originDescription,
1197
- resObjRoot: hadPlaceholders ? tree : void 0,
1198
- resolveOpts: hadPlaceholders ? resolveOpts : void 0
1199
- });
1200
- }
1201
- return new _Config(resolved, {
1202
- resolved: true,
1203
- parseBaseDir: this._parseBaseDir,
1204
- originDescription: this._originDescription
1205
- });
1206
- }
1207
- /**
1208
- * Resolves receiver substitutions using source as lookup context.
1209
- * Source's keys are NOT merged into the result — differs from
1210
- * `this.withFallback(source).resolve()` which includes source keys.
1211
- *
1212
- * Precondition (E12 decision 10): source must be resolved. If
1213
- * source.isResolved() is false, throws NotResolvedError.
1214
- *
1215
- * On an already-resolved receiver, resolveWith is a no-op (returns an
1216
- * equivalent resolved Config, source keys not included).
1217
- *
1218
- * E12 decisions 9, 10.
1219
- */
1220
- resolveWith(source, opts = {}) {
1221
- if (!source.isResolved()) {
1222
- throw new NotResolvedError("source");
1223
- }
1224
- if (this._resolved) {
1225
- return new _Config(this.root, {
1226
- resolved: true,
1227
- parseBaseDir: this._parseBaseDir,
1228
- originDescription: this._originDescription
1229
- });
1230
- }
1231
- const receiverTree = this._resObjRoot ?? hoconValueToResObj2(this.root);
1232
- const srcTree = hoconValueToResObj2(source.root);
1233
- const merged = mergeUnresolved(receiverTree, srcTree);
1234
- const resolveOpts = {
1235
- ...this._resolveOpts ?? { env: {}, baseDir: void 0, readFileSync: () => {
1236
- throw new Error("no files");
1237
- } },
1238
- allowUnresolved: opts.allowUnresolved ?? false,
1239
- useSystemEnvironment: opts.useSystemEnvironment ?? true,
1240
- originDescription: this._originDescription
1241
- };
1242
- const resolved = resolveTree(merged, resolveOpts);
1243
- if (resolved.kind !== "object") throw new Error("resolveWith: expected object root");
1244
- const receiverShapeForFilter = resObjToKeyShape(receiverTree);
1245
- const filtered = filterByReceiverShape(resolved, receiverShapeForFilter);
1246
- if (opts.allowUnresolved) {
1247
- const { stripped, hadPlaceholders } = stripPlaceholderFields(filtered);
1248
- return new _Config(stripped, {
1249
- resolved: !hadPlaceholders,
1250
- parseBaseDir: this._parseBaseDir,
1251
- originDescription: this._originDescription,
1252
- resObjRoot: hadPlaceholders ? receiverTree : void 0,
1253
- resolveOpts: hadPlaceholders ? resolveOpts : void 0
1254
- });
1255
- }
1256
- return new _Config(filtered, {
1257
- resolved: true,
1258
- parseBaseDir: this._parseBaseDir,
1259
- originDescription: this._originDescription
1260
- });
1261
- }
1262
- /**
1263
- * The whole config as plain JS data: objects, arrays, strings, numbers,
1264
- * booleans and `null`.
1265
- *
1266
- * Keys are reproduced exactly as the config carries them, `__proto__`,
1267
- * `constructor` and `prototype` included: each is defined as an **own data
1268
- * property**, so the returned object's prototype is always
1269
- * `Object.prototype`, and this call writes nothing to the global one.
1270
- *
1271
- * ### Passing the result to other code
1272
- *
1273
- * A config file — especially a `.properties` file or an env namespace you
1274
- * merged in — can therefore hand you an own `__proto__` key, and what happens
1275
- * next depends entirely on how the consumer copies it:
1276
- *
1277
- * ```ts
1278
- * const data = cfg.toObject()
1279
- * { ...data } // safe — own properties are copied as data
1280
- * structuredClone(data) // safe
1281
- * Object.assign({}, data) // NOT safe — [[Set]] on the {} target hits
1282
- * // Object.prototype's __proto__ setter: the key
1283
- * // vanishes and config data becomes the result's
1284
- * // prototype
1285
- * deepMerge({}, data) // NOT safe — a naive recursive merge reads
1286
- * // target['__proto__'], gets Object.prototype,
1287
- * // and writes to it: global pollution
1288
- * for (const k in data) … // prefer Object.entries / Object.keys
1289
- * ```
1290
- *
1291
- * Those two hazards come from the **destination** object's prototype, so no
1292
- * option here can disarm them — copy with spread or `structuredClone` instead.
1293
- *
1294
- * What `{ nullPrototype: true }` does give you is a result that inherits
1295
- * nothing: every object comes back with a `null` prototype, so reading
1296
- * `x.__proto__`, `x.constructor` or `x.toString` yields config data or
1297
- * `undefined` rather than something from `Object.prototype`, and code that
1298
- * merges *into* this object cannot climb out of it. Keys are all still
1299
- * present. The trade-off is the usual one for prototype-less objects: not
1300
- * `instanceof Object`, and no `hasOwnProperty` of their own.
1301
- *
1302
- * Numbers follow the JS number model, so an integer wider than 2^53 rounds
1303
- * here even when the config holds it exactly — read those with
1304
- * {@link Config.getString} instead.
1305
- */
1306
- toObject(opts) {
1307
- return hoconToJs(this.root, opts?.nullPrototype === true);
1308
- }
1309
- /**
1310
- * @internal Test-only: renders this resolved Config's value tree as canonical
1311
- * JSON (sorted keys, no whitespace). Used by Layer-2 fixture tests to compare
1312
- * against Lightbend ground truth. NOT part of the public API.
1313
- *
1314
- * Throws if the Config is unresolved (contains placeholders).
1315
- */
1316
- _renderJSONForTest() {
1317
- return renderHoconAsJSON(this.root);
1318
- }
1319
- lookupNode(path) {
1320
- const segments = splitConfigPath(path);
1321
- let current = this.root;
1322
- for (const seg of segments) {
1323
- if (current.kind !== "object") return void 0;
1324
- const next = current.fields.get(seg);
1325
- if (next === void 0) return void 0;
1326
- current = next;
1327
- }
1328
- return current;
1329
- }
1330
- /**
1331
- * _resObjRootSubtreeHasPlaceholders — walk _resObjRoot to the given path and
1332
- * return true if the subtree there contains any unresolved placeholder.
1333
- * Used by getConfig / getList (T2) to detect transitive unresolved placeholders
1334
- * in object / array subtrees that would otherwise appear to be "resolved" in the
1335
- * partial HoconValue root (because individual leaf fields are omitted rather than
1336
- * the whole subtree when their value is a direct placeholder scalar, but object
1337
- * sub-containers are retained in the partial root with the placeholder-keyed
1338
- * fields omitted from them — so the object appears "present but empty-ish").
1339
- */
1340
- _resObjRootSubtreeHasPlaceholders(path) {
1341
- const tree = this._resObjRoot;
1342
- if (!tree) return false;
1343
- const segments = splitConfigPath(path);
1344
- let cur = tree;
1345
- for (const seg of segments) {
1346
- const val = cur.fields.get(seg);
1347
- if (val === void 0) return false;
1348
- if (isResObj(val)) {
1349
- cur = val;
1350
- } else {
1351
- return valContainsPlaceholders(val);
1352
- }
1353
- }
1354
- return containsPlaceholders(cur);
1355
- }
1356
- requireScalar(path) {
1357
- const v = this.lookupNode(path);
1358
- if (v === void 0) {
1359
- if (!this._resolved && this._resObjRootSubtreeHasPlaceholders(path)) {
1360
- throw new NotResolvedError(path);
1361
- }
1362
- throw new ConfigError(`path not found: ${path}`, path);
1363
- }
1364
- if (v.kind !== "scalar") throw new ConfigError(`expected scalar at ${path}, got ${v.kind}`, path);
1365
- return v;
1366
- }
1367
- };
1368
- function splitConfigPath(path) {
1369
- const segments = [];
1370
- let i = 0;
1371
- while (i < path.length) {
1372
- if (path[i] === '"') {
1373
- i++;
1374
- let segment = "";
1375
- let closed = false;
1376
- while (i < path.length) {
1377
- const ch = path[i];
1378
- if (ch === "\\" && i + 1 < path.length) {
1379
- const next = path[i + 1];
1380
- segment += next;
1381
- i += 2;
1382
- continue;
1383
- }
1384
- if (ch === '"') {
1385
- closed = true;
1386
- i++;
1387
- break;
1388
- }
1389
- segment += ch;
1390
- i++;
1391
- }
1392
- if (!closed) throw new ConfigError(`unterminated quoted path segment: ${path}`, path);
1393
- segments.push(segment);
1394
- if (i < path.length && path[i] === ".") i++;
1395
- } else {
1396
- const dot = path.indexOf(".", i);
1397
- if (dot === -1) {
1398
- segments.push(path.slice(i));
1399
- break;
1400
- }
1401
- segments.push(path.slice(i, dot));
1402
- i = dot + 1;
1403
- }
1404
- }
1405
- return segments;
1406
- }
1407
- function scalarToJs(raw, valueType) {
1408
- switch (valueType) {
1409
- case "null":
1410
- return null;
1411
- case "boolean":
1412
- return raw === "true";
1413
- case "number":
1414
- return Number(raw);
1415
- case "string":
1416
- return raw;
1417
- }
1418
- }
1419
- function hoconToJs(v, nullPrototype = false) {
1420
- switch (v.kind) {
1421
- case "scalar":
1422
- return scalarToJs(v.raw, v.valueType);
1423
- case "array":
1424
- return v.items.map((item) => hoconToJs(item, nullPrototype));
1425
- case "object": {
1426
- const entries = Array.from(v.fields, ([k, val]) => [k, hoconToJs(val, nullPrototype)]);
1427
- if (nullPrototype) {
1428
- const obj = /* @__PURE__ */ Object.create(null);
1429
- for (const [k, val] of entries) Object.defineProperty(obj, k, {
1430
- value: val,
1431
- writable: true,
1432
- enumerable: true,
1433
- configurable: true
1434
- });
1435
- return obj;
1436
- }
1437
- return Object.fromEntries(entries);
1438
- }
1439
- }
1440
- }
1441
- function resObjToKeyShape(tree) {
1442
- const fields = /* @__PURE__ */ new Map();
1443
- for (const [k, v] of tree.fields) {
1444
- if (isSubst(v) || isConcat(v)) {
1445
- fields.set(k, { kind: "scalar", raw: "", valueType: "null" });
1446
- } else if (isResObj(v)) {
1447
- fields.set(k, resObjToKeyShape(v));
1448
- } else {
1449
- fields.set(k, v);
1450
- }
1451
- }
1452
- return { kind: "object", fields };
1453
- }
1454
- function stripPlaceholderFields(v) {
1455
- const fields = /* @__PURE__ */ new Map();
1456
- let hadPlaceholders = false;
1457
- for (const [k, val] of v.fields) {
1458
- if (val._kind === "subst-placeholder" || val._kind === "concat-placeholder") {
1459
- hadPlaceholders = true;
1460
- } else if (val.kind === "object") {
1461
- const inner = stripPlaceholderFields(val);
1462
- if (inner.hadPlaceholders) hadPlaceholders = true;
1463
- fields.set(k, inner.stripped);
1464
- } else {
1465
- fields.set(k, val);
1466
- }
1467
- }
1468
- return { stripped: { kind: "object", fields }, hadPlaceholders };
1469
- }
1470
- function filterByReceiverShape(resolved, receiverShape) {
1471
- const fields = /* @__PURE__ */ new Map();
1472
- for (const [k, rv] of resolved.fields) {
1473
- if (!receiverShape.fields.has(k)) continue;
1474
- const receiverVal = receiverShape.fields.get(k);
1475
- if (rv.kind === "object" && receiverVal.kind === "object") {
1476
- fields.set(k, filterByReceiverShape(rv, receiverVal));
1477
- } else {
1478
- fields.set(k, rv);
1479
- }
1480
- }
1481
- return { kind: "object", fields };
1482
- }
1483
- function renderHoconAsJSON(v) {
1484
- switch (v.kind) {
1485
- case "scalar": {
1486
- switch (v.valueType) {
1487
- case "null":
1488
- return "null";
1489
- case "boolean":
1490
- return v.raw;
1491
- case "number": {
1492
- const norm = normalizeLeadingZeroNumber(v.raw);
1493
- return JSON_NUMBER_RE.test(norm) ? norm : JSON.stringify(v.raw);
1494
- }
1495
- case "string":
1496
- return JSON.stringify(v.raw);
1497
- }
1498
- break;
1499
- }
1500
- case "array": {
1501
- const items = v.items.map(renderHoconAsJSON);
1502
- return `[${items.join(",")}]`;
1503
- }
1504
- case "object": {
1505
- const keys = [...v.fields.keys()].sort();
1506
- const pairs = keys.map((k) => {
1507
- const val = v.fields.get(k);
1508
- return `${JSON.stringify(k)}:${renderHoconAsJSON(val)}`;
1509
- });
1510
- return `{${pairs.join(",")}}`;
1511
- }
1512
- }
1513
- throw new Error(`renderHoconAsJSON: unsupported value kind (unresolved placeholder?)`);
1514
- }
1515
- var JSON_NUMBER_RE = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
1516
- function normalizeLeadingZeroNumber(raw) {
1517
- return raw.replace(/^([+-]?)0+(\d)/, "$1$2");
1518
- }
1519
-
1520
- // src/value-factory.ts
1521
- function fromMap(values, originDescription) {
1522
- const fields = guardStackDepth(
1523
- () => coerceObject(values, ""),
1524
- (msg) => depthError(`fromMap: ${msg}`)
1525
- );
1526
- const root = { kind: "object", fields };
1527
- return Config._fromResolvedValue(root, { originDescription });
1528
- }
1529
- var INT64_MAX = 9223372036854775807n;
1530
- var INT64_MIN = -9223372036854775808n;
1531
- function coerceObject(obj, atPath) {
1532
- const fields = /* @__PURE__ */ new Map();
1533
- for (const [k, v] of Object.entries(obj)) {
1534
- const childPath = atPath ? `${atPath}.${k}` : k;
1535
- fields.set(k, coerceValue(v, childPath));
1536
- }
1537
- return fields;
1538
- }
1539
- function coerceValue(v, atPath) {
1540
- if (v === null) {
1541
- return { kind: "scalar", raw: "null", valueType: "null" };
1542
- }
1543
- if (v === void 0) {
1544
- throw new ConfigError(
1545
- `fromMap: undefined is not a valid HOCON value at path "${atPath}"`,
1546
- atPath
1547
- );
1548
- }
1549
- switch (typeof v) {
1550
- case "string":
1551
- return { kind: "scalar", raw: v, valueType: "string" };
1552
- case "number": {
1553
- if (Number.isNaN(v) || !Number.isFinite(v)) {
1554
- throw new ConfigError(
1555
- `fromMap: ${v} is not representable in HOCON (NaN/Infinity not allowed) at path "${atPath}"`,
1556
- atPath
1557
- );
1558
- }
1559
- return { kind: "scalar", raw: Object.is(v, -0) ? "-0" : String(v), valueType: "number" };
1560
- }
1561
- case "boolean":
1562
- return { kind: "scalar", raw: v ? "true" : "false", valueType: "boolean" };
1563
- case "bigint": {
1564
- if (v > INT64_MAX || v < INT64_MIN) {
1565
- throw new ConfigError(
1566
- `fromMap: integer ${v} is out of int64 range (HOCON integers are int64; spec F0.5) at path "${atPath}"`,
1567
- atPath
1568
- );
1569
- }
1570
- return { kind: "scalar", raw: String(v), valueType: "number" };
1571
- }
1572
- case "object": {
1573
- if (Array.isArray(v)) {
1574
- const items = v.map((item, i) => coerceValue(item, `${atPath}[${i}]`));
1575
- return { kind: "array", items };
1576
- }
1577
- const fields = coerceObject(v, atPath);
1578
- return { kind: "object", fields };
1579
- }
1580
- default:
1581
- throw new ConfigError(
1582
- `fromMap: unsupported value type "${typeof v}" at path "${atPath}"`,
1583
- atPath
1584
- );
1585
- }
1586
- }
1
+ import {
2
+ fromMap
3
+ } from "../chunk-QY7ECGS6.js";
4
+ import {
5
+ ConfigError,
6
+ depthError,
7
+ guardStackDepth,
8
+ stripBom
9
+ } from "../chunk-WTXULUZS.js";
1587
10
 
1588
11
  // src/adapters/jsonc.ts
1589
12
  function parseJsonc(input, originDescription) {