@atscript/typescript 0.1.109 → 0.1.110

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.
@@ -1,4 +1,544 @@
1
+ //#region packages/typescript/src/runtime/validator-keys.ts
2
+ /**
3
+ * Annotation keys the validator pre-check reads, per kind of checked value — shared by the
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 = [
6
+ "meta.required",
7
+ "expect.minLength",
8
+ "expect.maxLength",
9
+ "expect.pattern"
10
+ ];
11
+ /** Annotations of a number node, in check order. */ const NUMBER_KEYS = [
12
+ "expect.int",
13
+ "expect.min",
14
+ "expect.max",
15
+ "expect.exclusiveMin",
16
+ "expect.exclusiveMax"
17
+ ];
18
+ /** Annotations of a boolean node. */ const BOOLEAN_KEYS = ["meta.required"];
19
+ /** Annotations of an array node, in check order. */ const ARRAY_KEYS = [
20
+ "expect.minLength",
21
+ "expect.maxLength",
22
+ "expect.array.uniqueItems"
23
+ ];
24
+ /**
25
+ * Every annotation key the validator pre-check reads. The order is the bit order of
26
+ * compiled-check layouts: changing it changes the layout format.
27
+ */ const VALIDATOR_KEYS = [
28
+ "meta.required",
29
+ "expect.minLength",
30
+ "expect.maxLength",
31
+ "expect.pattern",
32
+ "expect.int",
33
+ "expect.min",
34
+ "expect.max",
35
+ "expect.exclusiveMin",
36
+ "expect.exclusiveMax",
37
+ "expect.array.uniqueItems"
38
+ ];
39
+ /**
40
+ * The number a length / bound annotation compares with: the annotation is either the number
41
+ * itself or an object carrying it in `field` (`{ length }`, `{ minValue }`, …).
42
+ */ function boundOf(m, field) {
43
+ return typeof m === "number" ? m : m[field];
44
+ }
45
+
46
+ //#endregion
47
+ //#region packages/typescript/src/runtime/compiled-check/tracking.ts
48
+ /**
49
+ * Mutation tracking for build-time compiled validator checks.
50
+ *
51
+ * A compiled check is bound to the live type tree before use (see registry.ts): the bind
52
+ * verifies that the tree still has the structure the check was compiled for and snapshots
53
+ * the constraint values the check reads. Every tracked mutation of an object a bind has
54
+ * read bumps one global epoch, which makes every compiled check re-bind on its next use.
55
+ *
56
+ * 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.
60
+ */ const VALIDATOR_KEY_SET = new Set(VALIDATOR_KEYS);
61
+ /** Global mutation epoch: compiled checks bound in an older epoch re-bind before use. */ let epoch = 0;
62
+ /** Some bind has watched an object (until then no mutation can affect a compiled check). */ let tracking = false;
63
+ /** Objects (nodes, type defs, metadata / props maps) read by some compiled-check bind. */ const watched = /* @__PURE__ */ new WeakSet();
64
+ /** The current mutation epoch. */ function currentEpoch() {
65
+ return epoch;
66
+ }
67
+ /** Marks `obj` as read by a bind: tracked mutations of it invalidate compiled checks. */ function watch(obj) {
68
+ tracking = true;
69
+ watched.add(obj);
70
+ }
71
+ /** Records a tracked mutation of `obj` (a no-op unless some bind has read it). */ function touched(obj) {
72
+ if (tracking && watched.has(obj)) epoch++;
73
+ }
74
+ /**
75
+ * Makes every compiled validator check re-verify the type tree it was compiled for before
76
+ * its next use.
77
+ *
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:
82
+ * - a raw property write: `node.optional = …`, `node.type = …`, `node.metadata = …`,
83
+ * `type.items.push(…)`, `type.of = …`, `type.propsPatterns.push(…)`;
84
+ * - an in-place edit of an annotation value: mutating a constraint object
85
+ * (`metadata.get('expect.min').minValue = 5`), editing or pushing onto an
86
+ * `@expect.pattern` array directly (use `annotate(metadata, key, value, true)` instead).
87
+ *
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.
90
+ *
91
+ * Any mutation of a type a compiled check has bound to (tracked or invalidated) makes every
92
+ * compiled check re-bind once on its next use: cheap during startup / configuration, but
93
+ * avoid mutating validated types per request.
94
+ */ function invalidateCompiledValidators() {
95
+ epoch++;
96
+ }
97
+ /**
98
+ * Metadata map of runtime type nodes: a `Map` whose writes to validator annotation keys
99
+ * are tracked (see {@link invalidateCompiledValidators}). Reads are the builtin ones.
100
+ */ var AnnotationMap = class extends Map {
101
+ set(key, value) {
102
+ super.set(key, value);
103
+ if (tracking && VALIDATOR_KEY_SET.has(key)) touched(this);
104
+ return this;
105
+ }
106
+ delete(key) {
107
+ const deleted = super.delete(key);
108
+ if (deleted && tracking && VALIDATOR_KEY_SET.has(key)) touched(this);
109
+ return deleted;
110
+ }
111
+ clear() {
112
+ super.clear();
113
+ touched(this);
114
+ }
115
+ };
116
+ /** Props map of runtime object types: a `Map` whose writes are tracked. */ var PropsMap = class extends Map {
117
+ set(key, value) {
118
+ super.set(key, value);
119
+ touched(this);
120
+ return this;
121
+ }
122
+ delete(key) {
123
+ const deleted = super.delete(key);
124
+ if (deleted) touched(this);
125
+ return deleted;
126
+ }
127
+ clear() {
128
+ super.clear();
129
+ touched(this);
130
+ }
131
+ };
132
+ /** `true` when `key` is an annotation the validator pre-check reads. */ function isValidatorKey(key) {
133
+ return VALIDATOR_KEY_SET.has(key);
134
+ }
135
+
136
+ //#endregion
137
+ //#region packages/typescript/src/runtime/compiled-check/layout.ts
138
+ /**
139
+ * Layout of a compiled validator check: the structure a check was compiled for, as plain
140
+ * data. `buildLayout` (build-layout.ts) derives it from a type tree (the build-time model
141
+ * of a generated module, or a live tree in tests); the binder (registry.ts) verifies a
142
+ * live tree against it and collects the constraint values the compiled code reads into
143
+ * the K slots.
144
+ *
145
+ * ```
146
+ * Layout = [defs: Def[], root: Site, slotCount]
147
+ * Site = [optional: 0|1, keyMask, def: number | EXT | INTERP, patternShape, slot]
148
+ * Def = [FINAL, designType] | [FINAL, designType, literal]
149
+ * | [OBJECT, keys, sites] | [OBJECT_PATTERNS]
150
+ * | [ARRAY, of] | [UNION | INTERSECTION | TUPLE, items] | [UNKNOWN, kind]
151
+ * ```
152
+ * - A site is one annotated-type node (a class root, prop, array element, union / tuple /
153
+ * intersection item). A def is one type-def object: sites sharing a def index share the
154
+ * def object (by identity) at runtime, which is how shared and recursive types are
155
+ * compiled once.
156
+ * - `keyMask` has a bit (by {@link VALIDATOR_KEYS} index) per validator annotation that is
157
+ * *effective* on the node and relevant to its def (present; flags: truthy).
158
+ * `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).
160
+ * - `slot`: the site's first K slot (see {@link siteSlotCount}); `slotCount` is the total.
161
+ * - `EXT`: an anonymous reference into another module's type; bound to that type's own
162
+ * compiled check (as a template, against the referring node) when it has one, else
163
+ * checked by the interpreted pre-check.
164
+ * - `INTERP`: a node only known at runtime (e.g. a chained reference into another module's
165
+ * type): always checked by the interpreted pre-check.
166
+ */
167
+ /** Layout format version; checks of another version are ignored (interpreted). */ const LAYOUT_VERSION = 2;
168
+ const EXT = -1;
169
+ const INTERP = -2;
170
+ const D_FINAL = 0;
171
+ const D_OBJECT = 1;
172
+ const D_ARRAY = 2;
173
+ const D_UNION = 3;
174
+ const D_INTERSECTION = 4;
175
+ const D_TUPLE = 5;
176
+ const D_UNKNOWN = 6;
177
+ 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
+ /** Kind names of the def codes with `items`. */ const ITEMS_KIND_NAMES = {
184
+ [D_UNION]: "union",
185
+ [D_INTERSECTION]: "intersection",
186
+ [D_TUPLE]: "tuple"
187
+ };
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
+ const F_ERROR = 4;
191
+ const F_STRIP = 8;
192
+ const F_PARTIAL_DEEP = 16;
193
+ const F_PARTIAL_TOP = 32;
194
+ /** Key mask bit of a validator annotation. */ function bit(key) {
195
+ return 1 << VALIDATOR_KEYS.indexOf(key);
196
+ }
197
+ function bitsOf(keys) {
198
+ let bits = 0;
199
+ for (const key of keys) bits |= bit(key);
200
+ return bits;
201
+ }
202
+ const B_REQUIRED = bit("meta.required");
203
+ const B_MIN_LENGTH = bit("expect.minLength");
204
+ const B_MAX_LENGTH = bit("expect.maxLength");
205
+ const B_PATTERN = bit("expect.pattern");
206
+ const B_INT = bit("expect.int");
207
+ const B_MIN = bit("expect.min");
208
+ const B_MAX = bit("expect.max");
209
+ const B_EX_MIN = bit("expect.exclusiveMin");
210
+ const B_EX_MAX = bit("expect.exclusiveMax");
211
+ const B_UNIQUE = bit("expect.array.uniqueItems");
212
+ /** Annotations the pre-check reads per kind of value (see validator-keys.ts). */ const STRING_BITS = bitsOf(STRING_KEYS);
213
+ const NUMBER_BITS = bitsOf(NUMBER_KEYS);
214
+ const ARRAY_BITS = bitsOf(ARRAY_KEYS);
215
+ const BOOLEAN_BITS = bitsOf(BOOLEAN_KEYS);
216
+ /** Keys whose value the compiled code reads (one K slot each). */ const VALUE_BITS = B_MIN_LENGTH | B_MAX_LENGTH | B_MIN | B_MAX | B_EX_MIN | B_EX_MAX;
217
+ const FLAG_BITS = B_REQUIRED | B_INT | B_UNIQUE;
218
+ const ALL_BITS = (1 << VALIDATOR_KEYS.length) - 1;
219
+ /** The field holding the bound of each value key's object form. */ const BOUND_FIELDS = {
220
+ [B_MIN_LENGTH]: "length",
221
+ [B_MAX_LENGTH]: "length",
222
+ [B_MIN]: "minValue",
223
+ [B_MAX]: "maxValue",
224
+ [B_EX_MIN]: "exclusiveMinValue",
225
+ [B_EX_MAX]: "exclusiveMaxValue"
226
+ };
227
+ /**
228
+ * Validator annotations the pre-check reads for a node of this type def (the rest of the
229
+ * node's annotations cannot change its outcome, so they are not part of the layout).
230
+ */ function relevantBits(type) {
231
+ switch (type.kind) {
232
+ case "":
233
+ if (type.designType === "phantom" || type.value !== void 0) return 0;
234
+ switch (type.designType) {
235
+ case "string": return STRING_BITS;
236
+ case "number": return NUMBER_BITS;
237
+ case "boolean": return BOOLEAN_BITS;
238
+ default: return 0;
239
+ }
240
+ case "array": return ARRAY_BITS;
241
+ case "union": return ALL_BITS;
242
+ default: return 0;
243
+ }
244
+ }
245
+ /**
246
+ * {@link relevantBits} of a site (`undefined`: a type only known at runtime);
247
+ * `meta.required` also matters on any optional node.
248
+ */ function siteBits(type, optional) {
249
+ return (type === void 0 ? 0 : relevantBits(type)) | (optional ? B_REQUIRED : 0);
250
+ }
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
+ /** An optional node with `@meta.required`: `null` fails unless its type accepts `null`. */ function hasRejectSlot(site) {
269
+ return site[0] === 1 && (site[1] & B_REQUIRED) !== 0;
270
+ }
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
+ /**
299
+ * Computes a node's key mask and pattern shape over `relevant` bits, and — when `out` is
300
+ * given — writes the normalised annotation values from `out[at]` on (the K slots).
301
+ * Throws on annotation values the pre-check itself would throw on (the bind then fails
302
+ * and the interpreted pre-check runs, which reproduces that behaviour).
303
+ */ function readKeys(metadata, relevant, reader, out, at = 0) {
304
+ let mask = 0;
305
+ let shape = "";
306
+ let k = at;
307
+ if (metadata.size === 0) return {
308
+ mask,
309
+ shape
310
+ };
311
+ for (let i = 0; i < VALIDATOR_KEYS.length; i++) {
312
+ const b = 1 << i;
313
+ if ((relevant & b) === 0) continue;
314
+ const raw = metadata.get(VALIDATOR_KEYS[i]);
315
+ if ((b & FLAG_BITS) !== 0) {
316
+ if (raw) mask |= b;
317
+ continue;
318
+ }
319
+ if (b === B_PATTERN) {
320
+ if (!raw) continue;
321
+ if (!Array.isArray(raw)) throw new TypeError("expect.pattern is not an array");
322
+ mask |= b;
323
+ for (const entry of raw) {
324
+ const { pattern, flags } = entry;
325
+ if (!pattern) {
326
+ shape += "e";
327
+ continue;
328
+ }
329
+ const re = reader.regex(pattern, flags);
330
+ if (re.global || re.sticky) {
331
+ shape += "s";
332
+ break;
333
+ }
334
+ shape += "n";
335
+ if (out) out[k] = re;
336
+ k++;
337
+ }
338
+ continue;
339
+ }
340
+ if (raw === void 0) continue;
341
+ mask |= b;
342
+ if (out) out[k] = boundOf(raw, BOUND_FIELDS[b]);
343
+ k++;
344
+ }
345
+ return {
346
+ mask,
347
+ shape
348
+ };
349
+ }
350
+
351
+ //#endregion
352
+ //#region packages/typescript/src/runtime/compiled-check/registry.ts
353
+ /**
354
+ * Runtime registry and binder of build-time compiled validator checks.
355
+ *
356
+ * Generated `.as.js` modules (built with `tsPlugin({ compileValidators: true })`) call
357
+ * {@link registerCompiledCheck} once per class with the class's layout and a factory of
358
+ * its check. On first use, and again after each mutation epoch (see tracking.ts), the
359
+ * entry is bound: `bindLayout` verifies the live type tree against the layout and collects
360
+ * the constraint values into `K`; the factory turns `K` into the check function. A tree
361
+ * that no longer matches leaves the entry unbound for that epoch, so the interpreted
362
+ * pre-check runs instead — always correct, never stale.
363
+ *
364
+ * A registered entry is also a template: a node referencing a class of another module
365
+ * (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
367
+ * compiled code whenever their tree matches the referenced type's structure.
368
+ *
369
+ * The registry is module-local: classes registered with another copy of this runtime
370
+ * (dual ESM / CJS loads, duplicate installs) and subclasses of registered classes are
371
+ * simply validated by the interpreted pre-check.
372
+ */
373
+ /** Entries by class (own registrations only: a subclass is not registered). */ const entries = /* @__PURE__ */ new WeakMap();
374
+ /** Template bindings by referring node. */ const templates = /* @__PURE__ */ new WeakMap();
375
+ /** Some compiled check is registered (until then lookups return at once). */ let anyCompiled = false;
376
+ /** The option bits of `opts` for a compiled check's `flags` argument. */ function optionFlags(opts) {
377
+ const unknownProps = opts.unknownProps;
378
+ const partial = opts.partial;
379
+ return (unknownProps === "error" ? F_ERROR : unknownProps === "strip" ? F_STRIP : 0) | (partial === "deep" ? F_PARTIAL_DEEP : partial === true ? F_PARTIAL_TOP : 0);
380
+ }
381
+ /**
382
+ * Registers the build-time compiled validator check of a generated class (emitted into
383
+ * `.as.js` by `tsPlugin({ compileValidators: true })`; not meant to be called by hand).
384
+ * A layout of another format version is ignored, so the class stays interpreted.
385
+ */ function registerCompiledCheck(cls, version, layout, factory) {
386
+ if (version !== LAYOUT_VERSION) return;
387
+ entries.set(cls, {
388
+ layout,
389
+ factory,
390
+ epoch: -1,
391
+ fn: null,
392
+ binding: false
393
+ });
394
+ anyCompiled = true;
395
+ }
396
+ let autoCompile = null;
397
+ /** The compiled check to run for `def` in this call, or `null` (interpreted). */ function compiledCheckFor(def, env) {
398
+ if (!anyCompiled) return null;
399
+ let entry = entries.get(def);
400
+ if (entry === void 0) {
401
+ if (autoCompile === null) return null;
402
+ autoCompile(def);
403
+ entry = entries.get(def);
404
+ if (entry === void 0) return null;
405
+ }
406
+ return entry.epoch === currentEpoch() ? entry.fn : bind(entry, entry, def, env, false);
407
+ }
408
+ /** (Re)binds `entry`'s layout against `node` for the current epoch. */ function bind(binding, entry, node, env, template) {
409
+ binding.epoch = currentEpoch();
410
+ binding.fn = null;
411
+ binding.binding = true;
412
+ try {
413
+ const K = bindLayout(entry.layout, node, env, template);
414
+ if (K !== void 0) binding.fn = entry.factory(K, env);
415
+ } catch {} finally {
416
+ binding.binding = false;
417
+ }
418
+ return binding.fn;
419
+ }
420
+ /**
421
+ * Verifies the live tree of `node` against `layout` and collects the K slots; `undefined`
422
+ * when anything differs. A `template` bind (a node referring to the layout's class) leaves
423
+ * the root's `optional` to the referring site.
424
+ */ function bindLayout(layout, node, env, template) {
425
+ const [defs, root, slotCount] = layout;
426
+ const bound = [];
427
+ const K = [];
428
+ K.length = slotCount;
429
+ /** An EXT / INTERP site: its check, then whether its type is a literal. */ const bindRuntimeSite = (n, at, ext) => {
430
+ const type = n.type;
431
+ if (typeof type !== "object" || type === null || isPhantomType(n)) return false;
432
+ watch(n);
433
+ watch(type);
434
+ K[at] = ext ? externalCheck(n, env) : interpreted(n, env);
435
+ K[at + 1] = type.value !== void 0;
436
+ return true;
437
+ };
438
+ const bindSite = (site, n) => {
439
+ const [optional, mask, d, shape, at] = site;
440
+ if (d === INTERP) return bindRuntimeSite(n, at, false);
441
+ if (template && site === root ? optional !== 0 : !!n.optional !== (optional === 1)) return false;
442
+ watch(n);
443
+ const metadata = n.metadata;
444
+ if (!(metadata instanceof AnnotationMap)) return false;
445
+ watch(metadata);
446
+ let k = at;
447
+ if (hasRejectSlot(site)) K[k++] = n;
448
+ if (d === EXT) return readKeys(metadata, siteBits(void 0, optional === 1), env).mask === mask && bindRuntimeSite(n, k, true);
449
+ const type = n.type;
450
+ if (bound[d] === void 0) {
451
+ if (typeof type !== "object" || type === null) return false;
452
+ bound[d] = type;
453
+ if (!bindDef(defs[d], type)) return false;
454
+ } else if (bound[d] !== type) return false;
455
+ const read = readKeys(metadata, siteBits(type, optional === 1), env, K, k);
456
+ return read.mask === mask && read.shape === shape;
457
+ };
458
+ const bindSites = (sites, nodes) => {
459
+ if (!Array.isArray(nodes) || nodes.length !== sites.length) return false;
460
+ for (let i = 0; i < sites.length; i++) if (!bindSite(sites[i], nodes[i])) return false;
461
+ return true;
462
+ };
463
+ const bindDef = (def, type) => {
464
+ watch(type);
465
+ switch (def[0]) {
466
+ case D_FINAL: return type.kind === "" && type.designType === def[1] && (def.length === 2 ? type.value === void 0 : type.value === def[2]);
467
+ case D_OBJECT: {
468
+ const props = type.props;
469
+ if (type.kind !== "object" || !(props instanceof PropsMap) || !Array.isArray(type.propsPatterns) || type.propsPatterns.length > 0) return false;
470
+ watch(props);
471
+ const keys = def[1];
472
+ const sites = def[2];
473
+ if (props.size !== keys.length) return false;
474
+ let i = 0;
475
+ for (const [key, prop] of props) {
476
+ if (key !== keys[i] || !bindSite(sites[i], prop)) return false;
477
+ i++;
478
+ }
479
+ return true;
480
+ }
481
+ case D_OBJECT_PATTERNS: return type.kind === "object" && Array.isArray(type.propsPatterns) && type.propsPatterns.length > 0;
482
+ case D_ARRAY: return type.kind === "array" && bindSite(def[1], type.of);
483
+ case D_UNION:
484
+ case D_INTERSECTION:
485
+ case D_TUPLE: return type.kind === ITEMS_KIND_NAMES[def[0]] && bindSites(def[1], type.items);
486
+ case D_UNKNOWN: return type.kind === def[1];
487
+ default: return false;
488
+ }
489
+ };
490
+ return bindSite(root, node) ? K : void 0;
491
+ }
492
+ /** The interpreted pre-check of `node` (its subtree is read live on every call). */ function interpreted(node, env) {
493
+ const interp = env.interp;
494
+ return (value, flags, opts) => interp(node, value, flags, opts);
495
+ }
496
+ /**
497
+ * The check of a node referencing another module's type (called for a non-nullish value
498
+ * when the node is optional; the referring site handles `optional`): the referenced class's
499
+ * layout bound against the node when it matches, else the interpreted pre-check.
500
+ */ function externalCheck(node, env) {
501
+ const entry = templateOf(node);
502
+ if (entry !== void 0) {
503
+ let binding = templates.get(node);
504
+ if (binding === void 0 || binding.entry !== entry) {
505
+ binding = {
506
+ entry,
507
+ epoch: -1,
508
+ fn: null,
509
+ binding: false
510
+ };
511
+ templates.set(node, binding);
512
+ }
513
+ if (binding.binding) {
514
+ const pending = binding;
515
+ const fallback = interpreted(node, env);
516
+ return (value, flags, opts) => (pending.fn ?? fallback)(value, flags, opts);
517
+ }
518
+ const fn = binding.epoch === currentEpoch() ? binding.fn : bind(binding, entry, node, env, true);
519
+ if (fn !== null) return fn;
520
+ }
521
+ return interpreted(node, env);
522
+ }
523
+ /**
524
+ * The registered class whose layout a referring node binds against: the target of its
525
+ * (unchained) reference, through aliases of other modules' types.
526
+ */ function templateOf(node) {
527
+ let ref = node.ref;
528
+ for (let hops = 0; hops < 16 && ref !== void 0 && ref.field === ""; hops++) {
529
+ let target;
530
+ try {
531
+ target = ref.type();
532
+ } catch {
533
+ return;
534
+ }
535
+ const entry = entries.get(target);
536
+ if (entry === void 0 || entry.layout[1][2] !== EXT) return entry;
537
+ ref = target.ref;
538
+ }
539
+ }
1
540
 
