@atscript/typescript 0.1.110 → 0.2.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.
@@ -2,7 +2,8 @@
2
2
  /**
3
3
  * Annotation keys the validator pre-check reads, per kind of checked value — shared by the
4
4
  * interpreted pre-check (validator-fast-check.ts) and the compiled checks (compiled-check/).
5
- */ /** Annotations of a string node, in check order. */ const STRING_KEYS = [
5
+ */ /** The format of a `decimal` value (a string). */ const DECIMAL_RE = /^[+-]?\d+(\.\d+)?$/;
6
+ /** Annotations of a string node, in check order. */ const STRING_KEYS = [
6
7
  "meta.required",
7
8
  "expect.minLength",
8
9
  "expect.maxLength",
@@ -42,11 +43,18 @@
42
43
  */ function boundOf(m, field) {
43
44
  return typeof m === "number" ? m : m[field];
44
45
  }
46
+ /** The props of array item type `of` (an object) marked `@expect.array.key`, in order. */ function arrayKeyProps(of) {
47
+ const out = [];
48
+ if (of?.type.kind === "object") {
49
+ for (const [key, prop] of of.type.props) if (prop.metadata.get("expect.array.key")) out.push(key);
50
+ }
51
+ return out;
52
+ }
45
53
 
46
54
  //#endregion
47
55
  //#region packages/typescript/src/runtime/compiled-check/tracking.ts
48
56
  /**
49
- * Mutation tracking for build-time compiled validator checks.
57
+ * Mutation tracking for build-time compiled validator checks and cached layered metadata reads.
50
58
  *
51
59
  * A compiled check is bound to the live type tree before use (see registry.ts): the bind
52
60
  * verifies that the tree still has the structure the check was compiled for and snapshots
@@ -54,11 +62,17 @@
54
62
  * read bumps one global epoch, which makes every compiled check re-bind on its next use.
55
63
  *
56
64
  * Tracked: `annotate()`, the metadata / props `Map` methods (`set` / `delete` / `clear`),
57
- * the `defineAnnotatedType()` handle methods and `cloneRefProp()`. Raw property writes
58
- * (`node.optional = …`, `type.items.push(…)`, editing a constraint object in place, …)
59
- * cannot be seen: call {@link invalidateCompiledValidators} after them.
65
+ * the `defineAnnotatedType()` handle methods. Raw writes (`node.optional = …`,
66
+ * `node.metadata = …`, `type.items.push(…)`, editing a constraint object in place, …) cannot
67
+ * be seen: call {@link invalidateCompiledValidators} after them, with either validator engine.
60
68
  */ const VALIDATOR_KEY_SET = new Set(VALIDATOR_KEYS);
69
+ const mapSet = Map.prototype.set;
61
70
  /** Global mutation epoch: compiled checks bound in an older epoch re-bind before use. */ let epoch = 0;
71
+ /**
72
+ * Writes of metadata maps so far (any map, any key: `annotate()`, the `Map` methods, a node's map
73
+ * replaced, a layer flag or intrinsic mark registered): a lazy JSON schema or a layered map's
74
+ * flattened view built before the last one is built again (see `lazyJsonSchema`, `LayerMap`).
75
+ */ let metadataWrites = 0;
62
76
  /** Some bind has watched an object (until then no mutation can affect a compiled check). */ let tracking = false;
63
77
  /** Objects (nodes, type defs, metadata / props maps) read by some compiled-check bind. */ const watched = /* @__PURE__ */ new WeakSet();
64
78
  /** The current mutation epoch. */ function currentEpoch() {
@@ -72,27 +86,45 @@
72
86
  if (tracking && watched.has(obj)) epoch++;
73
87
  }
74
88
  /**
75
- * Makes every compiled validator check re-verify the type tree it was compiled for before
76
- * its next use.
89
+ * Makes every compiled validator check re-verify the type tree it was compiled for, and every
90
+ * node that reads metadata through other nodes re-read them, before its next use.
77
91
  *
78
- * Compiled checks (emitted with `tsPlugin({ compileValidators: true })`) see mutations made
79
- * through `annotate()`, the metadata / props `Map` methods, the `defineAnnotatedType()`
80
- * handle methods and `cloneRefProp()` automatically. Call this after changing a type tree
81
- * any other way:
92
+ * Validators (compiled checks emitted with `tsPlugin({ compileValidators: true })` and the
93
+ * interpreted walk alike) see mutations made through `annotate()`, the metadata / props `Map`
94
+ * methods and the `defineAnnotatedType()` handle methods automatically. Call this after
95
+ * changing a type tree any other way:
82
96
  * - a raw property write: `node.optional = …`, `node.type = …`, `node.metadata = …`,
83
97
  * `type.items.push(…)`, `type.of = …`, `type.propsPatterns.push(…)`;
84
98
  * - an in-place edit of an annotation value: mutating a constraint object
85
99
  * (`metadata.get('expect.min').minValue = 5`), editing or pushing onto an
86
100
  * `@expect.pattern` array directly (use `annotate(metadata, key, value, true)` instead).
87
101
  *
88
- * Without it the compiled check may keep validating against the old shape or values.
89
- * Types without compiled checks are always read live and never need it.
102
+ * Without it a compiled check may keep validating against the old shape or values, and a
103
+ * node that reads metadata through other nodes (a reference, a merged field, a path override)
104
+ * may keep reading the old values: the rule is the same for both engines.
90
105
  *
91
106
  * Any mutation of a type a compiled check has bound to (tracked or invalidated) makes every
92
107
  * compiled check re-bind once on its next use: cheap during startup / configuration, but
93
108
  * avoid mutating validated types per request.
94
109
  */ function invalidateCompiledValidators() {
95
110
  epoch++;
111
+ metadataWrites++;
112
+ }
113
+ /** The number of metadata writes so far (see `metadataWrites`). */ function metadataWriteCount() {
114
+ return metadataWrites;
115
+ }
116
+ /** Records a write of a node's metadata the maps do not see: the node's map replaced. */ function metadataReplaced() {
117
+ metadataWrites++;
118
+ }
119
+ /**
120
+ * `annotate(m, key, value, true)` where map `m` holds `own` as its own value of `key`: appended in
121
+ * place to an own list (the map sees no write: tracked here as one), else a list of both.
122
+ */ function appendOwn(m, key, own, value) {
123
+ if (Array.isArray(own)) {
124
+ own.push(value);
125
+ if (VALIDATOR_KEY_SET.has(key)) touched(m);
126
+ metadataWrites++;
127
+ } else m.set(key, [own, value]);
96
128
  }
97
129
  /**
98
130
  * Metadata map of runtime type nodes: a `Map` whose writes to validator annotation keys
@@ -101,16 +133,25 @@
101
133
  set(key, value) {
102
134
  super.set(key, value);
103
135
  if (tracking && VALIDATOR_KEY_SET.has(key)) touched(this);
136
+ metadataWrites++;
104
137
  return this;
105
138
  }
106
139
  delete(key) {
107
140
  const deleted = super.delete(key);
108
- if (deleted && tracking && VALIDATOR_KEY_SET.has(key)) touched(this);
141
+ if (deleted) {
142
+ if (tracking && VALIDATOR_KEY_SET.has(key)) touched(this);
143
+ metadataWrites++;
144
+ }
109
145
  return deleted;
110
146
  }
111
147
  clear() {
112
148
  super.clear();
113
149
  touched(this);
150
+ metadataWrites++;
151
+ }
152
+ /** A new map holding `entries`: no write (a new map is in no compiled check nor schema). */ constructor(entries) {
153
+ super();
154
+ if (entries) for (const [key, value] of entries) mapSet.call(this, key, value);
114
155
  }
115
156
  };
116
157
  /** Props map of runtime object types: a `Map` whose writes are tracked. */ var PropsMap = class extends Map {
@@ -128,9 +169,759 @@
128
169
  super.clear();
129
170
  touched(this);
130
171
  }
172
+ /** A new map holding `entries` (untracked: a new map is in no compiled check). */ constructor(entries) {
173
+ super();
174
+ if (entries) for (const [key, value] of entries) mapSet.call(this, key, value);
175
+ }
176
+ };
177
+
178
+ //#endregion
179
+ //#region packages/typescript/src/runtime/layers.ts
180
+ /**
181
+ * Metadata layers: the runtime's one metadata mechanism.
182
+ *
183
+ * A node's metadata is its own map plus an ordered list of base nodes (`b`, priority order:
184
+ * `b[0]` first). A read returns the own value, else the first base that has the key; an append
185
+ * key returns the bases' values (lowest priority first), then the own ones. Writes (`set`,
186
+ * `delete`, `clear`) are the own map's: `delete` lets a base's value show again, and a write on
187
+ * a base shows through every layer over it.
188
+ *
189
+ * Reads go through a flattened view of the effective entries, rebuilt on the first read after any
190
+ * metadata write (one global write counter: `metadataWriteCount`). The view is used only while
191
+ * every map below is tracked (an `AnnotationMap` or a `LayerMap`, whose writes the counter
192
+ * sees); otherwise the reads are live. A raw write the counter does not see (a node's map swapped,
193
+ * `node.metadata = X`, or edited in place) must be followed by `invalidateCompiledValidators()`,
194
+ * as compiled checks require (PERF-2).
195
+ */ function _define_property$2(obj, key, value) {
196
+ if (key in obj) Object.defineProperty(obj, key, {
197
+ value,
198
+ enumerable: true,
199
+ configurable: true,
200
+ writable: true
201
+ });
202
+ else obj[key] = value;
203
+ return obj;
204
+ }
205
+ /** Append keys: concatenated across layers (registered by generated code, `$ak`). */ const APPEND = 1;
206
+ /** `passedWhenReferred: false` keys: never read through a reference layer (`$nr`). */ const NOT_REFERRED = 2;
207
+ /** The flags of the registered keys (one lookup per read). */ const FLAGS = /* @__PURE__ */ new Map();
208
+ function flag(keys, f) {
209
+ for (const key of keys) FLAGS.set(key, (FLAGS.get(key) ?? 0) | f);
210
+ metadataReplaced();
211
+ }
212
+ /** Registers append keys (`mergeStrategy: 'append'`). */ function $ak(...keys) {
213
+ flag(keys, APPEND);
214
+ }
215
+ /** Registers `passedWhenReferred: false` keys. */ function $nr(...keys) {
216
+ flag(keys, NOT_REFERRED);
217
+ }
218
+ /** Whether `key` is an append key (see {@link $ak}). */ function isAppendKey(key) {
219
+ return ((FLAGS.get(key) ?? 0) & APPEND) !== 0;
220
+ }
221
+ const notReferred = (key) => ((FLAGS.get(key) ?? 0) & NOT_REFERRED) !== 0;
222
+ /**
223
+ * Intrinsic entries per metadata map: a primitive extension's own annotations
224
+ * (`string.required` → `meta.required`) are part of the type, so they pass every reference layer
225
+ * although their key is `passedWhenReferred: false` (0.1.110).
226
+ */ const INTRINSIC = /* @__PURE__ */ new WeakMap();
227
+ /** Marks `keys` of map `m` intrinsic (see {@link INTRINSIC}). */ function markIntrinsic(m, keys) {
228
+ let s = INTRINSIC.get(m);
229
+ if (!s) INTRINSIC.set(m, s = /* @__PURE__ */ new Set());
230
+ for (const k of keys) s.add(k);
231
+ metadataReplaced();
232
+ }
233
+ /**
234
+ * A map replacing `from` (layered over its bases now) keeps its intrinsic marks. (No write
235
+ * counted: the callers count the map replaced.)
236
+ */ function moveIntrinsic(from, to) {
237
+ const s = INTRINSIC.get(from);
238
+ if (s) INTRINSIC.set(to, s);
239
+ }
240
+ const MISS = Symbol("miss");
241
+ /** The view of a layered map without effective entries (never written: views stay internal). */ const NO_ENTRIES = new AnnotationMap();
242
+ const mapGet = Map.prototype.get;
243
+ const mapHas = Map.prototype.has;
244
+ const ownSize = Object.getOwnPropertyDescriptor(Map.prototype, "size").get;
245
+ let _Symbol_iterator = Symbol.iterator;
246
+ /**
247
+ * A metadata map that reads through base nodes (see the file comment). `r`: the bases are
248
+ * reference layers (a prop's / element's type, a chain ref, `extends`, merge operands), so
249
+ * `passedWhenReferred: false` keys are not read through them.
250
+ */ var LayerMap = class extends AnnotationMap {
251
+ /**
252
+ * The flattened view (built again after a metadata write), `undefined`: read live. Internal:
253
+ * this module's readers and the validators read it (`readable`, `filledMeta`), never write.
254
+ */ view() {
255
+ return this.w === metadataWriteCount() ? this.f : this.flatten();
256
+ }
257
+ flatten() {
258
+ this.w = -1;
259
+ let f;
260
+ if (tracked(this, /* @__PURE__ */ new Set())) {
261
+ const keys = this.liveKeys();
262
+ f = keys.length === 0 ? NO_ENTRIES : new AnnotationMap(keys.map((k) => [k, this.liveGet(k)]));
263
+ }
264
+ this.f = f;
265
+ this.w = metadataWriteCount();
266
+ return f;
267
+ }
268
+ /** The value of `key` (not concatenated), or `MISS`; `nr`: a `passedWhenReferred:false` key. */ lookup(key, nr) {
269
+ if (ownSize.call(this) !== 0) {
270
+ const v = mapGet.call(this, key);
271
+ if (v !== void 0 || mapHas.call(this, key)) return v;
272
+ }
273
+ if (nr && this.r) {
274
+ for (const n of this.b) {
275
+ const x = intrinsicLookup(n.metadata, key);
276
+ if (x !== MISS) return x;
277
+ }
278
+ return MISS;
279
+ }
280
+ for (const n of this.b) {
281
+ const m = n.metadata;
282
+ let x;
283
+ if (m.b === void 0) {
284
+ x = m.get(key);
285
+ if (x === void 0 && !m.has(key)) x = MISS;
286
+ } else x = m.lookup(key, nr);
287
+ if (x !== MISS) return x;
288
+ }
289
+ return MISS;
290
+ }
291
+ get(key) {
292
+ const view = this.w === metadataWriteCount() ? this.f : this.flatten();
293
+ return view === void 0 ? this.liveGet(key) : mapGet.call(view, key);
294
+ }
295
+ /** `get` read through the layers (see the file comment). */ liveGet(key) {
296
+ const f = FLAGS.get(key);
297
+ if (f !== void 0 && (f & APPEND) !== 0) return this.append(key);
298
+ const v = this.lookup(key, f !== void 0 && (f & NOT_REFERRED) !== 0);
299
+ return v === MISS ? void 0 : v;
300
+ }
301
+ has(key) {
302
+ const view = this.view();
303
+ return view === void 0 ? this.lookup(key, notReferred(key)) !== MISS : mapHas.call(view, key);
304
+ }
305
+ /** An append key: the bases' values (lowest priority first), then the own ones. */ append(key) {
306
+ const own = mapGet.call(this, key);
307
+ if (this.r && notReferred(key)) {
308
+ const parts = [];
309
+ const acc = {
310
+ out: parts,
311
+ seen: /* @__PURE__ */ new Map()
312
+ };
313
+ for (let i = this.b.length - 1; i >= 0; i--) collect(this.b[i].metadata, key, acc, true);
314
+ if (parts.length === 0) return own;
315
+ if (own !== void 0) parts.push(own);
316
+ return parts.length === 1 ? parts[0] : parts.flat();
317
+ }
318
+ let one;
319
+ let count = 0;
320
+ for (const n of this.b) {
321
+ const x = n.metadata.get(key);
322
+ if (x !== void 0 && ++count === 1) one = x;
323
+ }
324
+ if (count === 0) return own;
325
+ if (count === 1 && own === void 0) return one;
326
+ const parts = [];
327
+ collect(this, key, {
328
+ out: parts,
329
+ seen: /* @__PURE__ */ new Map()
330
+ }, false);
331
+ if (parts.length === 1) return parts[0];
332
+ const out = [];
333
+ for (const p of parts) if (Array.isArray(p)) out.push(...p);
334
+ else out.push(p);
335
+ return out;
336
+ }
337
+ /** The effective keys: own first, then the bases' in priority order. */ effectiveKeys() {
338
+ const view = this.view();
339
+ return view === void 0 ? this.liveKeys() : [...view.keys()];
340
+ }
341
+ liveKeys() {
342
+ const out = /* @__PURE__ */ new Set();
343
+ keysOf(this, false, out, /* @__PURE__ */ new Map());
344
+ return [...out];
345
+ }
346
+ keys() {
347
+ return this.effectiveKeys()[Symbol.iterator]();
348
+ }
349
+ values() {
350
+ return this.effectiveKeys().map((k) => this.get(k))[Symbol.iterator]();
351
+ }
352
+ entries() {
353
+ return this.effectiveKeys().map((k) => [k, this.get(k)])[Symbol.iterator]();
354
+ }
355
+ [_Symbol_iterator]() {
356
+ return this.entries();
357
+ }
358
+ forEach(cb, thisArg) {
359
+ for (const k of this.effectiveKeys()) cb.call(thisArg, this.get(k), k, this);
360
+ }
361
+ constructor(bases, reference = false, own) {
362
+ super(own), _define_property$2(this, "b", void 0), _define_property$2(this, "r", void 0), _define_property$2(this, "f", void 0), _define_property$2(this, "w", void 0);
363
+ this.b = bases;
364
+ this.r = reference;
365
+ this.f = void 0;
366
+ this.w = -1;
367
+ }
131
368
  };
