@o3co/ts.hocon 1.12.0 → 1.14.0

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