541
+ //#endregion
2
542
  //#region packages/typescript/src/runtime/validator-fast-check.ts
3
543
  function _define_property$1(obj, key, value) {
4
544
  if (key in obj) Object.defineProperty(obj, key, {
@@ -64,7 +604,7 @@ const BAIL = 2;
64
604
  if (opts.unknownProps === "strip") return fastCheckStripping(def, value, opts);
65
605
  stamp++;
66
606
  try {
67
- return fastCheck(def, value, TOP, opts) === PASS;
607
+ return check(def, value, opts) === PASS;
68
608
  } catch {
69
609
  return false;
70
610
  }
@@ -75,7 +615,7 @@ const BAIL = 2;
75
615
  stripping = true;
76
616
  let passed;
77
617
  try {
78
- passed = fastCheck(def, value, TOP, opts) === PASS;
618
+ passed = check(def, value, opts) === PASS;
79
619
  } catch {
80
620
  passed = false;
81
621
  } finally {
@@ -88,6 +628,14 @@ const BAIL = 2;
88
628
  }
89
629
  return passed;
90
630
  }
631
+ /**
632
+ * The pre-check of the root: the type's build-time compiled check when it has one bound to
633
+ * the live tree (see compiled-check/registry.ts), else the interpreted one. Both share the
634
+ * contract above and the strip state.
635
+ */ function check(def, value, opts) {
636
+ const compiled = compiledCheckFor(def, COMPILED_ENV);
637
+ return compiled === null ? fastCheck(def, value, TOP, opts) : compiled(value, TOP | optionFlags(opts), opts);
638
+ }
91
639
  const DECIMAL_RE = /^[+-]?\d+(\.\d+)?$/;
92
640
  const regexCache = /* @__PURE__ */ new Map();
93
641
  /** Compiled `@expect.pattern` regex, cached per (pattern, flags). */ function getRegex(pattern, flags) {
@@ -121,6 +669,14 @@ function acceptsNull(def) {
121
669
  }
122
670
  return false;
123
671
  }
672
+ /** What compiled checks share with the interpreted pre-check. */ const COMPILED_ENV = {
673
+ pk: pendingKeys,
674
+ ho: Object.prototype.hasOwnProperty,
675
+ dec: DECIMAL_RE,
676
+ regex: getRegex,
677
+ interp: fastCheck,
678
+ rn: rejectsNullAsRequired
679
+ };
124
680
  function fastCheck(def, value, flags, opts) {
125
681
  if (def.optional && (value === void 0 || value === null)) return value === null && rejectsNullAsRequired(def) ? FAIL : PASS;
126
682
  const type = def.type;
@@ -469,14 +1025,14 @@ function setMetaKeys(plan, k0, k1, k2, k3, k4) {
469
1025
  if (type.designType === "phantom") plan.op = OP_PHANTOM;
470
1026
  else if (type.value !== void 0) plan.op = OP_FINAL;
471
1027
  else if (type.designType === "string") {
472
- setMetaKeys(plan, "meta.required", "expect.minLength", "expect.maxLength", "expect.pattern");
1028
+ setMetaKeys(plan, ...STRING_KEYS);
473
1029
  plan.regexes = [];
474
1030
  plan.op = OP_STRING;
475
1031
  } else if (type.designType === "number") {
476
- setMetaKeys(plan, "expect.int", "expect.min", "expect.max", "expect.exclusiveMin", "expect.exclusiveMax");
1032
+ setMetaKeys(plan, ...NUMBER_KEYS);
477
1033
  plan.op = OP_NUMBER;
478
1034
  } else if (type.designType === "boolean") {
479
- setMetaKeys(plan, "meta.required");
1035
+ setMetaKeys(plan, ...BOOLEAN_KEYS);
480
1036
  plan.op = OP_BOOLEAN;
481
1037
  } else plan.op = OP_FINAL;
482
1038
  break;
@@ -502,7 +1058,7 @@ function setMetaKeys(plan, k0, k1, k2, k3, k4) {
502
1058
  break;
503
1059
  }
504
1060
  case "array":
505
- setMetaKeys(plan, "expect.minLength", "expect.maxLength", "expect.array.uniqueItems");
1061
+ setMetaKeys(plan, ...ARRAY_KEYS);
506
1062
  plan.of = type.of;
507
1063
  plan.ofPlan = planFor(type.of);
508
1064
  plan.op = OP_ARRAY;
@@ -1212,7 +1768,12 @@ const NON_PRIMITIVE_KINDS = new Set(["array", "object"]);
1212
1768
  /**
1213
1769
  * Creates a minimal annotated type node from a type def and metadata map.
1214
1770
  * Centralises the shape so callers never duplicate the boilerplate.
1215
- */ function createAnnotatedTypeNode(type, metadata, opts) {
1771
+ *
1772
+ * `metadata` is used as-is (the node keeps the caller's map, so later writes through it
1773
+ * apply). When omitted, the node gets a new, tracked metadata map. Compiled validator
1774
+ * checks only bind to nodes whose metadata is tracked; nodes built over a caller-supplied
1775
+ * `Map` are always validated by the interpreted validator.
1776
+ */ function createAnnotatedTypeNode(type, metadata = new AnnotationMap(), opts) {
1216
1777
  return {
1217
1778
  __is_atscript_annotated_type: true,
1218
1779
  type,
@@ -1223,6 +1784,26 @@ const NON_PRIMITIVE_KINDS = new Set(["array", "object"]);
1223
1784
  ref: opts?.ref
1224
1785
  };
1225
1786
  }
1787
+ /** A new tracked metadata map holding `entries` (see {@link createAnnotatedTypeNode}). */ function createMetadataMap(entries) {
1788
+ return new AnnotationMap(entries);
1789
+ }
1790
+ /**
1791
+ * The metadata map `defineAnnotatedType()` installs on `base`: `base.metadata` itself, except
1792
+ * that an absent map or an empty plain `Map` (what a generated class starts with:
1793
+ * `static metadata = new Map()`) is replaced by a new tracked map, so the node can bind to a
1794
+ * compiled validator check. A non-empty map or a `Map` subclass is always kept as-is (its
1795
+ * identity and overrides preserved; such a node stays interpreted).
1796
+ */ function baseMetadata(metadata) {
1797
+ return !metadata || Object.getPrototypeOf(metadata) === Map.prototype && metadata.size === 0 ? createMetadataMap() : metadata;
1798
+ }
1799
+ /** A new object type def (its props map is tracked, see {@link createAnnotatedTypeNode}). */ function createObjectTypeDef(tags = /* @__PURE__ */ new Set(), propsPatterns = []) {
1800
+ return {
1801
+ kind: "object",
1802
+ props: new PropsMap(),
1803
+ propsPatterns,
1804
+ tags
1805
+ };
1806
+ }
1226
1807
  /**
1227
1808
  * Type Guard to check if a type is atscript-annotated
1228
1809
  */ function isAnnotatedType(type) {
@@ -1235,8 +1816,10 @@ const NON_PRIMITIVE_KINDS = new Set(["array", "object"]);
1235
1816
  if (!metadata) return;
1236
1817
  if (asArray) if (metadata.has(key)) {
1237
1818
  const a = metadata.get(key);
1238
- if (Array.isArray(a)) a.push(value);
1239
- else metadata.set(key, [a, value]);
1819
+ if (Array.isArray(a)) {
1820
+ a.push(value);
1821
+ if (isValidatorKey(key)) touched(metadata);
1822
+ } else metadata.set(key, [a, value]);
1240
1823
  } else metadata.set(key, [value]);
1241
1824
  else metadata.set(key, value);
1242
1825
  }
@@ -1248,28 +1831,21 @@ const NON_PRIMITIVE_KINDS = new Set(["array", "object"]);
1248
1831
  const objType = parentType;
1249
1832
  const existing = objType.props.get(propName);
1250
1833
  if (!existing) return;
1251
- const clonedType = cloneTypeDef(existing.type);
1252
- objType.props.set(propName, createAnnotatedTypeNode(clonedType, new Map(existing.metadata), {
1253
- id: existing.id,
1254
- optional: existing.optional,
1255
- ref: existing.ref
1256
- }));
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
+ });
1257
1842
  }
1258
1843
  function cloneTypeDef(type) {
1259
1844
  if (type.kind === "object") {
1260
1845
  const obj = type;
1261
- const props = /* @__PURE__ */ new Map();
1262
- for (const [k, v] of obj.props) props.set(k, createAnnotatedTypeNode(v.type, new Map(v.metadata), {
1263
- id: v.id,
1264
- optional: v.optional,
1265
- ref: v.ref
1266
- }));
1267
- return {
1268
- kind: "object",
1269
- props,
1270
- propsPatterns: [...obj.propsPatterns],
1271
- tags: new Set(obj.tags)
1272
- };
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;
1273
1849
  }
1274
1850
  if (type.kind === "array") {
1275
1851
  const arr = type;
@@ -1314,14 +1890,15 @@ function cloneTypeDef(type) {
1314
1890
  const kind = _kind || "";
1315
1891
  const baseProvided = base !== void 0;
1316
1892
  const type = base?.type || {};
1893
+ touched(type);
1317
1894
  type.kind = kind;
1318
1895
  if (COMPLEX_KINDS.has(kind)) type.items = [];
1319
1896
  if (kind === "object") {
1320
- type.props = /* @__PURE__ */ new Map();
1897
+ type.props = new PropsMap();
1321
1898
  type.propsPatterns = [];
1322
1899
  }
1323
1900
  type.tags = /* @__PURE__ */ new Set();
1324
- const metadata = base?.metadata || /* @__PURE__ */ new Map();
1901
+ const metadata = baseMetadata(base?.metadata);
1325
1902
  const payload = {
1326
1903
  __is_atscript_annotated_type: true,
1327
1904
  metadata,
@@ -1339,18 +1916,22 @@ function cloneTypeDef(type) {
1339
1916
  },
1340
1917
  designType(value) {
1341
1918
  this.$def.designType = value;
1919
+ touched(this.$def);
1342
1920
  return this;
1343
1921
  },
1344
1922
  value(value) {
1345
1923
  this.$def.value = value;
1924
+ touched(this.$def);
1346
1925
  return this;
1347
1926
  },
1348
1927
  of(value) {
1349
1928
  this.$def.of = value;
1929
+ touched(this.$def);
1350
1930
  return this;
1351
1931
  },
1352
1932
  item(value) {
1353
1933
  this.$def.items.push(value);
1934
+ touched(this.$def);
1354
1935
  return this;
1355
1936
  },
1356
1937
  prop(name, value) {
@@ -1362,10 +1943,12 @@ function cloneTypeDef(type) {
1362
1943
  pattern,
1363
1944
  def
1364
1945
  });
1946
+ touched(this.$def);
1365
1947
  return this;
1366
1948
  },
1367
1949
  optional(value = true) {
1368
1950
  this.$type.optional = value;
1951
+ touched(this.$type);
1369
1952
  return this;
1370
1953
  },
1371
1954
  copyMetadata(fromMetadata, ignore) {
@@ -1374,6 +1957,7 @@ function cloneTypeDef(type) {
1374
1957
  },
1375
1958
  refTo(type, chain) {
1376
1959
  const node = this.$type;
1960
+ touched(node);
1377
1961
  const field = chain ? chain.join(".") : "";
1378
1962
  if (isAnnotatedType(type)) {
1379
1963
  let newBase = type;
@@ -1645,18 +2229,18 @@ function cloneTypeDef(type) {
1645
2229
  }
1646
2230
  /** `@expect.minLength` / `maxLength` → `minItems` / `maxItems` on an array schema. */ function applyArrayConstraints(schema, meta) {
1647
2231
  const minLength = meta.get("expect.minLength");
1648
- if (minLength !== void 0) schema.minItems = typeof minLength === "number" ? minLength : minLength.length;
2232
+ if (minLength !== void 0) schema.minItems = boundOf(minLength, "length");
1649
2233
  const maxLength = meta.get("expect.maxLength");
1650
- if (maxLength !== void 0) schema.maxItems = typeof maxLength === "number" ? maxLength : maxLength.length;
2234
+ if (maxLength !== void 0) schema.maxItems = boundOf(maxLength, "length");
1651
2235
  }
1652
2236
  /** String / number constraints on a scalar schema whose `type` is already set. */ function applyScalarConstraints(schema, meta) {
1653
2237
  if (schema.type === "number" && meta.get("expect.int")) schema.type = "integer";
1654
2238
  if (schema.type === "string") {
1655
2239
  if (meta.get("meta.required")) schema.minLength = 1;
1656
2240
  const minLength = meta.get("expect.minLength");
1657
- if (minLength !== void 0) schema.minLength = typeof minLength === "number" ? minLength : minLength.length;
2241
+ if (minLength !== void 0) schema.minLength = boundOf(minLength, "length");
1658
2242
  const maxLength = meta.get("expect.maxLength");
1659
- if (maxLength !== void 0) schema.maxLength = typeof maxLength === "number" ? maxLength : maxLength.length;
2243
+ if (maxLength !== void 0) schema.maxLength = boundOf(maxLength, "length");
1660
2244
  const patterns = meta.get("expect.pattern");
1661
2245
  if (patterns?.length) if (patterns.length === 1) schema.pattern = patterns[0].pattern;
1662
2246
  else schema.allOf = (schema.allOf || []).concat(patterns.map((p) => ({ pattern: p.pattern })));
@@ -1672,9 +2256,6 @@ function cloneTypeDef(type) {
1672
2256
  if (exMax !== void 0) schema.exclusiveMaximum = boundOf(exMax, "exclusiveMaxValue");
1673
2257
  }
1674
2258
  }
1675
- /** A number-bound annotation's value: the bare number, or its `field` in the object form. */ function boundOf(m, field) {
1676
- return typeof m === "number" ? m : m[field];
1677
- }
1678
2259
  const LOWER_BOUNDS = new Set([
1679
2260
  "minimum",
1680
2261
  "exclusiveMinimum",
@@ -1878,87 +2459,4 @@ const UPPER_BOUNDS = new Set([
1878
2459
  }
1879
2460
 
1880
2461
  //#endregion
1881
- Object.defineProperty(exports, 'Validator', {
1882
- enumerable: true,
1883
- get: function () {
1884
- return Validator;
1885
- }
1886
- });
1887
- Object.defineProperty(exports, 'ValidatorError', {
1888
- enumerable: true,
1889
- get: function () {
1890
- return ValidatorError;
1891
- }
1892
- });
1893
- Object.defineProperty(exports, 'annotate', {
1894
- enumerable: true,
1895
- get: function () {
1896
- return annotate;
1897
- }
1898
- });
1899
- Object.defineProperty(exports, 'buildJsonSchema', {
1900
- enumerable: true,
1901
- get: function () {
1902
- return buildJsonSchema;
1903
- }
1904
- });
1905
- Object.defineProperty(exports, 'cloneRefProp', {
1906
- enumerable: true,
1907
- get: function () {
1908
- return cloneRefProp;
1909
- }
1910
- });
1911
- Object.defineProperty(exports, 'createAnnotatedTypeNode', {
1912
- enumerable: true,
1913
- get: function () {
1914
- return createAnnotatedTypeNode;
1915
- }
1916
- });
1917
- Object.defineProperty(exports, 'defineAnnotatedType', {
1918
- enumerable: true,
1919
- get: function () {
1920
- return defineAnnotatedType;
1921
- }
1922
- });
1923
- Object.defineProperty(exports, 'detectDiscriminator', {
1924
- enumerable: true,
1925
- get: function () {
1926
- return detectDiscriminator;
1927
- }
1928
- });
1929
- Object.defineProperty(exports, 'forAnnotatedType', {
1930
- enumerable: true,
1931
- get: function () {
1932
- return forAnnotatedType;
1933
- }
1934
- });
1935
- Object.defineProperty(exports, 'fromJsonSchema', {
1936
- enumerable: true,
1937
- get: function () {
1938
- return fromJsonSchema;
1939
- }
1940
- });
1941
- Object.defineProperty(exports, 'isAnnotatedType', {
1942
- enumerable: true,
1943
- get: function () {
1944
- return isAnnotatedType;
1945
- }
1946
- });
1947
- Object.defineProperty(exports, 'isAnnotatedTypeOfPrimitive', {
1948
- enumerable: true,
1949
- get: function () {
1950
- return isAnnotatedTypeOfPrimitive;
1951
- }
1952
- });
1953
- Object.defineProperty(exports, 'isPhantomType', {
1954
- enumerable: true,
1955
- get: function () {
1956
- return isPhantomType;
1957
- }
1958
- });
1959
- Object.defineProperty(exports, 'mergeJsonSchemas', {
1960
- enumerable: true,
1961
- get: function () {
1962
- return mergeJsonSchemas;
1963
- }
1964
- });
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 };