arktype 3.0.0-beta.2 → 3.0.0-rc.1

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 (100) hide show
  1. package/README.md +55 -20
  2. package/out/_internal/regex/quantify.d.ts +17 -1
  3. package/out/_internal/schema/refinements/range.d.ts +2 -1
  4. package/out/_internal/schema/roots/domain.d.ts +1 -0
  5. package/out/_internal/schema/roots/root.d.ts +3 -1
  6. package/out/_internal/schema/roots/union.d.ts +8 -3
  7. package/out/_internal/schema/shared/compile.d.ts +2 -0
  8. package/out/_internal/schema/shared/declare.d.ts +9 -6
  9. package/out/_internal/schema/shared/errors.d.ts +3 -0
  10. package/out/_internal/schema/shared/issues.d.ts +5 -1
  11. package/out/_internal/schema/shared/issuesLean.d.ts +4 -0
  12. package/out/_internal/schema/shared/issuesNone.d.ts +1 -0
  13. package/out/_internal/schema/shared/issuesNoneLean.d.ts +1 -0
  14. package/out/_internal/schema/shared/standardFailure.d.ts +1 -0
  15. package/out/_internal/schema/shared/toJsonSchema.d.ts +16 -3
  16. package/out/_internal/schema/shared/transform.d.ts +1 -0
  17. package/out/_internal/sets/constraint.d.ts +2 -0
  18. package/out/_internal/sets/fromJsonSchema.d.ts +3 -1
  19. package/out/_internal/util/registry.d.ts +1 -1
  20. package/out/attributes.d.ts +12 -8
  21. package/out/chunk-2FVJ5JBN.js +161 -0
  22. package/out/{chunk-QBX4MEQR.js → chunk-3HZC67MT.js} +15 -15
  23. package/out/{chunk-5TN5JRP7.js → chunk-3KBOPH3J.js} +63 -41
  24. package/out/{chunk-GPNWBJL3.js → chunk-3WYMLH45.js} +17 -11
  25. package/out/{chunk-NIZDOWFU.js → chunk-46PLKNON.js} +2 -2
  26. package/out/{chunk-7JXN4WJX.js → chunk-4FTHWK63.js} +1 -1
  27. package/out/{chunk-EA2DNEDI.js → chunk-4HREHNIV.js} +12 -12
  28. package/out/{chunk-ZFB6DQWY.js → chunk-4J7H2ELX.js} +6 -11
  29. package/out/{chunk-7SVIUP6X.js → chunk-4MUH2MO4.js} +2 -2
  30. package/out/{chunk-J7CKAEDX.js → chunk-4NZCLVBD.js} +1 -1
  31. package/out/{chunk-RAM6G3F6.js → chunk-54U3D6OV.js} +26 -25
  32. package/out/{chunk-HA3POWOU.js → chunk-5FNHK7CC.js} +6 -5
  33. package/out/{chunk-KVQCLBJR.js → chunk-7SUZFAHZ.js} +241 -66
  34. package/out/{chunk-YMYPW3L5.js → chunk-AMNHRY72.js} +3 -3
  35. package/out/{chunk-UH6XKS3C.js → chunk-BQR65UPE.js} +30 -9
  36. package/out/{chunk-V4TZHFNK.js → chunk-BWKJV74G.js} +1 -1
  37. package/out/{chunk-7N3JEHA4.js → chunk-CXHXN7DF.js} +1 -1
  38. package/out/{chunk-FY4M7GE7.js → chunk-E4OQHHFS.js} +4 -4
  39. package/out/{chunk-CGWRW4JZ.js → chunk-ERGIJZFA.js} +4 -4
  40. package/out/{chunk-OA5Q2JLI.js → chunk-H44UG6HG.js} +8 -4
  41. package/out/{chunk-A7A6FDBS.js → chunk-I65VSWGS.js} +50 -44
  42. package/out/{chunk-C5JGK6GT.js → chunk-J2BFVWVY.js} +20 -3
  43. package/out/{chunk-W77ROLOT.js → chunk-JIILWIU4.js} +1 -1
  44. package/out/{chunk-5WRZ25AB.js → chunk-LMUBBBHJ.js} +4 -4
  45. package/out/{chunk-CQU7WIIR.js → chunk-P3HEEGB5.js} +6 -6
  46. package/out/{chunk-JZ4KBCMM.js → chunk-RKJNLXEQ.js} +21 -13
  47. package/out/{chunk-XMEK4I7J.js → chunk-TM22D5DL.js} +887 -266
  48. package/out/{chunk-PIFOURNM.js → chunk-TQYLOZRT.js} +11 -4
  49. package/out/{chunk-YN3XRJ7H.js → chunk-UJJGG4VQ.js} +1 -1
  50. package/out/{chunk-NIYAI7AF.js → chunk-US6BWOGJ.js} +3 -3
  51. package/out/{chunk-57LF5Y5P.js → chunk-W2XOI5DY.js} +1 -1
  52. package/out/{chunk-KDMHK4KP.js → chunk-XVLEFUSY.js} +2 -2
  53. package/out/{chunk-SGFGLENC.js → chunk-YPN67JMD.js} +3 -3
  54. package/out/cli.d.ts +5 -1
  55. package/out/cli.js +301 -49
  56. package/out/codecs.d.ts +4 -3
  57. package/out/codecs.js +18 -18
  58. package/out/config.js +8 -8
  59. package/out/declare.d.ts +2 -4
  60. package/out/errors.js +8 -8
  61. package/out/fn.d.ts +2 -2
  62. package/out/fromJsonSchema.d.ts +1 -1
  63. package/out/generic.d.ts +7 -4
  64. package/out/i18n.js +5 -5
  65. package/out/index.js +19 -19
  66. package/out/internal.js +32 -32
  67. package/out/island.js +18 -18
  68. package/out/islandDependency.js +33 -33
  69. package/out/jsonSchema/infer.d.ts +16 -6
  70. package/out/jsonSchema/validate.d.ts +16 -4
  71. package/out/keywords/functions.d.ts +4 -169
  72. package/out/keywords/keywords.d.ts +1 -1
  73. package/out/keywords/phrases.d.ts +3 -168
  74. package/out/keywords/ts.js +14 -14
  75. package/out/locales/de.js +6 -6
  76. package/out/locales/en.js +15 -15
  77. package/out/match.d.ts +12 -9
  78. package/out/mutatesInput.js +14 -14
  79. package/out/nary.d.ts +219 -193
  80. package/out/parser/definition.d.ts +2 -2
  81. package/out/parser/shift/operator/default.d.ts +2 -2
  82. package/out/parser/tupleExpressions.d.ts +2 -0
  83. package/out/precompiled.js +11 -11
  84. package/out/runtime.d.ts +1 -1
  85. package/out/runtime.js +5 -5
  86. package/out/schema.js +11 -11
  87. package/out/schemaInternal.js +29 -17
  88. package/out/schemaRuntime.js +4 -4
  89. package/out/schemaRuntimeLean.js +60 -36
  90. package/out/schemaRuntimeNone.js +52 -31
  91. package/out/schemaRuntimeNoneLean.js +52 -31
  92. package/out/type.d.ts +3 -3
  93. package/out/util.js +14 -11
  94. package/out/variants/base.d.ts +9 -8
  95. package/out/variants/object.d.ts +14 -6
  96. package/package.json +4 -4
  97. package/skills/arktype/SKILL.md +17 -17
  98. package/skills/arktype/references/migrating.md +13 -13
  99. package/skills/arktype/references/precompile.md +4 -4
  100. package/out/chunk-CSVAPWDE.js +0 -83
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  InternalFnParser
3
- } from "./chunk-7JXN4WJX.js";
3
+ } from "./chunk-4FTHWK63.js";
4
4
  import {
5
5
  Hkt,
6
6
  Scanner,
@@ -10,7 +10,7 @@ import {
10
10
  import {
11
11
  emptyCollectionDefaults,
12
12
  stringifyJson
13
- } from "./chunk-EA2DNEDI.js";
13
+ } from "./chunk-4HREHNIV.js";
14
14
  import {
15
15
  BaseRoot,
16
16
  BaseScope,
@@ -47,11 +47,11 @@ import {
47
47
  writeForeignArkMessage,
48
48
  writeUnboundableMessage,
49
49
  writeUnresolvableMessage
50
- } from "./chunk-KVQCLBJR.js";
50
+ } from "./chunk-7SUZFAHZ.js";
51
51
  import {
52
52
  WeakCache,
53
53
  defineLazily
54
- } from "./chunk-YN3XRJ7H.js";
54
+ } from "./chunk-UJJGG4VQ.js";
55
55
  import {
56
56
  ToJsonSchema,
57
57
  constraintKeys,
@@ -60,12 +60,12 @@ import {
60
60
  rootKinds,
61
61
  schemaKindsRightOf,
62
62
  unionJsonSchemaWritersKey
63
- } from "./chunk-CQU7WIIR.js";
63
+ } from "./chunk-P3HEEGB5.js";
64
64
  import {
65
65
  openApiNull,
66
66
  writeNullableJsonSchema,
67
67
  writeUnionJsonSchema
68
- } from "./chunk-57LF5Y5P.js";
68
+ } from "./chunk-W2XOI5DY.js";
69
69
  import {
70
70
  Backslash,
71
71
  editsBetween,
@@ -74,25 +74,26 @@ import {
74
74
  } from "./chunk-TACLEIDM.js";
75
75
  import {
76
76
  compileLiteralPropAccess
77
- } from "./chunk-PIFOURNM.js";
77
+ } from "./chunk-TQYLOZRT.js";
78
78
  import {
79
79
  $ark,
80
80
  ArkErrors,
81
81
  asTemplated
82
- } from "./chunk-A7A6FDBS.js";
82
+ } from "./chunk-I65VSWGS.js";
83
83
  import {
84
84
  defining,
85
85
  execMorph,
86
86
  hasArkKind,
87
87
  inProgress,
88
88
  isCustomIssue,
89
+ isIoFinal,
89
90
  isNode,
90
91
  isResolutionFinal,
91
92
  makeRootAndArrayPropertiesMutable,
92
93
  printSelfAsThis,
93
94
  queueUnchecked,
94
95
  throwOnDefault
95
- } from "./chunk-5TN5JRP7.js";
96
+ } from "./chunk-3KBOPH3J.js";
96
97
  import {
97
98
  Callable,
98
99
  ParseError,
@@ -131,7 +132,7 @@ import {
131
132
  tryParseWellFormedNumber,
132
133
  unset,
133
134
  writeInvalidDateMessage
134
- } from "./chunk-QBX4MEQR.js";
135
+ } from "./chunk-3HZC67MT.js";
135
136
 
136
137
  // ../sets/out/refinements.js
137
138
  var stricter = (l, r) => l.isStricterThan(r) ? l : r;
@@ -310,6 +311,7 @@ var isNumberSubdomainOf = (l, r) => (r.numberAllowsNaN || !l.numberAllowsNaN) &&
310
311
 
311
312
  // ../sets/out/constraint.js
312
313
  var basisOf = (inner) => inner.proto ?? inner.domain;