132
- /** `true` when `key` is an annotation the validator pre-check reads. */ function isValidatorKey(key) {
133
- return VALIDATOR_KEY_SET.has(key);
369
+ Object.defineProperty(LayerMap.prototype, "size", {
370
+ get() {
371
+ const view = this.view();
372
+ if (view !== void 0) return view.size;
373
+ return metaEmpty(this) ? 0 : this.effectiveKeys().length;
374
+ },
375
+ configurable: true
376
+ });
377
+ /**
378
+ * Every map of `m`'s layers is tracked (an `AnnotationMap` or a `LayerMap`, whose writes count in
379
+ * `metadataWrites`), so a flattened view of `m` stays right until the next write.
380
+ */ function tracked(m, seen) {
381
+ const p = Object.getPrototypeOf(m);
382
+ if (p !== AnnotationMap.prototype && p !== LayerMap.prototype) return false;
383
+ const b = m.b;
384
+ if (b !== void 0 && !seen.has(m)) {
385
+ seen.add(m);
386
+ for (const n of b) if (!tracked(n.metadata, seen)) return false;
387
+ }
388
+ return true;
389
+ }
390
+ /** `key`'s intrinsic value in `m` or its bases (see {@link INTRINSIC}), or `MISS`. */ function intrinsicLookup(m, key) {
391
+ if (INTRINSIC.get(m)?.has(key)) {
392
+ if (m instanceof LayerMap ? mapHas.call(m, key) : m.has(key)) return m instanceof LayerMap ? mapGet.call(m, key) : m.get(key);
393
+ }
394
+ const b = m.b;
395
+ if (b !== void 0) for (const n of b) {
396
+ const x = intrinsicLookup(n.metadata, key);
397
+ if (x !== MISS) return x;
398
+ }
399
+ return MISS;
400
+ }
401
+ /**
402
+ * Whether a layer walk visits `m` (reached `filtered` or not): each map once, except that a map
403
+ * first reached `filtered` (through a reference layer) is visited again when reached unfiltered
404
+ * (a diamond: a direct base over the same node), as the layered `get` reads it. `seen`: the maps
405
+ * visited, `true` while only filtered.
406
+ */ function visit(m, filtered, seen) {
407
+ const was = seen.get(m);
408
+ if (was !== void 0 && (filtered || !was)) return false;
409
+ seen.set(m, filtered);
410
+ return true;
411
+ }
412
+ /**
413
+ * The values of `key` of `m` and its bases (lowest priority first), each map once (see
414
+ * {@link visit}). `filtered`: reached through a reference layer with a `passedWhenReferred: false`
415
+ * key — only intrinsic entries count (see {@link INTRINSIC}), down to the bottom.
416
+ */ function collect(m, key, acc, filtered) {
417
+ const was = acc.seen.get(m);
418
+ if (!visit(m, filtered, acc.seen)) return;
419
+ const layer = m instanceof LayerMap ? m : void 0;
420
+ if (layer) {
421
+ const below = filtered || layer.r && notReferred(key);
422
+ for (let i = layer.b.length - 1; i >= 0; i--) collect(layer.b[i].metadata, key, acc, below);
423
+ }
424
+ const intrinsic = INTRINSIC.get(m)?.has(key) === true;
425
+ if ((filtered ? intrinsic : !(was === true && intrinsic)) && (layer ? mapHas.call(m, key) : m.has(key))) acc.out.push(layer ? mapGet.call(m, key) : m.get(key));
426
+ }
427
+ /**
428
+ * The keys of `m` (own first, then its bases'), each map once (see {@link visit}). `filtered`:
429
+ * reached through a reference layer.
430
+ */ function keysOf(m, filtered, out, seen) {
431
+ if (!visit(m, filtered, seen)) return;
432
+ const layer = m instanceof LayerMap ? m : void 0;
433
+ const own = layer ? Map.prototype.keys.call(m) : m.keys();
434
+ const intrinsic = INTRINSIC.get(m);
435
+ for (const k of own) if (!filtered || !notReferred(k) || intrinsic?.has(k)) out.add(k);
436
+ if (layer) for (const n of layer.b) keysOf(n.metadata, filtered || layer.r, out, seen);
437
+ }
438
+ /**
439
+ * `m` has no entry (own or through its bases): the validators' `metadata.size === 0` fast path,
440
+ * without computing a layered map's effective size. May answer `false` for a map whose only base
441
+ * entries are filtered out (`passedWhenReferred: false`): the slow path then finds nothing.
442
+ */ function metaEmpty(m) {
443
+ const b = m.b;
444
+ if (b === void 0) return m.size === 0;
445
+ const view = m.view();
446
+ if (view !== void 0) return view.size === 0;
447
+ if (ownSize.call(m) !== 0) return false;
448
+ for (const n of b) if (!metaEmpty(n.metadata)) return false;
449
+ return true;
450
+ }
451
+ /**
452
+ * `m` for reading: a layered map's flattened view (see `LayerMap.view`), else `m` itself.
453
+ * The validators read builtin maps this way (never write: a view is shared).
454
+ */ function readable(m) {
455
+ return m.b === void 0 ? m : m.view() ?? m;
456
+ }
457
+ /**
458
+ * {@link readable}`(m)`, or `undefined` when `m` has no entry: the validators' "no constraint"
459
+ * fast path and their reads in one (a plain map costs what `metaEmpty` did).
460
+ */ function filledMeta(m) {
461
+ if (m.b === void 0) return m.size === 0 ? void 0 : m;
462
+ const view = m.view();
463
+ if (view !== void 0) return view.size === 0 ? void 0 : view;
464
+ return metaEmpty(m) ? void 0 : m;
465
+ }
466
+ /**
467
+ * Watches `m` and every base (node and map, transitively) for a compiled check's bind (see
468
+ * `compiled-check/tracking.ts`): a tracked write to any of them re-binds the check. `false` when
469
+ * one of the maps is untracked (a plain `Map`): such a tree stays interpreted.
470
+ */ function watchLayer(m, seen) {
471
+ watch(m);
472
+ const b = m.b;
473
+ if (b === void 0) return m instanceof AnnotationMap;
474
+ let ok = true;
475
+ for (const n of b) {
476
+ const nm = n.metadata;
477
+ if (seen?.has(nm)) continue;
478
+ (seen ?? (seen = /* @__PURE__ */ new Set())).add(nm);
479
+ watch(n);
480
+ ok = watchLayer(nm, seen) && ok;
481
+ }
482
+ return ok;
483
+ }
484
+ /** The own entries of `m` (a layered map's, not read through its bases). */ function ownEntries(m) {
485
+ return m instanceof LayerMap ? [...Map.prototype.entries.call(m)] : m;
486
+ }
487
+ /** The own value of `key` of `m` (not read through its bases). */ function ownValue(m, key) {
488
+ return m instanceof LayerMap ? mapGet.call(m, key) : m.get(key);
489
+ }
490
+ /**
491
+ * `annotate(map, key, value, true)` on a layered map: appends to the own list. For an append
492
+ * key that is the own part of the concatenation; for another list key the own list starts as
493
+ * the value read (as when the node held a copy).
494
+ */ function annotateLayer(m, key, value) {
495
+ if (mapHas.call(m, key)) {
496
+ appendOwn(m, key, mapGet.call(m, key), value);
497
+ return;
498
+ }
499
+ const read = isAppendKey(key) ? void 0 : m.get(key);
500
+ m.set(key, read === void 0 ? [value] : Array.isArray(read) ? [...read, value] : [read, value]);
501
+ }
502
+
503
+ //#endregion
504
+ //#region packages/typescript/src/runtime/stateless-regex.ts
505
+ /**
506
+ * The regex a validator tests with: one whose `test` keeps no state between calls.
507
+ *
508
+ * With the `g` or `y` flag, `RegExp.prototype.test` starts at `lastIndex` and moves it
509
+ * (past a match, or back to 0 after a miss), so one regex object shared by every check of a
510
+ * pattern would accept and reject the same value on alternate calls. The flags are dropped
511
+ * when the regex is compiled, which costs nothing per test: `g` does not change what `test`
512
+ * finds from `lastIndex` 0, and `y` matches only at `lastIndex` 0 — at the start of the
513
+ * value — so it becomes an anchor at the start of the input (`^`, or a look-behind under
514
+ * `m`, where `^` also matches after a line break). Other regexes are returned as they are.
515
+ */ function statelessRegExp(re) {
516
+ if (!re.global && !re.sticky) return re;
517
+ const flags = re.flags.replace(/[gy]/g, "");
518
+ if (!re.sticky) return new RegExp(re.source, flags);
519
+ return new RegExp(`${re.multiline ? "(?<![\\s\\S])" : "^"}(?:${re.source})`, flags);
520
+ }
521
+ /**
522
+ * The source of a pattern written with `flags` as a JSON Schema `pattern` (which has no flags),
523
+ * matching the same strings as the validator's regex:
524
+ *
525
+ * - `s`: every `.` outside a character class becomes `[\s\S]`;
526
+ * - `i`: every character that has case variants becomes a class of them (`a` → `[aA]`,
527
+ * `[a-f]` → `[a-fA-F]`, with `u` also `s` → `[sSſ]`, `\w` → `[\wſK]`); a pattern
528
+ * using what has no flag-free form — a backreference, a Unicode property escape or (with `u`)
529
+ * `\b` / `\B` / `\W` in a class, a range of more than 1024 characters with non-ASCII ones — is
530
+ * also wrapped in a modifier group `(?i:…)`;
531
+ * - `m`: the pattern is wrapped in a modifier group `(?m:…)` (`^` / `$` at line breaks have no
532
+ * flag-free form without look-behinds);
533
+ * - `y`: matches at the start of the value only (see {@link statelessRegExp}): `^(?:…)`;
534
+ * - `g` changes nothing; `u` is the dialect of the pattern (JSON Schema validators commonly compile
535
+ * patterns with it — ajv does).
536
+ *
537
+ * Modifier groups (ES2025) are understood by JavaScript engines from 2024 on (Node.js 23+, V8 12.5+)
538
+ * and by some other regex dialects (.NET, PCRE2, Python 3.6+), not by all.
539
+ */ function jsonSchemaPattern(pattern, flags) {
540
+ if (!flags) return pattern;
541
+ const unicode = flags.includes("u");
542
+ const modifiers = /* @__PURE__ */ new Set();
543
+ let body = pattern;
544
+ if (flags.includes("i") || flags.includes("s")) {
545
+ const translated = translateFlags(pattern, unicode, flags.includes("i"), flags.includes("s"));
546
+ if (translated) {
547
+ body = translated.source;
548
+ if (translated.modifier) modifiers.add("i");
549
+ } else for (const flag of "is") if (flags.includes(flag)) modifiers.add(flag);
550
+ }
551
+ if (flags.includes("m")) modifiers.add("m");
552
+ if (modifiers.size > 0) body = `(?${[...modifiers].sort().join("")}:${body})`;
553
+ return flags.includes("y") ? `^(?:${body})` : body;
554
+ }
555
+ /**
556
+ * Characters case-insensitive matching relates to characters that case mapping does not lead to
557
+ * from them (`k` → `K`, but `K` (U+212A) only folds to `k`): groups closing the search of
558
+ * {@link caseVariants} (the regex engine then keeps those that match).
559
+ */ const FOLD_GROUPS = [
560
+ "kKK",
561
+ "sSſ",
562
+ "ÅåÅ",
563
+ "ßẞ",
564
+ "DŽDždž",
565
+ "LJLjlj",
566
+ "NJNjnj",
567
+ "DZDzdz",
568
+ "ͅΙιι",
569
+ "ΐΐ",
570
+ "Ββϐ",
571
+ "Εεϵ",
572
+ "Θθϑϴ",
573
+ "Κκϰ",
574
+ "µΜμ",
575
+ "Ππϖ",
576
+ "Ρρϱ",
577
+ "Σςσ",
578
+ "Φφϕ",
579
+ "ΩωΩ",
580
+ "ΰΰ",
581
+ "Ввᲀ",
582
+ "Ддᲁ",
583
+ "Ооᲂ",
584
+ "Ссᲃ",
585
+ "Ттᲄᲅ",
586
+ "Ъъᲆ",
587
+ "Ѣѣᲇ",
588
+ "Ṡṡẛ",
589
+ "ᲈꙊꙋ",
590
+ "ſtst",
591
+ ...[
592
+ 8064,
593
+ 8080,
594
+ 8096
595
+ ].flatMap((base) => Array.from({ length: 8 }, (_, k) => String.fromCodePoint(base + k, base + k + 8))),
596
+ "ᾳᾼ",
597
+ "ῃῌ",
598
+ "ῳῼ"
599
+ ];
600
+ let foldGroupOf;
601
+ /** The characters matching `ch` under `i` (with `u`: case folding), `ch` first. */ const variantCache = /* @__PURE__ */ new Map();
602
+ function caseVariants(ch, unicode) {
603
+ const key = `${unicode ? "u" : ""}${ch}`;
604
+ let out = variantCache.get(key);
605
+ if (!out) {
606
+ if (!foldGroupOf) {
607
+ foldGroupOf = /* @__PURE__ */ new Map();
608
+ for (const group of FOLD_GROUPS) for (const member of group) foldGroupOf.set(member, group);
609
+ }
610
+ const single = (x) => unicode ? x.length === String.fromCodePoint(x.codePointAt(0)).length : x.length === 1;
611
+ const found = new Set([ch]);
612
+ const queue = [ch];
613
+ while (queue.length > 0) {
614
+ const x = queue.pop();
615
+ for (const y of [
616
+ x.toLowerCase(),
617
+ x.toUpperCase(),
618
+ ...foldGroupOf.get(x) ?? ""
619
+ ]) if (single(y) && !found.has(y)) {
620
+ found.add(y);
621
+ queue.push(y);
622
+ }
623
+ }
624
+ const re = new RegExp(`^${escapeChar(ch, unicode)}$`, unicode ? "iu" : "i");
625
+ out = [...found].filter((x) => x === ch || re.test(x));
626
+ variantCache.set(key, out);
627
+ }
628
+ return out;
629
+ }
630
+ /** A character as a regex escape (`\uXXXX`, or `\u{…}` with `u` outside the BMP). */ function escapeChar(ch, unicode) {
631
+ const cp = ch.codePointAt(0);
632
+ return cp > 65535 && unicode ? `\\u{${cp.toString(16).toUpperCase()}}` : `\\u${cp.toString(16).toUpperCase().padStart(4, "0")}`;
633
+ }
634
+ /** A character as a member of a character class (escaped where needed). */ function classChar(ch, unicode) {
635
+ const cp = ch.codePointAt(0);
636
+ if (/[\\\][\-^]/.test(ch)) return `\\${ch}`;
637
+ if (cp < 32 || cp > 126) return escapeChar(ch, unicode);
638
+ return ch;
639
+ }
640
+ /** `ch` outside a class, as it matches under `i` (a class of its case variants). */ function caseLiteral(ch, raw, unicode) {
641
+ const variants = caseVariants(ch, unicode);
642
+ return variants.length === 1 ? raw : `[${variants.map((v) => classChar(v, unicode)).join("")}]`;
643
+ }
644
+ /** The ranges of a sorted list of code points, as class members. */ function classRanges(points, unicode) {
645
+ let out = "";
646
+ for (let k = 0; k < points.length;) {
647
+ let end = k;
648
+ while (end + 1 < points.length && points[end + 1] === points[end] + 1) end++;
649
+ const lo = String.fromCodePoint(points[k]);
650
+ const hi = String.fromCodePoint(points[end]);
651
+ out += end === k ? classChar(lo, unicode) : `${classChar(lo, unicode)}-${classChar(hi, unicode)}`;
652
+ k = end + 1;
653
+ }
654
+ return out;
655
+ }
656
+ /** The largest range of non-ASCII characters whose case variants are spelled out. */ const MAX_RANGE = 1024;
657
+ /** What `\w` also matches under `iu` (characters folding to a word character). */ const WORD_FOLDS = "\\u017F\\u212A";
658
+ /**
659
+ * `pattern` with `i` (characters → classes of their case variants) and `s` (`.` → `[\s\S]`)
660
+ * applied (`modifier`: what has no flag-free form, see {@link jsonSchemaPattern}), or
661
+ * `undefined` when it is not parsed.
662
+ */ function translateFlags(pattern, unicode, ignoreCase, dotAll) {
663
+ let out = "";
664
+ let i = 0;
665
+ let modifier = false;
666
+ const n = pattern.length;
667
+ /** The character at `i` (a code point with `u`). */ const charAt = (at) => unicode ? String.fromCodePoint(pattern.codePointAt(at)) : pattern[at];
668
+ /**
669
+ * Reads an escape at `i` (after the backslash): its character (`ch`), or as written (`raw`)
670
+ * with what it needs (`modifier`: no flag-free form under `i`), or `undefined` (not parsed).
671
+ */ const readEscape = (inClass) => {
672
+ const start = i - 1;
673
+ const c = pattern[i];
674
+ if (c === void 0) return;
675
+ i++;
676
+ const raw = () => pattern.slice(start, i);
677
+ switch (c) {
678
+ case "d":
679
+ case "D":
680
+ case "s":
681
+ case "S": return { raw: raw() };
682
+ case "w": return {
683
+ raw: raw(),
684
+ word: true
685
+ };
686
+ case "W": return {
687
+ raw: raw(),
688
+ word: true,
689
+ modifier: inClass && unicode
690
+ };
691
+ case "b": return inClass ? {
692
+ ch: "\b",
693
+ raw: raw()
694
+ } : {
695
+ raw: raw(),
696
+ modifier: unicode
697
+ };
698
+ case "B": return inClass ? void 0 : {
699
+ raw: raw(),
700
+ modifier: unicode
701
+ };
702
+ case "p":
703
+ case "P": {
704
+ if (!unicode) return {
705
+ ch: c,
706
+ raw: raw()
707
+ };
708
+ const end = pattern.indexOf("}", i);
709
+ if (pattern[i] !== "{" || end < 0) return;
710
+ i = end + 1;
711
+ return {
712
+ raw: raw(),
713
+ modifier: true
714
+ };
715
+ }
716
+ case "k": {
717
+ const name = /^<[^>]*>/.exec(pattern.slice(i));
718
+ if (name) {
719
+ i += name[0].length;
720
+ return {
721
+ raw: raw(),
722
+ modifier: true
723
+ };
724
+ }
725
+ return unicode ? void 0 : {
726
+ ch: "k",
727
+ raw: raw()
728
+ };
729
+ }
730
+ case "c": {
731
+ const next = pattern[i];
732
+ if (next && /[A-Za-z]/.test(next)) {
733
+ i++;
734
+ return {
735
+ ch: String.fromCodePoint(next.codePointAt(0) % 32),
736
+ raw: raw()
737
+ };
738
+ }
739
+ return;
740
+ }
741
+ case "x": {
742
+ const hex = pattern.slice(i, i + 2);
743
+ if (!/^[\da-fA-F]{2}$/.test(hex)) return;
744
+ i += 2;
745
+ return {
746
+ ch: String.fromCodePoint(Number.parseInt(hex, 16)),
747
+ raw: raw()
748
+ };
749
+ }
750
+ case "u": {
751
+ if (unicode && pattern[i] === "{") {
752
+ const end = pattern.indexOf("}", i);
753
+ if (end < 0) return;
754
+ const cp = Number.parseInt(pattern.slice(i + 1, end), 16);
755
+ i = end + 1;
756
+ return {
757
+ ch: String.fromCodePoint(cp),
758
+ raw: raw()
759
+ };
760
+ }
761
+ const hex = pattern.slice(i, i + 4);
762
+ if (!/^[\da-fA-F]{4}$/.test(hex)) return;
763
+ i += 4;
764
+ let code = Number.parseInt(hex, 16);
765
+ if (unicode && code >= 55296 && code <= 56319) {
766
+ const low = /^\\u([dD][c-fC-F][\da-fA-F]{2})/.exec(pattern.slice(i));
767
+ if (low) {
768
+ i += 6;
769
+ code = 65536 + (code - 55296 << 10) + (Number.parseInt(low[1], 16) - 56320);
770
+ }
771
+ }
772
+ return {
773
+ ch: String.fromCodePoint(code),
774
+ raw: raw()
775
+ };
776
+ }
777
+ case "0": return /\d/.test(pattern[i] ?? "") ? void 0 : {
778
+ ch: "\0",
779
+ raw: raw()
780
+ };
781
+ case "f":
782
+ case "n":
783
+ case "r":
784
+ case "t":
785
+ case "v": return {
786
+ ch: {
787
+ f: "\f",
788
+ n: "\n",
789
+ r: "\r",
790
+ t: " ",
791
+ v: "\v"
792
+ }[c],
793
+ raw: raw()
794
+ };
795
+ default: {
796
+ if (/[1-9]/.test(c)) {
797
+ if (unicode || !inClass) {
798
+ while (/\d/.test(pattern[i] ?? "")) i++;
799
+ return inClass ? void 0 : {
800
+ raw: raw(),
801
+ modifier: true
802
+ };
803
+ }
804
+ return;
805
+ }
806
+ i = start + 1;
807
+ const ch = charAt(i);
808
+ i += ch.length;
809
+ return {
810
+ ch,
811
+ raw: raw()
812
+ };
813
+ }
814
+ }
815
+ };
816
+ /** Reads a character class at `i` (`[…]`), its characters with their case variants. */ const readClass = () => {
817
+ const start = i;
818
+ i++;
819
+ let negated = "";
820
+ if (pattern[i] === "^") {
821
+ negated = "^";
822
+ i++;
823
+ }
824
+ const items = [];
825
+ while (i < n && pattern[i] !== "]") {
826
+ if (pattern[i] === "\\") {
827
+ i++;
828
+ const esc = readEscape(true);
829
+ if (!esc) return;
830
+ modifier || (modifier = !!esc.modifier && ignoreCase);
831
+ items.push(esc.ch === void 0 ? {
832
+ raw: esc.raw,
833
+ word: esc.word
834
+ } : { ch: esc.ch });
835
+ continue;
836
+ }
837
+ const ch = charAt(i);
838
+ i += ch.length;
839
+ items.push(ch === "-" ? { dash: true } : { ch });
840
+ }
841
+ if (i >= n) return;
842
+ i++;
843
+ if (!ignoreCase) return pattern.slice(start, i);
844
+ const points = /* @__PURE__ */ new Set();
845
+ let body = "";
846
+ const addChar = (ch) => {
847
+ for (const v of caseVariants(ch, unicode)) points.add(v.codePointAt(0));
848
+ };
849
+ for (let k = 0; k < items.length; k++) {
850
+ const item = items[k];
851
+ const dash = items[k + 1];
852
+ const hi = items[k + 2];
853
+ if ("ch" in item && dash && "dash" in dash && hi && "ch" in hi) {
854
+ const lo = item.ch.codePointAt(0);
855
+ const top = hi.ch.codePointAt(0);
856
+ if (top > 127 && top - lo >= MAX_RANGE) {
857
+ modifier = true;
858
+ body += `${classChar(item.ch, unicode)}-${classChar(hi.ch, unicode)}`;
859
+ } else for (let cp = lo; cp <= top; cp++) addChar(String.fromCodePoint(cp));
860
+ k += 2;
861
+ continue;
862
+ }
863
+ if ("dash" in item) points.add(45);
864
+ else if ("raw" in item) {
865
+ body += item.raw;
866
+ if (item.word && unicode && item.raw === "\\w") body += WORD_FOLDS;
867
+ } else addChar(item.ch);
868
+ }
869
+ body += classRanges([...points].sort((a, b) => a - b), unicode);
870
+ return `[${negated}${body}]`;
871
+ };
872
+ while (i < n) {
873
+ const c = pattern[i];
874
+ if (c === "\\") {
875
+ i++;
876
+ const esc = readEscape(false);
877
+ if (!esc) return;
878
+ if (!ignoreCase) out += esc.raw;
879
+ else if (esc.ch !== void 0) out += caseLiteral(esc.ch, esc.raw, unicode);
880
+ else {
881
+ modifier || (modifier = !!esc.modifier);
882
+ out += esc.word && unicode ? esc.raw === "\\w" ? `[\\w${WORD_FOLDS}]` : `[^\\w${WORD_FOLDS}]` : esc.raw;
883
+ }
884
+ continue;
885
+ }
886
+ if (c === "[") {
887
+ const cls = readClass();
888
+ if (cls === void 0) return;
889
+ out += cls;
890
+ continue;
891
+ }
892
+ if (c === "(") {
893
+ if (pattern[i + 1] === "?") {
894
+ const header = /^\(\?(?::|=|!|<=|<!|<[^>]+>)/.exec(pattern.slice(i));
895
+ if (!header) return;
896
+ out += header[0];
897
+ i += header[0].length;
898
+ continue;
899
+ }
900
+ out += c;
901
+ i++;
902
+ continue;
903
+ }
904
+ if (c === "{") {
905
+ const quantifier = /^\{\d+(?:,\d*)?\}/.exec(pattern.slice(i));
906
+ if (quantifier) {
907
+ out += quantifier[0];
908
+ i += quantifier[0].length;
909
+ continue;
910
+ }
911
+ }
912
+ if (c === "." && dotAll) {
913
+ out += "[\\s\\S]";
914
+ i++;
915
+ continue;
916
+ }
917
+ const ch = charAt(i);
918
+ i += ch.length;
919
+ out += ignoreCase && !"^$|)*+?.]}{".includes(ch) ? caseLiteral(ch, ch, unicode) : ch;
920
+ }
921
+ return {
922
+ source: out,
923
+ modifier
924
+ };
134
925
  }
135
926
 
136
927
  //#endregion
@@ -156,7 +947,7 @@
156
947
  * - `keyMask` has a bit (by {@link VALIDATOR_KEYS} index) per validator annotation that is
157
948
  * *effective* on the node and relevant to its def (present; flags: truthy).
158
949
  * `patternShape` has one char per `@expect.pattern` entry: `e` (empty, skipped),
159
- * `n` (checked), `s` (stateful `g` / `y` regex: the check bails to the walk there).
950
+ * `n` (checked).
160
951
  * - `slot`: the site's first K slot (see {@link siteSlotCount}); `slotCount` is the total.
161
952
  * - `EXT`: an anonymous reference into another module's type; bound to that type's own
162
953
  * compiled check (as a template, against the referring node) when it has one, else
@@ -164,7 +955,11 @@
164
955
  * - `INTERP`: a node only known at runtime (e.g. a chained reference into another module's
165
956
  * type): always checked by the interpreted pre-check.
166
957
  */
167
- /** Layout format version; checks of another version are ignored (interpreted). */ const LAYOUT_VERSION = 2;
958
+ /**
959
+ * Layout format version, also of the emitted checks' contract with the runtime (5: 'strip'
960
+ * records `object, key` pairs at every depth); checks of another version are ignored
961
+ * (interpreted).
962
+ */ const LAYOUT_VERSION = 5;
168
963
  const EXT = -1;
169
964
  const INTERP = -2;
170
965
  const D_FINAL = 0;
@@ -175,18 +970,11 @@ const D_INTERSECTION = 4;
175
970
  const D_TUPLE = 5;
176
971
  const D_UNKNOWN = 6;
177
972
  const D_OBJECT_PATTERNS = 7;
178
- /** Def codes of the kinds with `items`, by kind name. */ const ITEMS_KIND_CODES = {
179
- union: D_UNION,
180
- intersection: D_INTERSECTION,
181
- tuple: D_TUPLE
182
- };
183
973
  /** Kind names of the def codes with `items`. */ const ITEMS_KIND_NAMES = {
184
974
  [D_UNION]: "union",
185
975
  [D_INTERSECTION]: "intersection",
186
976
  [D_TUPLE]: "tuple"
187
977
  };
188
- /** Bits of a compiled check's `flags` argument: the pre-check's TOP / IN_UNION, then options. */ const F_TOP = 1;
189
- const F_IN_UNION = 2;
190
978
  const F_ERROR = 4;
191
979
  const F_STRIP = 8;
192
980
  const F_PARTIAL_DEEP = 16;
@@ -248,53 +1036,9 @@ const ALL_BITS = (1 << VALIDATOR_KEYS.length) - 1;
248
1036
  */ function siteBits(type, optional) {
249
1037
  return (type === void 0 ? 0 : relevantBits(type)) | (optional ? B_REQUIRED : 0);
250
1038
  }
251
- /**
252
- * Number of K slots a site takes, from its first slot on:
253
- * - INTERP: its interpreted check, then whether its type is a literal;
254
- * - otherwise, for an optional `@meta.required` node ({@link hasRejectSlot}): the node
255
- * (its `null` is rejected unless its type accepts `null`, decided live);
256
- * - then EXT: the bound check of the referenced type, and whether that type is a literal;
257
- * any other site: its annotation values (see {@link keySlots}).
258
- */ function siteSlotCount(site) {
259
- const [, mask, def, shape] = site;
260
- if (def === INTERP) return 2;
261
- let n = (hasRejectSlot(site) ? 1 : 0) + (def === EXT ? 2 : 0);
262
- if (def !== EXT) {
263
- for (let bits = mask & VALUE_BITS; bits !== 0; bits &= bits - 1) n++;
264
- for (const c of shape) if (c === "n") n++;
265
- }
266
- return n;
267
- }
268
1039
  /** An optional node with `@meta.required`: `null` fails unless its type accepts `null`. */ function hasRejectSlot(site) {
269
1040
  return site[0] === 1 && (site[1] & B_REQUIRED) !== 0;
270
1041
  }
271
- /** The K slot of each annotation value of a site whose values start at slot `at`. */ function keySlots(mask, shape, at) {
272
- let k = at;
273
- const next = (b) => (mask & b) === 0 ? -1 : k++;
274
- const minLength = next(B_MIN_LENGTH);
275
- const maxLength = next(B_MAX_LENGTH);
276
- const patterns = [];
277
- for (const c of shape) if (c === "n") patterns.push(k++);
278
- return {
279
- minLength,
280
- maxLength,
281
- patterns,
282
- min: next(B_MIN),
283
- max: next(B_MAX),
284
- exMin: next(B_EX_MIN),
285
- exMax: next(B_EX_MAX)
286
- };
287
- }
288
- /** The child sites of a def. */ function childSites(def) {
289
- switch (def[0]) {
290
- case D_OBJECT: return def[2];
291
- case D_ARRAY: return [def[1]];
292
- case D_UNION:
293
- case D_INTERSECTION:
294
- case D_TUPLE: return def[1];
295
- default: return [];
296
- }
297
- }
298
1042
  /**
299
1043
  * Computes a node's key mask and pattern shape over `relevant` bits, and — when `out` is
300
1044
  * given — writes the normalised annotation values from `out[at]` on (the K slots).
@@ -304,14 +1048,15 @@ const ALL_BITS = (1 << VALIDATOR_KEYS.length) - 1;
304
1048
  let mask = 0;
305
1049
  let shape = "";
306
1050
  let k = at;
307
- if (metadata.size === 0) return {
1051
+ const meta = filledMeta(metadata);
1052
+ if (meta === void 0) return {
308
1053
  mask,
309
1054
  shape
310
1055
  };
311
1056
  for (let i = 0; i < VALIDATOR_KEYS.length; i++) {
312
1057
  const b = 1 << i;
313
1058
  if ((relevant & b) === 0) continue;
314
- const raw = metadata.get(VALIDATOR_KEYS[i]);
1059
+ const raw = meta.get(VALIDATOR_KEYS[i]);
315
1060
  if ((b & FLAG_BITS) !== 0) {
316
1061
  if (raw) mask |= b;
317
1062
  continue;
@@ -327,10 +1072,6 @@ const ALL_BITS = (1 << VALIDATOR_KEYS.length) - 1;
327
1072
  continue;
328
1073
  }
329
1074
  const re = reader.regex(pattern, flags);
330
- if (re.global || re.sticky) {
331
- shape += "s";
332
- break;
333
- }
334
1075
  shape += "n";
335
1076
  if (out) out[k] = re;
336
1077
  k++;
@@ -363,7 +1104,7 @@ const ALL_BITS = (1 << VALIDATOR_KEYS.length) - 1;
363
1104
  *
364
1105
  * A registered entry is also a template: a node referencing a class of another module
365
1106
  * (an `EXT` site) binds that class's layout against itself — its own annotations feed `K`
366
- * — so cross-module references, aliases of imported types and cloned imported props run
1107
+ * — so cross-module references, aliases of imported types and their derived props run
367
1108
  * compiled code whenever their tree matches the referenced type's structure.
368
1109
  *
369
1110
  * The registry is module-local: classes registered with another copy of this runtime
@@ -442,7 +1183,7 @@ let autoCompile = null;
442
1183
  watch(n);
443
1184
  const metadata = n.metadata;
444
1185
  if (!(metadata instanceof AnnotationMap)) return false;
445
- watch(metadata);
1186
+ if (!watchLayer(metadata)) return false;
446
1187
  let k = at;
447
1188
  if (hasRejectSlot(site)) K[k++] = n;
448
1189
  if (d === EXT) return readKeys(metadata, siteBits(void 0, optional === 1), env).mask === mask && bindRuntimeSite(n, k, true);
@@ -498,6 +1239,16 @@ let autoCompile = null;
498
1239
  * when the node is optional; the referring site handles `optional`): the referenced class's
499
1240
  * layout bound against the node when it matches, else the interpreted pre-check.
500
1241
  */ function externalCheck(node, env) {
1242
+ const own = entries.get(node);
1243
+ if (own !== void 0) {
1244
+ if (own.binding) {
1245
+ const fallback = interpreted(node, env);
1246
+ return (value, flags, opts) => (own.fn ?? fallback)(value, flags, opts);
1247
+ }
1248
+ const fn = own.epoch === currentEpoch() ? own.fn : bind(own, own, node, env, false);
1249
+ if (fn !== null) return fn;
1250
+ return interpreted(node, env);
1251
+ }
501
1252
  const entry = templateOf(node);
502
1253
  if (entry !== void 0) {
503
1254
  let binding = templates.get(node);
@@ -525,7 +1276,8 @@ let autoCompile = null;
525
1276
  * (unchained) reference, through aliases of other modules' types.
526
1277
  */ function templateOf(node) {
527
1278
  let ref = node.ref;
528
- for (let hops = 0; hops < 16 && ref !== void 0 && ref.field === ""; hops++) {
1279
+ for (const seen = /* @__PURE__ */ new Set(); ref !== void 0 && ref.field === "" && !seen.has(ref);) {
1280
+ seen.add(ref);
529
1281
  let target;
530
1282
  try {
531
1283
  target = ref.type();
@@ -564,37 +1316,38 @@ function _define_property$1(obj, key, value) {
564
1316
  * after a validator was created are always honoured — the same as the full walk.
565
1317
  *
566
1318
  * Result contract (relative to the full walk over the same node and value):
567
- * - `PASS` — the walk returns `true`, collects no errors and has no side effects other
568
- * than the strips recorded here (see below).
1319
+ * - `PASS` — the walk returns `true`, collects no errors and records the strips recorded
1320
+ * here (see below).
569
1321
  * - `FAIL` — the walk returns `false`. Inside a union, every node the walk would visit
570
- * was visited here too (so a walk that would throw makes this throw first) and the
571
- * walk's only side effects for this node are the strips recorded here. Outside unions
1322
+ * was visited here too (so a walk that would throw makes this throw first). Outside unions
572
1323
  * a `FAIL` always ends in the walk, so it may be returned early.
573
1324
  * - `BAIL` — not decidable here; the caller must run the full walk.
574
1325
  *
575
1326
  * Union branches are tried in declared order, continuing past `FAIL` and stopping
576
1327
  * at `BAIL`, which keeps union results identical to the walk.
577
1328
  *
578
- * `unknownProps: 'strip'`: the walk deletes an object's unknown keys right after the object
579
- * passes (even when an ancestor fails later). This check records those deletions only for
580
- * the top-level object (`pendingKeys`), whose strip is the walk's last read of the input:
581
- * deferring an earlier strip past later reads could be observed by them (a prototype, a
582
- * proxy or an accessor over the stripped object), so a nested object with unknown keys
583
- * bails, as does any object visit once a strip is pending (a later intersection member).
584
- * The recorded keys are deleted, in the walk's order, only when the whole value passes —
585
- * so a `PASS` result still has exactly the walk's side effects, and `FAIL` / `BAIL` leave
1329
+ * `unknownProps: 'strip'`: like the walk, this check records the unknown keys of each object
1330
+ * that passes (`pendingStrips`, in the order the objects complete), drops what a rejected union
1331
+ * branch recorded, and deletes the keys only when the whole value passes. Neither reads a
1332
+ * stripped input, so a `PASS` performs exactly the walk's deletions and `FAIL` / `BAIL` leave
586
1333
  * the value untouched for the walk.
587
1334
  */ const FAIL = 0;
588
1335
  const PASS = 1;
589
1336
  const BAIL = 2;
590
1337
  /** Node is at walk depth 0 (only object props / array & tuple items increase depth). */ const TOP = 1;
591
1338
  /** Node is inside a union branch — failures must be exhaustive (see contract). */ const IN_UNION = 2;
1339
+ /**
1340
+ * Wasted union branches (see {@link unionWaste}) after which a call memoizes nested unions: a
1341
+ * union nested in its own branches, many branches each, is checked again from every branch of
1342
+ * every union above it — (branches)^(depth) work. Ordinary unions waste a few branches at most;
1343
+ * the memo would cost them more than it saves.
1344
+ */ const WASTE_BEFORE_MEMO = 16;
592
1345
  /** Incremented per {@link fastCheckPasses} call; snapshots verified in older calls re-verify. */ let stamp = 0;
593
1346
  /** A 'strip' {@link fastCheckPasses} call is in progress (the pending strips below are its own). */ let stripping = false;
594
1347
  /**
595
- * Unknown keys of the top-level object the walk would delete (`unknownProps: 'strip'`), in
596
- * the walk's deletion order. Deleted when the call passes, dropped otherwise.
597
- */ const pendingKeys = [];
1348
+ * The unknown keys the walk would delete (`unknownProps: 'strip'`): `object, key, …` in the
1349
+ * walk's deletion order. Deleted when the call passes, dropped otherwise.
1350
+ */ const pendingStrips = [];
598
1351
  /**
599
1352
  * `true` only when the full walk over `value` is guaranteed to pass with no errors and
600
1353
  * no side effects other than its 'strip' deletions, which are then performed here, as the
@@ -603,16 +1356,21 @@ const BAIL = 2;
603
1356
  */ function fastCheckPasses(def, value, opts) {
604
1357
  if (opts.unknownProps === "strip") return fastCheckStripping(def, value, opts);
605
1358
  stamp++;
1359
+ if (COMPILED_ENV.m !== void 0) COMPILED_ENV.m = void 0;
1360
+ let passed;
606
1361
  try {
607
- return check(def, value, opts) === PASS;
1362
+ passed = check(def, value, opts) === PASS;
608
1363
  } catch {
609
- return false;
1364
+ passed = false;
610
1365
  }
1366
+ if (COMPILED_ENV.m !== void 0) COMPILED_ENV.m = void 0;
1367
+ return passed;
611
1368
  }
612
1369
  /** {@link fastCheckPasses} for `unknownProps: 'strip'`: performs the recorded strips on a pass. */ function fastCheckStripping(def, value, opts) {
613
1370
  if (stripping) return false;
614
1371
  stamp++;
615
1372
  stripping = true;
1373
+ if (COMPILED_ENV.m !== void 0) COMPILED_ENV.m = void 0;
616
1374
  let passed;
617
1375
  try {
618
1376
  passed = check(def, value, opts) === PASS;
@@ -621,12 +1379,27 @@ const BAIL = 2;
621
1379
  } finally {
622
1380
  stripping = false;
623
1381
  }
1382
+ if (COMPILED_ENV.m !== void 0) COMPILED_ENV.m = void 0;
1383
+ performStrips(pendingStrips, passed);
1384
+ return passed;
1385
+ }
1386
+ /**
1387
+ * Deletes the recorded unknown keys (`unknownProps: 'strip'`; `object, key, …` in deletion order)
1388
+ * when the call `passed`, and empties the list either way. Shared by the walk and the pre-check:
1389
+ * the same deletes in the same order (a failing `delete`, e.g. of a frozen object's key, throws
1390
+ * at the same key).
1391
+ */ function performStrips(strips, passed) {
624
1392
  try {
625
- if (passed) for (const key of pendingKeys) delete value[key];
1393
+ if (passed) for (let i = 0; i < strips.length; i += 2) delete strips[i][strips[i + 1]];
626
1394
  } finally {
627
- pendingKeys.length = 0;
1395
+ strips.length = 0;
628
1396
  }
629
- return passed;
1397
+ }
1398
+ /** The strips `list` recorded after its first `kept` entries (a union's own), or `undefined`. */ function stripsSince(list, kept) {
1399
+ return list.length > kept ? list.slice(kept) : void 0;
1400
+ }
1401
+ /** Records in `target` again the strips a memoized union recorded (see {@link stripsSince}). */ function stripAgain(target, strips) {
1402
+ if (strips !== void 0) for (const entry of strips) target.push(entry);
630
1403
  }
631
1404
  /**
632
1405
  * The pre-check of the root: the type's build-time compiled check when it has one bound to
@@ -636,9 +1409,12 @@ const BAIL = 2;
636
1409
  const compiled = compiledCheckFor(def, COMPILED_ENV);
637
1410
  return compiled === null ? fastCheck(def, value, TOP, opts) : compiled(value, TOP | optionFlags(opts), opts);
638
1411
  }
639
- const DECIMAL_RE = /^[+-]?\d+(\.\d+)?$/;
640
1412
  const regexCache = /* @__PURE__ */ new Map();
641
- /** Compiled `@expect.pattern` regex, cached per (pattern, flags). */ function getRegex(pattern, flags) {
1413
+ /**
1414
+ * Compiled `@expect.pattern` regex, cached per (pattern, flags). Compiled without the
1415
+ * stateful `g` / `y` flags (see {@link statelessRegExp}): every engine tests with it, and
1416
+ * gets the same result on every call.
1417
+ */ function getRegex(pattern, flags) {
642
1418
  let byFlags = regexCache.get(pattern);
643
1419
  if (!byFlags) {
644
1420
  byFlags = /* @__PURE__ */ new Map();
@@ -647,7 +1423,7 @@ const regexCache = /* @__PURE__ */ new Map();
647
1423
  const flagsKey = flags || "";
648
1424
  let regex = byFlags.get(flagsKey);
649
1425
  if (!regex) {
650
- regex = new RegExp(pattern, flags);
1426
+ regex = statelessRegExp(new RegExp(pattern, flags));
651
1427
  byFlags.set(flagsKey, regex);
652
1428
  }
653
1429
  return regex;
@@ -656,7 +1432,8 @@ const regexCache = /* @__PURE__ */ new Map();
656
1432
  * `true` when `def` (an optional field holding `null`) carries `@meta.required` and its
657
1433
  * type does not itself accept `null`. Shared by the walk and the fast pre-check.
658
1434
  */ function rejectsNullAsRequired(def) {
659
- return def.metadata.size > 0 && !!def.metadata.get("meta.required") && !acceptsNull(def);
1435
+ const metadata = filledMeta(def.metadata);
1436
+ return metadata !== void 0 && !!metadata.get("meta.required") && !acceptsNull(def);
660
1437
  }
661
1438
  function acceptsNull(def) {
662
1439
  const type = def.type;
@@ -670,13 +1447,136 @@ function acceptsNull(def) {
670
1447
  return false;
671
1448
  }
672
1449
  /** What compiled checks share with the interpreted pre-check. */ const COMPILED_ENV = {
673
- pk: pendingKeys,
1450
+ pk: pendingStrips,
674
1451
  ho: Object.prototype.hasOwnProperty,
675
1452
  dec: DECIMAL_RE,
676
1453
  regex: getRegex,
677
1454
  interp: fastCheck,
678
- rn: rejectsNullAsRequired
1455
+ rn: rejectsNullAsRequired,
1456
+ m: void 0,
1457
+ n: 0,
1458
+ w: 0,
1459
+ wa: unionWaste,
1460
+ mg: memoGet,
1461
+ ms: memoSet
679
1462
  };
1463
+ /**
1464
+ * A union branch failed after branches of nested unions over objects did (`COMPILED_ENV.n`, the
1465
+ * failed branches of unions over objects inside union branches, moved): work
1466
+ * a later branch of the same outermost union may do again. Past {@link WASTE_BEFORE_MEMO} wasted
1467
+ * branches since the outermost union was entered, the call memoizes the unions over objects it
1468
+ * checks inside union branches (`memoGet` / `memoSet`): each such union is then decided once per
1469
+ * value, flags and options — the same result (a pre-check outcome depends on nothing else: the
1470
+ * input is not changed during the call, see the contract above) and the same strips, recorded
1471
+ * again on a reuse.
1472
+ */ function unionWaste() {
1473
+ if (++COMPILED_ENV.w === WASTE_BEFORE_MEMO && COMPILED_ENV.m === void 0) COMPILED_ENV.m = /* @__PURE__ */ new Map();
1474
+ }
1475
+ /**
1476
+ * The outcome memoized for union `key` (a node, or a compiled union's key) over `value`, or -1;
1477
+ * records the strips the union recorded when it was decided.
1478
+ */ function memoGet(key, value, flags, opts) {
1479
+ const entries = COMPILED_ENV.m.get(value);
1480
+ if (entries !== void 0) {
1481
+ for (let i = 0; i < entries.length; i += 5) if (entries[i] === key && entries[i + 1] === flags && entries[i + 2] === opts) {
1482
+ stripAgain(pendingStrips, entries[i + 4]);
1483
+ return entries[i + 3];
1484
+ }
1485
+ }
1486
+ return -1;
1487
+ }
1488
+ /**
1489
+ * Memoizes the outcome of union `key` over `value` (see {@link memoGet}), entered with `kept`
1490
+ * pending strips (the ones after them are its own).
1491
+ */ function memoSet(key, value, flags, opts, result, kept) {
1492
+ const memo = COMPILED_ENV.m;
1493
+ const strips = stripsSince(pendingStrips, kept);
1494
+ const entries = memo.get(value);
1495
+ if (entries === void 0) memo.set(value, [
1496
+ key,
1497
+ flags,
1498
+ opts,
1499
+ result,
1500
+ strips
1501
+ ]);
1502
+ else entries.push(key, flags, opts, result, strips);
1503
+ }
1504
+ /**
1505
+ * The `fastCheck` union case: branches in declared order (see the contract above). A union over
1506
+ * an object inside a union branch counts its failed branches and, once the call made the memo,
1507
+ * is decided once (see `unionWaste`).
1508
+ */ function fastCheckUnion(def, value, flags, opts) {
1509
+ let nested = false;
1510
+ if ((flags & IN_UNION) === 0) COMPILED_ENV.w = 0;
1511
+ else if (typeof value === "object" && value !== null) {
1512
+ if (COMPILED_ENV.m !== void 0) return memoizedUnion(def, value, flags, opts);
1513
+ nested = true;
1514
+ }
1515
+ const branchFlags = flags | IN_UNION;
1516
+ const kept = pendingStrips.length;
1517
+ for (const item of def.type.items) {
1518
+ const failures = COMPILED_ENV.n;
1519
+ const result = fastCheck(item, value, branchFlags, opts);
1520
+ if (result !== FAIL) return unionMatchResult(result, item, def.metadata, value);
1521
+ if (COMPILED_ENV.n !== failures) unionWaste();
1522
+ if (nested) COMPILED_ENV.n++;
1523
+ if (pendingStrips.length !== kept) pendingStrips.length = kept;
1524
+ }
1525
+ return FAIL;
1526
+ }
1527
+ /** {@link fastCheckUnion} of a union plan (the same memo entries: keyed by the node). */ function checkPlanUnion(plan, value, flags, opts) {
1528
+ let nested = false;
1529
+ if ((flags & IN_UNION) === 0) COMPILED_ENV.w = 0;
1530
+ else if (typeof value === "object" && value !== null) {
1531
+ if (COMPILED_ENV.m !== void 0) return memoizedUnion(plan.def, value, flags, opts, plan);
1532
+ nested = true;
1533
+ }
1534
+ const branchFlags = flags | IN_UNION;
1535
+ const kept = pendingStrips.length;
1536
+ for (const child of plan.children) {
1537
+ const failures = COMPILED_ENV.n;
1538
+ const result = checkPlan(child, value, branchFlags, opts);
1539
+ if (result !== FAIL) return unionMatchResult(result, child.def, plan.metadata, value);
1540
+ if (COMPILED_ENV.n !== failures) unionWaste();
1541
+ if (nested) COMPILED_ENV.n++;
1542
+ if (pendingStrips.length !== kept) pendingStrips.length = kept;
1543
+ }
1544
+ return FAIL;
1545
+ }
1546
+ /** The branches of a union (see {@link fastCheckUnion}); `nested`: its failed branches count. */ function unionBranches(def, value, flags, opts, nested) {
1547
+ const branchFlags = flags | IN_UNION;
1548
+ const kept = pendingStrips.length;
1549
+ for (const item of def.type.items) {
1550
+ const failures = COMPILED_ENV.n;
1551
+ const result = fastCheck(item, value, branchFlags, opts);
1552
+ if (result !== FAIL) return unionMatchResult(result, item, def.metadata, value);
1553
+ if (COMPILED_ENV.n !== failures) unionWaste();
1554
+ if (nested) COMPILED_ENV.n++;
1555
+ if (pendingStrips.length !== kept) pendingStrips.length = kept;
1556
+ }
1557
+ return FAIL;
1558
+ }
1559
+ /** {@link unionBranches} of a union plan. */ function planUnionBranches(plan, value, flags, opts, nested) {
1560
+ const branchFlags = flags | IN_UNION;
1561
+ const kept = pendingStrips.length;
1562
+ for (const child of plan.children) {
1563
+ const failures = COMPILED_ENV.n;
1564
+ const result = checkPlan(child, value, branchFlags, opts);
1565
+ if (result !== FAIL) return unionMatchResult(result, child.def, plan.metadata, value);
1566
+ if (COMPILED_ENV.n !== failures) unionWaste();
1567
+ if (nested) COMPILED_ENV.n++;
1568
+ if (pendingStrips.length !== kept) pendingStrips.length = kept;
1569
+ }
1570
+ return FAIL;
1571
+ }
1572
+ /** A union over object `value` inside a union branch, once the call made the memo. */ function memoizedUnion(def, value, flags, opts, plan) {
1573
+ const known = memoGet(def, value, flags, opts);
1574
+ if (known >= 0) return known;
1575
+ const kept = pendingStrips.length;
1576
+ const result = plan === void 0 ? unionBranches(def, value, flags, opts, true) : planUnionBranches(plan, value, flags, opts, true);
1577
+ if (result !== BAIL) memoSet(def, value, flags, opts, result, kept);
1578
+ return result;
1579
+ }
680
1580
  function fastCheck(def, value, flags, opts) {
681
1581
  if (def.optional && (value === void 0 || value === null)) return value === null && rejectsNullAsRequired(def) ? FAIL : PASS;
682
1582
  const type = def.type;
@@ -684,21 +1584,8 @@ function fastCheck(def, value, flags, opts) {
684
1584
  case "": return fastCheckFinal(def, value);
685
1585
  case "object": return fastCheckObject(def, value, flags, opts);
686
1586
  case "array": return fastCheckArray(def, value, flags, opts);
687
- case "union": {
688
- const branchFlags = flags | IN_UNION;
689
- for (const item of type.items) {
690
- const result = fastCheck(item, value, branchFlags, opts);
691
- if (result !== FAIL) return unionMatchResult(result, item, def.metadata, value);
692
- if (pendingKeys.length > 0) return BAIL;
693
- }
694
- return FAIL;
695
- }
696
- case "intersection":
697
- for (const item of type.items) {
698
- const result = fastCheck(item, value, flags, opts);
699
- if (result !== PASS) return result;
700
- }
701
- return PASS;
1587
+ case "union": return fastCheckUnion(def, value, flags, opts);
1588
+ case "intersection": return fastCheckIntersection(type, value, flags, opts);
702
1589
  case "tuple": {
703
1590
  const items = type.items;
704
1591
  if (!Array.isArray(value) || value.length !== items.length) return FAIL;
@@ -735,8 +1622,9 @@ function fastCheckFinal(def, value) {
735
1622
  /**
736
1623
  * Mirrors Validator.validateUnionConstraints: union-level constraints on the matched value
737
1624
  * (`null` / objects pass; the caller skips literal branches).
738
- */ function fastCheckUnionConstraints(metadata, value) {
739
- if (metadata.size === 0) return PASS;
1625
+ */ function fastCheckUnionConstraints(meta, value) {
1626
+ const metadata = filledMeta(meta);
1627
+ if (metadata === void 0) return PASS;
740
1628
  switch (typeof value) {
741
1629
  case "string": return fastCheckString(metadata, value);
742
1630
  case "number": return fastCheckNumber(metadata, value);
@@ -745,11 +1633,13 @@ function fastCheckFinal(def, value) {
745
1633
  default: return PASS;
746
1634
  }
747
1635
  }
748
- function fastCheckBoolean(metadata, value) {
749
- return metadata.size === 0 ? PASS : booleanConstraints(value, metadata.get("meta.required"));
1636
+ function fastCheckBoolean(meta, value) {
1637
+ const metadata = filledMeta(meta);
1638
+ return metadata === void 0 ? PASS : booleanConstraints(value, metadata.get("meta.required"));
750
1639
  }
751
- function fastCheckString(metadata, value) {
752
- if (metadata.size === 0) return PASS;
1640
+ function fastCheckString(meta, value) {
1641
+ const metadata = filledMeta(meta);
1642
+ if (metadata === void 0) return PASS;
753
1643
  if (metadata.get("meta.required") && value.trim().length === 0) return FAIL;
754
1644
  const minLength = metadata.get("expect.minLength");
755
1645
  if (minLength !== void 0 && value.length < (typeof minLength === "number" ? minLength : minLength.length)) return FAIL;
@@ -758,14 +1648,13 @@ function fastCheckString(metadata, value) {
758
1648
  const patterns = metadata.get("expect.pattern");
759
1649
  if (patterns) for (const { pattern, flags } of patterns) {
760
1650
  if (!pattern) continue;
761
- const regex = getRegex(pattern, flags);
762
- if (regex.global || regex.sticky) return BAIL;
763
- if (!regex.test(value)) return FAIL;
1651
+ if (!getRegex(pattern, flags).test(value)) return FAIL;
764
1652
  }
765
1653
  return PASS;
766
1654
  }
767
- function fastCheckNumber(metadata, value) {
768
- if (metadata.size === 0) return PASS;
1655
+ function fastCheckNumber(meta, value) {
1656
+ const metadata = filledMeta(meta);
1657
+ if (metadata === void 0) return PASS;
769
1658
  return numberConstraints(value, metadata.get("expect.int"), metadata.get("expect.min"), metadata.get("expect.max"), metadata.get("expect.exclusiveMin"), metadata.get("expect.exclusiveMax"));
770
1659
  }
771
1660
  function booleanConstraints(value, required) {
@@ -782,6 +1671,16 @@ function numberConstraints(value, int, min, max, exMin, exMax) {
782
1671
  /** `@expect.minLength` / `@expect.maxLength` (strings and arrays). */ function lengthFails(length, minLength, maxLength) {
783
1672
  return minLength !== void 0 && length < (typeof minLength === "number" ? minLength : minLength.length) || maxLength !== void 0 && length > (typeof maxLength === "number" ? maxLength : maxLength.length);
784
1673
  }
1674
+ /**
1675
+ * {@link fastCheck} of an intersection (a function of its own: `fastCheck` stays small, so the
1676
+ * engine inlines it in the hot object and prop checks).
1677
+ */ function fastCheckIntersection(type, value, flags, opts) {
1678
+ for (const item of type.items) {
1679
+ const result = fastCheck(item, value, flags, opts);
1680
+ if (result !== PASS) return result;
1681
+ }
1682
+ return PASS;
1683
+ }
785
1684
  /** Array constraints; duplicate detection (`uniqueItems`) is left to the walk. */ function arrayConstraints(length, minLength, maxLength, uniqueItems) {
786
1685
  if (lengthFails(length, minLength, maxLength)) return FAIL;
787
1686
  return uniqueItems ? BAIL : PASS;
@@ -790,7 +1689,6 @@ function fastCheckObject(def, value, flags, opts) {
790
1689
  if (typeof value !== "object" || value === null || Array.isArray(value)) return FAIL;
791
1690
  const type = def.type;
792
1691
  if (type.propsPatterns.length > 0) return BAIL;
793
- if (pendingKeys.length > 0) return BAIL;
794
1692
  const unknownProps = opts.unknownProps;
795
1693
  const inUnion = (flags & IN_UNION) !== 0;
796
1694
  if (unknownProps === "error" && !inUnion && hasUnknownKey(type.props, value)) return FAIL;
@@ -809,19 +1707,14 @@ function fastCheckObject(def, value, flags, opts) {
809
1707
  }
810
1708
  }
811
1709
  if (result !== PASS) return result;
812
- if (unknownProps === "strip") return pendStrips(type.props, value, flags);
1710
+ if (unknownProps === "strip") {
1711
+ pendStrips(type.props, value);
1712
+ return PASS;
1713
+ }
813
1714
  return unknownProps === "error" && inUnion && hasUnknownKey(type.props, value) ? FAIL : PASS;
814
1715
  }
815
- /**
816
- * Records the unknown keys of a passing top-level object: the walk deletes them at this
817
- * point, after its last read of the input. A nested object's strip would be followed by
818
- * more reads, so it is left to the walk.
819
- */ function pendStrips(props, value, flags) {
820
- for (const key of Object.keys(value)) if (isUnknownKey(props, key)) {
821
- if ((flags & TOP) === 0) return BAIL;
822
- pendingKeys.push(key);
823
- }
824
- return PASS;
1716
+ /** Records the unknown keys of a passing object (see `pendingStrips`). */ function pendStrips(props, value) {
1717
+ for (const key of Object.keys(value)) if (isUnknownKey(props, key)) pendingStrips.push(value, key);
825
1718
  }
826
1719
  /** `true` when `value` has a key the walk treats as unknown. */ function hasUnknownKey(props, value) {
827
1720
  for (const key of Object.keys(value)) if (isUnknownKey(props, key)) return true;
@@ -833,8 +1726,8 @@ function fastCheckObject(def, value, flags, opts) {
833
1726
  }
834
1727
  function fastCheckArray(def, value, flags, opts) {
835
1728
  if (!Array.isArray(value)) return FAIL;
836
- const metadata = def.metadata;
837
- if (metadata.size > 0) {
1729
+ const metadata = filledMeta(def.metadata);
1730
+ if (metadata !== void 0) {
838
1731
  const result = fastCheckArrayConstraints(metadata, value);
839
1732
  if (result !== PASS) return result;
840
1733
  }
@@ -976,12 +1869,12 @@ function planFor(def) {
976
1869
  }
977
1870
  }
978
1871
  /** Brings the annotation values up to date (once per call, when a constraint is read). */ function refreshMeta(plan) {
979
- const metadata = plan.metadata;
980
- if (!(metadata.size === 0 ? plan.m0 === void 0 && plan.m1 === void 0 && plan.m2 === void 0 && plan.m3 === void 0 && plan.m4 === void 0 : metadata.get(plan.k0) === plan.m0 && (plan.k1 === void 0 || metadata.get(plan.k1) === plan.m1) && (plan.k2 === void 0 || metadata.get(plan.k2) === plan.m2) && (plan.k3 === void 0 || metadata.get(plan.k3) === plan.m3) && (plan.k4 === void 0 || metadata.get(plan.k4) === plan.m4))) snapshotMeta(plan);
1872
+ const metadata = filledMeta(plan.metadata);
1873
+ if (!(metadata === void 0 ? plan.m0 === void 0 && plan.m1 === void 0 && plan.m2 === void 0 && plan.m3 === void 0 && plan.m4 === void 0 : metadata.get(plan.k0) === plan.m0 && (plan.k1 === void 0 || metadata.get(plan.k1) === plan.m1) && (plan.k2 === void 0 || metadata.get(plan.k2) === plan.m2) && (plan.k3 === void 0 || metadata.get(plan.k3) === plan.m3) && (plan.k4 === void 0 || metadata.get(plan.k4) === plan.m4))) snapshotMeta(plan);
981
1874
  plan.metaStamp = stamp;
982
1875
  }
983
1876
  function snapshotMeta(plan) {
984
- const metadata = plan.metadata;
1877
+ const metadata = readable(plan.metadata);
985
1878
  plan.m0 = metadata.get(plan.k0);
986
1879
  plan.m1 = metadata.get(plan.k1);
987
1880
  plan.m2 = metadata.get(plan.k2);
@@ -1084,14 +1977,7 @@ function setMetaKeys(plan, k0, k1, k2, k3, k4) {
1084
1977
  case OP_NUMBER: return typeof value === "number" && Number.isFinite(value) ? checkNumber(plan, value) : FAIL;
1085
1978
  case OP_OBJECT: return checkObject(plan, value, flags, opts);
1086
1979
  case OP_ARRAY: return checkArray(plan, value, flags, opts);
1087
- case OP_UNION: {
1088
- const branchFlags = flags | IN_UNION;
1089
- for (const child of plan.children) {
1090
- const result = checkPlan(child, value, branchFlags, opts);
1091
- if (result !== FAIL) return unionMatchResult(result, child.def, plan.metadata, value);
1092
- }
1093
- return FAIL;
1094
- }
1980
+ case OP_UNION: return checkPlanUnion(plan, value, flags, opts);
1095
1981
  case OP_BOOLEAN:
1096
1982
  if (typeof value !== "boolean") return FAIL;
1097
1983
  if (plan.metaStamp !== stamp) refreshMeta(plan);
@@ -1113,16 +1999,13 @@ function setMetaKeys(plan, k0, k1, k2, k3, k4) {
1113
1999
  if (!pattern) continue;
1114
2000
  let entry = plan.regexes[i];
1115
2001
  if (entry === void 0 || entry.pattern !== pattern || entry.flags !== flags) {
1116
- const re = getRegex(pattern, flags);
1117
2002
  entry = {
1118
2003
  pattern,
1119
2004
  flags,
1120
- re,
1121
- stateful: re.global || re.sticky
2005
+ re: getRegex(pattern, flags)
1122
2006
  };
1123
2007
  plan.regexes[i] = entry;
1124
2008
  }
1125
- if (entry.stateful) return BAIL;
1126
2009
  if (!entry.re.test(value)) return FAIL;
1127
2010
  }
1128
2011
  }
@@ -1181,7 +2064,9 @@ function setMetaKeys(plan, k0, k1, k2, k3, k4) {
1181
2064
  const byKey = plan.byKey;
1182
2065
  for (const key of Object.keys(value)) {
1183
2066
  const known = byKey.get(key);
1184
- if (known === void 0 || known.op === OP_PHANTOM) return unknownProps === "error" ? FAIL : BAIL;
2067
+ if (known !== void 0 && known.op !== OP_PHANTOM) continue;
2068
+ if (unknownProps === "error") return FAIL;
2069
+ pendingStrips.push(value, key);
1185
2070
  }
1186
2071
  }
1187
2072
  return PASS;
@@ -1261,6 +2146,16 @@ function _define_property(obj, key, value) {
1261
2146
  if (details?.length) error.details = details;
1262
2147
  errors.push(error);
1263
2148
  if (errors.length >= this.opts.errorLimit) this.limitExceeded = true;
2149
+ return error;
2150
+ }
2151
+ /** Adds `error`, already made, to the errors of the current level (as {@link error} does). */ report(error) {
2152
+ let errors = this.stackErrors[this.stackErrors.length - 1];
2153
+ if (!errors) if (this.stackErrors.length > 0) {
2154
+ errors = [];
2155
+ this.stackErrors[this.stackErrors.length - 1] = errors;
2156
+ } else errors = this.errors;
2157
+ errors.push(error);
2158
+ if (errors.length >= this.opts.errorLimit) this.limitExceeded = true;
1264
2159
  }
1265
2160
  throw() {
1266
2161
  throw new ValidatorError(this.errors);
@@ -1282,8 +2177,13 @@ function _define_property(obj, key, value) {
1282
2177
  this.limitExceeded = false;
1283
2178
  if (this.shortcuts && !this.opts.skipList && typeof this.opts.partial !== "function" && fastCheckPasses(this.def, value, this.opts)) return true;
1284
2179
  this.context = context;
2180
+ this.unionDepth = 0;
2181
+ this.unionMemo = void 0;
2182
+ if (this.strips.length > 0) this.strips.length = 0;
1285
2183
  const passed = this.validateSafe(this.def, value);
1286
2184
  this.context = void 0;
2185
+ if (this.unionMemo !== void 0) this.unionMemo = void 0;
2186
+ if (this.strips.length > 0) performStrips(this.strips, passed);
1287
2187
  if (!passed) {
1288
2188
  if (safe) return false;
1289
2189
  this.throw();
@@ -1298,16 +2198,26 @@ function _define_property(obj, key, value) {
1298
2198
  */ get shortcuts() {
1299
2199
  return this.constructor === Validator && !this.hasPlugins && !this.hasReplace;
1300
2200
  }
1301
- validateSafe(def, value) {
2201
+ /** Validates `value` against `def` (after `replace`, `optional` and the plugins). */ validateSafe(def, value) {
1302
2202
  if (this.limitExceeded) return false;
1303
- if (this.hasReplace) {
1304
- let replaced = this.replaceCache.get(def);
1305
- if (replaced === void 0) {
1306
- replaced = this.opts.replace(def, this.buildPath());
1307
- this.replaceCache.set(def, replaced);
2203
+ if (this.hasReplace) def = this.replaced(def);
2204
+ if (def.optional && (value === void 0 || value === null)) {
2205
+ if (value === null && rejectsNullAsRequired(def)) {
2206
+ this.error(requiredMessage(def));
2207
+ return false;
1308
2208
  }
1309
- def = replaced;
2209
+ return true;
2210
+ }
2211
+ if (this.hasPlugins) {
2212
+ const decided = this.preCheck(def, value);
2213
+ if (decided !== void 0) return decided;
1310
2214
  }
2215
+ return this.validateAnnotatedType(def, value);
2216
+ }
2217
+ /**
2218
+ * What {@link validateSafe} decides of `def` (replaced) before its own validation: an
2219
+ * optional `def` passes `undefined` / `null`, a plugin may decide — `undefined` to go on.
2220
+ */ preCheck(def, value) {
1311
2221
  if (def.optional && (value === void 0 || value === null)) {
1312
2222
  if (value === null && rejectsNullAsRequired(def)) {
1313
2223
  this.error(requiredMessage(def));
@@ -1315,11 +2225,55 @@ function _define_property(obj, key, value) {
1315
2225
  }
1316
2226
  return true;
1317
2227
  }
1318
- if (this.hasPlugins) for (const plugin of this.opts.plugins) {
1319
- const result = plugin(this, def, value);
1320
- if (result === false || result === true) return result;
2228
+ if (this.hasPlugins) {
2229
+ const ctx = this.pluginCtx ?? (this.pluginCtx = this.pluginContext());
2230
+ for (const plugin of this.opts.plugins) {
2231
+ const result = plugin(ctx, def, value);
2232
+ if (result === false || result === true) return result;
2233
+ }
1321
2234
  }
1322
- return this.validateAnnotatedType(def, value);
2235
+ }
2236
+ /**
2237
+ * The plugins' view of this validator: its state read live; `validateAnnotatedType` drops the
2238
+ * strips a failed call recorded (a failed validation at any level strips nothing).
2239
+ */ pluginContext() {
2240
+ return Object.defineProperties({
2241
+ validateAnnotatedType: (def, value) => {
2242
+ const kept = this.strips.length;
2243
+ const passed = this.validateAnnotatedType(def, value);
2244
+ if (!passed && this.strips.length !== kept) this.strips.length = kept;
2245
+ return passed;
2246
+ },
2247
+ error: (message, path, details) => this.error(message, path, details)
2248
+ }, {
2249
+ opts: {
2250
+ get: () => this.opts,
2251
+ enumerable: true
2252
+ },
2253
+ path: {
2254
+ get: () => this.path,
2255
+ enumerable: true
2256
+ },
2257
+ root: {
2258
+ get: () => this.root,
2259
+ enumerable: true
2260
+ },
2261
+ context: {
2262
+ get: () => this.context,
2263
+ set: (context) => {
2264
+ this.context = context;
2265
+ },
2266
+ enumerable: true
2267
+ }
2268
+ });
2269
+ }
2270
+ /** `def` as the `replace` option replaces it at the current path (memoized per node). */ replaced(def) {
2271
+ let replaced = this.replaceCache.get(def);
2272
+ if (replaced === void 0) {
2273
+ replaced = this.opts.replace(def, this.buildPath());
2274
+ this.replaceCache.set(def, replaced);
2275
+ }
2276
+ return replaced;
1323
2277
  }
1324
2278
  get path() {
1325
2279
  return this.buildPath();
@@ -1347,29 +2301,84 @@ function _define_property(obj, key, value) {
1347
2301
  if (item.optional || type.kind !== "" || type.value === void 0 || type.designType === "phantom") break;
1348
2302
  if (type.value === value) return true;
1349
2303
  }
2304
+ let nested = false;
2305
+ let path;
2306
+ if (this.unionDepth > 0) {
2307
+ if (typeof value === "object" && value !== null) {
2308
+ if (this.unionMemo !== void 0) {
2309
+ path = this.buildPath();
2310
+ const known = this.decided(def, value, path);
2311
+ if (known !== void 0) {
2312
+ if (known.error === void 0) {
2313
+ stripAgain(this.strips, known.strips);
2314
+ return this.validateUnionConstraints(def, known.item, value);
2315
+ }
2316
+ this.report(known.error);
2317
+ return false;
2318
+ }
2319
+ }
2320
+ nested = true;
2321
+ }
2322
+ } else this.wasted = 0;
2323
+ const kept = this.strips.length;
1350
2324
  let details;
1351
2325
  for (const item of items) {
1352
2326
  this.stackErrors.push(null);
1353
- if (this.validateSafe(item, value)) {
2327
+ const failures = this.nestedFailures;
2328
+ this.unionDepth++;
2329
+ const passed = this.validateSafe(item, value);
2330
+ this.unionDepth--;
2331
+ if (passed) {
1354
2332
  this.stackErrors.pop();
2333
+ if (path !== void 0) this.decide(def, value, path, kept, item, void 0);
1355
2334
  return this.validateUnionConstraints(def, item, value);
1356
2335
  }
2336
+ if (this.strips.length !== kept) this.strips.length = kept;
1357
2337
  const branchErrors = this.stackErrors.pop();
1358
2338
  if (this.limitExceeded) this.limitExceeded = false;
2339
+ if (this.nestedFailures !== failures) this.wasteBranch();
2340
+ if (nested) this.nestedFailures++;
1359
2341
  if (branchErrors) if (details) for (const err of branchErrors) details.push(err);
1360
2342
  else details = branchErrors;
1361
2343
  }
1362
2344
  const expected = items.map((item, i) => `[${item.type.kind || item.type.designType}(${i})]`).join(", ");
1363
- this.error(`Value does not match any of the allowed types: ${expected}`, void 0, details);
2345
+ const error = this.error(`Value does not match any of the allowed types: ${expected}`, void 0, details);
2346
+ if (path !== void 0) this.decide(def, value, path, kept, void 0, error);
1364
2347
  return false;
1365
2348
  }
2349
+ /** A union branch failed after branches of nested unions over objects did (see `unionMemo`). */ wasteBranch() {
2350
+ if (++this.wasted === WASTE_BEFORE_MEMO && this.unionMemo === void 0) this.unionMemo = /* @__PURE__ */ new Map();
2351
+ }
2352
+ /** The outcome this call recorded for union `def` over `value` at `path` (see `unionMemo`). */ decided(def, value, path) {
2353
+ const outcomes = this.unionMemo.get(value);
2354
+ if (outcomes !== void 0) {
2355
+ const { unknownProps } = this.opts;
2356
+ for (const outcome of outcomes) if (outcome.def === def && outcome.path === path && outcome.unknownProps === unknownProps) return outcome;
2357
+ }
2358
+ }
2359
+ /**
2360
+ * Records the outcome of union `def` over `value` at `path`, entered with `kept` strips (the
2361
+ * ones after them are its own).
2362
+ */ decide(def, value, path, kept, item, error) {
2363
+ const outcome = {
2364
+ def,
2365
+ path,
2366
+ unknownProps: this.opts.unknownProps,
2367
+ item,
2368
+ error,
2369
+ strips: stripsSince(this.strips, kept)
2370
+ };
2371
+ const outcomes = this.unionMemo.get(value);
2372
+ if (outcomes === void 0) this.unionMemo.set(value, [outcome]);
2373
+ else outcomes.push(outcome);
2374
+ }
1366
2375
  /**
1367
2376
  * Constraints annotated on the union itself (`@expect.min 0` on `number | null`)
1368
2377
  * apply to the non-null value that matched `branch`, on top of the branch's own.
1369
2378
  * A literal branch (an enum value) is exempt: its value is fixed.
1370
2379
  */ validateUnionConstraints(def, branch, value) {
1371
2380
  const metadata = def.metadata;
1372
- if (metadata.size === 0 || branch.type.value !== void 0) return true;
2381
+ if (metaEmpty(metadata) || branch.type.value !== void 0) return true;
1373
2382
  switch (typeof value) {
1374
2383
  case "string": return this.validateStringConstraints(metadata, value);
1375
2384
  case "number": return this.validateNumberConstraints(metadata, value);
@@ -1380,10 +2389,28 @@ function _define_property(obj, key, value) {
1380
2389
  default: return true;
1381
2390
  }
1382
2391
  }
1383
- validateIntersection(def, value) {
2392
+ /** Every member must pass, each on its own (JSON Schema `allOf`). */ validateIntersection(def, value) {
1384
2393
  for (const item of def.type.items) if (!this.validateSafe(item, value)) return false;
1385
2394
  return true;
1386
2395
  }
2396
+ /**
2397
+ * An unknown key (`unknownProps`): 'error' reports it, 'strip' adds it to the keys to strip
2398
+ * (returned; recorded in `strips` once the object passed).
2399
+ */ unknownKey(key, keysToStrip) {
2400
+ if (this.opts.unknownProps === "error") {
2401
+ this.push(key);
2402
+ this.error(`Unexpected property`);
2403
+ this.pop(true);
2404
+ } else if (this.opts.unknownProps === "strip") (keysToStrip ?? (keysToStrip = [])).push(key);
2405
+ return keysToStrip;
2406
+ }
2407
+ /** The `skipList` keys of the object at the current path. */ skipListHere() {
2408
+ if (!this.opts.skipList) return;
2409
+ let skipList;
2410
+ const path = this.depth > 0 ? `${this.buildPath()}.` : "";
2411
+ for (const item of this.opts.skipList) if (item.startsWith(path)) (skipList ?? (skipList = /* @__PURE__ */ new Set())).add(item.slice(path.length));
2412
+ return skipList;
2413
+ }
1387
2414
  validateTuple(def, value) {
1388
2415
  if (!Array.isArray(value) || value.length !== def.type.items.length) {
1389
2416
  this.error(`Expected array of length ${def.type.items.length}`);
@@ -1406,7 +2433,7 @@ function _define_property(obj, key, value) {
1406
2433
  this.error("Expected array");
1407
2434
  return false;
1408
2435
  }
1409
- if (def.metadata.size > 0 && !this.validateArrayConstraints(def.metadata, value, def.type.of)) return false;
2436
+ if (!metaEmpty(def.metadata) && !this.validateArrayConstraints(def.metadata, value, def.type.of)) return false;
1410
2437
  let i = 0;
1411
2438
  let passed = true;
1412
2439
  for (const item of value) {
@@ -1420,7 +2447,8 @@ function _define_property(obj, key, value) {
1420
2447
  }
1421
2448
  return passed;
1422
2449
  }
1423
- /** `@expect.minLength` / `maxLength` / `array.uniqueItems` checks for an array value. */ validateArrayConstraints(metadata, value, of) {
2450
+ /** `@expect.minLength` / `maxLength` / `array.uniqueItems` checks for an array value. */ validateArrayConstraints(meta, value, of) {
2451
+ const metadata = readable(meta);
1424
2452
  const minLength = metadata.get("expect.minLength");
1425
2453
  if (minLength !== void 0) {
1426
2454
  const length = typeof minLength === "number" ? minLength : minLength.length;
@@ -1443,14 +2471,11 @@ function _define_property(obj, key, value) {
1443
2471
  if (uniqueItems) {
1444
2472
  const separator = "▼↩";
1445
2473
  const seen = /* @__PURE__ */ new Set();
1446
- const keyProps = /* @__PURE__ */ new Set();
1447
- if (of?.type.kind === "object") {
1448
- for (const [key, val] of of.type.props.entries()) if (val.metadata.get("expect.array.key")) keyProps.add(key);
1449
- }
2474
+ const keyProps = arrayKeyProps(of);
1450
2475
  for (let idx = 0; idx < value.length; idx++) {
1451
2476
  const item = value[idx];
1452
2477
  let key;
1453
- if (keyProps.size > 0) {
2478
+ if (keyProps.length > 0) {
1454
2479
  key = "";
1455
2480
  for (const prop of keyProps) key += JSON.stringify(item[prop]) + separator;
1456
2481
  } else key = JSON.stringify(item);
@@ -1472,15 +2497,7 @@ function _define_property(obj, key, value) {
1472
2497
  }
1473
2498
  let passed = true;
1474
2499
  let keysToStrip;
1475
- let skipList;
1476
- if (this.opts.skipList) {
1477
- const path = this.depth > 0 ? `${this.buildPath()}.` : "";
1478
- for (const item of this.opts.skipList) if (item.startsWith(path)) {
1479
- const key = item.slice(path.length);
1480
- if (!skipList) skipList = /* @__PURE__ */ new Set();
1481
- skipList.add(key);
1482
- }
1483
- }
2500
+ const skipList = this.opts.skipList ? this.skipListHere() : void 0;
1484
2501
  let partialFunctionMatched = false;
1485
2502
  if (typeof this.opts.partial === "function") partialFunctionMatched = this.opts.partial(def, this.buildPath());
1486
2503
  for (const [key, item] of def.type.props.entries()) {
@@ -1511,11 +2528,13 @@ function _define_property(obj, key, value) {
1511
2528
  if (matched.length > 0) {
1512
2529
  this.push(key);
1513
2530
  let keyPassed = false;
2531
+ const kept = this.strips.length;
1514
2532
  for (const { def: propDef } of matched) {
1515
2533
  if (this.validateSafe(propDef, value[key])) {
1516
2534
  keyPassed = true;
1517
2535
  break;
1518
2536
  }
2537
+ if (this.strips.length !== kept) this.strips.length = kept;
1519
2538
  this.clear();
1520
2539
  }
1521
2540
  if (!keyPassed) {
@@ -1524,19 +2543,16 @@ function _define_property(obj, key, value) {
1524
2543
  passed = false;
1525
2544
  if (this.limitExceeded) return false;
1526
2545
  } else this.pop(false);
1527
- } else if (this.opts.unknownProps === "error") {
1528
- this.push(key);
1529
- this.error(`Unexpected property`);
1530
- this.pop(true);
1531
- if (this.limitExceeded) return false;
1532
- passed = false;
1533
- } else if (this.opts.unknownProps === "strip") {
1534
- if (!keysToStrip) keysToStrip = [];
1535
- keysToStrip.push(key);
2546
+ } else {
2547
+ keysToStrip = this.unknownKey(key, keysToStrip);
2548
+ if (this.opts.unknownProps === "error") {
2549
+ if (this.limitExceeded) return false;
2550
+ passed = false;
2551
+ }
1536
2552
  }
1537
2553
  }
1538
2554
  }
1539
- if (passed && keysToStrip) for (const key of keysToStrip) delete value[key];
2555
+ if (passed && keysToStrip !== void 0) for (const key of keysToStrip) this.strips.push(value, key);
1540
2556
  return passed;
1541
2557
  }
1542
2558
  validatePrimitive(def, value) {
@@ -1603,8 +2619,9 @@ function _define_property(obj, key, value) {
1603
2619
  validateString(def, value) {
1604
2620
  return this.validateStringConstraints(def.metadata, value);
1605
2621
  }
1606
- /** `@meta.required` / `@expect.minLength` / `maxLength` / `pattern` checks for a string value. */ validateStringConstraints(metadata, value) {
1607
- if (metadata.size === 0) return true;
2622
+ /** `@meta.required` / `@expect.minLength` / `maxLength` / `pattern` checks for a string value. */ validateStringConstraints(meta, value) {
2623
+ const metadata = filledMeta(meta);
2624
+ if (metadata === void 0) return true;
1608
2625
  const filled = metadata.get("meta.required");
1609
2626
  if (filled) {
1610
2627
  if (value.trim().length === 0) {
@@ -1644,8 +2661,9 @@ function _define_property(obj, key, value) {
1644
2661
  validateNumber(def, value) {
1645
2662
  return this.validateNumberConstraints(def.metadata, value);
1646
2663
  }
1647
- /** `@expect.int` / `min` / `max` / `exclusiveMin` / `exclusiveMax` checks for a number value. */ validateNumberConstraints(metadata, value) {
1648
- if (metadata.size === 0) return true;
2664
+ /** `@expect.int` / `min` / `max` / `exclusiveMin` / `exclusiveMax` checks for a number value. */ validateNumberConstraints(meta, value) {
2665
+ const metadata = filledMeta(meta);
2666
+ if (metadata === void 0) return true;
1649
2667
  const int = metadata.get("expect.int");
1650
2668
  if (int && value % 1 !== 0) {
1651
2669
  const message = typeof int === "object" && int.message ? int.message : `Expected integer, got ${value}`;
@@ -1682,8 +2700,9 @@ function _define_property(obj, key, value) {
1682
2700
  validateBoolean(def, value) {
1683
2701
  return this.validateBooleanConstraints(def.metadata, value);
1684
2702
  }
1685
- /** `@meta.required` check for a boolean value (must be `true`). */ validateBooleanConstraints(metadata, value) {
1686
- if (metadata.size === 0) return true;
2703
+ /** `@meta.required` check for a boolean value (must be `true`). */ validateBooleanConstraints(meta, value) {
2704
+ const metadata = filledMeta(meta);
2705
+ if (metadata === void 0) return true;
1687
2706
  const filled = metadata.get("meta.required");
1688
2707
  if (filled) {
1689
2708
  if (value !== true) {
@@ -1706,12 +2725,36 @@ function _define_property(obj, key, value) {
1706
2725
  _define_property(this, "depth", void 0);
1707
2726
  _define_property(this, "limitExceeded", void 0);
1708
2727
  _define_property(this, "context", void 0);
2728
+ /**
2729
+ * The unions over objects this call decided inside union branches (value → outcomes). A union
2730
+ * nested in its own branches, many branches each, is reached again with the same value and path
2731
+ * from every branch of every union above it — (branches)^(depth) work. The memo is made once
2732
+ * the call has wasted {@link WASTE_BEFORE_MEMO} union branches (failed after branches of nested
2733
+ * unions over objects failed) since the outermost union, as in the pre-check — ordinary walks
2734
+ * never make it. It decides each such union once, with the same result and the same error object
2735
+ * (both depend only on these, the options and the input, which the walk never changes), and
2736
+ * records the same strips again.
2737
+ */ _define_property(this, "unionMemo", void 0);
2738
+ /** Union branches being checked (`> 0`: inside a union branch). */ _define_property(this, "unionDepth", void 0);
2739
+ /** Failed branches of unions over objects inside union branches (see `unionMemo`). */ _define_property(this, "nestedFailures", void 0);
2740
+ /** Wasted union branches since the outermost union was entered (see `unionMemo`). */ _define_property(this, "wasted", void 0);
2741
+ /**
2742
+ * `unknownProps: 'strip'`: the unknown keys of the objects that passed (`object, key, …`), in the
2743
+ * order the objects completed, then in key order. A rejected union branch, pattern property
2744
+ * attempt or plugin sub-validation drops what it recorded; the keys are deleted once the whole
2745
+ * call passes (`performStrips`).
2746
+ */ _define_property(this, "strips", void 0);
2747
+ /** The context the plugins get (see {@link pluginContext}), made on the first plugin call. */ _define_property(this, "pluginCtx", void 0);
1709
2748
  this.def = def;
1710
2749
  this.errors = [];
1711
2750
  this.stackErrors = [];
1712
2751
  this.pathSegments = [];
1713
2752
  this.depth = 0;
1714
2753
  this.limitExceeded = false;
2754
+ this.unionDepth = 0;
2755
+ this.nestedFailures = 0;
2756
+ this.wasted = 0;
2757
+ this.strips = [];
1715
2758
  this.opts = {
1716
2759
  partial: false,
1717
2760
  unknownProps: "error",
@@ -1776,12 +2819,12 @@ const NON_PRIMITIVE_KINDS = new Set(["array", "object"]);
1776
2819
  */ function createAnnotatedTypeNode(type, metadata = new AnnotationMap(), opts) {
1777
2820
  return {
1778
2821
  __is_atscript_annotated_type: true,
1779
- type,
1780
2822
  metadata,
2823
+ type,
1781
2824
  validator: validatorMethod,
2825
+ ref: opts?.ref,
1782
2826
  id: opts?.id,
1783
- optional: opts?.optional,
1784
- ref: opts?.ref
2827
+ optional: opts?.optional
1785
2828
  };
1786
2829
  }
1787
2830
  /** A new tracked metadata map holding `entries` (see {@link createAnnotatedTypeNode}). */ function createMetadataMap(entries) {
@@ -1812,61 +2855,23 @@ const NON_PRIMITIVE_KINDS = new Set(["array", "object"]);
1812
2855
  /**
1813
2856
  * Standalone annotate function that handles both replace and append (array) strategies.
1814
2857
  * Used by the handle's .annotate() method and by generated mutation statements.
2858
+ *
2859
+ * A layered map (a reference, an override, a merged field: see `layers.ts`) appends after the
2860
+ * values its bases give.
1815
2861
  */ function annotate(metadata, key, value, asArray) {
1816
2862
  if (!metadata) return;
1817
- if (asArray) if (metadata.has(key)) {
1818
- const a = metadata.get(key);
1819
- if (Array.isArray(a)) {
1820
- a.push(value);
1821
- if (isValidatorKey(key)) touched(metadata);
1822
- } else metadata.set(key, [a, value]);
1823
- } else metadata.set(key, [value]);
2863
+ if (asArray && metadata instanceof LayerMap) {
2864
+ annotateLayer(metadata, key, value);
2865
+ return;
2866
+ }
2867
+ if (asArray) if (metadata.has(key)) appendOwn(metadata, key, metadata.get(key), value);
2868
+ else metadata.set(key, [value]);
1824
2869
  else metadata.set(key, value);
1825
2870
  }
1826
- /**
1827
- * Clones a property's type tree in-place so mutations don't leak to shared refs.
1828
- * Used by mutating annotate codegen when paths cross ref boundaries.
1829
- */ function cloneRefProp(parentType, propName) {
1830
- if (parentType.kind !== "object") return;
1831
- const objType = parentType;
1832
- const existing = objType.props.get(propName);
1833
- if (!existing) return;
1834
- objType.props.set(propName, cloneNode(existing, cloneTypeDef(existing.type)));
1835
- }
1836
- /** A copy of `node` (own metadata map) over `type`. */ function cloneNode(node, type) {
1837
- return createAnnotatedTypeNode(type, createMetadataMap(node.metadata), {
1838
- id: node.id,
1839
- optional: node.optional,
1840
- ref: node.ref
1841
- });
1842
- }
1843
- function cloneTypeDef(type) {
1844
- if (type.kind === "object") {
1845
- const obj = type;
1846
- const clone = createObjectTypeDef(new Set(obj.tags), [...obj.propsPatterns]);
1847
- for (const [k, v] of obj.props) clone.props.set(k, cloneNode(v, v.type));
1848
- return clone;
1849
- }
1850
- if (type.kind === "array") {
1851
- const arr = type;
1852
- return {
1853
- kind: "array",
1854
- of: arr.of,
1855
- tags: new Set(arr.tags)
1856
- };
1857
- }
1858
- if (type.kind === "union" || type.kind === "intersection" || type.kind === "tuple") {
1859
- const complex = type;
1860
- return {
1861
- kind: type.kind,
1862
- items: [...complex.items],
1863
- tags: new Set(complex.tags)
1864
- };
1865
- }
1866
- return {
1867
- ...type,
1868
- tags: new Set(type.tags)
1869
- };
2871
+ /** The node at prop path `chain` below `type` (through objects), `undefined` when none. */ function propAtChain(type, chain) {
2872
+ let node = type;
2873
+ for (const key of chain) node = node?.type?.kind === "object" ? node.type.props.get(key) : void 0;
2874
+ return node;
1870
2875
  }
1871
2876
  /**
1872
2877
  * Creates a builder handle for constructing a {@link TAtscriptAnnotatedType} at runtime.
@@ -1888,24 +2893,23 @@ function cloneTypeDef(type) {
1888
2893
  * @returns A builder handle for fluent type construction.
1889
2894
  */ function defineAnnotatedType(_kind, base) {
1890
2895
  const kind = _kind || "";
1891
- const baseProvided = base !== void 0;
1892
2896
  const type = base?.type || {};
1893
2897
  touched(type);
1894
2898
  type.kind = kind;
2899
+ type.tags = /* @__PURE__ */ new Set();
1895
2900
  if (COMPLEX_KINDS.has(kind)) type.items = [];
1896
2901
  if (kind === "object") {
1897
2902
  type.props = new PropsMap();
1898
2903
  type.propsPatterns = [];
1899
2904
  }
1900
- type.tags = /* @__PURE__ */ new Set();
1901
2905
  const metadata = baseMetadata(base?.metadata);
1902
- const payload = {
2906
+ if (base && base.metadata !== metadata) metadataReplaced();
2907
+ base = base ? Object.assign(base, {
1903
2908
  __is_atscript_annotated_type: true,
1904
2909
  metadata,
1905
2910
  type,
1906
2911
  validator: validatorMethod
1907
- };
1908
- base = base ? Object.assign(base, payload) : payload;
2912
+ }) : createAnnotatedTypeNode(type, metadata);
1909
2913
  return {
1910
2914
  $type: base,
1911
2915
  $def: type,
@@ -1940,7 +2944,7 @@ function cloneTypeDef(type) {
1940
2944
  },
1941
2945
  propPattern(pattern, def) {
1942
2946
  this.$def.propsPatterns.push({
1943
- pattern,
2947
+ pattern: statelessRegExp(pattern),
1944
2948
  def
1945
2949
  });
1946
2950
  touched(this.$def);
@@ -1955,67 +2959,44 @@ function cloneTypeDef(type) {
1955
2959
  for (const [key, value] of fromMetadata.entries()) if (!ignore || !ignore.has(key)) this.$metadata.set(key, value);
1956
2960
  return this;
1957
2961
  },
1958
- refTo(type, chain) {
2962
+ ref(target, chain) {
2963
+ var _node;
2964
+ const at = $ft(target, ...chain ?? []);
1959
2965
  const node = this.$type;
1960
2966
  touched(node);
1961
- const field = chain ? chain.join(".") : "";
1962
- if (isAnnotatedType(type)) {
1963
- let newBase = type;
1964
- const typeName = type.name || "Unknown";
1965
- if (chain) for (let i = 0; i < chain.length; i++) {
1966
- const c = chain[i];
1967
- if (newBase.type.kind === "object" && newBase.type.props.has(c)) newBase = newBase.type.props.get(c);
1968
- else {
1969
- const keys = chain.slice(0, i + 1).map((k) => `["${k}"]`).join("");
1970
- throw new Error(`Can't find prop ${typeName}${keys}`);
1971
- }
1972
- }
1973
- node.type = baseProvided ? cloneTypeDef(newBase.type) : newBase.type;
1974
- node.id = node.id ?? newBase.id;
1975
- node.ref = {
1976
- type: () => type,
1977
- field
1978
- };
1979
- } else if (typeof type === "function") {
1980
- const lazyType = type;
1981
- const ownId = node.id;
1982
- node.ref = {
1983
- type: lazyType,
1984
- field
1985
- };
1986
- const placeholder = node.type;
1987
- Object.defineProperty(node, "type", {
1988
- get() {
1989
- const t = lazyType();
1990
- if (!isAnnotatedType(t)) {
1991
- Object.defineProperty(node, "type", {
1992
- value: placeholder,
1993
- writable: false,
1994
- configurable: true
1995
- });
1996
- return placeholder;
1997
- }
1998
- let target = t;
1999
- if (chain) for (const c of chain) if (target.type.kind === "object" && target.type.props.has(c)) target = target.type.props.get(c);
2000
- else return t.type;
2001
- node.id = ownId ?? target.id;
2002
- const resolved = baseProvided ? cloneTypeDef(target.type) : target.type;
2003
- Object.defineProperty(node, "type", {
2004
- value: resolved,
2005
- writable: false,
2006
- configurable: true
2007
- });
2008
- return resolved;
2009
- },
2010
- configurable: true
2011
- });
2012
- } else throw new TypeError(`${type} is not annotated type`);
2967
+ node.type = at.type;
2968
+ node.ref = {
2969
+ type: () => target,
2970
+ field: chain ? fieldOf(chain) : ""
2971
+ };
2972
+ (_node = node).id ?? (_node.id = at.id);
2973
+ return this.over([at], true);
2974
+ },
2975
+ over(bases, reference) {
2976
+ for (const b of bases) readyNode(b);
2977
+ const node = this.$type;
2978
+ touched(node);
2979
+ const metadata = new LayerMap(bases, reference, ownEntries(this.$metadata));
2980
+ moveIntrinsic(this.$metadata, metadata);
2981
+ node.metadata = metadata;
2982
+ this.$metadata = metadata;
2983
+ metadataReplaced();
2984
+ return this;
2985
+ },
2986
+ type(of) {
2987
+ const node = this.$type;
2988
+ touched(node);
2989
+ node.type = readyNode(of).type;
2013
2990
  return this;
2014
2991
  },
2015
2992
  annotate(key, value, asArray) {
2016
2993
  annotate(this.$metadata, key, value, asArray);
2017
2994
  return this;
2018
2995
  },
2996
+ intrinsic(...keys) {
2997
+ markIntrinsic(this.$metadata, keys);
2998
+ return this;
2999
+ },
2019
3000
  id(value) {
2020
3001
  this.$type.id = value;
2021
3002
  return this;
@@ -2046,417 +3027,425 @@ function cloneTypeDef(type) {
2046
3027
  }
2047
3028
 
2048
3029
  //#endregion
2049
- //#region packages/typescript/src/runtime/traverse.ts
3030
+ //#region packages/typescript/src/runtime/cut.ts
3031
+ var _globalThis, _Symbol_for;
2050
3032
  /**
2051
- * Type-safe dispatch over `TAtscriptAnnotatedType` by its `type.kind`.
2052
- *
2053
- * Provides the common `switch (def.type.kind)` pattern used by
2054
- * the validator, JSON-schema builder, and serializer.
2055
- * Each caller supplies its own handlers that control recursion.
2056
- *
2057
- * When a `phantom` handler is provided, phantom types (`designType === 'phantom'`)
2058
- * are dispatched to it instead of `final`. This allows consumers to skip or
2059
- * handle phantom props without polluting their `final` handler.
2060
- */ function forAnnotatedType(def, handlers) {
2061
- switch (def.type.kind) {
2062
- case "": {
2063
- const typed = def;
2064
- if (handlers.phantom && typed.type.designType === "phantom") return handlers.phantom(typed);
2065
- return handlers.final(typed);
2066
- }
2067
- case "object": return handlers.object(def);
2068
- case "array": return handlers.array(def);
2069
- case "union": return handlers.union(def);
2070
- case "intersection": return handlers.intersection(def);
2071
- case "tuple": return handlers.tuple(def);
2072
- default: throw new Error(`Unknown type kind "${def.type.kind}"`);
2073
- }
3033
+ * Defs standing for another one to the cut (a shell's def → the def it shells; a deserialized
3034
+ * def → its payload tag's token). Shared by every copy of the runtime (types built by one, read
3035
+ * by another).
3036
+ */ const origins = (_globalThis = globalThis)[_Symbol_for = Symbol.for("@atscript/typescript:cut-origins:1")] ?? (_globalThis[_Symbol_for] = /* @__PURE__ */ new WeakMap());
3037
+ /** Def `copy` stands for def `of` to the cut (for what `of` stands for). */ function cutAs(copy, of) {
3038
+ origins.set(copy, typeof of === "object" && of !== null && origins.get(of) || of);
3039
+ }
3040
+ /** The cut key of `node` (see above). */ function cutKey(node) {
3041
+ const def = node.type;
3042
+ return node.id ?? origins.get(def) ?? def;
3043
+ }
3044
+ /** Whether `key` is expanded on `path`. */ function onPath(path, key) {
3045
+ for (let p = path; p; p = p.up) if (p.key === key) return true;
3046
+ return false;
3047
+ }
3048
+ /** The path below `node` reached on `path`; `false` where `node` is cut. */ function enterCut(path, node) {
3049
+ if (node.type.kind === "") return path;
3050
+ const key = cutKey(node);
3051
+ return onPath(path, key) ? false : {
3052
+ key,
3053
+ up: path
3054
+ };
2074
3055
  }
2075
3056
 
2076
3057
  //#endregion
2077
- //#region packages/typescript/src/runtime/json-schema.ts
3058
+ //#region packages/typescript/src/runtime/blocks.ts
2078
3059
  /**
2079
- * Detects a discriminator property across union items.
2080
- *
2081
- * Scans all items for object-typed members that share a common property
2082
- * with distinct const/literal values. If exactly one such property exists,
2083
- * it is returned as the discriminator. Returns `null` when no qualifying
2084
- * property exists, or when more than one does (ambiguous).
2085
- */ function detectDiscriminator(items) {
2086
- if (items.length < 2) return null;
2087
- for (const item of items) if (item.type.kind !== "object") return null;
2088
- const firstObj = items[0].type;
2089
- const candidates = [];
2090
- for (const [propName, propType] of firstObj.props.entries()) if (propType.type.kind === "" && propType.type.value !== void 0) candidates.push(propName);
2091
- let result = null;
2092
- for (const candidate of candidates) {
2093
- const values = /* @__PURE__ */ new Set();
2094
- const indexMapping = {};
2095
- let valid = true;
2096
- for (let i = 0; i < items.length; i++) {
2097
- const prop = items[i].type.props.get(candidate);
2098
- if (!prop || prop.type.kind !== "" || prop.type.value === void 0) {
2099
- valid = false;
2100
- break;
2101
- }
2102
- const val = prop.type.value;
2103
- if (values.has(val)) {
2104
- valid = false;
2105
- break;
2106
- }
2107
- values.add(val);
2108
- indexMapping[String(val)] = i;
2109
- }
2110
- if (valid) {
2111
- if (result) return null;
2112
- result = {
2113
- propertyName: candidate,
2114
- indexMapping
2115
- };
2116
- }
2117
- }
2118
- return result;
3060
+ * The runtime helpers of the generated structure: node lookup (`$f`),
3061
+ * annotated aliases and `as` copies (`$alias`), shells (`$sh`), blocks with static ranks
3062
+ * (`$blk`) and the import-cycle queue (`$q` / `$end`). Merges are not computed here: the
3063
+ * generated code prints their final structure (hidden classes, `.over` layers).
3064
+ */
3065
+ /**
3066
+ * Thrown when a statement reads what is not built yet (a class of an import cycle's module still
3067
+ * evaluating, a CommonJS cycle's `undefined` import, a def without its props): `$q` queues it.
3068
+ */ const NOT_READY = /* @__PURE__ */ new Error("atscript: type not built yet");
3069
+ /**
3070
+ * `x` as an annotated type whose def can be read, else `NOT_READY`: a class of an import cycle's
3071
+ * module not evaluated yet (CommonJS: `undefined`), or an alias class (declared with
3072
+ * `type = null`) before its `$alias` ran.
3073
+ */ function readyNode(x) {
3074
+ if (!isAnnotatedType(x) || x.type === null || x.type === void 0) throw NOT_READY;
3075
+ return x;
3076
+ }
3077
+ /** `x` as a built class (its builder ran: its def has a kind), else `NOT_READY`. */ function builtNode(x) {
3078
+ const n = readyNode(x);
3079
+ if (n.type.kind === void 0) throw NOT_READY;
3080
+ return n;
3081
+ }
3082
+ /** The child of `n` at step `s`: a prop, `[]` (array element) or `|i` (union / tuple item i). */ function child(n, s) {
3083
+ const t = n.type;
3084
+ if (!t?.kind) return;
3085
+ if (s === "[]") return t.of;
3086
+ if (s[0] === "|") return t.items?.[Number(s.slice(1))];
3087
+ return t.props?.get(s) ?? t.propsPatterns?.find((p) => patternStep(p.pattern) === s)?.def;
3088
+ }
3089
+ /** The step naming prop pattern `re` (`*` is `/./`). */ function patternStep(re) {
3090
+ return re.source === "." && re.flags === "" ? "*" : `/${re.source}/${re.flags}`;
3091
+ }
3092
+ /** A chain's `ref.field`: its props (`a.b`), without the union steps a nullable one takes. */ function fieldOf(chain) {
3093
+ return chain.filter((s) => s[0] !== "|").join(".");
2119
3094
  }
2120
3095
  /**
2121
- * Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
2122
- *
2123
- * Translates the atscript type structure and validation metadata
2124
- * (min/max, patterns, integer constraints, etc.) into a standard JSON Schema.
2125
- *
2126
- * @example
2127
- * ```ts
2128
- * import { buildJsonSchema } from '@atscript/typescript'
2129
- *
2130
- * const schema = buildJsonSchema(MyInterface)
2131
- * // { type: 'object', properties: { ... }, required: [...] }
2132
- * ```
2133
- *
2134
- * @param type - The annotated type to convert.
2135
- * @returns A JSON Schema object.
2136
- */ function buildJsonSchema(type) {
2137
- const defs = {};
2138
- let hasDefs = false;
2139
- const buildObject = (d) => {
2140
- const properties = {};
2141
- const required = [];
2142
- for (const [key, val] of d.type.props.entries()) {
2143
- if (isPhantomType(val)) continue;
2144
- properties[key] = build(val);
2145
- if (!val.optional) required.push(key);
2146
- }
2147
- const schema = {
2148
- type: "object",
2149
- properties
2150
- };
2151
- if (required.length > 0) schema.required = required;
2152
- return schema;
2153
- };
2154
- const build = (def) => {
2155
- if (def.id && def.type.kind === "object" && def !== type) {
2156
- const name = def.id;
2157
- if (!defs[name]) {
2158
- hasDefs = true;
2159
- defs[name] = {};
2160
- defs[name] = buildObject(def);
2161
- }
2162
- return { $ref: `#/$defs/${name}` };
2163
- }
2164
- const meta = def.metadata;
2165
- return forAnnotatedType(def, {
2166
- phantom() {
2167
- return {};
2168
- },
2169
- object(d) {
2170
- return buildObject(d);
2171
- },
2172
- array(d) {
2173
- const schema = {
2174
- type: "array",
2175
- items: build(d.type.of)
2176
- };
2177
- applyArrayConstraints(schema, meta);
2178
- return schema;
2179
- },
2180
- union(d) {
2181
- const disc = detectDiscriminator(d.type.items);
2182
- if (disc) {
2183
- const oneOf = d.type.items.map(build);
2184
- const mapping = {};
2185
- for (const [val, idx] of Object.entries(disc.indexMapping)) {
2186
- const item = d.type.items[idx];
2187
- mapping[val] = item.id && defs[item.id] ? `#/$defs/${item.id}` : `#/oneOf/${idx}`;
2188
- }
2189
- return {
2190
- oneOf,
2191
- discriminator: {
2192
- propertyName: disc.propertyName,
2193
- mapping
2194
- }
2195
- };
2196
- }
2197
- const anyOf = d.type.items.map(build);
2198
- if (meta.size > 0) applyUnionConstraints(anyOf, meta);
2199
- return { anyOf };
2200
- },
2201
- intersection(d) {
2202
- return { allOf: d.type.items.map(build) };
2203
- },
2204
- tuple(d) {
2205
- return {
2206
- type: "array",
2207
- items: d.type.items.map(build),
2208
- additionalItems: false
2209
- };
2210
- },
2211
- final(d) {
2212
- const schema = {};
2213
- if (d.type.value !== void 0) schema.const = d.type.value;
2214
- if (d.type.designType && d.type.designType !== "any") {
2215
- const dt = d.type.designType;
2216
- schema.type = dt === "undefined" ? "null" : dt === "decimal" ? "string" : dt;
2217
- }
2218
- applyScalarConstraints(schema, meta);
2219
- return schema;
2220
- }
2221
- });
3096
+ * The node at `path` below `root` (see {@link child}); `NOT_READY` while it is not built, or
3097
+ * while a pending shell (an import cycle's, see {@link $ps}) would replace it.
3098
+ */ function $f(root, ...path) {
3099
+ return nodeAt(root, path, PLAIN);
3100
+ }
3101
+ /** {@link $f} for a reader of the node's def (`.ref(T, chain)`, `$alias`): its final def. */ function $ft(root, ...path) {
3102
+ return nodeAt(root, path, TYPED);
3103
+ }
3104
+ /** {@link $f} for a shell that clones the node's def: once every shell put into it (a guard). */ function $fc(root, ...path) {
3105
+ return nodeAt(root, path, CLONED);
3106
+ }
3107
+ /** How a read uses the node (see {@link changedBy}). */ const PLAIN = 0;
3108
+ const TYPED = 1;
3109
+ const CLONED = 2;
3110
+ function nodeAt(root, path, typed) {
3111
+ let n = readyNode(root);
3112
+ const shells = pendingShells.get(n);
3113
+ if (shells && changedBy(shells, path, typed)) throw NOT_READY;
3114
+ for (const s of path) {
3115
+ const c = child(n, s);
3116
+ if (!c) throw NOT_READY;
3117
+ n = c;
3118
+ }
3119
+ const t = n.type;
3120
+ if (typed !== PLAIN && t.kind === "" && t.designType === void 0) throw NOT_READY;
3121
+ return n;
3122
+ }
3123
+ /**
3124
+ * Class `P` is `T` with annotations of its own (an annotated alias, an `annotate T as P` copy;
3125
+ * `chain`: `type P = T.a.b`, a chain ref): T's def (at `chain`), and metadata layered over it
3126
+ * (P's own entries kept; a chain ref is a reference layer).
3127
+ */ function $alias(P, T, chain) {
3128
+ var _node, _node1;
3129
+ const root = readyNode(T);
3130
+ const target = readyNode($ft(root, ...chain ?? []));
3131
+ const node = P;
3132
+ touched(node);
3133
+ node.type = target.type;
3134
+ const own = node.metadata;
3135
+ node.metadata = new LayerMap([target], !!chain, ownEntries(node.metadata));
3136
+ moveIntrinsic(own, node.metadata);
3137
+ metadataReplaced();
3138
+ const recs = records.get(own);
3139
+ if (recs) records.set(node.metadata, recs);
3140
+ node.ref = {
3141
+ type: () => root,
3142
+ field: chain ? fieldOf(chain) : ""
2222
3143
  };
2223
- const schema = build(type);
2224
- if (hasDefs) return {
2225
- ...schema,
2226
- $defs: defs
3144
+ (_node = node).id ?? (_node.id = target.id);
3145
+ (_node1 = node).validator ?? (_node1.validator = validatorMethod);
3146
+ return node;
3147
+ }
3148
+ /** Shell nodes → the def they were put in (a shell is its position's: the exact path). */ const shellIn = /* @__PURE__ */ new WeakMap();
3149
+ /**
3150
+ * Shell defs → the node they were made for: a shell node over a node with a shell def starts
3151
+ * with that def, and gets its own on its first step of kind 2 (the exact path).
3152
+ */ const shellDefOf = /* @__PURE__ */ new WeakMap();
3153
+ /**
3154
+ * A shell node over `base`: metadata layered over base; its def IS base's def (a reference, read
3155
+ * when used: a def base gets later — a clone a shell of another class puts in — is the shell's
3156
+ * too) until a step below it gives the shell a def of its own (kind 2: `type` is assigned).
3157
+ */ function shellNode(base) {
3158
+ const node = {
3159
+ __is_atscript_annotated_type: true,
3160
+ metadata: new LayerMap([base])
2227
3161
  };
2228
- return schema;
2229
- }
2230
- /** `@expect.minLength` / `maxLength` → `minItems` / `maxItems` on an array schema. */ function applyArrayConstraints(schema, meta) {
2231
- const minLength = meta.get("expect.minLength");
2232
- if (minLength !== void 0) schema.minItems = boundOf(minLength, "length");
2233
- const maxLength = meta.get("expect.maxLength");
2234
- if (maxLength !== void 0) schema.maxItems = boundOf(maxLength, "length");
2235
- }
2236
- /** String / number constraints on a scalar schema whose `type` is already set. */ function applyScalarConstraints(schema, meta) {
2237
- if (schema.type === "number" && meta.get("expect.int")) schema.type = "integer";
2238
- if (schema.type === "string") {
2239
- if (meta.get("meta.required")) schema.minLength = 1;
2240
- const minLength = meta.get("expect.minLength");
2241
- if (minLength !== void 0) schema.minLength = boundOf(minLength, "length");
2242
- const maxLength = meta.get("expect.maxLength");
2243
- if (maxLength !== void 0) schema.maxLength = boundOf(maxLength, "length");
2244
- const patterns = meta.get("expect.pattern");
2245
- if (patterns?.length) if (patterns.length === 1) schema.pattern = patterns[0].pattern;
2246
- else schema.allOf = (schema.allOf || []).concat(patterns.map((p) => ({ pattern: p.pattern })));
2247
- }
2248
- if (schema.type === "number" || schema.type === "integer") {
2249
- const min = meta.get("expect.min");
2250
- if (min !== void 0) schema.minimum = boundOf(min, "minValue");
2251
- const max = meta.get("expect.max");
2252
- if (max !== void 0) schema.maximum = boundOf(max, "maxValue");
2253
- const exMin = meta.get("expect.exclusiveMin");
2254
- if (exMin !== void 0) schema.exclusiveMinimum = boundOf(exMin, "exclusiveMinValue");
2255
- const exMax = meta.get("expect.exclusiveMax");
2256
- if (exMax !== void 0) schema.exclusiveMaximum = boundOf(exMax, "exclusiveMaxValue");
2257
- }
2258
- }
2259
- const LOWER_BOUNDS = new Set([
2260
- "minimum",
2261
- "exclusiveMinimum",
2262
- "minLength",
2263
- "minItems"
2264
- ]);
2265
- const UPPER_BOUNDS = new Set([
2266
- "maximum",
2267
- "exclusiveMaximum",
2268
- "maxLength",
2269
- "maxItems"
2270
- ]);
3162
+ Object.defineProperty(node, SHELL, { value: {
3163
+ b: base,
3164
+ t: void 0,
3165
+ id: void 0,
3166
+ ref: void 0
3167
+ } });
3168
+ Object.defineProperty(node, "type", SHELL_TYPE);
3169
+ node.validator = validatorMethod;
3170
+ Object.defineProperty(node, "ref", SHELL_REF);
3171
+ Object.defineProperty(node, "id", SHELL_ID);
3172
+ node.optional = base.optional;
3173
+ return node;
3174
+ }
3175
+ /** A shell node's own state: its base, and the def / ref / id it was given (`undefined`: base's). */ const SHELL = Symbol("shell");
3176
+ const SHELL_TYPE = {
3177
+ get() {
3178
+ const s = this[SHELL];
3179
+ return s.t ?? s.b.type;
3180
+ },
3181
+ set(d) {
3182
+ this[SHELL].t = d;
3183
+ },
3184
+ enumerable: true,
3185
+ configurable: true
3186
+ };
3187
+ const SHELL_REF = {
3188
+ get() {
3189
+ const s = this[SHELL];
3190
+ return s.ref ? s.ref.v : s.b.ref;
3191
+ },
3192
+ set(v) {
3193
+ this[SHELL].ref = { v };
3194
+ },
3195
+ enumerable: true,
3196
+ configurable: true
3197
+ };
3198
+ const SHELL_ID = {
3199
+ get() {
3200
+ const s = this[SHELL];
3201
+ return s.id ? s.id.v : s.b.id;
3202
+ },
3203
+ set(v) {
3204
+ this[SHELL].id = { v };
3205
+ },
3206
+ enumerable: true,
3207
+ configurable: true
3208
+ };
3209
+ /** A def of node `holder`'s with the same entries as `d` (its children replaceable by shells). */ function shellDef(d, holder) {
3210
+ const c = { ...d };
3211
+ if (d.tags) c.tags = new Set(d.tags);
3212
+ if (d.props) {
3213
+ c.props = new PropsMap(d.props);
3214
+ c.propsPatterns = [...d.propsPatterns ?? []];
3215
+ }
3216
+ if (d.items) c.items = [...d.items];
3217
+ shellDefOf.set(c, holder);
3218
+ cutAs(c, d);
3219
+ return c;
3220
+ }
3221
+ /** Puts `node` at step `s` of def `d`. */ function put(d, s, node) {
3222
+ if (s === "[]") {
3223
+ d.of = node;
3224
+ touched(d);
3225
+ } else if (s[0] === "|") {
3226
+ d.items[Number(s.slice(1))] = node;
3227
+ touched(d);
3228
+ } else d.props.set(s, node);
3229
+ }
2271
3230
  /**
2272
- * Puts union-level constraints onto the matching `anyOf` members (numbers, strings,
2273
- * arrays; nested `anyOf` members recursively). When a member already has the same
2274
- * bound, the stricter one wins; patterns accumulate.
2275
- */ function applyUnionConstraints(members, meta) {
2276
- for (const member of members) {
2277
- if (Array.isArray(member.anyOf)) {
2278
- applyUnionConstraints(member.anyOf, meta);
2279
- continue;
2280
- }
2281
- if (member.const !== void 0) continue;
2282
- const type = member.type;
2283
- const extra = { type };
2284
- if (type === "array") applyArrayConstraints(extra, meta);
2285
- else if (type === "string" || type === "number" || type === "integer") applyScalarConstraints(extra, meta);
2286
- else continue;
2287
- if (extra.type === "integer") member.type = "integer";
2288
- for (const [key, value] of Object.entries(extra)) {
2289
- if (key === "type") continue;
2290
- if (key === "pattern" || key === "allOf") {
2291
- const patterns = key === "pattern" ? [{ pattern: value }] : value;
2292
- if (member.pattern === void 0 && key === "pattern" && !member.allOf) member.pattern = value;
2293
- else member.allOf = (member.allOf || []).concat(patterns);
2294
- } else if (member[key] === void 0) member[key] = value;
2295
- else if (LOWER_BOUNDS.has(key)) member[key] = Math.max(member[key], value);
2296
- else if (UPPER_BOUNDS.has(key)) member[key] = Math.min(member[key], value);
2297
- }
3231
+ * The node of `T` at `path`, with T's own shells along it (idempotent). Step kinds:
3232
+ * 0 — the def and the child are T's own (descend); 1 — the def is T's, the child is not (a shell
3233
+ * node replaces it); 2 — the def is not T's (the node gets a shell def first, then as 1).
3234
+ */ function ensure(T, path) {
3235
+ let cur = T;
3236
+ for (const [s, kind] of path) {
3237
+ let c = child(cur, s);
3238
+ if (!c) throw NOT_READY;
3239
+ if (kind === 2 && shellDefOf.get(cur.type) !== cur) {
3240
+ touched(cur);
3241
+ cur.type = shellDef(cur.type, cur);
3242
+ }
3243
+ if (kind !== 0 && shellIn.get(c) !== cur.type) {
3244
+ c = shellNode(c);
3245
+ put(cur.type, s, c);
3246
+ shellIn.set(c, cur.type);
3247
+ }
3248
+ cur = c;
3249
+ }
3250
+ return cur;
3251
+ }
3252
+ /** Ensures T's shells along each path (see {@link ensure}). */ function $sh(T, paths) {
3253
+ const target = builtNode(T);
3254
+ for (const path of paths) ensure(target, path);
3255
+ const pending = pendingShells.get(target);
3256
+ if (pending) {
3257
+ const done = new Set(paths.flatMap(stagesOf).map((p) => JSON.stringify(p)));
3258
+ const rest = pending.filter((p) => !done.has(JSON.stringify(p)));
3259
+ if (rest.length > 0) pendingShells.set(target, rest);
3260
+ else pendingShells.delete(target);
2298
3261
  }
2299
3262
  }
2300
3263
  /**
2301
- * Converts a JSON Schema object into a {@link TAtscriptAnnotatedType}.
2302
- *
2303
- * This is the inverse of {@link buildJsonSchema}. A round-trip
2304
- * `buildJsonSchema(fromJsonSchema(schema))` preserves structure and constraints.
2305
- *
2306
- * Supports the JSON Schema subset produced by `buildJsonSchema` plus
2307
- * common extensions like `oneOf` (treated as union) and `enum` (union of literals).
2308
- *
2309
- * @example
2310
- * ```ts
2311
- * import { fromJsonSchema } from '@atscript/typescript'
2312
- *
2313
- * const type = fromJsonSchema({ type: 'object', properties: { name: { type: 'string' } }, required: ['name'] })
2314
- * type.validator().validate({ name: 'Alice' }) // passes
2315
- * ```
2316
- *
2317
- * @param schema - A JSON Schema object.
2318
- * @returns An annotated type with full validator support.
2319
- */ function fromJsonSchema(schema) {
2320
- const defsSource = schema.$defs || schema.definitions || {};
2321
- const resolved = /* @__PURE__ */ new Map();
2322
- const convert = (s) => {
2323
- if (!s || Object.keys(s).length === 0) return defineAnnotatedType().designType("any").$type;
2324
- if (s.$ref) {
2325
- const refName = s.$ref.replace(/^#\/(\$defs|definitions)\//, "");
2326
- if (resolved.has(refName)) return resolved.get(refName);
2327
- if (defsSource[refName]) {
2328
- const placeholder = defineAnnotatedType().designType("any").$type;
2329
- resolved.set(refName, placeholder);
2330
- const type = convert(defsSource[refName]);
2331
- resolved.set(refName, type);
2332
- return type;
2333
- }
2334
- throw new Error(`Unresolvable $ref: ${s.$ref}`);
2335
- }
2336
- if ("const" in s) {
2337
- const val = s.const;
2338
- const dt = val === null ? "null" : typeof val;
2339
- return defineAnnotatedType().designType(dt).value(val).$type;
2340
- }
2341
- if (s.enum) {
2342
- const handle = defineAnnotatedType("union");
2343
- for (const val of s.enum) {
2344
- const dt = val === null ? "null" : typeof val;
2345
- handle.item(defineAnnotatedType().designType(dt).value(val).$type);
2346
- }
2347
- return handle.$type;
2348
- }
2349
- if (s.anyOf) {
2350
- const handle = defineAnnotatedType("union");
2351
- for (const item of s.anyOf) handle.item(convert(item));
2352
- return handle.$type;
2353
- }
2354
- if (s.oneOf) {
2355
- const handle = defineAnnotatedType("union");
2356
- for (const item of s.oneOf) handle.item(convert(item));
2357
- return handle.$type;
2358
- }
2359
- if (s.allOf && !s.type) {
2360
- const handle = defineAnnotatedType("intersection");
2361
- for (const item of s.allOf) handle.item(convert(item));
2362
- return handle.$type;
2363
- }
2364
- if (Array.isArray(s.type)) {
2365
- const handle = defineAnnotatedType("union");
2366
- for (const t of s.type) handle.item(convert({
2367
- ...s,
2368
- type: t
2369
- }));
2370
- return handle.$type;
2371
- }
2372
- if (s.type === "object") {
2373
- const handle = defineAnnotatedType("object");
2374
- const required = new Set(s.required || []);
2375
- if (s.properties) for (const [key, propSchema] of Object.entries(s.properties)) {
2376
- const propType = convert(propSchema);
2377
- if (!required.has(key)) propType.optional = true;
2378
- handle.prop(key, propType);
2379
- }
2380
- return handle.$type;
2381
- }
2382
- if (s.type === "array") {
2383
- if (Array.isArray(s.items)) {
2384
- const handle = defineAnnotatedType("tuple");
2385
- for (const item of s.items) handle.item(convert(item));
2386
- return handle.$type;
2387
- }
2388
- const itemType = s.items ? convert(s.items) : defineAnnotatedType().designType("any").$type;
2389
- const handle = defineAnnotatedType("array").of(itemType);
2390
- if (typeof s.minItems === "number") handle.annotate("expect.minLength", { length: s.minItems });
2391
- if (typeof s.maxItems === "number") handle.annotate("expect.maxLength", { length: s.maxItems });
2392
- return handle.$type;
2393
- }
2394
- if (s.type === "string") {
2395
- const handle = defineAnnotatedType().designType("string").tags("string");
2396
- if (typeof s.minLength === "number") handle.annotate("expect.minLength", { length: s.minLength });
2397
- if (typeof s.maxLength === "number") handle.annotate("expect.maxLength", { length: s.maxLength });
2398
- if (s.pattern) handle.annotate("expect.pattern", { pattern: s.pattern }, true);
2399
- if (s.allOf) {
2400
- for (const item of s.allOf) if (item.pattern) handle.annotate("expect.pattern", { pattern: item.pattern }, true);
2401
- }
2402
- return handle.$type;
2403
- }
2404
- if (s.type === "integer") {
2405
- const handle = defineAnnotatedType().designType("number").tags("number");
2406
- handle.annotate("expect.int", true);
2407
- annotateNumberBounds(handle, s);
2408
- return handle.$type;
2409
- }
2410
- if (s.type === "number") {
2411
- const handle = defineAnnotatedType().designType("number").tags("number");
2412
- annotateNumberBounds(handle, s);
2413
- return handle.$type;
2414
- }
2415
- if (s.type === "boolean") return defineAnnotatedType().designType("boolean").tags("boolean").$type;
2416
- if (s.type === "null") return defineAnnotatedType().designType("null").tags("null").$type;
2417
- return defineAnnotatedType().designType("any").$type;
2418
- };
2419
- return convert(schema);
3264
+ * The shells a class of an import cycle's module will get (`$sh` runs once what they shell is
3265
+ * built): a read through a node they replace, or into a def they clone, waits for them.
3266
+ */ const pendingShells = /* @__PURE__ */ new WeakMap();
3267
+ /** Registers class `T`'s shells as pending (see {@link $sh}): first statement of its module. */ function $ps(T, paths) {
3268
+ const seen = /* @__PURE__ */ new Set();
3269
+ pendingShells.set(T, paths.flatMap(stagesOf).filter((p) => {
3270
+ const k = JSON.stringify(p);
3271
+ return !seen.has(k) && !!seen.add(k);
3272
+ }));
2420
3273
  }
2421
3274
  /**
2422
- * Maps `minimum` / `maximum` / `exclusiveMinimum` / `exclusiveMaximum` onto
2423
- * `@expect.min` / `max` / `exclusiveMin` / `exclusiveMax`. Also reads the draft-4 form,
2424
- * where `exclusiveMinimum: true` makes `minimum` exclusive.
2425
- */ function annotateNumberBounds(handle, s) {
2426
- if (typeof s.minimum === "number") if (s.exclusiveMinimum === true) handle.annotate("expect.exclusiveMin", { exclusiveMinValue: s.minimum });
2427
- else handle.annotate("expect.min", { minValue: s.minimum });
2428
- if (typeof s.maximum === "number") if (s.exclusiveMaximum === true) handle.annotate("expect.exclusiveMax", { exclusiveMaxValue: s.maximum });
2429
- else handle.annotate("expect.max", { maxValue: s.maximum });
2430
- if (typeof s.exclusiveMinimum === "number") handle.annotate("expect.exclusiveMin", { exclusiveMinValue: s.exclusiveMinimum });
2431
- if (typeof s.exclusiveMaximum === "number") handle.annotate("expect.exclusiveMax", { exclusiveMaxValue: s.exclusiveMaximum });
3275
+ * The last step index of each stage of shell path `path` (see {@link stagesOf}): every step that
3276
+ * shells, and the path's last (the build's stage index walks them too, `js-next.ts`
3277
+ * `shellPathsOf`).
3278
+ */ function stageEnds(path) {
3279
+ return path.flatMap(([, kind], j) => kind !== 0 || j === path.length - 1 ? [j] : []);
3280
+ }
3281
+ /** The stages of shell path `path`: each prefix ending at a step that shells, and the path. */ function stagesOf(path) {
3282
+ return stageEnds(path).map((j) => path.slice(0, j + 1));
2432
3283
  }
2433
3284
  /**
2434
- * Merges multiple annotated types into a combined schema map with shared `$defs`.
2435
- *
2436
- * Each type must have an `id`. The returned `schemas` object contains individual
2437
- * schemas keyed by type id, and `$defs` contains all shared type definitions
2438
- * deduplicated across schemas.
2439
- *
2440
- * @param types - Array of annotated types, each with an `id`.
2441
- * @returns An object with `schemas` (keyed by id) and shared `$defs`.
2442
- */ function mergeJsonSchemas(types) {
2443
- const mergedDefs = {};
2444
- const schemas = {};
2445
- for (const type of types) {
2446
- const name = type.id;
2447
- if (!name) throw new Error("mergeJsonSchemas: all types must have an id");
2448
- const schema = buildJsonSchema(type);
2449
- if (schema.$defs) {
2450
- for (const [defName, defSchema] of Object.entries(schema.$defs)) if (!mergedDefs[defName]) mergedDefs[defName] = defSchema;
2451
- const { $defs: _, ...rest } = schema;
2452
- schemas[name] = rest;
2453
- } else schemas[name] = schema;
3285
+ * Whether a read at `path` meets what pending shell stages change: a stage (a shell path up to a
3286
+ * step of kind 1 / 2) replaces the node at its end in the def above it (kind 2: in a clone of
3287
+ * that def). A read through that node waits; a read of the def above it waits for a clone
3288
+ * (`TYPED`: it captures the def) or for any stage (`CLONED`: it copies the def's entries).
3289
+ */ function changedBy(shells, path, typed) {
3290
+ for (const s of shells) {
3291
+ const n = s.length;
3292
+ let i = 0;
3293
+ while (i < n && i < path.length && path[i] === s[i][0]) i++;
3294
+ if (i === n || typed !== PLAIN && i === n - 1 && path.length === n - 1 && (typed === CLONED || s[n - 1][1] === 2)) return true;
2454
3295
  }
2455
- return {
2456
- schemas,
2457
- $defs: mergedDefs
2458
- };
3296
+ return false;
3297
+ }
3298
+ function compare(a, b) {
3299
+ return a[0] - b[0] || (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0) || a[2] - b[2] || a[3] - b[3];
3300
+ }
3301
+ const records = /* @__PURE__ */ new WeakMap();
3302
+ function recordsOf(m) {
3303
+ let r = records.get(m);
3304
+ if (!r) records.set(m, r = /* @__PURE__ */ new Map());
3305
+ return r;
3306
+ }
3307
+ /**
3308
+ * A block write of a replace key: ignored when the own value is one a higher-ranked block wrote
3309
+ * (a raw write since makes it nobody's: the block applies).
3310
+ */ function writeKey(m, key, value, rank) {
3311
+ const recs = recordsOf(m);
3312
+ const r = recs.get(key);
3313
+ if (r && ownValue(m, key) === r.value && compare(r.rank, rank) > 0) return;
3314
+ m.set(key, value);
3315
+ recs.set(key, {
3316
+ rank,
3317
+ value
3318
+ });
3319
+ }
3320
+ /**
3321
+ * A block write of an append key: the own list is the elements written before any block (by
3322
+ * the builder, or a raw write since), then every block's part by rank.
3323
+ */ function appendKey(m, key, values, rank) {
3324
+ const recs = recordsOf(m);
3325
+ let r = recs.get(key);
3326
+ const own = ownValue(m, key);
3327
+ if (!r || own !== r.value || r.value.length !== r.length) {
3328
+ const before = own === void 0 ? [] : Array.isArray(own) ? [...own] : [own];
3329
+ r = {
3330
+ before,
3331
+ parts: [],
3332
+ value: before,
3333
+ length: 0
3334
+ };
3335
+ }
3336
+ const { parts } = r;
3337
+ let at = 0;
3338
+ while (at < parts.length && compare(parts[at].rank, rank) < 0) at++;
3339
+ if (at < parts.length && compare(parts[at].rank, rank) === 0) parts[at].values = values;
3340
+ else parts.splice(at, 0, {
3341
+ rank,
3342
+ values
3343
+ });
3344
+ const value = [...r.before];
3345
+ for (const p of parts) value.push(...p.values);
3346
+ m.set(key, value);
3347
+ r.value = value;
3348
+ r.length = value.length;
3349
+ recs.set(key, r);
3350
+ }
3351
+ function writeEntry(m, anns, rank) {
3352
+ const values = /* @__PURE__ */ new Map();
3353
+ for (const [key, value, list] of anns) if (list) {
3354
+ const xs = values.get(key);
3355
+ values.set(key, xs ? [...xs, value] : [value]);
3356
+ } else values.set(key, value);
3357
+ for (const [key, value] of values) if (isAppendKey(key)) appendKey(m, key, Array.isArray(value) ? value : [value], rank);
3358
+ else writeKey(m, key, value, rank);
3359
+ }
3360
+ /** The module ids of the blocks applied (the bundled-schema guard reads them). */ const applied = /* @__PURE__ */ new Set();
3361
+ /** The module ids of every block applied so far. */ function appliedBlockModules() {
3362
+ return applied;
3363
+ }
3364
+ /**
3365
+ * Block `index` of a module of rank `R` (`[import depth, module id]`; `null`: an `as` copy's
3366
+ * entries, below every block) on `T`: ensures each entry's shells, then writes its annotations
3367
+ * with rank (R, index, entry index). Re-applying a block is idempotent.
3368
+ */ function $blk(R, index, T, entries) {
3369
+ const target = builtNode(T);
3370
+ const nodes = entries.map(([, ...paths]) => paths.map((path) => ensure(target, path)));
3371
+ entries.forEach(([anns], e) => {
3372
+ const rank = R ? [
3373
+ R[0],
3374
+ R[1],
3375
+ index,
3376
+ e
3377
+ ] : [
3378
+ -1,
3379
+ "",
3380
+ index,
3381
+ e
3382
+ ];
3383
+ for (const node of nodes[e]) writeEntry(node.metadata, anns, rank);
3384
+ });
3385
+ if (R) applied.add(R[1]);
3386
+ }
3387
+ const queue = [];
3388
+ /**
3389
+ * Whether `e` is a statement's wait — a class not built yet (`NOT_READY`), a binding in its
3390
+ * temporal dead zone — rather than its failure.
3391
+ */ const isWait = (e) => e === NOT_READY || e instanceof ReferenceError;
3392
+ /**
3393
+ * Runs `fn` (a statement reading a class of another module of its import cycle), or queues it
3394
+ * when that class is not built yet (ESM: its temporal dead zone; CommonJS: `undefined`). `own`:
3395
+ * the module's own list of queued statements (a module in no import cycle, see {@link $end}).
3396
+ */ function $q(fn, own) {
3397
+ try {
3398
+ fn();
3399
+ } catch (error) {
3400
+ if (!isWait(error)) throw error;
3401
+ queue.push(fn);
3402
+ own?.push(fn);
3403
+ }
3404
+ }
3405
+ /**
3406
+ * The last statement of a module: runs the queued statements that can run now, in order. A module
3407
+ * in no import cycle passes its own queued statements (`own`, see {@link $q}) and throws when one
3408
+ * of them still waits: nothing it waits for can come later. (A module of an import cycle is
3409
+ * checked when the build loads the cycle from each of its modules.)
3410
+ */ function $end(own) {
3411
+ let progress = true;
3412
+ while (progress && queue.length > 0) {
3413
+ progress = false;
3414
+ for (let i = 0; i < queue.length;) {
3415
+ try {
3416
+ queue[i]();
3417
+ } catch (error) {
3418
+ if (isWait(error)) {
3419
+ i++;
3420
+ continue;
3421
+ }
3422
+ queue.splice(i, 1);
3423
+ throw error;
3424
+ }
3425
+ queue.splice(i, 1);
3426
+ progress = true;
3427
+ }
3428
+ }
3429
+ const left = own?.filter((fn) => queue.includes(fn)) ?? [];
3430
+ if (left.length > 0) {
3431
+ for (const fn of left) queue.splice(queue.indexOf(fn), 1);
3432
+ throw new Error(`atscript: ${left.length} statement(s) of this module never ran: they wait for each other (an internal code generation error: please report it)`);
3433
+ }
3434
+ }
3435
+ /** How many statements wait for a class of an import cycle (0 once every module loaded). */ function pendingStatements() {
3436
+ return queue.length;
3437
+ }
3438
+
3439
+ //#endregion
3440
+ //#region packages/typescript/src/runtime/unique-name.ts
3441
+ /**
3442
+ * `base`, or — when `taken` reports it taken — the first `<base><sep><n>` (n = 1, 2, …) it
3443
+ * does not.
3444
+ */ function uniqueName(base, taken, sep) {
3445
+ let name = base;
3446
+ for (let n = 1; taken(name); n++) name = `${base}${sep}${n}`;
3447
+ return name;
2459
3448
  }
2460
3449
 
2461
3450
  //#endregion
2462
- export { D_UNKNOWN as A, LAYOUT_VERSION as B, D_ARRAY as C, D_OBJECT_PATTERNS as D, D_OBJECT as E, F_PARTIAL_TOP as F, keySlots as G, STRING_BITS as H, F_STRIP as I, siteSlotCount as J, readKeys as K, F_TOP as L, F_ERROR as M, F_IN_UNION as N, D_TUPLE as O, F_PARTIAL_DEEP as P, INTERP as R, B_UNIQUE as S, D_INTERSECTION as T, childSites as U, NUMBER_BITS as V, hasRejectSlot as W, isValidatorKey as X, invalidateCompiledValidators as Y, getRegex as _, forAnnotatedType as a, B_INT as b, createAnnotatedTypeNode as c, defineAnnotatedType as d, isAnnotatedType as f, ValidatorError as g, Validator as h, mergeJsonSchemas as i, EXT as j, D_UNION as k, createMetadataMap as l, isPhantomType as m, detectDiscriminator as n, annotate as o, isAnnotatedTypeOfPrimitive as p, siteBits as q, fromJsonSchema as r, cloneRefProp as s, buildJsonSchema as t, createObjectTypeDef as u, registerCompiledCheck as v, D_FINAL as w, B_REQUIRED as x, ARRAY_BITS as y, ITEMS_KIND_CODES as z };
3451
+ export { statelessRegExp as A, VALIDATOR_KEYS as B, isAnnotatedTypeOfPrimitive as C, ValidatorError as D, Validator as E, watchLayer as F, boundOf as H, invalidateCompiledValidators as I, metadataWriteCount as L, $nr as M, LayerMap as N, registerCompiledCheck as O, metaEmpty as P, touched as R, isAnnotatedType as S, propAtChain as T, arrayKeyProps as V, annotate as _, $f as a, createObjectTypeDef as b, $ps as c, appliedBlockModules as d, pendingStatements as f, enterCut as g, cutKey as h, $end as i, $ak as j, jsonSchemaPattern as k, $q as l, cutAs as m, $alias as n, $fc as o, stageEnds as p, $blk as r, $ft as s, uniqueName as t, $sh as u, createAnnotatedTypeNode as v, isPhantomType as w, defineAnnotatedType as x, createMetadataMap as y, DECIMAL_RE as z };