314
+ var asOptionalDisjoint = (disjoint) => new Disjoint(...disjoint.map((entry) => ({ ...entry, optional: true })));
313
315
  var intersectConstraints = function (s) {
314
316
  const head = s.r.shift();
315
317
  if (!head) {
@@ -317,9 +319,9 @@ var intersectConstraints = function (s) {
317
319
  if (s.roots.length && result.is("structure"))
318
320
  result = s.ctx.$.node("intersection", { structure: result });
319
321
  for (const root of s.roots) {
320
- if (result instanceof Disjoint)
321
- return result;
322
322
  result = intersectOrPipeNodes(root, result, s.ctx);
323
+ if (result instanceof Disjoint)
324
+ return asOptionalDisjoint(result);
323
325
  }
324
326
  return result;
325
327
  }
@@ -328,8 +330,9 @@ var intersectConstraints = function (s) {
328
330
  const result = intersectOrPipeNodes(s.l[i], head, s.ctx);
329
331
  if (result === null)
330
332
  continue;
331
- if (result instanceof Disjoint)
332
- return result;
333
+ if (result instanceof Disjoint) {
334
+ return s.derivedR?.has(head) || s.derivedL?.has(s.l[i]) ? asOptionalDisjoint(result) : result;
335
+ }
333
336
  if (result.isRoot()) {
334
337
  s.roots.push(result);
335
338
  s.l.splice(i, 1);
@@ -338,22 +341,39 @@ var intersectConstraints = function (s) {
338
341
  const isNarrowedRefinement = s.kind === "intersection" && result !== s.l[i] && result !== head;
339
342
  if (matched || isNarrowedRefinement) {
340
343
  s.l.splice(i--, 1);
341
- if (!s.l.includes(result))
344
+ if (!s.l.includes(result)) {
345
+ if (result !== head || s.derivedR?.has(head))
346
+ (s.derivedR ??= /* @__PURE__ */ new Set()).add(result);
342
347
  s.r.push(result);
348
+ }
343
349
  } else {
350
+ if (result !== s.l[i])
351
+ (s.derivedL ??= /* @__PURE__ */ new Set()).add(result);
344
352
  s.l[i] = result;
345
- if (s.kind === "intersection")
346
- for (const node2 of s.l[i].impliedBy ?? [])
353
+ if (s.kind === "intersection") {
354
+ for (const node2 of s.l[i].impliedBy ?? []) {
355
+ ;
356
+ (s.derivedR ??= /* @__PURE__ */ new Set()).add(node2);
347
357
  appendUnique(s.r, node2);
358
+ }
359
+ }
348
360
  }
349
361
  matched = true;
350
362
  }
351
- if (!matched)
363
+ if (!matched) {
364
+ ;
365
+ (s.derivedL ??= /* @__PURE__ */ new Set()).add(head);
352
366
  s.l.push(head);
367
+ }
353
368
  if (s.kind === "intersection") {
354
- if (head.impliedBy)
355
- for (const node2 of head.impliedBy)
369
+ if (head.impliedBy) {
370
+ const headDerived = s.derivedR?.has(head);
371
+ for (const node2 of head.impliedBy) {
372
+ if (headDerived)
373
+ (s.derivedR ??= /* @__PURE__ */ new Set()).add(node2);
356
374
  appendUnique(s.r, node2);
375
+ }
376
+ }
357
377
  }
358
378
  return intersectConstraints(s);
359
379
  };
@@ -368,7 +388,22 @@ var sortSiblings = function (nodes) {
368
388
  }
369
389
  return nodes;
370
390
  };
371
- var compareSiblings = function (l, r) { return l.is("required") || l.is("optional") ? compareKeys(l.key, r.key) || compareHashes(l.hash, r.hash) : l.kind === r.kind ? compareHashes(l.hash, r.hash) : l.kind < r.kind ? -1 : 1 };
391
+ var compareSiblings = function (l, r) { return l.is("required") || l.is("optional") ? compareKeys(l.key, r.key) || compareHashes(l.hash, r.hash) : l.kind < r.kind ? -1 : l.kind > r.kind ? 1 : l.is("alias") ? compareAliases(l, r) : compareHashes(l.hash, r.hash) };
392
+ var compareAliases = function (l, r) {
393
+ if (!l.operands || !r.operands) {
394
+ return l.operands ? 1 : r.operands ? -1 : compareHashes(l.hash, r.hash);
395
+ }
396
+ if (l.operator !== r.operator)
397
+ return l.operator < r.operator ? -1 : 1;
398
+ const lOperands = sortSiblings(l.operands);
399
+ const rOperands = sortSiblings(r.operands);
400
+ for (let i = 0; i < lOperands.length && i < rOperands.length; i++) {
401
+ const order = compareSiblings(lOperands[i], rOperands[i]);
402
+ if (order)
403
+ return order;
404
+ }
405
+ return lOperands.length - rOperands.length || compareHashes(l.hash, r.hash);
406
+ };
372
407
  var compareHashes = function (l, r) {
373
408
  if (l.includes("$ark")) {
374
409
  let i = 0;
@@ -501,8 +536,14 @@ var morph = {
501
536
  },
502
537
  ...defineRightwardIntersections("morph", function (l, r, ctx) {
503
538
  const headTersection = l.head ? intersectOrPipeNodes(l.head, r, ctx) : r;
504
- return headTersection instanceof Disjoint ? headTersection : headTersection.equals(l.head) ? l : ctx.$.node("morph", {
539
+ if (headTersection instanceof Disjoint)
540
+ return headTersection;
541
+ const declaredIn = l.declaredIn ? intersectOrPipeNodes(l.declaredIn, r, ctx) : void 0;
542
+ if (declaredIn instanceof Disjoint)
543
+ return declaredIn;
544
+ return headTersection.equals(l.head) && (!declaredIn || declaredIn.equals(l.declaredIn)) ? l : ctx.$.node("morph", {
505
545
  ...l.inner,
546
+ ...declaredIn && { declaredIn },
506
547
  morphs: [headTersection, ...l.piped]
507
548
  });
508
549
  })
@@ -785,14 +826,18 @@ var resolveCase = function (ctx, key) {
785
826
  const entry = ctx.defaultPairs[i];
786
827
  if (!caseCtx.branchIndices.includes(entry.originalIndex)) {
787
828
  const intersection2 = intersectNodesRoot(entry.branch._in, discriminantNode, ctx.node.$);
788
- if (!(intersection2 instanceof Disjoint) || // a branch disjoint above the case may reach it through a primitive's
829
+ if (!(intersection2 instanceof Disjoint) || disjointLeavesKeyOverlap(entry.branch._in, intersection2) || // a branch disjoint above the case may reach it through a primitive's
789
830
  // keys, e.g. a string's characters
790
831
  intersection2.some((disjointEntry) => disjointEntry.path.length < ctx.location.path.length) && entry.branch._in.overlaps(primitiveDiscriminantNode ??= discriminantCaseToNode(caseCtx.condition, ctx.location.path, ctx.node.$, { includesPrimitives: true }))) {
791
832
  const overlapping = pruneDiscriminant(entry.branch, ctx.location);
792
- resolvedEntries?.push({
793
- originalIndex: entry.originalIndex,
794
- branch: overlapping
795
- });
833
+ if (overlapping === null)
834
+ resolvedEntries = null;
835
+ else {
836
+ resolvedEntries?.push({
837
+ originalIndex: entry.originalIndex,
838
+ branch: overlapping
839
+ });
840
+ }
796
841
  }
797
842
  nextDefaults.push(entry);
798
843
  }
@@ -1309,6 +1354,54 @@ var primitivePrototypes = [
1309
1354
  Symbol.prototype
1310
1355
  ];
1311
1356
  var isReadableOnPrimitive = function (key) { return key !== void 0 && (typeof key === "number" || typeof key === "string" && integerLikeMatcher.test(key) || primitivePrototypes.some((proto3) => key in proto3)) };
1357
+ var builtinObjectPrototypes = [
1358
+ Object.prototype,
1359
+ Array.prototype,
1360
+ Function.prototype,
1361
+ RegExp.prototype,
1362
+ Error.prototype
1363
+ ];
1364
+ var builtinNonEnumerableKeys = /* @__PURE__ */ new Set([
1365
+ "prototype",
1366
+ "lastIndex",
1367
+ "stack",
1368
+ "cause"
1369
+ ]);
1370
+ var isBuiltinNonEnumerableKey = (key) => builtinNonEnumerableKeys.has(key) || builtinObjectPrototypes.some((proto3) => key in proto3);
1371
+ var disjointLeavesKeyOverlap = (branch, disjoint) => disjoint.length > 0 && disjoint.every((entry) => disjointEntryLeavesKeyOverlap(branch, entry, 0));
1372
+ var disjointEntryLeavesKeyOverlap = function (node2, entry, depth) {
1373
+ if (depth >= entry.path.length)
1374
+ return false;
1375
+ if (node2.is("alias")) {
1376
+ return isResolutionFinal() ? disjointEntryLeavesKeyOverlap(node2.resolution, entry, depth) : false;
1377
+ }
1378
+ if (node2.is("union")) {
1379
+ return node2.branches.some((b) => disjointEntryLeavesKeyOverlap(b, entry, depth));
1380
+ }
1381
+ if (!node2.is("intersection") || !node2.structure)
1382
+ return false;
1383
+ const key = entry.path[depth];
1384
+ if (typeof key === "number") {
1385
+ const sequence2 = node2.structure.sequence;
1386
+ if (!sequence2)
1387
+ return false;
1388
+ if (!sequence2.postfix) {
1389
+ const element = key < sequence2.leading.length ? sequence2.tuple[key].node : sequence2.variadic;
1390
+ return element ? disjointEntryLeavesKeyOverlap(element, entry, depth + 1) : false;
1391
+ }
1392
+ return sequence2.tuple.some((el) => disjointEntryLeavesKeyOverlap(el.node, entry, depth + 1));
1393
+ }
1394
+ const prop = node2.structure.byKey[key];
1395
+ if (prop)
1396
+ return disjointEntryLeavesKeyOverlap(prop.value, entry, depth + 1);
1397
+ if (entry.undeclared)
1398
+ return isBuiltinNonEnumerableKey(key);
1399
+ if (!node2.structure.index)
1400
+ return false;
1401
+ if (isBuiltinNonEnumerableKey(key))
1402
+ return true;
1403
+ return depth < entry.path.length - 1 && node2.structure.index.some((idx) => idx.signature.allowsUnused(key) && disjointEntryLeavesKeyOverlap(idx.value, entry, depth + 1));
1404
+ };
1312
1405
  var writeIndiscriminableMorphMessage = function (lDescription, rDescription) { return `An unordered union of a type including a morph and a type with overlapping input is indeterminate:
1313
1406
  Left: ${lDescription}
1314
1407
  Right: ${rDescription}
@@ -1318,10 +1411,11 @@ Left: ${lDescription}
1318
1411
  Right: ${rDescription}`;
1319
1412
 
1320
1413
  // ../sets/out/roots/unit.js
1414
+ var deferUnitIntersection = (l, r, ctx) => ctx.$.lazilyResolve(() => r.allowsUnused(l.unit) ? l : $ark.kw.never.internal, `${l.id}&${r.id}`, "&", [l, r]);
1321
1415
  var unit = {
1322
1416
  intersections: {
1323
1417
  unit: (l, r) => Disjoint.init("unit", l, r),
1324
- ...defineRightwardIntersections("unit", function (l, r) {
1418
+ ...defineRightwardIntersections("unit", function (l, r, ctx) {
1325
1419
  const rBasis = r.is("intersection") ? r.basis ?? r.children.find((rConstraint) => rConstraint.implied?.allowsUnused(l.unit) === false)?.implied : r;
1326
1420
  if (rBasis && !rBasis.allowsUnused(l.unit)) {
1327
1421
  const rDomain = rBasis.is("domain") ? rBasis : rBasis.is("proto") ? $ark.kw.object : null;
@@ -1331,9 +1425,28 @@ var unit = {
1331
1425
  }
1332
1426
  return Disjoint.init("assignability", l, rBasis);
1333
1427
  }
1334
- if (r.allowsUnused(l.unit))
1428
+ if (!r.is("intersection"))
1335
1429
  return l;
1336
- return Disjoint.init("assignability", l, r.is("intersection") ? r.children.find((rConstraint) => !rConstraint.allowsUnused(l.unit)) : r);
1430
+ if (!isResolutionFinal() && r.hasAlias)
1431
+ return deferUnitIntersection(l, r, ctx);
1432
+ const deferOnError = !isResolutionFinal() && Boolean(r.inner.predicate || r.userCode);
1433
+ for (const rConstraint of r.children) {
1434
+ if (rConstraint === rBasis)
1435
+ continue;
1436
+ if (deferOnError) {
1437
+ try {
1438
+ if (rConstraint.allowsUnused(l.unit))
1439
+ continue;
1440
+ } catch (e) {
1441
+ if (e instanceof ParseError)
1442
+ throw e;
1443
+ return deferUnitIntersection(l, r, ctx);
1444
+ }
1445
+ } else if (rConstraint.allowsUnused(l.unit))
1446
+ continue;
1447
+ return Disjoint.init("assignability", l, rConstraint);
1448
+ }
1449
+ return l;
1337
1450
  })
1338
1451
  }
1339
1452
  };
@@ -1851,8 +1964,17 @@ var _pipeMorphed = function (from, to, ctx) {
1851
1964
  morphs[morphs.length - 1] = outIntersection;
1852
1965
  } else
1853
1966
  morphs.push(to);
1967
+ let declaredOut;
1968
+ if (from.inner.declaredOut && to.is("intersection") && !to.basis && !to.isUnknown() && (isIoFinal() || !from.inner.declaredOut.hasAlias && !to.hasAlias)) {
1969
+ const outTersection = intersectOrPipeNodes(from.inner.declaredOut, to, ctx);
1970
+ if (outTersection instanceof Disjoint)
1971
+ return outTersection;
1972
+ declaredOut = outTersection._out;
1973
+ }
1854
1974
  return ctx.$.node("morph", {
1855
1975
  morphs,
1976
+ ...from.inner.declaredIn && { declaredIn: from.inner.declaredIn },
1977
+ ...declaredOut && { declaredOut },
1856
1978
  inverse: from.inner.inverse
1857
1979
  });
1858
1980
  }
@@ -1866,7 +1988,7 @@ var _pipeMorphed = function (from, to, ctx) {
1866
1988
  };
1867
1989
 
1868
1990
  // ../sets/out/toJsonSchema.js
1869
- var isNonArray = (data) => !Array.isArray(data);
1991
+ var isNonArray = (data) => typeof data !== "function" && !Array.isArray(data);
1870
1992
  var jsonSchemaWriters = {
1871
1993
  union: writeUnionJsonSchema,
1872
1994
  nullable: writeNullableJsonSchema
@@ -1889,7 +2011,7 @@ var rootToJsonSchema = function (node2, opts) {
1889
2011
  code,
1890
2012
  handler === ToJsonSchema.defaultConfig.fallback[code] ? (fallbackCtx) => ToJsonSchema.throw(code, fallbackCtx, ctx.path) : handler
1891
2013
  ]);
1892
- const schema = Object.assign(typeof ctx.dialect === "string" ? { $schema: ctx.dialect } : {}, toJsonSchemaRecurse(node2, ctx));
2014
+ const schema = Object.assign(typeof ctx.dialect === "string" ? { $schema: ctx.dialect } : {}, toJsonSchemaRecurse(ctx.io === "out" ? node2._out : node2, ctx));
1893
2015
  if (Array.isArray(ctx.aliasDefs)) {
1894
2016
  const missing = ctx.aliasDefs.find((name) => !ctx.aliasesFound.has(name));
1895
2017
  if (missing !== void 0)
@@ -1930,21 +2052,23 @@ var toJsonSchemaRecurse = function (node2, ctx) {
1930
2052
  nameDef(node2, aliasName, ctx);
1931
2053
  }
1932
2054
  const i = ctx.open.lastIndexOf(node2.id);
1933
- if (i !== -1 && ctx.open.slice(i).every((id) => !(id in ctx.defNamesById)) || ctx.useRefs && !node2.alwaysExpandJsonSchema)
2055
+ if (i !== -1 && ctx.open.slice(i).every((id) => !hasOwn(ctx.defNamesById, id)) || ctx.useRefs && !node2.alwaysExpandJsonSchema)
1934
2056
  nameDef(node2, nameOfId(node2.id), ctx);
1935
- const name = ctx.defNamesById[node2.id];
1936
- if (name !== void 0 && (i !== -1 || ctx.defs[name]))
2057
+ const name = hasOwn(ctx.defNamesById, node2.id) ? ctx.defNamesById[node2.id] : void 0;
2058
+ if (name !== void 0 && (i !== -1 || hasOwn(ctx.defs, name) && ctx.defs[name] !== void 0))
1937
2059
  return refTo(name, ctx);
1938
2060
  ctx.open.push(node2.id);
1939
2061
  const schema = toResolvedJsonSchema(node2, ctx);
1940
2062
  ctx.open.pop();
1941
- const defName = ctx.defNamesById[node2.id];
2063
+ const defName = hasOwn(ctx.defNamesById, node2.id) ? ctx.defNamesById[node2.id] : void 0;
1942
2064
  if (defName === void 0)
1943
2065
  return schema;
1944
- ctx.defs[defName] = schema;
2066
+ defineValue(ctx.defs, defName, schema);
1945
2067
  return refTo(defName, ctx);
1946
2068
  };
1947
- var refTo = (name, ctx) => ({ $ref: ctx.refPrefix + name });
2069
+ var refTo = (name, ctx) => ({
2070
+ $ref: ctx.refPrefix + encodeURIComponent(name.replace(/~/g, "~0").replace(/\//g, "~1"))
2071
+ });
1948
2072
  var nameOfId = (id) => id.replace(/(\d)_\d+$|\d+$/, "$1");
1949
2073
  var aliasNameOf = function (node2) { return node2.isIo ? aliasNameOf(node2.operands[0]) : node2.reference === node2.resolution.id ? nameOfId(node2.reference) : void 0 };
1950
2074
  var addAliasNames = function ($, ctx) {
@@ -1987,27 +2111,103 @@ var addAliasNames = function ($, ctx) {
1987
2111
  }
1988
2112
  };
1989
2113
  var nameDef = function (node2, name, ctx) {
1990
- if (node2.id in ctx.defNamesById)
2114
+ if (hasOwn(ctx.defNamesById, node2.id))
1991
2115
  return;
1992
2116
  let unique = name;
1993
- for (let i = 2; unique in ctx.defs; i++)
2117
+ for (let i = 2; hasOwn(ctx.defs, unique); i++)
1994
2118
  unique = `${name}${i}`;
1995
- ctx.defs[unique] = void 0;
1996
- ctx.defNamesById[node2.id] = unique;
2119
+ defineValue(ctx.defs, unique, void 0);
2120
+ defineValue(ctx.defNamesById, node2.id, unique);
1997
2121
  };
1998
- var toResolvedJsonSchema = function (node2, ctx, writeInner = () => innerToJsonSchemaByKind[node2.kind](node2, ctx)) {
1999
- const { jsonSchema } = node2.meta;
2000
- const result = jsonSchema ? {} : writeInner();
2122
+ var nonJsonAnnotation = Symbol();
2123
+ var jsonAnnotationValue = function (value, seen = /* @__PURE__ */ new Set()) {
2124
+ if (value === null || typeof value === "boolean" || typeof value === "string")
2125
+ return value;
2126
+ if (typeof value === "number")
2127
+ return Number.isFinite(value) ? value : nonJsonAnnotation;
2128
+ if (value instanceof Date) {
2129
+ return Number.isNaN(value.getTime()) ? nonJsonAnnotation : value.toISOString();
2130
+ }
2131
+ if (typeof value !== "object" || seen.has(value))
2132
+ return nonJsonAnnotation;
2133
+ seen.add(value);
2134
+ if (Array.isArray(value)) {
2135
+ const out2 = [];
2136
+ for (let i = 0; i < value.length; i++) {
2137
+ if (!(i in value)) {
2138
+ seen.delete(value);
2139
+ return nonJsonAnnotation;
2140
+ }
2141
+ const jsonItem = jsonAnnotationValue(value[i], seen);
2142
+ if (jsonItem === nonJsonAnnotation) {
2143
+ seen.delete(value);
2144
+ return nonJsonAnnotation;
2145
+ }
2146
+ out2.push(jsonItem);
2147
+ }
2148
+ seen.delete(value);
2149
+ return out2;
2150
+ }
2151
+ const proto3 = Object.getPrototypeOf(value);
2152
+ if (proto3 !== Object.prototype && proto3 !== null) {
2153
+ seen.delete(value);
2154
+ return nonJsonAnnotation;
2155
+ }
2156
+ const out = {};
2157
+ for (const [k, prop] of Object.entries(value)) {
2158
+ const jsonProp = jsonAnnotationValue(prop, seen);
2159
+ if (jsonProp === nonJsonAnnotation) {
2160
+ seen.delete(value);
2161
+ return nonJsonAnnotation;
2162
+ }
2163
+ defineValue(out, k, jsonProp);
2164
+ }
2165
+ seen.delete(value);
2166
+ return out;
2167
+ };
2168
+ var examplesAnnotationValue = function (value) {
2169
+ if (!Array.isArray(value))
2170
+ return void 0;
2171
+ if (!value.length)
2172
+ return [];
2173
+ const out = [];
2174
+ for (let i = 0; i < value.length; i++) {
2175
+ if (!(i in value))
2176
+ continue;
2177
+ const jsonEntry = jsonAnnotationValue(value[i]);
2178
+ if (jsonEntry !== nonJsonAnnotation)
2179
+ out.push(jsonEntry);
2180
+ }
2181
+ return out.length ? out : void 0;
2182
+ };
2183
+ var writeNodeAnnotations = function (result, node2, ctx) {
2001
2184
  for (const k in node2.meta) {
2002
2185
  if (!annotationKeys.has(k) && !k.startsWith("x-"))
2003
2186
  continue;
2004
2187
  const v = node2.meta[k];
2005
2188
  if (typeof v === "function" && k !== "default")
2006
2189
  continue;
2007
- const jsonValue = typeof v !== "function" && $ark.kw.jsonData.allows(v) ? v : k === "default" ? ctx.fallback.defaultValue({ code: "defaultValue", value: v }) : node2.metaJson[k];
2190
+ let jsonValue;
2191
+ if (k === "examples")
2192
+ jsonValue = examplesAnnotationValue(v);
2193
+ else if (k === "default") {
2194
+ jsonValue = typeof v !== "function" && $ark.kw.jsonData.allows(v) ? v : ctx.fallback.defaultValue({
2195
+ code: "defaultValue",
2196
+ value: v
2197
+ });
2198
+ } else {
2199
+ const converted = jsonAnnotationValue(v);
2200
+ if (converted !== nonJsonAnnotation)
2201
+ jsonValue = converted;
2202
+ }
2008
2203
  if (jsonValue !== void 0)
2009
2204
  writeAnnotation(result, k, jsonValue, ctx);
2010
2205
  }
2206
+ };
2207
+ var toResolvedJsonSchema = function (node2, ctx, writeInner = () => innerToJsonSchemaByKind[node2.kind](node2, ctx)) {
2208
+ const { jsonSchema } = node2.meta;
2209
+ const result = jsonSchema ? {} : writeInner();
2210
+ writeNodeAnnotations(result, node2, ctx);
2011
2211
  return jsonSchema ? Object.assign(result, jsonSchema) : result;
2012
2212
  };
2013
2213
  var annotationKeys = /* @__PURE__ */ new Set([
@@ -2023,11 +2223,29 @@ var annotationKeys = /* @__PURE__ */ new Set([
2023
2223
  "contentEncoding",
2024
2224
  "contentMediaType"
2025
2225
  ]);
2026
- var branchGroupsToJsonSchema = function (node2, branchGroups, ctx) { return (
2027
- // special case to simplify { const: true } | { const: false }
2028
- // to the canonical JSON Schema representation { type: "boolean" }
2029
- branchGroups.length === 1 && branchGroups[0].equals($ark.kw.boolean) ? { type: "boolean" } : ctx.writers.union(branchGroups.map((group) => toJsonSchemaRecurse(group, ctx)), ctx.target, node2.meta, node2.metaJson, discriminantOf(branchGroups, ctx))
2030
- ) };
2226
+ var branchGroupsToJsonSchema = function (node2, branchGroups, ctx) {
2227
+ if (branchGroups.length === 1 && branchGroups[0].equals($ark.kw.boolean))
2228
+ return { type: "boolean" };
2229
+ const branchSchemas = branchGroups.map((group) => toJsonSchemaRecurse(group, ctx));
2230
+ if (!isEmptyObject(node2.meta)) {
2231
+ const unionAnnotations = {};
2232
+ writeNodeAnnotations(unionAnnotations, node2, ctx);
2233
+ if (!isEmptyObject(unionAnnotations)) {
2234
+ for (let i = 0; i < branchSchemas.length; i++) {
2235
+ const branch = branchSchemas[i];
2236
+ const group = branchGroups[i];
2237
+ if ("$ref" in branch || group.meta.jsonSchema)
2238
+ continue;
2239
+ const branchDict = branch;
2240
+ for (const [k, v] of Object.entries(unionAnnotations)) {
2241
+ if (hasOwn(branchDict, k) && (branchDict[k] === v || k in group.meta && group.meta[k] === node2.meta[k]))
2242
+ delete branchDict[k];
2243
+ }
2244
+ }
2245
+ }
2246
+ }
2247
+ return ctx.writers.union(branchSchemas, ctx.target, node2.meta, node2.metaJson, discriminantOf(branchGroups, ctx));
2248
+ };
2031
2249
  var discriminantOf = function (branches, ctx) {
2032
2250
  const tagsByBranch = [];
2033
2251
  for (const branch of branches) {
@@ -2280,16 +2498,16 @@ var reduceObjectJsonSchema = function (node2, schema, ctx) {
2280
2498
  for (const index2 of node2.index ?? [])
2281
2499
  schema = writeIndex(index2, node2, schema, ctx, indexes);
2282
2500
  const indexKeys = indexes.keys;
2283
- const rejectsUndeclared = node2.undeclared === "reject" || node2.undeclared === "delete" && ctx.io !== "in";
2501
+ const rejectsUndeclared = node2.undeclared === "reject" || node2.undeclared === "delete" && ctx.io === "out";
2284
2502
  if (indexKeys.length === 1 && rejectsUndeclared && !schema.patternProperties && ctx.target !== "openapi-3.0" && node2.props.every((prop) => typeof prop.key === "symbol" || indexKeys[0].node.allows(prop.key))) {
2285
2503
  schema.propertyNames = indexKeys[0].key;
2286
- if (declaredValuesExtend(node2, indexKeys[0].valueNode))
2504
+ if (declaredValuesExtend(node2, indexKeys[0].valueNode, ctx))
2287
2505
  schema.additionalProperties = indexKeys[0].value;
2288
2506
  else
2289
2507
  schema.patternProperties = { "": indexKeys[0].value };
2290
2508
  return schema;
2291
2509
  }
2292
- if (schema.patternProperties?.[""] && Object.keys(schema.patternProperties).length === 1 && indexes.anyString && declaredValuesExtend(node2, indexes.anyString)) {
2510
+ if (schema.patternProperties?.[""] && Object.keys(schema.patternProperties).length === 1 && indexes.anyString && declaredValuesExtend(node2, indexes.anyString, ctx)) {
2293
2511
  schema.additionalProperties = schema.patternProperties[""];
2294
2512
  delete schema.patternProperties;
2295
2513
  }
@@ -2305,13 +2523,13 @@ var reduceObjectJsonSchema = function (node2, schema, ctx) {
2305
2523
  }
2306
2524
  return schema;
2307
2525
  };
2308
- var declaredValuesExtend = (node2, value) => node2.props.every((prop) => typeof prop.key === "symbol" || jsonValueOf(prop).extends(value));
2526
+ var declaredValuesExtend = (node2, value, ctx) => node2.props.every((prop) => typeof prop.key === "symbol" || jsonValueOf(prop, ctx).extends(value));
2309
2527
  var writeProps = function (node2, schema, ctx) {
2310
2528
  const path = ctx.path;
2311
2529
  schema.properties = {};
2312
2530
  for (const prop of node2.props) {
2313
2531
  ctx.path = appendStringifiedKey(path, prop.key);
2314
- const valueSchema = toJsonSchemaRecurse(jsonValueOf(prop), ctx);
2532
+ const valueSchema = toJsonSchemaRecurse(jsonValueOf(prop, ctx), ctx);
2315
2533
  if (typeof prop.key === "symbol") {
2316
2534
  schema = ctx.fallback.symbolKey({
2317
2535
  code: "symbolKey",
@@ -2327,15 +2545,18 @@ var writeProps = function (node2, schema, ctx) {
2327
2545
  defineValue(schema.properties, prop.key, valueSchema);
2328
2546
  }
2329
2547
  ctx.path = path;
2330
- if (node2.requiredKeys.length && schema.properties) {
2331
- schema.required = node2.requiredKeys.filter((k) => typeof k === "string" && k in schema.properties);
2548
+ if (node2.required?.length && schema.properties) {
2549
+ const required2 = node2.required.flatMap((prop) => typeof prop.key !== "string" || !(prop.key in schema.properties) || ctx.io === "out" && prop.value.allowsUnused(void 0) ? [] : [prop.key]);
2550
+ if (required2.length)
2551
+ schema.required = required2;
2332
2552
  }
2333
2553
  return schema;
2334
2554
  };
2335
2555
  var writeIndex = function (index2, node2, schema, ctx, indexes) {
2556
+ const indexValue = ctx.io === "out" ? withoutUndefined(index2.value, ctx) : index2.value;
2336
2557
  const path = ctx.path;
2337
2558
  ctx.path = `${path}[${index2.signature.expression}]`;
2338
- const valueJsonSchema = toJsonSchemaRecurse(index2.value, ctx);
2559
+ const valueJsonSchema = toJsonSchemaRecurse(indexValue, ctx);
2339
2560
  ctx.path = path;
2340
2561
  for (const keyBranch of index2.signature.branches) {
2341
2562
  if (!keyBranch.extends($ark.kw.string)) {
@@ -2362,22 +2583,50 @@ var writeIndex = function (index2, node2, schema, ctx, indexes) {
2362
2583
  }
2363
2584
  const pattern2 = keyPatternOf(keyIn, ctx);
2364
2585
  if (pattern2 !== void 0 && // OpenAPI 3.0 has no patternProperties, only additionalProperties
2365
- (ctx.target !== "openapi-3.0" || pattern2 === "" && declaredValuesExtend(node2, index2.value))) {
2586
+ (ctx.target !== "openapi-3.0" || pattern2 === "" && declaredValuesExtend(node2, indexValue, ctx))) {
2366
2587
  defineValue(schema.patternProperties ??= {}, pattern2, valueJsonSchema);
2367
2588
  if (pattern2 === "")
2368
- indexes.anyString = index2.value;
2589
+ indexes.anyString = indexValue;
2369
2590
  continue;
2370
2591
  }
2371
2592
  indexes.keys.push({
2372
2593
  node: keyIn,
2373
2594
  key: keySchema ?? toResolvedJsonSchema(keyIn, ctx),
2374
2595
  value: valueJsonSchema,
2375
- valueNode: index2.value
2596
+ valueNode: indexValue
2376
2597
  });
2377
2598
  }
2378
2599
  return schema;
2379
2600
  };
2380
- var jsonValueOf = function (prop) { return prop.optional && prop.value.branches.some((branch) => branch.hasUnit(void 0)) ? prop.value.$.schema(prop.value.branches.filter((branch) => !branch.hasUnit(void 0))) : prop.value };
2601
+ var aliasNameForStripped = function (value, stripped, ctx) {
2602
+ if (stripped.is("alias"))
2603
+ return void 0;
2604
+ if (value.is("alias"))
2605
+ return aliasNameOf(value);
2606
+ if (!ctx.aliasDefs)
2607
+ return void 0;
2608
+ if (!ctx.aliasScopes.has(value.$))
2609
+ addAliasNames(value.$, ctx);
2610
+ if (hasOwn(ctx.aliasNamesById, stripped.id))
2611
+ return void 0;
2612
+ if (stripped.alwaysExpandJsonSchema && !Array.isArray(ctx.aliasDefs))
2613
+ return void 0;
2614
+ return ctx.aliasNamesById[value.id];
2615
+ };
2616
+ var withoutUndefined = function (value, ctx) {
2617
+ const resolved = value.is("alias") ? value.resolution : value;
2618
+ if (!resolved.branches.some((branch) => branch.hasUnit(void 0)))
2619
+ return value;
2620
+ const stripped = resolved.$.schema(resolved.branches.filter((branch) => !branch.hasUnit(void 0)));
2621
+ const result = isEmptyObject(resolved.meta) ? stripped : stripped.configure(resolved.meta, "self");
2622
+ if (ctx) {
2623
+ const name = aliasNameForStripped(value, result, ctx);
2624
+ if (name !== void 0)
2625
+ nameDef(result, name, ctx);
2626
+ }
2627
+ return result;
2628
+ };
2629
+ var jsonValueOf = (prop, ctx) => prop.optional || ctx.io === "out" ? withoutUndefined(prop.value, ctx) : prop.value;
2381
2630
  var keyPatternOf = function (key, ctx) {
2382
2631
  if (key.is("domain"))
2383
2632
  return "";
@@ -2386,7 +2635,35 @@ var keyPatternOf = function (key, ctx) {
2386
2635
  const [refinement] = key.refinements;
2387
2636
  return refinement.is("pattern") && isJsonSchemaPattern(refinement, ctx) ? refinement.rule : void 0;
2388
2637
  };
2389
- var isJsonSchemaPattern = function (node2, ctx) { return !node2.flags || [...node2.flags].every((flag) => flag === "d" || flag === "g" || flag === "u" && (ctx.target === "draft-2020-12" || ctx.target === "openapi-3.1")) };
2638
+ var differsUnderUnicodeFlag = function (source) {
2639
+ try {
2640
+ new RegExp(source, "u");
2641
+ } catch {
2642
+ return true;
2643
+ }
2644
+ for (let i = 0; i < source.length; i++) {
2645
+ if (source[i] === "\\") {
2646
+ const escaped = source[++i];
2647
+ if ((escaped === "p" || escaped === "P" || escaped === "u") && source[i + 1] === "{")
2648
+ return true;
2649
+ }
2650
+ }
2651
+ return false;
2652
+ };
2653
+ var isJsonSchemaPattern = function (node2, ctx) {
2654
+ let hasU = false;
2655
+ if (node2.flags) {
2656
+ for (const flag of node2.flags) {
2657
+ if (flag === "u") {
2658
+ if (ctx.target !== "draft-2020-12" && ctx.target !== "openapi-3.1")
2659
+ return false;
2660
+ hasU = true;
2661
+ } else if (flag !== "d" && flag !== "g")
2662
+ return false;
2663
+ }
2664
+ }
2665
+ return hasU || !differsUnderUnicodeFlag(node2.rule);
2666
+ };
2390
2667
  var writeDefault = function (schema, defaultInput, ctx) {
2391
2668
  const value = typeof defaultInput === "function" ? defaultInput() : defaultInput;
2392
2669
  const jsonDefault = $ark.kw.jsonData.allows(value) ? value : ctx.fallback.defaultValue({ code: "defaultValue", value });
@@ -2413,7 +2690,7 @@ var reduceSequenceJsonSchema = function (node2, schema, ctx) {
2413
2690
  schema.prefixItems = prefixSchemas;
2414
2691
  }
2415
2692
  if (node2.minLength)
2416
- schema.minItems = node2.minLength;
2693
+ schema.minItems = Math.max(schema.minItems ?? 0, node2.minLength);
2417
2694
  if (node2.variadic) {
2418
2695
  ctx.path = `${path}[number]`;
2419
2696
  const variadicItemSchema = toJsonSchemaRecurse(node2.variadic, ctx);
@@ -2423,8 +2700,9 @@ var reduceSequenceJsonSchema = function (node2, schema, ctx) {
2423
2700
  schema.additionalItems = variadicItemSchema;
2424
2701
  else
2425
2702
  schema.items = variadicItemSchema;
2426
- if (node2.maxLength)
2427
- schema.maxItems = node2.maxLength;
2703
+ if (node2.maxLength) {
2704
+ schema.maxItems = Math.min(schema.maxItems ?? Number.POSITIVE_INFINITY, node2.maxLength);
2705
+ }
2428
2706
  if (postfixSchemas) {
2429
2707
  schema = ctx.fallback.arrayPostfix({
2430
2708
  code: "arrayPostfix",
@@ -2432,14 +2710,15 @@ var reduceSequenceJsonSchema = function (node2, schema, ctx) {
2432
2710
  elements: postfixSchemas
2433
2711
  });
2434
2712
  }
2435
- } else if (isOpenApi)
2436
- schema.maxItems = node2.maxLength;
2437
- else {
2713
+ } else if (isOpenApi) {
2714
+ schema.maxItems = Math.min(schema.maxItems ?? Number.POSITIVE_INFINITY, node2.maxLength);
2715
+ } else {
2438
2716
  if (isDraft07)
2439
2717
  schema.additionalItems = false;
2440
2718
  else
2441
2719
  schema.items = false;
2442
- delete schema.maxItems;
2720
+ if (schema.maxItems !== void 0 && schema.maxItems >= node2.maxLength)
2721
+ delete schema.maxItems;
2443
2722
  }
2444
2723
  if (isOpenApi && prefixSchemas) {
2445
2724
  schema = ctx.fallback.arrayPrefix({
@@ -2469,7 +2748,7 @@ var reduceJsonSchemaByKind = {
2469
2748
  code: "patternFlags",
2470
2749
  base,
2471
2750
  pattern: node2.rule,
2472
- flags: node2.flags
2751
+ flags: node2.flags ?? ""
2473
2752
  });
2474
2753
  }
2475
2754
  if (base.pattern) {
@@ -2572,7 +2851,7 @@ var reduceJsonSchemaByKind = {
2572
2851
  }
2573
2852
  },
2574
2853
  predicate: function (node2, base, ctx) { return (
2575
- // JSON Schema's object type already excludes arrays
2854
+ // JSON Schema's object type already excludes arrays and functions
2576
2855
  node2.predicate === isNonArray ? base : ctx.fallback.predicate({
2577
2856
  code: "predicate",
2578
2857
  base,
@@ -2608,6 +2887,8 @@ var numberDomain = {
2608
2887
  numberAllowsNaN: false,
2609
2888
  numberAllowsInfinity: false
2610
2889
  };
2890
+ var maxReadDepth = 512;
2891
+ var maxValueDepth = 64;
2611
2892
  var readJsonSchema = function (schema, document = schema) {
2612
2893
  const $schema = String(isJsonSchemaObject(document) && document.$schema);
2613
2894
  const documentResource = { schema: document, uri: documentUri };
@@ -2620,6 +2901,10 @@ var readJsonSchema = function (schema, document = schema) {
2620
2901
  resourcesByUri: void 0,
2621
2902
  rootsByRef: {},
2622
2903
  refsBeingRead: [],
2904
+ shallowRefs: /* @__PURE__ */ new Set(),
2905
+ inPredicate: 0,
2906
+ reading: /* @__PURE__ */ new Set(),
2907
+ depth: 0,
2623
2908
  cyclesByRef: {}
2624
2909
  };
2625
2910
  const id = idOf(document, ctx);
@@ -2637,45 +2922,90 @@ var read = function (schema, pointer, ctx) {
2637
2922
  return schema ? $ark.kw.unknown : $ark.kw.never;
2638
2923
  if (!isJsonSchemaObject(schema))
2639
2924
  return throwParseError(writeInvalidJsonSchemaMessage(pointer, schema));
2640
- const o = schema;
2641
- for (const k in o)
2642
- checkKeyword(o, k, pointer, ctx);
2643
- if (o.$ref !== void 0 && ctx.dialectBefore2019)
2644
- return readRef(o.$ref, pointer, ctx);
2925
+ if (ctx.depth >= maxReadDepth)
2926
+ return throwParseError(writeMaxDepthMessage(pointer));
2927
+ if (ctx.reading.has(schema))
2928
+ return throwParseError(writeCircularSchemaMessage(pointer));
2929
+ ctx.reading.add(schema);
2930
+ ctx.depth++;
2645
2931
  const enclosing = ctx.resource;
2646
- const id = schema === enclosing.schema ? void 0 : idOf(o, ctx);
2647
- if (id !== void 0) {
2648
- ctx.resource = {
2649
- schema,
2650
- uri: resolveUri(id, enclosing.uri, `${pointer}/${ctx.idKey}`)
2651
- };
2652
- }
2653
- let result = $ark.kw.unknown;
2654
- for (const readKeywords of keywordReaders) {
2655
- const constraint = readKeywords(o, pointer, ctx);
2656
- if (constraint)
2657
- result = intersectRoots(result, constraint);
2932
+ try {
2933
+ const o = schema;
2934
+ for (const k in o)
2935
+ checkKeyword(o, k, pointer, ctx);
2936
+ if (o.$ref !== void 0 && ctx.dialectBefore2019)
2937
+ return readRef(o.$ref, pointer, ctx);
2938
+ const id = schema === enclosing.schema ? void 0 : idOf(o, ctx);
2939
+ if (id !== void 0) {
2940
+ ctx.resource = {
2941
+ schema,
2942
+ uri: resolveUri(id, enclosing.uri, `${pointer}/${ctx.idKey}`)
2943
+ };
2944
+ }
2945
+ let result = $ark.kw.unknown;
2946
+ for (const readKeywords of keywordReaders) {
2947
+ const constraint = readKeywords(o, pointer, ctx);
2948
+ if (constraint)
2949
+ result = intersectRoots(result, constraint);
2950
+ }
2951
+ if (o.type === void 0 && o.nullable === true)
2952
+ result = unionOf([result, typeRoots().null]);
2953
+ return withAnnotations(result, o, pointer);
2954
+ } finally {
2955
+ ctx.resource = enclosing;
2956
+ ctx.depth--;
2957
+ ctx.reading.delete(schema);
2658
2958
  }
2659
- ctx.resource = enclosing;
2660
- return withAnnotations(result, o);
2661
2959
  };
2662
2960
  var readRef = function (ref, pointer, ctx) {
2663
2961
  const target = resolveRef(ref, pointer, ctx);
2664
2962
  const key = target.resource.uri === documentUri ? `#${target.fragment}` : `${target.resource.uri}#${target.fragment}`;
2665
- if (key in ctx.rootsByRef)
2963
+ if (hasOwn(ctx.rootsByRef, key))
2666
2964
  return ctx.rootsByRef[key];
2667
2965
  if (ctx.refsBeingRead.includes(key)) {
2966
+ if (ctx.inPredicate > 0 && ctx.shallowRefs.has(key))
2967
+ return throwParseError(writeShallowCycleMessage(ref, pointer));
2668
2968
  ctx.cyclesByRef[key] ??= jsonSchemaScope().openSynthetic(`synthetic${hashOf(`${key}
2669
2969
  ${printable(target.schema)}`)}`);
2670
2970
  return jsonSchemaScope().lazilyResolve(() => ctx.rootsByRef[key], ctx.cyclesByRef[key].id);
2671
2971
  }
2672
2972
  const enclosing = ctx.resource;
2973
+ const prevReading = ctx.reading;
2974
+ const hadShallow = ctx.shallowRefs.has(key);
2673
2975
  ctx.resource = target.resource;
2976
+ ctx.reading = /* @__PURE__ */ new Set();
2674
2977
  ctx.refsBeingRead.push(key);
2675
- const root = read(target.schema, ref, ctx);
2676
- ctx.refsBeingRead.pop();
2677
- ctx.resource = enclosing;
2678
- return ctx.rootsByRef[key] = root;
2978
+ ctx.shallowRefs.add(key);
2979
+ try {
2980
+ const root = read(target.schema, ref, ctx);
2981
+ return ctx.rootsByRef[key] = root;
2982
+ } finally {
2983
+ if (!hadShallow)
2984
+ ctx.shallowRefs.delete(key);
2985
+ ctx.refsBeingRead.pop();
2986
+ ctx.reading = prevReading;
2987
+ ctx.resource = enclosing;
2988
+ }
2989
+ };
2990
+ var withShallowPredicate = (ctx, read2) => {
2991
+ ctx.inPredicate++;
2992
+ try {
2993
+ return read2();
2994
+ } finally {
2995
+ ctx.inPredicate--;
2996
+ }
2997
+ };
2998
+ var withChildValue = function (ctx, read2) {
2999
+ const prevShallowRefs = ctx.shallowRefs;
3000
+ const prevInPredicate = ctx.inPredicate;
3001
+ ctx.shallowRefs = /* @__PURE__ */ new Set();
3002
+ ctx.inPredicate = 0;
3003
+ try {
3004
+ return read2();
3005
+ } finally {
3006
+ ctx.shallowRefs = prevShallowRefs;
3007
+ ctx.inPredicate = prevInPredicate;
3008
+ }
2679
3009
  };
2680
3010
  var resolveRef = function (ref, pointer, ctx) {
2681
3011
  if (ref === "#" || ref.startsWith("#/"))
@@ -2744,9 +3074,11 @@ var indexResources = function (ctx) {
2744
3074
  [ctx.documentResource.uri]: ctx.documentResource
2745
3075
  };
2746
3076
  const visited = /* @__PURE__ */ new Set();
2747
- const visit = (schema, enclosing) => {
3077
+ const visit = (schema, enclosing, pointer, depth) => {
2748
3078
  if (!isJsonSchemaObject(schema) || visited.has(schema))
2749
3079
  return;
3080
+ if (depth >= maxReadDepth)
3081
+ throwParseError(writeMaxDepthMessage(pointer));
2750
3082
  visited.add(schema);
2751
3083
  const o = schema;
2752
3084
  const id = schema === ctx.document ? void 0 : idOf(o, ctx);
@@ -2762,23 +3094,31 @@ var indexResources = function (ctx) {
2762
3094
  }
2763
3095
  for (const k in o) {
2764
3096
  const kind = keywordValueKinds[k];
3097
+ const keyPointer = `${pointer}/${escapePointer(k)}`;
2765
3098
  if (kind === "schema")
2766
- visit(o[k], resource);
2767
- else if (kind === "items" || kind === "schemas" || kind === "branches")
2768
- for (const v of isArray(o[k]) ? o[k] : [o[k]])
2769
- visit(v, resource);
2770
- else if ((kind === "schemasByKey" || kind === "dependencies") && isJsonSchemaObject(o[k]))
2771
- for (const v of Object.values(o[k]))
2772
- visit(v, resource);
3099
+ visit(o[k], resource, keyPointer, depth + 1);
3100
+ else if (kind === "items" || kind === "schemas" || kind === "branches") {
3101
+ if (isArray(o[k])) {
3102
+ for (let i = 0; i < o[k].length; i++)
3103
+ visit(o[k][i], resource, `${keyPointer}/${i}`, depth + 1);
3104
+ } else
3105
+ visit(o[k], resource, keyPointer, depth + 1);
3106
+ } else if ((kind === "schemasByKey" || kind === "dependencies") && isJsonSchemaObject(o[k])) {
3107
+ for (const [subKey, v] of Object.entries(o[k])) {
3108
+ visit(v, resource, `${keyPointer}/${escapePointer(subKey)}`, depth + 1);
3109
+ }
3110
+ }
2773
3111
  }
2774
3112
  if (schema === ctx.document && isJsonSchemaObject(o.components)) {
2775
3113
  const { schemas } = o.components;
2776
- if (isJsonSchemaObject(schemas))
2777
- for (const v of Object.values(schemas))
2778
- visit(v, resource);
3114
+ if (isJsonSchemaObject(schemas)) {
3115
+ for (const [subKey, v] of Object.entries(schemas)) {
3116
+ visit(v, resource, `${pointer}/components/schemas/${escapePointer(subKey)}`, depth + 1);
3117
+ }
3118
+ }
2779
3119
  }
2780
3120
  };
2781
- visit(ctx.document, ctx.documentResource);
3121
+ visit(ctx.document, ctx.documentResource, "#", 0);
2782
3122
  return resourcesByUri;
2783
3123
  };
2784
3124
  var anchorsOf = function (o, ctx) {
@@ -2799,8 +3139,14 @@ var intersectRoots = (l, r) => intersectNodesRoot(l, r, jsonSchemaScope()).toNev
2799
3139
  var keywordReaders = [
2800
3140
  (o, pointer, ctx) => o.$ref === void 0 ? void 0 : readRef(o.$ref, pointer, ctx),
2801
3141
  (o) => o.type === void 0 ? void 0 : unionOf(typeNamesOf(o).map((name) => typeRoots()[name])),
2802
- (o) => o.const === void 0 ? void 0 : constRoot(o.const),
2803
- (o) => o.enum === void 0 ? void 0 : unionOf(o.enum.map(constRoot)),
3142
+ (o, pointer) => o.const === void 0 ? void 0 : constRoot(o.const, `${pointer}/const`),
3143
+ function (o, pointer) {
3144
+ if (o.enum === void 0)
3145
+ return;
3146
+ const items = o.enum;
3147
+ const seen = /* @__PURE__ */ new Set([items]);
3148
+ return unionOf(items.map((v, i) => constRoot(v, `${pointer}/enum/${i}`, 0, seen)));
3149
+ },
2804
3150
  function (o) {
2805
3151
  const constraints = [];
2806
3152
  if (o.minimum !== void 0)
@@ -2821,7 +3167,7 @@ var keywordReaders = [
2821
3167
  const divisor2 = o.multipleOf;
2822
3168
  constraints.push(Number.isInteger(divisor2) ? { divisor: divisor2 } : {
2823
3169
  predicate: [
2824
- opaque(["multipleOf", divisor2], `a multiple of ${divisor2}`, (data) => Number.isInteger(data / divisor2))
3170
+ opaque(["multipleOf", divisor2], `a multiple of ${divisor2}`, isDecimalMultipleOf(divisor2))
2825
3171
  ]
2826
3172
  });
2827
3173
  }
@@ -2845,36 +3191,40 @@ var keywordReaders = [
2845
3191
  (o, pointer, ctx) => constrainOwnType("array", readArray(o, pointer, ctx)),
2846
3192
  (o, pointer, ctx) => constrainOwnType("object", readObject(o, pointer, ctx)),
2847
3193
  (o, pointer, ctx) => o.allOf === void 0 ? void 0 : readEach(o.allOf, `${pointer}/allOf`, ctx).reduce(intersectRoots, $ark.kw.unknown),
2848
- (o, pointer, ctx) => o.anyOf === void 0 ? void 0 : unionOf(readEach(o.anyOf, `${pointer}/anyOf`, ctx)),
3194
+ (o, pointer, ctx) => o.anyOf === void 0 ? void 0 : unionOf(withShallowPredicate(ctx, () => readEach(o.anyOf, `${pointer}/anyOf`, ctx))),
2849
3195
  function (o, pointer, ctx) {
2850
3196
  if (o.oneOf === void 0)
2851
3197
  return;
2852
- const branches = readEach(o.oneOf, `${pointer}/oneOf`, ctx);
2853
- return branchesAreDisjoint(branches) ? unionOf(branches) : opaqueRoot(["oneOf", idsOf(branches)], `exactly one of ${branches.map((branch) => branch.description).join(", ")}`, (data) => branches.filter((branch) => branch.allows(data)).length === 1);
3198
+ const branches = withShallowPredicate(ctx, () => readEach(o.oneOf, `${pointer}/oneOf`, ctx));
3199
+ return branchesAreDisjoint(branches) ? unionOf(branches) : opaqueRoot(["oneOf", idsOf(branches)], `exactly one of ${branches.map(expectedOf).join(", ")}`, (data) => branches.filter((branch) => branch.allows(data)).length === 1);
2854
3200
  },
2855
3201
  function (o, pointer, ctx) {
2856
3202
  if (o.not === void 0)
2857
3203
  return;
2858
- const negated = read(o.not, `${pointer}/not`, ctx);
3204
+ const negated = withShallowPredicate(ctx, () => read(o.not, `${pointer}/not`, ctx));
2859
3205
  if (negated.isUnknown())
2860
3206
  return $ark.kw.never;
2861
- return opaqueRoot(["not", negated.id], `other than ${negated.description}`, (data) => !negated.allows(data));
3207
+ return opaqueRoot(["not", negated.id], `other than ${expectedOf(negated)}`, (data) => !negated.allows(data));
2862
3208
  },
2863
3209
  function (o, pointer, ctx) {
2864
3210
  if (o.if === void 0 || o.then === void 0 && o.else === void 0)
2865
3211
  return;
2866
- const condition = read(o.if, `${pointer}/if`, ctx);
2867
- const consequent = read(o.then ?? true, `${pointer}/then`, ctx);
2868
- const alternative = read(o.else ?? true, `${pointer}/else`, ctx);
2869
- return opaqueRoot(["if", idsOf([condition, consequent, alternative])], `${consequent.description} if ${condition.description}, else ${alternative.description}`, (data) => condition.allows(data) ? consequent.allows(data) : alternative.allows(data));
3212
+ const [condition, consequent, alternative] = withShallowPredicate(ctx, () => [
3213
+ read(o.if, `${pointer}/if`, ctx),
3214
+ read(o.then ?? true, `${pointer}/then`, ctx),
3215
+ read(o.else ?? true, `${pointer}/else`, ctx)
3216
+ ]);
3217
+ return opaqueRoot(["if", idsOf([condition, consequent, alternative])], `${expectedOf(consequent)} if ${expectedOf(condition)}, else ${expectedOf(alternative)}`, (data) => condition.allows(data) ? consequent.allows(data) : alternative.allows(data));
2870
3218
  }
2871
3219
  ];
2872
3220
  var readArray = function (o, pointer, ctx) {
2873
3221
  const constraints = [];
2874
3222
  const elementsKey = isArray(o.items) ? "items" : "prefixItems";
2875
3223
  const restKey = elementsKey === "items" ? "additionalItems" : "items";
2876
- const elements = readEach(o[elementsKey] ?? [], `${pointer}/${elementsKey}`, ctx);
2877
- const rest = read(o[restKey] ?? true, `${pointer}/${restKey}`, ctx);
3224
+ const [elements, rest] = withChildValue(ctx, () => [
3225
+ readEach(o[elementsKey] ?? [], `${pointer}/${elementsKey}`, ctx),
3226
+ read(o[restKey] ?? true, `${pointer}/${restKey}`, ctx)
3227
+ ]);
2878
3228
  if (elements.length === 0 && rest.isNever())
2879
3229
  constraints.push({ exactLength: 0 });
2880
3230
  else if (elements.length || !rest.isUnknown()) {
@@ -2889,17 +3239,17 @@ var readArray = function (o, pointer, ctx) {
2889
3239
  if (o.uniqueItems === true) {
2890
3240
  constraints.push({
2891
3241
  predicate: [
2892
- opaque(["uniqueItems"], "an array of unique items", (data) => data.every((item, i) => data.slice(i + 1).every((other) => !jsonEquals(item, other))))
3242
+ opaque(["uniqueItems"], "an array of unique items", hasUniqueItems)
2893
3243
  ]
2894
3244
  });
2895
3245
  }
2896
3246
  const min2 = o.minContains ?? 1;
2897
3247
  const max2 = o.maxContains ?? Number.POSITIVE_INFINITY;
2898
3248
  if (o.contains !== void 0 && (min2 !== 0 || max2 !== Number.POSITIVE_INFINITY)) {
2899
- const contained = read(o.contains, `${pointer}/contains`, ctx);
3249
+ const contained = withChildValue(ctx, () => read(o.contains, `${pointer}/contains`, ctx));
2900
3250
  constraints.push({
2901
3251
  predicate: [
2902
- opaque(["contains", contained.id, min2, max2], min2 === 1 && max2 === Number.POSITIVE_INFINITY ? `an array containing ${contained.description}` : `an array with ${describeCount(min2, max2, "item that is", "items that are")} ${contained.description}`, (data) => {
3252
+ opaque(["contains", contained.id, min2, max2], min2 === 1 && max2 === Number.POSITIVE_INFINITY ? `an array containing ${expectedOf(contained)}` : `an array with ${describeCount(min2, max2, "item that is", "items that are")} ${expectedOf(contained)}`, (data) => {
2903
3253
  const count = data.filter((item) => contained.allows(item)).length;
2904
3254
  return count >= min2 && count <= max2;
2905
3255
  })
@@ -2911,14 +3261,14 @@ var readArray = function (o, pointer, ctx) {
2911
3261
  var readObject = function (o, pointer, ctx) {
2912
3262
  const properties = o.properties ?? {};
2913
3263
  const patternProperties = o.patternProperties ?? {};
2914
- const additional = read(o.additionalProperties ?? true, `${pointer}/additionalProperties`, ctx);
3264
+ const additional = withChildValue(ctx, () => read(o.additionalProperties ?? true, `${pointer}/additionalProperties`, ctx));
2915
3265
  const patterns = Object.keys(patternProperties).map((source) => {
2916
3266
  const patternPointer = `${pointer}/patternProperties/${escapePointer(source)}`;
2917
3267
  const schema = patternSchemaOf(source, patternPointer);
2918
3268
  return {
2919
3269
  schema,
2920
3270
  matcher: new RegExp(schema.rule, schema.flags),
2921
- value: read(patternProperties[source], patternPointer, ctx)
3271
+ value: withChildValue(ctx, () => read(patternProperties[source], patternPointer, ctx))
2922
3272
  };
2923
3273
  });
2924
3274
  const isDeclared = (k) => hasOwn(properties, k) || patterns.some((p) => p.matcher.test(k));
@@ -2937,21 +3287,12 @@ var readObject = function (o, pointer, ctx) {
2937
3287
  order: []
2938
3288
  };
2939
3289
  for (const key of /* @__PURE__ */ new Set([...Object.keys(properties), ...required2])) {
2940
- const value = patterns.filter((p) => p.matcher.test(key)).reduce((result, p) => intersectRoots(result, p.value), hasOwn(properties, key) ? read(properties[key], `${pointer}/properties/${escapePointer(key)}`, ctx) : isDeclared(key) ? $ark.kw.unknown : additional);
3290
+ const value = patterns.filter((p) => p.matcher.test(key)).reduce((result, p) => intersectRoots(result, p.value), hasOwn(properties, key) ? withChildValue(ctx, () => read(properties[key], `${pointer}/properties/${escapePointer(key)}`, ctx)) : isDeclared(key) ? $ark.kw.unknown : additional);
2941
3291
  const isRequired = required2.includes(key);
2942
3292
  if (isRequired && value.isNever())
2943
3293
  return [$ark.kw.never];
2944
3294
  if (key in Object.prototype) {
2945
- structure2.index.push({
2946
- signature: {
2947
- domain: "string",
2948
- pattern: [{ rule: `^${escapeRegex(key)}$` }]
2949
- },
2950
- value
2951
- });
2952
- if (isRequired) {
2953
- structure2.predicate.push(opaque(["ownKey", key], `an object with its own ${key}`, (data) => hasOwn(data, key)));
2954
- }
3295
+ addPrototypeKeyConstraint(structure2, key, value, isRequired);
2955
3296
  continue;
2956
3297
  }
2957
3298
  structure2.order.push(key);
@@ -2969,7 +3310,7 @@ var readObject = function (o, pointer, ctx) {
2969
3310
  additional.id,
2970
3311
  Object.keys(properties),
2971
3312
  patterns.map((p) => p.schema)
2972
- ], `an object whose other properties are ${additional.description}`, (data) => Object.keys(data).every((k) => isDeclared(k) || additional.allows(data[k]))));
3313
+ ], `an object whose other properties are ${expectedOf(additional)}`, (data) => Object.keys(data).every((k) => isDeclared(k) || additional.allows(data[k]))));
2973
3314
  }
2974
3315
  }
2975
3316
  structure2.predicate.push(...readKeyPredicates(o, pointer, ctx));
@@ -2978,9 +3319,9 @@ var readObject = function (o, pointer, ctx) {
2978
3319
  var readKeyPredicates = function (o, pointer, ctx) {
2979
3320
  const predicates = [];
2980
3321
  if (o.propertyNames !== void 0) {
2981
- const names = read(o.propertyNames, `${pointer}/propertyNames`, ctx);
3322
+ const names = withChildValue(ctx, () => read(o.propertyNames, `${pointer}/propertyNames`, ctx));
2982
3323
  if (!$ark.kw.string.extends(names)) {
2983
- predicates.push(opaque(["propertyNames", names.id], `an object whose keys are ${names.description}`, (data) => Object.keys(data).every((k) => names.allows(k))));
3324
+ predicates.push(opaque(["propertyNames", names.id], `an object whose keys are ${expectedOf(names)}`, (data) => Object.keys(data).every((k) => names.allows(k))));
2984
3325
  }
2985
3326
  }
2986
3327
  const min2 = o.minProperties ?? 0;
@@ -3004,10 +3345,10 @@ var readKeyPredicates = function (o, pointer, ctx) {
3004
3345
  continue;
3005
3346
  predicates.push(opaque(["dependentRequired", key, dependency], `an object with ${dependency.join(", ")} if it has ${key}`, (data) => !hasOwn(data, key) || dependency.every((k) => hasOwn(data, k))));
3006
3347
  } else {
3007
- const dependent = read(dependency, `${pointer}/${keyword}/${escapePointer(key)}`, ctx);
3348
+ const dependent = withShallowPredicate(ctx, () => read(dependency, `${pointer}/${keyword}/${escapePointer(key)}`, ctx));
3008
3349
  if (dependent.isUnknown())
3009
3350
  continue;
3010
- predicates.push(opaque(["dependentSchemas", key, dependent.id], `${dependent.description} if it has ${key}`, (data) => !hasOwn(data, key) || dependent.allows(data)));
3351
+ predicates.push(opaque(["dependentSchemas", key, dependent.id], `${expectedOf(dependent)} if it has ${key}`, (data) => !hasOwn(data, key) || dependent.allows(data)));
3011
3352
  }
3012
3353
  }
3013
3354
  }
@@ -3027,7 +3368,7 @@ var notArray = /* @__PURE__ */ cached(function () {
3027
3368
  $ark.sets.disjointOf = disjointFromArray;
3028
3369
  return jsonSchemaNode("predicate", {
3029
3370
  predicate: isNonArray,
3030
- meta: { description: "not an array" }
3371
+ meta: { description: "not an array or function" }
3031
3372
  });
3032
3373
  });
3033
3374
  var disjointFromArray = function (node2) {
@@ -3046,12 +3387,7 @@ var typeRoots = /* @__PURE__ */ cached(function () { return ({
3046
3387
  array: $ark.kw.Array,
3047
3388
  object: jsonSchemaRoot({ domain: "object", predicate: [notArray()] })
3048
3389
  }) });
3049
- var otherThan = function (...branches) { return unionOf([
3050
- ...branches,
3051
- jsonSchemaRoot(["bigint", "symbol", { unit: void 0 }]),
3052
- typeRoots().boolean,
3053
- typeRoots().null
3054
- ]) };
3390
+ var otherThan = (...branches) => unionOf([...branches, typeRoots().boolean, typeRoots().null]);
3055
3391
  var unconstrainedBy = /* @__PURE__ */ cached(function () {
3056
3392
  const { number, string, array, object: object2 } = typeRoots();
3057
3393
  return {
@@ -3061,15 +3397,88 @@ var unconstrainedBy = /* @__PURE__ */ cached(function () {
3061
3397
  object: otherThan(number, string, array)
3062
3398
  };
3063
3399
  });
3064
- var constRoot = function (value) { return isArray(value) ? jsonSchemaRoot(value.length === 0 ? { proto: Array, exactLength: 0 } : { proto: Array, sequence: { prefix: value.map(constRoot) } }) : isJsonSchemaObject(value) ? jsonSchemaRoot({
3065
- domain: "object",
3066
- predicate: [notArray()],
3067
- required: Object.entries(value).map(([key, v]) => ({
3068
- key,
3069
- value: constRoot(v)
3070
- })),
3071
- undeclared: "reject"
3072
- }) : jsonSchemaRoot({ unit: value }) };
3400
+ var addPrototypeKeyConstraint = function (target, key, value, isRequired) {
3401
+ target.index.push({
3402
+ signature: {
3403
+ domain: "string",
3404
+ pattern: [{ rule: `^${escapeRegex(key)}$` }]
3405
+ },
3406
+ value
3407
+ });
3408
+ if (isRequired) {
3409
+ target.predicate.push(opaque(["ownKey", key], `an object with its own ${key}`, (data) => hasOwn(data, key)));
3410
+ }
3411
+ };
3412
+ var decimalParts = function (n) {
3413
+ const s = `${n}`;
3414
+ const eIndex = s.indexOf("e");
3415
+ const mantissa = eIndex === -1 ? s : s.slice(0, eIndex);
3416
+ let exp = eIndex === -1 ? 0 : Number(s.slice(eIndex + 1));
3417
+ const dot = mantissa.indexOf(".");
3418
+ if (dot !== -1) {
3419
+ exp -= mantissa.length - dot - 1;
3420
+ return [BigInt(mantissa.slice(0, dot) + mantissa.slice(dot + 1)), exp];
3421
+ }
3422
+ return [BigInt(mantissa), exp];
3423
+ };
3424
+ var isDecimalMultipleOf = function (divisor2) {
3425
+ const [sCoeff, sExp] = decimalParts(divisor2);
3426
+ return (data) => {
3427
+ if (data === 0)
3428
+ return true;
3429
+ if (!Number.isFinite(data))
3430
+ return false;
3431
+ const [dCoeff, dExp] = decimalParts(data);
3432
+ const expDiff = dExp - sExp;
3433
+ if (expDiff >= 0) {
3434
+ if (sCoeff === 1n)
3435
+ return true;
3436
+ return dCoeff * 10n ** BigInt(expDiff) % sCoeff === 0n;
3437
+ }
3438
+ if (expDiff < -21)
3439
+ return false;
3440
+ return dCoeff % (sCoeff * 10n ** BigInt(-expDiff)) === 0n;
3441
+ };
3442
+ };
3443
+ var constObjectRoot = function (value, pointer, depth, seen) {
3444
+ const required2 = [];
3445
+ const index2 = [];
3446
+ const predicate2 = [notArray()];
3447
+ for (const [key, v] of Object.entries(value)) {
3448
+ const propValue = constRoot(v, `${pointer}/${escapePointer(key)}`, depth, seen);
3449
+ if (key in Object.prototype)
3450
+ addPrototypeKeyConstraint({ index: index2, predicate: predicate2 }, key, propValue, true);
3451
+ else
3452
+ required2.push({ key, value: propValue });
3453
+ }
3454
+ return jsonSchemaRoot({
3455
+ domain: "object",
3456
+ predicate: predicate2,
3457
+ required: required2,
3458
+ ...index2.length && { index: index2 },
3459
+ undeclared: "reject"
3460
+ });
3461
+ };
3462
+ var constRoot = function (value, pointer, depth = 0, seen = /* @__PURE__ */ new Set()) {
3463
+ const isArr = isArray(value);
3464
+ if (!isArr && !isJsonSchemaObject(value))
3465
+ return jsonSchemaRoot({ unit: value });
3466
+ if (depth >= maxValueDepth)
3467
+ return throwParseError(writeMaxDepthMessage(pointer, maxValueDepth));
3468
+ if (seen.has(value))
3469
+ return throwParseError(writeCircularSchemaMessage(pointer));
3470
+ seen.add(value);
3471
+ try {
3472
+ return isArr ? jsonSchemaRoot(value.length === 0 ? { proto: Array, exactLength: 0 } : {
3473
+ proto: Array,
3474
+ sequence: {
3475
+ prefix: value.map((v, i) => constRoot(v, `${pointer}/${i}`, depth + 1, seen))
3476
+ }
3477
+ }) : constObjectRoot(value, pointer, depth + 1, seen);
3478
+ } finally {
3479
+ seen.delete(value);
3480
+ }
3481
+ };
3073
3482
  var predicatesByKey = /* @__PURE__ */ new WeakCache();
3074
3483
  var opaque = function (key, description, predicate2) {
3075
3484
  const cacheKey = JSON.stringify(key);
@@ -3088,9 +3497,41 @@ var describeCount = function (min2, max2, one, many) {
3088
3497
  var readEach = (schemas, pointer, ctx) => schemas.map((schema, i) => read(schema, `${pointer}/${i}`, ctx));
3089
3498
  var unionOf = (roots) => jsonSchemaNode("union", { branches: roots.flatMap((root) => root.branches) });
3090
3499
  var branchesAreDisjoint = function (branches) { return branches.every((l, i) => branches.slice(i + 1).every((r) => intersectNodesRoot(l, r, jsonSchemaScope()) instanceof Disjoint)) };
3091
- var withAnnotations = function (root, o) {
3500
+ var expectedOf = (root) => typeof root.meta.expected === "string" ? root.meta.expected : root.description;
3501
+ var checkAnnotationValue = function (value, pointer, depth = 0, seen = /* @__PURE__ */ new Set()) {
3502
+ if (typeof value !== "object" || value === null)
3503
+ return;
3504
+ if (depth >= maxValueDepth)
3505
+ throwParseError(writeMaxDepthMessage(pointer, maxValueDepth));
3506
+ if (seen.has(value))
3507
+ throwParseError(writeCircularSchemaMessage(pointer));
3508
+ seen.add(value);
3509
+ try {
3510
+ if (isArray(value)) {
3511
+ for (let i = 0; i < value.length; i++) {
3512
+ if (i in value)
3513
+ checkAnnotationValue(value[i], `${pointer}/${i}`, depth + 1, seen);
3514
+ }
3515
+ } else {
3516
+ for (const [key, v] of Object.entries(value)) {
3517
+ checkAnnotationValue(v, `${pointer}/${escapePointer(key)}`, depth + 1, seen);
3518
+ }
3519
+ }
3520
+ } finally {
3521
+ seen.delete(value);
3522
+ }
3523
+ };
3524
+ var withAnnotations = function (root, o, pointer) {
3525
+ if (o.default !== void 0)
3526
+ checkAnnotationValue(o.default, `${pointer}/default`);
3527
+ if (o.examples !== void 0)
3528
+ checkAnnotationValue(o.examples, `${pointer}/examples`);
3092
3529
  const meta = flatMorph(annotationKeys2, (i, k) => o[k] === void 0 ? [] : [k, o[k]]);
3093
- return Object.keys(meta).length === 0 || root.is("alias") ? root : root.configure(meta, "self");
3530
+ if (Object.keys(meta).length === 0 || root.is("alias"))
3531
+ return root;
3532
+ if (typeof meta.description === "string")
3533
+ meta.expected = expectedOf(root);
3534
+ return root.configure(meta, "self");
3094
3535
  };
3095
3536
  var annotationKeys2 = [
3096
3537
  "title",
@@ -3129,6 +3570,90 @@ var patternSchemaOf = function (source, pointer) {
3129
3570
  const flags = flagsOf(source);
3130
3571
  return flags ? { rule: source, flags } : { rule: source };
3131
3572
  };
3573
+ var canonicalJsonKey = function (value, seen, budget) {
3574
+ if (value === null)
3575
+ return "null";
3576
+ switch (typeof value) {
3577
+ case "string":
3578
+ return JSON.stringify(value);
3579
+ case "number":
3580
+ return `${value}`;
3581
+ case "boolean":
3582
+ return value ? "true" : "false";
3583
+ case "bigint":
3584
+ return `${value}n`;
3585
+ case "undefined":
3586
+ return "undefined";
3587
+ case "object": {
3588
+ if (budget.remaining <= 0)
3589
+ return "...";
3590
+ if (seen.has(value))
3591
+ return "@";
3592
+ budget.remaining--;
3593
+ seen.add(value);
3594
+ try {
3595
+ if (isArray(value)) {
3596
+ const parts2 = [];
3597
+ for (let i = 0; i < value.length; i++) {
3598
+ if (budget.remaining <= 0) {
3599
+ parts2.push(`...(${value.length})`);
3600
+ break;
3601
+ }
3602
+ budget.remaining--;
3603
+ parts2.push(canonicalJsonKey(value[i], seen, budget));
3604
+ }
3605
+ return `[${parts2.join(",")}]`;
3606
+ }
3607
+ const keys = Object.keys(value).sort();
3608
+ const parts = [];
3609
+ for (let i = 0; i < keys.length; i++) {
3610
+ if (budget.remaining <= 0) {
3611
+ parts.push(`...(${keys.length})`);
3612
+ break;
3613
+ }
3614
+ budget.remaining--;
3615
+ const k = keys[i];
3616
+ parts.push(`${JSON.stringify(k)}:${canonicalJsonKey(value[k], seen, budget)}`);
3617
+ }
3618
+ return `{${parts.join(",")}}`;
3619
+ } finally {
3620
+ seen.delete(value);
3621
+ }
3622
+ }
3623
+ default:
3624
+ return "?";
3625
+ }
3626
+ };
3627
+ var hasUniqueItems = function (data) {
3628
+ if (data.length <= 1)
3629
+ return true;
3630
+ let primitives;
3631
+ let objects;
3632
+ let seen;
3633
+ for (let i = 0; i < data.length; i++) {
3634
+ const item = data[i];
3635
+ if (typeof item !== "object" || item === null) {
3636
+ if (typeof item === "number" && Number.isNaN(item))
3637
+ continue;
3638
+ primitives ??= /* @__PURE__ */ new Set();
3639
+ if (primitives.has(item))
3640
+ return false;
3641
+ primitives.add(item);
3642
+ } else {
3643
+ seen ??= /* @__PURE__ */ new Set();
3644
+ const key = canonicalJsonKey(item, seen, { remaining: 256 });
3645
+ objects ??= /* @__PURE__ */ new Map();
3646
+ const bucket = objects.get(key);
3647
+ if (bucket) {
3648
+ if (bucket.some((other) => jsonEquals(item, other)))
3649
+ return false;
3650
+ bucket.push(item);
3651
+ } else
3652
+ objects.set(key, [item]);
3653
+ }
3654
+ }
3655
+ return true;
3656
+ };
3132
3657
  var jsonEquals = function (l, r) {
3133
3658
  if (l === r)
3134
3659
  return true;
@@ -3266,9 +3791,7 @@ var checkKeyword = function (o, k, pointer, ctx) {
3266
3791
  checkNullable(o, pointer);
3267
3792
  };
3268
3793
  var checkNullable = function (o, pointer) {
3269
- if (o.type === void 0)
3270
- throwParseError(writeNullableWithoutTypeMessage(`${pointer}/nullable`));
3271
- if (o.nullable === false && (isArray(o.type) ? o.type : [o.type]).includes("null"))
3794
+ if (o.type !== void 0 && o.nullable === false && (isArray(o.type) ? o.type : [o.type]).includes("null"))
3272
3795
  throwParseError(writeNonNullableNullMessage(`${pointer}/nullable`));
3273
3796
  };
3274
3797
  var writeUnparsableSchemaMessage = (actual) => `Schema must be a Type, a Standard JSON Schema or a JSON Schema (was ${actual})`;
@@ -3278,8 +3801,10 @@ var writeInvalidKeywordMessage = (pointer, expected, actual) => `${pointer} must
3278
3801
  var writeUnsupportedKeywordMessage = (pointer) => `${pointer} can't be read as a set of values`;
3279
3802
  var writeUnsupportedRefMessage = (ref, pointer) => `${pointer} must reference a schema in its own document (was ${ref})`;
3280
3803
  var writeUnresolvableRefMessage = (ref) => `$ref ${ref} doesn't resolve to a schema in its document`;
3281
- var writeNullableWithoutTypeMessage = (pointer) => `${pointer} must be beside a type, to which it adds null`;
3282
3804
  var writeNonNullableNullMessage = (pointer) => `${pointer} can't be false beside a type that includes null`;
3805
+ var writeShallowCycleMessage = (ref, pointer) => `${pointer} has a shallow $ref cycle (${ref})`;
3806
+ var writeCircularSchemaMessage = (pointer) => `JSON Schema at ${pointer} is circular`;
3807
+ var writeMaxDepthMessage = (pointer, maxDepth = maxReadDepth) => `JSON Schema at ${pointer} exceeds maximum nesting depth of ${maxDepth}`;
3283
3808
 
3284
3809
  // ../sets/out/formats.js
3285
3810
  var standardRootsByIo = {
@@ -4101,7 +4626,7 @@ var InternalChainedMatchParser = class extends Callable {
4101
4626
  this.in = In;
4102
4627
  }
4103
4628
  at(key, cases) {
4104
- if (this.key)
4629
+ if (this.key !== void 0)
4105
4630
  throwParseError(doubleAtMessage);
4106
4631
  if (this.branches.length)
4107
4632
  throwParseError(chainedAtMessage);
@@ -4112,7 +4637,12 @@ var InternalChainedMatchParser = class extends Callable {
4112
4637
  return this.caseEntry(this.$.parse(def), resolver);
4113
4638
  }
4114
4639
  caseEntry(node2, resolver) {
4115
- const wrappableNode = this.key ? this.$.parse({ [this.key]: node2 }) : node2;
4640
+ const wrappableNode = this.key !== void 0 ? this.$.node("intersection", {
4641
+ domain: this.$.node("domain", { domain: "object" }),
4642
+ structure: this.$.node("structure", {
4643
+ required: [this.$.node("required", { key: this.key, value: node2 })]
4644
+ })
4645
+ }) : node2;
4116
4646
  const branch = wrappableNode.pipe(resolver);
4117
4647
  this.branches.push(branch);
4118
4648
  return this;
@@ -4142,17 +4672,20 @@ var InternalChainedMatchParser = class extends Callable {
4142
4672
  default(defaultCase) {
4143
4673
  if (typeof defaultCase === "function")
4144
4674
  this.case(intrinsic.unknown, defaultCase);
4675
+ const shouldThrow = defaultCase === "never" || defaultCase === "assert";
4145
4676
  const schema = {
4146
4677
  branches: this.branches,
4147
4678
  ordered: true
4148
4679
  };
4149
- if (defaultCase === "never" || defaultCase === "assert")
4680
+ if (shouldThrow)
4150
4681
  schema.meta = { onFail: throwOnDefault };
4151
- const cases = this.$.node("union", schema);
4682
+ let cases = this.$.node("union", schema);
4683
+ if (shouldThrow && cases.meta.onFail !== throwOnDefault)
4684
+ cases = cases.configureRefs({ onFail: throwOnDefault }, "self");
4152
4685
  if (!this.in)
4153
4686
  return this.$.fin(cases);
4154
4687
  let inputValidatedCases = this.in.pipe(cases);
4155
- if (defaultCase === "never" || defaultCase === "assert") {
4688
+ if (shouldThrow) {
4156
4689
  inputValidatedCases = inputValidatedCases.configureRefs({
4157
4690
  onFail: throwOnDefault
4158
4691
  }, "self");
@@ -4163,13 +4696,109 @@ var InternalChainedMatchParser = class extends Callable {
4163
4696
  var chainedAtMessage = `A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')`;
4164
4697
  var doubleAtMessage = `At most one key matcher may be specified per expression`;
4165
4698
 
4699
+ // out/parser/tupleExpressions.js
4700
+ var maybeParseTupleExpression = function (def, ctx) { return isIndexZeroExpression(def) ? indexZeroParsers[def[0]](def, ctx) : isIndexOneExpression(def) ? indexOneParsers[def[1]](def, ctx) : null };
4701
+ var assertTupleArity = function (def, operator, min2, max2 = min2) {
4702
+ if (def.length < min2)
4703
+ throwParseError(writeMissingRightOperandMessage(operator, ""));
4704
+ if (def.length > max2) {
4705
+ throwParseError(writeUnexpectedTupleElementsMessage(operator, min2 === max2 ? min2 : `${min2} or ${max2}`, def.length));
4706
+ }
4707
+ };
4708
+ var parseKeyOfTuple = (def, ctx) => {
4709
+ assertTupleArity(def, "keyof", 2);
4710
+ return ctx.$.parseOwn(def[1], ctx).keyof();
4711
+ };
4712
+ var parseBranchTuple = function (def, ctx) {
4713
+ assertTupleArity(def, def[1], 3);
4714
+ if (def[2] === void 0)
4715
+ return throwParseError(writeMissingRightOperandMessage(def[1], ""));
4716
+ const l = ctx.$.parseOwn(def[0], ctx);
4717
+ const r = ctx.$.parseOwn(def[2], ctx);
4718
+ if (def[1] === "|")
4719
+ return ctx.$.node("union", { branches: [l, r] });
4720
+ const result = def[1] === "&" ? intersectNodesRoot(l, r, ctx.$) : pipeNodesRoot(l, r, ctx.$);
4721
+ if (result instanceof Disjoint)
4722
+ return result.throw();
4723
+ if (def[1] === "&")
4724
+ checkWrittenIntersection(result, l, r);
4725
+ return result;
4726
+ };
4727
+ var parseArrayTuple = (def, ctx) => {
4728
+ assertTupleArity(def, "[]", 2);
4729
+ return ctx.$.parseOwn(def[0], ctx).rawArray();
4730
+ };
4731
+ var parseMorphTuple = function (def, ctx) {
4732
+ assertTupleArity(def, "=>", 3);
4733
+ if (typeof def[2] !== "function") {
4734
+ return throwParseError(writeMalformedFunctionalExpressionMessage("=>", def[2]));
4735
+ }
4736
+ return ctx.$.parseOwn(def[0], ctx).pipe(def[2]);
4737
+ };
4738
+ var writeMalformedFunctionalExpressionMessage = (operator, value) => `${operator === ":" ? "Narrow" : "Morph"} expression requires a function following '${operator}' (was ${typeof value})`;
4739
+ var parseNarrowTuple = function (def, ctx) {
4740
+ assertTupleArity(def, ":", 3);
4741
+ if (typeof def[2] !== "function") {
4742
+ return throwParseError(writeMalformedFunctionalExpressionMessage(":", def[2]));
4743
+ }
4744
+ return ctx.$.parseOwn(def[0], ctx).rawConstrainOut("predicate", def[2]);
4745
+ };
4746
+ var parseMetaTuple = (def, ctx) => {
4747
+ assertTupleArity(def, "@", 3, 4);
4748
+ return ctx.$.parseOwn(def[0], ctx).configure(def[2], def[3]);
4749
+ };
4750
+ var defineIndexOneParsers = (parsers) => parsers;
4751
+ var postfixParsers = defineIndexOneParsers({
4752
+ "[]": parseArrayTuple,
4753
+ "?": (def) => {
4754
+ assertTupleArity(def, "?", 2);
4755
+ return throwParseError(shallowOptionalMessage);
4756
+ }
4757
+ });
4758
+ var infixParsers = defineIndexOneParsers({
4759
+ "|": parseBranchTuple,
4760
+ "&": parseBranchTuple,
4761
+ ":": parseNarrowTuple,
4762
+ "=>": parseMorphTuple,
4763
+ "|>": parseBranchTuple,
4764
+ "@": parseMetaTuple,
4765
+ // since object and tuple literals parse there via `parseProperty`,
4766
+ // they must be shallow if parsed directly as a tuple expression
4767
+ "=": (def) => {
4768
+ assertTupleArity(def, "=", 3);
4769
+ return throwParseError(shallowDefaultableMessage);
4770
+ }
4771
+ });
4772
+ var indexOneParsers = { ...postfixParsers, ...infixParsers };
4773
+ var isIndexOneExpression = (def) => isOperatorOf(def[1], indexOneParsers);
4774
+ var defineIndexZeroParsers = (parsers) => parsers;
4775
+ var indexZeroParsers = defineIndexZeroParsers({
4776
+ keyof: parseKeyOfTuple,
4777
+ instanceof: function (def, ctx) {
4778
+ if (typeof def[1] !== "function") {
4779
+ return throwParseError(writeInvalidConstructorMessage(objectKindOrDomainOf(def[1])));
4780
+ }
4781
+ const branches = def.slice(1).map((ctor) => typeof ctor === "function" ? ctx.$.node("proto", { proto: ctor }) : throwParseError(writeInvalidConstructorMessage(objectKindOrDomainOf(ctor))));
4782
+ return branches.length === 1 ? branches[0] : ctx.$.node("union", { branches });
4783
+ },
4784
+ "===": (def, ctx) => ctx.$.units(def.slice(1))
4785
+ });
4786
+ var isIndexZeroExpression = (def) => isOperatorOf(def[0], indexZeroParsers);
4787
+ var isOperatorOf = (element, parsers) => typeof element === "string" && hasOwn(parsers, element);
4788
+ var writeInvalidConstructorMessage = (actual) => `Expected a constructor following 'instanceof' operator (was ${actual})`;
4789
+ var writeUnexpectedTupleElementsMessage = (operator, expected, actual) => `Tuple expression with operator '${operator}' requires ${expected} elements (got ${actual})`;
4790
+
4166
4791
  // out/parser/property.js
4167
4792
  var parseProperty = function (def, ctx) {
4168
4793
  if (isArray(def)) {
4169
- if (def[1] === "=")
4794
+ if (def[1] === "=") {
4795
+ assertTupleArity(def, "=", 3);
4170
4796
  return [ctx.$.parseOwn(def[0], ctx), "=", def[2]];
4171
- if (def[1] === "?")
4797
+ }
4798
+ if (def[1] === "?") {
4799
+ assertTupleArity(def, "?", 2);
4172
4800
  return [ctx.$.parseOwn(def[0], ctx), "?"];
4801
+ }
4173
4802
  }
4174
4803
  return parseInnerDefinition(def, ctx);
4175
4804
  };
@@ -4289,72 +4918,6 @@ var preparseKey = function (key) { return typeof key === "symbol" ? { kind: "req
4289
4918
  } };
4290
4919
  var writeInvalidSpreadTypeMessage = (def) => `Spread operand must resolve to an object literal type (was ${def})`;
4291
4920
 
4292
- // out/parser/tupleExpressions.js
4293
- var maybeParseTupleExpression = function (def, ctx) { return isIndexZeroExpression(def) ? indexZeroParsers[def[0]](def, ctx) : isIndexOneExpression(def) ? indexOneParsers[def[1]](def, ctx) : null };
4294
- var parseKeyOfTuple = (def, ctx) => ctx.$.parseOwn(def[1], ctx).keyof();
4295
- var parseBranchTuple = function (def, ctx) {
4296
- if (def[2] === void 0)
4297
- return throwParseError(writeMissingRightOperandMessage(def[1], ""));
4298
- const l = ctx.$.parseOwn(def[0], ctx);
4299
- const r = ctx.$.parseOwn(def[2], ctx);
4300
- if (def[1] === "|")
4301
- return ctx.$.node("union", { branches: [l, r] });
4302
- const result = def[1] === "&" ? intersectNodesRoot(l, r, ctx.$) : pipeNodesRoot(l, r, ctx.$);
4303
- if (result instanceof Disjoint)
4304
- return result.throw();
4305
- if (def[1] === "&")
4306
- checkWrittenIntersection(result, l, r);
4307
- return result;
4308
- };
4309
- var parseArrayTuple = (def, ctx) => ctx.$.parseOwn(def[0], ctx).rawArray();
4310
- var parseMorphTuple = function (def, ctx) {
4311
- if (typeof def[2] !== "function") {
4312
- return throwParseError(writeMalformedFunctionalExpressionMessage("=>", def[2]));
4313
- }
4314
- return ctx.$.parseOwn(def[0], ctx).pipe(def[2]);
4315
- };
4316
- var writeMalformedFunctionalExpressionMessage = (operator, value) => `${operator === ":" ? "Narrow" : "Morph"} expression requires a function following '${operator}' (was ${typeof value})`;
4317
- var parseNarrowTuple = function (def, ctx) {
4318
- if (typeof def[2] !== "function") {
4319
- return throwParseError(writeMalformedFunctionalExpressionMessage(":", def[2]));
4320
- }
4321
- return ctx.$.parseOwn(def[0], ctx).rawConstrainOut("predicate", def[2]);
4322
- };
4323
- var parseMetaTuple = (def, ctx) => ctx.$.parseOwn(def[0], ctx).configure(def[2], def[3]);
4324
- var defineIndexOneParsers = (parsers) => parsers;
4325
- var postfixParsers = defineIndexOneParsers({
4326
- "[]": parseArrayTuple,
4327
- "?": () => throwParseError(shallowOptionalMessage)
4328
- });
4329
- var infixParsers = defineIndexOneParsers({
4330
- "|": parseBranchTuple,
4331
- "&": parseBranchTuple,
4332
- ":": parseNarrowTuple,
4333
- "=>": parseMorphTuple,
4334
- "|>": parseBranchTuple,
4335
- "@": parseMetaTuple,
4336
- // since object and tuple literals parse there via `parseProperty`,
4337
- // they must be shallow if parsed directly as a tuple expression
4338
- "=": () => throwParseError(shallowDefaultableMessage)
4339
- });
4340
- var indexOneParsers = { ...postfixParsers, ...infixParsers };
4341
- var isIndexOneExpression = (def) => isOperatorOf(def[1], indexOneParsers);
4342
- var defineIndexZeroParsers = (parsers) => parsers;
4343
- var indexZeroParsers = defineIndexZeroParsers({
4344
- keyof: parseKeyOfTuple,
4345
- instanceof: function (def, ctx) {
4346
- if (typeof def[1] !== "function") {
4347
- return throwParseError(writeInvalidConstructorMessage(objectKindOrDomainOf(def[1])));
4348
- }
4349
- const branches = def.slice(1).map((ctor) => typeof ctor === "function" ? ctx.$.node("proto", { proto: ctor }) : throwParseError(writeInvalidConstructorMessage(objectKindOrDomainOf(ctor))));
4350
- return branches.length === 1 ? branches[0] : ctx.$.node("union", { branches });
4351
- },
4352
- "===": (def, ctx) => ctx.$.units(def.slice(1))
4353
- });
4354
- var isIndexZeroExpression = (def) => isOperatorOf(def[0], indexZeroParsers);
4355
- var isOperatorOf = (element, parsers) => typeof element === "string" && hasOwn(parsers, element);
4356
- var writeInvalidConstructorMessage = (actual) => `Expected a constructor following 'instanceof' operator (was ${actual})`;
4357
-
4358
4921
  // out/parser/tupleLiteral.js
4359
4922
  var parseTupleLiteral = function (def, ctx) {
4360
4923
  let sequences = [{}];
@@ -4447,6 +5010,10 @@ var appendSpreadBranch = function (base, branch) {
4447
5010
  if (spread.prefix)
4448
5011
  for (const node2 of spread.prefix)
4449
5012
  appendRequiredElement(base, node2);
5013
+ if (spread.defaultables) {
5014
+ for (const [node2, def] of spread.defaultables)
5015
+ appendDefaultableElement(base, node2, def);
5016
+ }
4450
5017
  if (spread.optionals)
4451
5018
  for (const node2 of spread.optionals)
4452
5019
  appendOptionalElement(base, node2);
@@ -4466,7 +5033,9 @@ var spreadDefaultableMessage = "A spread element cannot have a default";
4466
5033
  var defaultablePostOptionalMessage = "A defaultable element may not follow an optional element without a default";
4467
5034
 
4468
5035
  // out/parser/definition.js
5036
+ var maxCachedDefs = 4096;
4469
5037
  var parseCache = /* @__PURE__ */ new WeakMap();
5038
+ var parseCacheSizes = /* @__PURE__ */ new WeakMap();
4470
5039
  var parseInnerDefinition = function (def, ctx) {
4471
5040
  if (typeof def === "string") {
4472
5041
  if (ctx.args && Object.keys(ctx.args).some((k) => def.includes(k))) {
@@ -4485,6 +5054,16 @@ var parseInnerDefinition = function (def, ctx) {
4485
5054
  const result = parseString(def, ctx);
4486
5055
  const node2 = isArray(result) ? result[0] : result;
4487
5056
  if (!inProgress.definitions || !node2.hasAlias) {
5057
+ scopeCache = parseCache.get(ctx.$) ?? scopeCache;
5058
+ if (!(def in scopeCache)) {
5059
+ const size = (parseCacheSizes.get(ctx.$) ?? 0) + 1;
5060
+ if (size > maxCachedDefs) {
5061
+ scopeCache = /* @__PURE__ */ Object.create(null);
5062
+ parseCache.set(ctx.$, scopeCache);
5063
+ parseCacheSizes.set(ctx.$, 1);
5064
+ } else
5065
+ parseCacheSizes.set(ctx.$, size);
5066
+ }
4488
5067
  scopeCache[def] = result;
4489
5068
  $ark.reached?.store(mark, scopeCache, def);
4490
5069
  }
@@ -4668,7 +5247,7 @@ var fits = function (value, facts) {
4668
5247
  if (typeof value === "string") {
4669
5248
  return facts.base === "string" && value.length >= (facts.min ?? 0) && value.length <= (facts.max ?? Infinity);
4670
5249
  }
4671
- return typeof value === "number" && (facts.base === "number" || facts.base === "integer" && Number.isInteger(value)) && value >= (facts.min ?? -Infinity) && value <= (facts.max ?? Infinity);
5250
+ return typeof value === "number" && Number.isFinite(value) && (facts.base === "number" || facts.base === "integer" && Number.isInteger(value)) && (facts.min === void 0 || (facts.minExclusive ? value > facts.min : value >= facts.min)) && (facts.max === void 0 || (facts.maxExclusive ? value < facts.max : value <= facts.max));
4672
5251
  };
4673
5252
  var rangeFacts = function (d, min2, max2) {
4674
5253
  if (!min2 && (d.base === "string" || d.base === "array"))
@@ -4705,6 +5284,8 @@ var scanRange = function (def) {
4705
5284
  return;
4706
5285
  min2 = +left + (leftOp === "<" ? step : 0);
4707
5286
  }
5287
+ if (min2 !== void 0 && !Number.isFinite(min2) || max2 !== void 0 && !Number.isFinite(max2))
5288
+ return;
4708
5289
  if ((min2 ?? 0) > (max2 ?? Infinity))
4709
5290
  return;
4710
5291
  if (min2 === max2 && (op.length === 1 || leftOp === "<"))
@@ -4713,13 +5294,17 @@ var scanRange = function (def) {
4713
5294
  return;
4714
5295
  if (isLength || op.length === 2 && (!left || leftOp === "<="))
4715
5296
  return rangeFacts({ pure: true, base: of.base, of: of.of }, min2, max2);
5297
+ if (of.base === "integer" && (min2 !== void 0 && !Number.isSafeInteger(min2) || max2 !== void 0 && !Number.isSafeInteger(max2)))
5298
+ return;
4716
5299
  return {
4717
5300
  key: def,
4718
5301
  domains: numberBits,
4719
5302
  pure: true,
4720
5303
  base: of.base,
4721
5304
  min: min2,
4722
- max: max2
5305
+ minExclusive: of.base === "number" && (left ? leftOp === "<" : op === ">"),
5306
+ max: max2,
5307
+ maxExclusive: of.base === "number" && op === "<"
4723
5308
  };
4724
5309
  };
4725
5310
  var splitTop = function (def, separator) {
@@ -4865,6 +5450,7 @@ var regexFacts = (v) => ({
4865
5450
  domains: stringBits,
4866
5451
  pure: true
4867
5452
  });
5453
+ var maxScannedDefs = 4096;
4868
5454
  var scanned = /* @__PURE__ */ new Map();
4869
5455
  var scanLeaf = function (def) {
4870
5456
  let facts = scanned.get(def);
@@ -4874,6 +5460,8 @@ var scanLeaf = function (def) {
4874
5460
  } catch {
4875
5461
  facts = null;
4876
5462
  }
5463
+ if (scanned.size >= maxScannedDefs)
5464
+ scanned.clear();
4877
5465
  scanned.set(def, facts);
4878
5466
  }
4879
5467
  return facts ?? void 0;
@@ -4920,7 +5508,7 @@ var fnKey = (fn) => {
4920
5508
  fnIds.set(fn, id = ++fnCount);
4921
5509
  return `#${id}`;
4922
5510
  };
4923
- var defaultKey = (of, value) => `${wrap(of)}=${typeof value === "function" ? fnKey(value) : `${typeof value}:${String(value)}`}`;
5511
+ var defaultKey = function (of, value) { return `${wrap(of)}=${typeof value === "function" ? fnKey(value) : typeof value === "string" ? `string:${JSON.stringify(value)}` : typeof value === "number" && Object.is(value, -0) ? "number:-0" : `${typeof value}:${String(value)}`}` };
4924
5512
  var nodeFacts = function (node2) {
4925
5513
  if (node2.isNever() || node2.topAlias)
4926
5514
  return;
@@ -5051,7 +5639,7 @@ var walkLiteral = function (def, facts, outer) {
5051
5639
  if (of.defaults && (isTuple || key.kind === "optional"))
5052
5640
  return;
5053
5641
  if (isTuple && v[1] === "=") {
5054
- if (!isThunk(v[2]) && (hasDomain(v[2], "object") || !fits(v[2], of)))
5642
+ if (!isThunk(v[2]) && (hasDomain(v[2], "object") || typeof v[2] === "symbol" || !fits(v[2], of)))
5055
5643
  return;
5056
5644
  facts.pure = false;
5057
5645
  }
@@ -5191,14 +5779,19 @@ var metaFacts = function (d, meta) { return ({
5191
5779
  names: void 0,
5192
5780
  literal: false
5193
5781
  }) };
5194
- var isPlainMeta = function (meta) {
5195
- if (!hasDomain(meta, "object") || !isPlainObject(meta))
5196
- return false;
5197
- for (const k in meta) {
5198
- if (!"description expected title".includes(k) || typeof meta[k] !== "string")
5199
- return false;
5782
+ var snapshotPlainMeta = function (meta) {
5783
+ if (!hasDomain(meta, "object") || !isPlainObject(meta) || Object.getOwnPropertySymbols(meta).length)
5784
+ return;
5785
+ const copy = {};
5786
+ for (const k of Object.keys(meta)) {
5787
+ if (k !== "description" && k !== "expected" && k !== "title")
5788
+ return;
5789
+ const v = meta[k];
5790
+ if (typeof v !== "string")
5791
+ return;
5792
+ copy[k] = v;
5200
5793
  }
5201
- return true;
5794
+ return copy;
5202
5795
  };
5203
5796
  var deferredMethods = {
5204
5797
  array: (d) => arrayFacts(d.facts),
@@ -5246,32 +5839,48 @@ var deferredMethods = {
5246
5839
  tags: new Map([...facts.tags ?? [], ...rf.tags ?? []])
5247
5840
  };
5248
5841
  },
5249
- describe: (d, [description, selector]) => typeof description === "string" && !selector ? metaFacts(d, { description }) : void 0,
5250
- configure: (d, [meta, selector]) => isPlainMeta(meta) && !selector ? metaFacts(d, meta) : void 0,
5842
+ describe: (d, [description, selector]) => typeof description === "string" && selector === void 0 ? metaFacts(d, { description }) : void 0,
5843
+ configure: function (d, args) {
5844
+ if (args[1] !== void 0)
5845
+ return;
5846
+ const copy = snapshotPlainMeta(args[0]);
5847
+ if (!copy)
5848
+ return;
5849
+ args[0] = copy;
5850
+ return metaFacts(d, copy);
5851
+ },
5251
5852
  to: function ({ facts }, [r]) {
5252
5853
  const to = typeof r === "string" ? scanAnd(r) : r instanceof RegExp ? regexFacts(r) : deferred.get(r)?.facts;
5253
5854
  return facts.key === "string.trim" && refinesString(to) ? { key: `string.trim>${to.key}`, domains: stringBits, pure: false } : void 0;
5254
5855
  },
5255
5856
  onUndeclaredKey: function ({ facts }, [rule]) { return facts.domains === objectBits && facts.cyclic !== true && (rule === "reject" || rule === "ignore") ? {
5256
5857
  ...facts,
5257
- key: `${facts.key}+${rule}`,
5858
+ key: `${wrap(facts)}+${rule}`,
5859
+ terms: void 0,
5860
+ values: void 0,
5861
+ of: void 0,
5258
5862
  pure: rule === "ignore" && facts.pure,
5259
5863
  names: void 0,
5260
- entries: void 0
5864
+ entries: void 0,
5865
+ literal: false
5261
5866
  } : void 0 },
5262
5867
  exclude: function ({ facts }, [r]) {
5263
5868
  const excluded = typeof r === "string" ? scanLeaf(r) : void 0;
5264
- if (!facts.terms || !facts.values || !excluded?.values)
5869
+ if (!facts.terms || !facts.values || !excluded?.values || // every term must be a single canonical literal (not "boolean" or a settled "@node")
5870
+ facts.terms.length !== facts.values.length || facts.terms.some((t) => t[0] === "@"))
5265
5871
  return;
5266
5872
  const remaining = facts.values.filter((v) => !excluded.values.includes(v));
5267
5873
  const excludedTerms = excluded.terms ?? [excluded.key];
5268
5874
  const kept = facts.terms.filter((t) => !excludedTerms.includes(t));
5269
5875
  if (!kept.length || kept.length !== remaining.length)
5270
5876
  return;
5877
+ let domains = 0;
5878
+ for (const v of remaining)
5879
+ domains |= unitBitsOf(domainOf(v));
5271
5880
  return {
5272
5881
  key: kept.join("|"),
5273
5882
  terms: kept.length > 1 ? kept : void 0,
5274
- domains: facts.domains,
5883
+ domains,
5275
5884
  pure: true,
5276
5885
  values: remaining,
5277
5886
  units: true
@@ -5354,7 +5963,7 @@ var canDefer = function ($) {
5354
5963
  void $.cfg;
5355
5964
  return true;
5356
5965
  };
5357
- var literalOf = function (value) { return typeof value === "string" ? `'${value}'` : typeof value === "number" || value === null || typeof value === "boolean" ? `${value}` : value === void 0 ? "undefined" : "?" };
5966
+ var literalOf = function (value) { return typeof value === "string" ? value.includes("'") || value.includes("\\") ? "?" : `'${value}'` : typeof value === "number" || value === null || typeof value === "boolean" ? `${value}` : value === void 0 ? "undefined" : "?" };
5358
5967
  var deferUnits = function (values, $) {
5359
5968
  const literals = values.map(literalOf);
5360
5969
  return literals.length === 1 ? deferDefinition(literals[0], $) : deferUnion(literals, $);
@@ -5363,13 +5972,23 @@ var deferredRecord = function ($, generic) {
5363
5972
  const instantiate = (...args) => {
5364
5973
  const [k, v] = args;
5365
5974
  const into = { key: "", domains: 0, pure: true };
5366
- const key = canDefer($) && valueFacts(k, into)?.[0];
5367
- const value = key && (typeof v === "string" ? scanUnion(v) : valueFacts(v, into)?.[0]);
5975
+ const keyEntry = args.length === 2 && canDefer($) ? valueFacts(k, into) : void 0;
5976
+ let valueEntry;
5977
+ if (keyEntry) {
5978
+ if (typeof v === "string") {
5979
+ const facts = scanUnion(v);
5980
+ if (facts)
5981
+ valueEntry = [facts, v];
5982
+ } else
5983
+ valueEntry = valueFacts(v, into);
5984
+ }
5985
+ const key = keyEntry?.[0];
5986
+ const value = valueEntry?.[0];
5368
5987
  return !value || !key || !key.pure || key.units || key.domains & ~(stringBits | symbolBits) || value.defaults || value.cyclic ? generic()(...args) : defer({
5369
5988
  key: `Record<${key.key === "string" ? "" : `${key.key},`}${value.key}>`,
5370
5989
  domains: objectBits,
5371
5990
  pure: value.pure
5372
- }, $, () => generic()(k, v));
5991
+ }, $, () => generic()(keyEntry[1], valueEntry[1]));
5373
5992
  };
5374
5993
  return Object.setPrototypeOf(instantiate, new Proxy({}, {
5375
5994
  get: (_, k) => generic()[k],
@@ -5734,6 +6353,14 @@ export {
5734
6353
  InternalChainedMatchParser,
5735
6354
  chainedAtMessage,
5736
6355
  doubleAtMessage,
6356
+ maybeParseTupleExpression,
6357
+ assertTupleArity,
6358
+ parseKeyOfTuple,
6359
+ parseMorphTuple,
6360
+ writeMalformedFunctionalExpressionMessage,
6361
+ parseNarrowTuple,
6362
+ writeInvalidConstructorMessage,
6363
+ writeUnexpectedTupleElementsMessage,
5737
6364
  parseProperty,
5738
6365
  invalidOptionalKeyKindMessage,
5739
6366
  invalidDefaultableKeyKindMessage,
@@ -5743,12 +6370,6 @@ export {
5743
6370
  nonLeadingSpreadError,
5744
6371
  preparseKey,
5745
6372
  writeInvalidSpreadTypeMessage,
5746
- maybeParseTupleExpression,
5747
- parseKeyOfTuple,
5748
- parseMorphTuple,
5749
- writeMalformedFunctionalExpressionMessage,
5750
- parseNarrowTuple,
5751
- writeInvalidConstructorMessage,
5752
6373
  parseTupleLiteral,
5753
6374
  writeNonArraySpreadMessage,
5754
6375
  multipleVariadicMesage,