@atscript/typescript 0.1.108 → 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, {
@@ -24,31 +564,78 @@ function _define_property$1(obj, key, value) {
24
564
  * after a validator was created are always honoured — the same as the full walk.
25
565
  *
26
566
  * Result contract (relative to the full walk over the same node and value):
27
- * - `PASS` — the walk returns `true`, collects no errors and has no side effects.
28
- * - `FAIL` — the walk returns `false`; every node the walk would visit was visited
29
- * here too (so a walk that would throw makes this throw first) and the walk has
30
- * no side effects for this node.
567
+ * - `PASS` — the walk returns `true`, collects no errors and has no side effects other
568
+ * than the strips recorded here (see below).
569
+ * - `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
572
+ * a `FAIL` always ends in the walk, so it may be returned early.
31
573
  * - `BAIL` — not decidable here; the caller must run the full walk.
32
574
  *
33
575
  * Union branches are tried in declared order, continuing past `FAIL` and stopping
34
576
  * at `BAIL`, which keeps union results identical to the walk.
577
+ *
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
586
+ * the value untouched for the walk.
35
587
  */ const FAIL = 0;
36
588
  const PASS = 1;
37
589
  const BAIL = 2;
38
590
  /** Node is at walk depth 0 (only object props / array & tuple items increase depth). */ const TOP = 1;
39
591
  /** Node is inside a union branch — failures must be exhaustive (see contract). */ const IN_UNION = 2;
40
592
  /** Incremented per {@link fastCheckPasses} call; snapshots verified in older calls re-verify. */ let stamp = 0;
593
+ /** A 'strip' {@link fastCheckPasses} call is in progress (the pending strips below are its own). */ let stripping = false;
41
594
  /**
42
- * `true` only when the full walk over `value` is guaranteed to pass with no errors
43
- * and no side effects. Any other outcome (including a throw) means "run the walk".
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 = [];
598
+ /**
599
+ * `true` only when the full walk over `value` is guaranteed to pass with no errors and
600
+ * no side effects other than its 'strip' deletions, which are then performed here, as the
601
+ * walk would. Any other outcome (including a throw) leaves `value` untouched and means
602
+ * "run the walk".
44
603
  */ function fastCheckPasses(def, value, opts) {
604
+ if (opts.unknownProps === "strip") return fastCheckStripping(def, value, opts);
45
605
  stamp++;
46
606
  try {
47
- return fastCheck(def, value, TOP, opts) === PASS;
607
+ return check(def, value, opts) === PASS;
48
608
  } catch {
49
609
  return false;
50
610
  }
51
611
  }
612
+ /** {@link fastCheckPasses} for `unknownProps: 'strip'`: performs the recorded strips on a pass. */ function fastCheckStripping(def, value, opts) {
613
+ if (stripping) return false;
614
+ stamp++;
615
+ stripping = true;
616
+ let passed;
617
+ try {
618
+ passed = check(def, value, opts) === PASS;
619
+ } catch {
620
+ passed = false;
621
+ } finally {
622
+ stripping = false;
623
+ }
624
+ try {
625
+ if (passed) for (const key of pendingKeys) delete value[key];
626
+ } finally {
627
+ pendingKeys.length = 0;
628
+ }
629
+ return passed;
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
+ }
52
639
  const DECIMAL_RE = /^[+-]?\d+(\.\d+)?$/;
53
640
  const regexCache = /* @__PURE__ */ new Map();
54
641
  /** Compiled `@expect.pattern` regex, cached per (pattern, flags). */ function getRegex(pattern, flags) {
@@ -82,6 +669,14 @@ function acceptsNull(def) {
82
669
  }
83
670
  return false;
84
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
+ };
85
680
  function fastCheck(def, value, flags, opts) {
86
681
  if (def.optional && (value === void 0 || value === null)) return value === null && rejectsNullAsRequired(def) ? FAIL : PASS;
87
682
  const type = def.type;
@@ -94,6 +689,7 @@ function fastCheck(def, value, flags, opts) {
94
689
  for (const item of type.items) {
95
690
  const result = fastCheck(item, value, branchFlags, opts);
96
691
  if (result !== FAIL) return unionMatchResult(result, item, def.metadata, value);
692
+ if (pendingKeys.length > 0) return BAIL;
97
693
  }
98
694
  return FAIL;
99
695
  }
@@ -170,15 +766,17 @@ function fastCheckString(metadata, value) {
170
766
  }
171
767
  function fastCheckNumber(metadata, value) {
172
768
  if (metadata.size === 0) return PASS;
173
- return numberConstraints(value, metadata.get("expect.int"), metadata.get("expect.min"), metadata.get("expect.max"));
769
+ return numberConstraints(value, metadata.get("expect.int"), metadata.get("expect.min"), metadata.get("expect.max"), metadata.get("expect.exclusiveMin"), metadata.get("expect.exclusiveMax"));
174
770
  }
175
771
  function booleanConstraints(value, required) {
176
772
  return required && value !== true ? FAIL : PASS;
177
773
  }
178
- function numberConstraints(value, int, min, max) {
774
+ function numberConstraints(value, int, min, max, exMin, exMax) {
179
775
  if (int && value % 1 !== 0) return FAIL;
180
776
  if (min !== void 0 && value < (typeof min === "number" ? min : min.minValue)) return FAIL;
181
777
  if (max !== void 0 && value > (typeof max === "number" ? max : max.maxValue)) return FAIL;
778
+ if (exMin !== void 0 && value <= (typeof exMin === "number" ? exMin : exMin.exclusiveMinValue)) return FAIL;
779
+ if (exMax !== void 0 && value >= (typeof exMax === "number" ? exMax : exMax.exclusiveMaxValue)) return FAIL;
182
780
  return PASS;
183
781
  }
184
782
  /** `@expect.minLength` / `@expect.maxLength` (strings and arrays). */ function lengthFails(length, minLength, maxLength) {
@@ -192,9 +790,12 @@ function fastCheckObject(def, value, flags, opts) {
192
790
  if (typeof value !== "object" || value === null || Array.isArray(value)) return FAIL;
193
791
  const type = def.type;
194
792
  if (type.propsPatterns.length > 0) return BAIL;
793
+ if (pendingKeys.length > 0) return BAIL;
794
+ const unknownProps = opts.unknownProps;
795
+ const inUnion = (flags & IN_UNION) !== 0;
796
+ if (unknownProps === "error" && !inUnion && hasUnknownKey(type.props, value)) return FAIL;
195
797
  const partial = opts.partial;
196
798
  const skipUndefined = partial === "deep" || partial === true && (flags & TOP) !== 0;
197
- const inUnion = (flags & IN_UNION) !== 0;
198
799
  const propFlags = flags & IN_UNION;
199
800
  let result = PASS;
200
801
  for (const [key, item] of type.props) {
@@ -208,16 +809,28 @@ function fastCheckObject(def, value, flags, opts) {
208
809
  }
209
810
  }
210
811
  if (result !== PASS) return result;
211
- const unknownProps = opts.unknownProps;
212
- if (unknownProps === "error" || unknownProps === "strip") {
213
- const props = type.props;
214
- for (const key of Object.keys(value)) {
215
- const known = props.get(key);
216
- if (known === void 0 || isPhantomType(known)) return unknownProps === "error" ? FAIL : BAIL;
217
- }
812
+ if (unknownProps === "strip") return pendStrips(type.props, value, flags);
813
+ return unknownProps === "error" && inUnion && hasUnknownKey(type.props, value) ? FAIL : PASS;
814
+ }
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);
218
823
  }
219
824
  return PASS;
220
825
  }
826
+ /** `true` when `value` has a key the walk treats as unknown. */ function hasUnknownKey(props, value) {
827
+ for (const key of Object.keys(value)) if (isUnknownKey(props, key)) return true;
828
+ return false;
829
+ }
830
+ /** `true` when the walk treats `key` as unknown (no prop, or a phantom one). */ function isUnknownKey(props, key) {
831
+ const known = props.get(key);
832
+ return known === void 0 || isPhantomType(known);
833
+ }
221
834
  function fastCheckArray(def, value, flags, opts) {
222
835
  if (!Array.isArray(value)) return FAIL;
223
836
  const metadata = def.metadata;
@@ -261,7 +874,7 @@ const plans = /* @__PURE__ */ new WeakMap();
261
874
  constructor(def) {
262
875
  _define_property$1(this, "def", void 0);
263
876
  /** Call in which the node structure was last verified (`-1`: must rebuild). */ _define_property$1(this, "stamp", void 0);
264
- /** Call in which the annotation values (`m0`–`m3`) were last verified. */ _define_property$1(this, "metaStamp", void 0);
877
+ /** Call in which the annotation values (`m0`–`m4`) were last verified. */ _define_property$1(this, "metaStamp", void 0);
265
878
  _define_property$1(this, "op", void 0);
266
879
  _define_property$1(this, "type", void 0);
267
880
  _define_property$1(this, "optional", void 0);
@@ -273,15 +886,17 @@ const plans = /* @__PURE__ */ new WeakMap();
273
886
  /**
274
887
  * Annotation keys the node's check reads, and their values (`undefined` when absent):
275
888
  * string `meta.required, expect.minLength, maxLength, pattern`; number `expect.int, min,
276
- * max`; boolean `meta.required`; array `expect.minLength, maxLength, array.uniqueItems`.
889
+ * max, exclusiveMin, exclusiveMax`; boolean `meta.required`; array `expect.minLength, maxLength, array.uniqueItems`.
277
890
  */ _define_property$1(this, "k0", void 0);
278
891
  _define_property$1(this, "k1", void 0);
279
892
  _define_property$1(this, "k2", void 0);
280
893
  _define_property$1(this, "k3", void 0);
894
+ _define_property$1(this, "k4", void 0);
281
895
  _define_property$1(this, "m0", void 0);
282
896
  _define_property$1(this, "m1", void 0);
283
897
  _define_property$1(this, "m2", void 0);
284
898
  _define_property$1(this, "m3", void 0);
899
+ _define_property$1(this, "m4", void 0);
285
900
  _define_property$1(this, "props", void 0);
286
901
  _define_property$1(this, "propsPatterns", void 0);
287
902
  _define_property$1(this, "keys", void 0);
@@ -307,10 +922,12 @@ const plans = /* @__PURE__ */ new WeakMap();
307
922
  this.k1 = void 0;
308
923
  this.k2 = void 0;
309
924
  this.k3 = void 0;
925
+ this.k4 = void 0;
310
926
  this.m0 = void 0;
311
927
  this.m1 = void 0;
312
928
  this.m2 = void 0;
313
929
  this.m3 = void 0;
930
+ this.m4 = void 0;
314
931
  this.props = void 0;
315
932
  this.propsPatterns = void 0;
316
933
  this.keys = EMPTY;
@@ -360,7 +977,7 @@ function planFor(def) {
360
977
  }
361
978
  /** Brings the annotation values up to date (once per call, when a constraint is read). */ function refreshMeta(plan) {
362
979
  const metadata = plan.metadata;
363
- if (!(metadata.size === 0 ? plan.m0 === void 0 && plan.m1 === void 0 && plan.m2 === void 0 && plan.m3 === 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))) snapshotMeta(plan);
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);
364
981
  plan.metaStamp = stamp;
365
982
  }
366
983
  function snapshotMeta(plan) {
@@ -369,12 +986,14 @@ function snapshotMeta(plan) {
369
986
  plan.m1 = metadata.get(plan.k1);
370
987
  plan.m2 = metadata.get(plan.k2);
371
988
  plan.m3 = metadata.get(plan.k3);
989
+ plan.m4 = metadata.get(plan.k4);
372
990
  }
373
- function setMetaKeys(plan, k0, k1, k2, k3) {
991
+ function setMetaKeys(plan, k0, k1, k2, k3, k4) {
374
992
  plan.k0 = k0;
375
993
  plan.k1 = k1;
376
994
  plan.k2 = k2;
377
995
  plan.k3 = k3;
996
+ plan.k4 = k4;
378
997
  snapshotMeta(plan);
379
998
  plan.metaStamp = stamp;
380
999
  }
@@ -400,20 +1019,20 @@ function setMetaKeys(plan, k0, k1, k2, k3) {
400
1019
  plan.of = void 0;
401
1020
  plan.ofPlan = void 0;
402
1021
  plan.items = void 0;
403
- setMetaKeys(plan, void 0, void 0, void 0, void 0);
1022
+ setMetaKeys(plan);
404
1023
  switch (type.kind) {
405
1024
  case "":
406
1025
  if (type.designType === "phantom") plan.op = OP_PHANTOM;
407
1026
  else if (type.value !== void 0) plan.op = OP_FINAL;
408
1027
  else if (type.designType === "string") {
409
- setMetaKeys(plan, "meta.required", "expect.minLength", "expect.maxLength", "expect.pattern");
1028
+ setMetaKeys(plan, ...STRING_KEYS);
410
1029
  plan.regexes = [];
411
1030
  plan.op = OP_STRING;
412
1031
  } else if (type.designType === "number") {
413
- setMetaKeys(plan, "expect.int", "expect.min", "expect.max", void 0);
1032
+ setMetaKeys(plan, ...NUMBER_KEYS);
414
1033
  plan.op = OP_NUMBER;
415
1034
  } else if (type.designType === "boolean") {
416
- setMetaKeys(plan, "meta.required", void 0, void 0, void 0);
1035
+ setMetaKeys(plan, ...BOOLEAN_KEYS);
417
1036
  plan.op = OP_BOOLEAN;
418
1037
  } else plan.op = OP_FINAL;
419
1038
  break;
@@ -439,7 +1058,7 @@ function setMetaKeys(plan, k0, k1, k2, k3) {
439
1058
  break;
440
1059
  }
441
1060
  case "array":
442
- setMetaKeys(plan, "expect.minLength", "expect.maxLength", "expect.array.uniqueItems", void 0);
1061
+ setMetaKeys(plan, ...ARRAY_KEYS);
443
1062
  plan.of = type.of;
444
1063
  plan.ofPlan = planFor(type.of);
445
1064
  plan.op = OP_ARRAY;
@@ -511,7 +1130,7 @@ function setMetaKeys(plan, k0, k1, k2, k3) {
511
1130
  }
512
1131
  /** Plan counterpart of {@link fastCheckNumber}; constraint objects are read live. */ function checkNumber(plan, value) {
513
1132
  if (plan.metaStamp !== stamp) refreshMeta(plan);
514
- return numberConstraints(value, plan.m0, plan.m1, plan.m2);
1133
+ return numberConstraints(value, plan.m0, plan.m1, plan.m2, plan.m3, plan.m4);
515
1134
  }
516
1135
  /** Plan counterpart of {@link fastCheckObject}. */ function checkObject(plan, value, flags, opts) {
517
1136
  if (typeof value !== "object" || value === null || Array.isArray(value)) return FAIL;
@@ -1025,7 +1644,7 @@ function _define_property(obj, key, value) {
1025
1644
  validateNumber(def, value) {
1026
1645
  return this.validateNumberConstraints(def.metadata, value);
1027
1646
  }
1028
- /** `@expect.int` / `min` / `max` checks for a number value. */ validateNumberConstraints(metadata, value) {
1647
+ /** `@expect.int` / `min` / `max` / `exclusiveMin` / `exclusiveMax` checks for a number value. */ validateNumberConstraints(metadata, value) {
1029
1648
  if (metadata.size === 0) return true;
1030
1649
  const int = metadata.get("expect.int");
1031
1650
  if (int && value % 1 !== 0) {
@@ -1036,23 +1655,30 @@ function _define_property(obj, key, value) {
1036
1655
  const min = metadata.get("expect.min");
1037
1656
  if (min !== void 0) {
1038
1657
  const minValue = typeof min === "number" ? min : min.minValue;
1039
- if (value < minValue) {
1040
- const message = typeof min === "object" && min.message ? min.message : `Expected minimum ${minValue}, got ${value}`;
1041
- this.error(message);
1042
- return false;
1043
- }
1658
+ if (value < minValue) return this.numberBoundFailed(min, "minimum", minValue, value);
1044
1659
  }
1045
1660
  const max = metadata.get("expect.max");
1046
1661
  if (max !== void 0) {
1047
1662
  const maxValue = typeof max === "number" ? max : max.maxValue;
1048
- if (value > maxValue) {
1049
- const message = typeof max === "object" && max.message ? max.message : `Expected maximum ${maxValue}, got ${value}`;
1050
- this.error(message);
1051
- return false;
1052
- }
1663
+ if (value > maxValue) return this.numberBoundFailed(max, "maximum", maxValue, value);
1664
+ }
1665
+ const exMin = metadata.get("expect.exclusiveMin");
1666
+ if (exMin !== void 0) {
1667
+ const bound = typeof exMin === "number" ? exMin : exMin.exclusiveMinValue;
1668
+ if (value <= bound) return this.numberBoundFailed(exMin, "greater than", bound, value);
1669
+ }
1670
+ const exMax = metadata.get("expect.exclusiveMax");
1671
+ if (exMax !== void 0) {
1672
+ const bound = typeof exMax === "number" ? exMax : exMax.exclusiveMaxValue;
1673
+ if (value >= bound) return this.numberBoundFailed(exMax, "less than", bound, value);
1053
1674
  }
1054
1675
  return true;
1055
1676
  }
1677
+ /** Reports a failed number bound: its custom message, else `Expected <label> <bound>, got <value>`. */ numberBoundFailed(annotation, label, bound, value) {
1678
+ const message = typeof annotation === "object" && annotation.message ? annotation.message : `Expected ${label} ${bound}, got ${value}`;
1679
+ this.error(message);
1680
+ return false;
1681
+ }
1056
1682
  validateBoolean(def, value) {
1057
1683
  return this.validateBooleanConstraints(def.metadata, value);
1058
1684
  }
@@ -1142,7 +1768,12 @@ const NON_PRIMITIVE_KINDS = new Set(["array", "object"]);
1142
1768
  /**
1143
1769
  * Creates a minimal annotated type node from a type def and metadata map.
1144
1770
  * Centralises the shape so callers never duplicate the boilerplate.
1145
- */ 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) {
1146
1777
  return {
1147
1778
  __is_atscript_annotated_type: true,
1148
1779
  type,
@@ -1153,6 +1784,26 @@ const NON_PRIMITIVE_KINDS = new Set(["array", "object"]);
1153
1784
  ref: opts?.ref
1154
1785
  };
1155
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
+ }
1156
1807
  /**
1157
1808
  * Type Guard to check if a type is atscript-annotated
1158
1809
  */ function isAnnotatedType(type) {
@@ -1165,8 +1816,10 @@ const NON_PRIMITIVE_KINDS = new Set(["array", "object"]);
1165
1816
  if (!metadata) return;
1166
1817
  if (asArray) if (metadata.has(key)) {
1167
1818
  const a = metadata.get(key);
1168
- if (Array.isArray(a)) a.push(value);
1169
- 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]);
1170
1823
  } else metadata.set(key, [value]);
1171
1824
  else metadata.set(key, value);
1172
1825
  }
@@ -1178,28 +1831,21 @@ const NON_PRIMITIVE_KINDS = new Set(["array", "object"]);
1178
1831
  const objType = parentType;
1179
1832
  const existing = objType.props.get(propName);
1180
1833
  if (!existing) return;
1181
- const clonedType = cloneTypeDef(existing.type);
1182
- objType.props.set(propName, createAnnotatedTypeNode(clonedType, new Map(existing.metadata), {
1183
- id: existing.id,
1184
- optional: existing.optional,
1185
- ref: existing.ref
1186
- }));
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
+ });
1187
1842
  }
1188
1843
  function cloneTypeDef(type) {
1189
1844
  if (type.kind === "object") {
1190
1845
  const obj = type;
1191
- const props = /* @__PURE__ */ new Map();
1192
- for (const [k, v] of obj.props) props.set(k, createAnnotatedTypeNode(v.type, new Map(v.metadata), {
1193
- id: v.id,
1194
- optional: v.optional,
1195
- ref: v.ref
1196
- }));
1197
- return {
1198
- kind: "object",
1199
- props,
1200
- propsPatterns: [...obj.propsPatterns],
1201
- tags: new Set(obj.tags)
1202
- };
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;
1203
1849
  }
1204
1850
  if (type.kind === "array") {
1205
1851
  const arr = type;
@@ -1244,14 +1890,15 @@ function cloneTypeDef(type) {
1244
1890
  const kind = _kind || "";
1245
1891
  const baseProvided = base !== void 0;
1246
1892
  const type = base?.type || {};
1893
+ touched(type);
1247
1894
  type.kind = kind;
1248
1895
  if (COMPLEX_KINDS.has(kind)) type.items = [];
1249
1896
  if (kind === "object") {
1250
- type.props = /* @__PURE__ */ new Map();
1897
+ type.props = new PropsMap();
1251
1898
  type.propsPatterns = [];
1252
1899
  }
1253
1900
  type.tags = /* @__PURE__ */ new Set();
1254
- const metadata = base?.metadata || /* @__PURE__ */ new Map();
1901
+ const metadata = baseMetadata(base?.metadata);
1255
1902
  const payload = {
1256
1903
  __is_atscript_annotated_type: true,
1257
1904
  metadata,
@@ -1269,18 +1916,22 @@ function cloneTypeDef(type) {
1269
1916
  },
1270
1917
  designType(value) {
1271
1918
  this.$def.designType = value;
1919
+ touched(this.$def);
1272
1920
  return this;
1273
1921
  },
1274
1922
  value(value) {
1275
1923
  this.$def.value = value;
1924
+ touched(this.$def);
1276
1925
  return this;
1277
1926
  },
1278
1927
  of(value) {
1279
1928
  this.$def.of = value;
1929
+ touched(this.$def);
1280
1930
  return this;
1281
1931
  },
1282
1932
  item(value) {
1283
1933
  this.$def.items.push(value);
1934
+ touched(this.$def);
1284
1935
  return this;
1285
1936
  },
1286
1937
  prop(name, value) {
@@ -1292,10 +1943,12 @@ function cloneTypeDef(type) {
1292
1943
  pattern,
1293
1944
  def
1294
1945
  });
1946
+ touched(this.$def);
1295
1947
  return this;
1296
1948
  },
1297
1949
  optional(value = true) {
1298
1950
  this.$type.optional = value;
1951
+ touched(this.$type);
1299
1952
  return this;
1300
1953
  },
1301
1954
  copyMetadata(fromMetadata, ignore) {
@@ -1304,6 +1957,7 @@ function cloneTypeDef(type) {
1304
1957
  },
1305
1958
  refTo(type, chain) {
1306
1959
  const node = this.$type;
1960
+ touched(node);
1307
1961
  const field = chain ? chain.join(".") : "";
1308
1962
  if (isAnnotatedType(type)) {
1309
1963
  let newBase = type;
@@ -1575,36 +2229,42 @@ function cloneTypeDef(type) {
1575
2229
  }
1576
2230
  /** `@expect.minLength` / `maxLength` → `minItems` / `maxItems` on an array schema. */ function applyArrayConstraints(schema, meta) {
1577
2231
  const minLength = meta.get("expect.minLength");
1578
- if (minLength !== void 0) schema.minItems = typeof minLength === "number" ? minLength : minLength.length;
2232
+ if (minLength !== void 0) schema.minItems = boundOf(minLength, "length");
1579
2233
  const maxLength = meta.get("expect.maxLength");
1580
- if (maxLength !== void 0) schema.maxItems = typeof maxLength === "number" ? maxLength : maxLength.length;
2234
+ if (maxLength !== void 0) schema.maxItems = boundOf(maxLength, "length");
1581
2235
  }
1582
2236
  /** String / number constraints on a scalar schema whose `type` is already set. */ function applyScalarConstraints(schema, meta) {
1583
2237
  if (schema.type === "number" && meta.get("expect.int")) schema.type = "integer";
1584
2238
  if (schema.type === "string") {
1585
2239
  if (meta.get("meta.required")) schema.minLength = 1;
1586
2240
  const minLength = meta.get("expect.minLength");
1587
- if (minLength !== void 0) schema.minLength = typeof minLength === "number" ? minLength : minLength.length;
2241
+ if (minLength !== void 0) schema.minLength = boundOf(minLength, "length");
1588
2242
  const maxLength = meta.get("expect.maxLength");
1589
- if (maxLength !== void 0) schema.maxLength = typeof maxLength === "number" ? maxLength : maxLength.length;
2243
+ if (maxLength !== void 0) schema.maxLength = boundOf(maxLength, "length");
1590
2244
  const patterns = meta.get("expect.pattern");
1591
2245
  if (patterns?.length) if (patterns.length === 1) schema.pattern = patterns[0].pattern;
1592
2246
  else schema.allOf = (schema.allOf || []).concat(patterns.map((p) => ({ pattern: p.pattern })));
1593
2247
  }
1594
2248
  if (schema.type === "number" || schema.type === "integer") {
1595
2249
  const min = meta.get("expect.min");
1596
- if (min !== void 0) schema.minimum = typeof min === "number" ? min : min.minValue;
2250
+ if (min !== void 0) schema.minimum = boundOf(min, "minValue");
1597
2251
  const max = meta.get("expect.max");
1598
- if (max !== void 0) schema.maximum = typeof max === "number" ? max : max.maxValue;
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");
1599
2257
  }
1600
2258
  }
1601
2259
  const LOWER_BOUNDS = new Set([
1602
2260
  "minimum",
2261
+ "exclusiveMinimum",
1603
2262
  "minLength",
1604
2263
  "minItems"
1605
2264
  ]);
1606
2265
  const UPPER_BOUNDS = new Set([
1607
2266
  "maximum",
2267
+ "exclusiveMaximum",
1608
2268
  "maxLength",
1609
2269
  "maxItems"
1610
2270
  ]);
@@ -1744,14 +2404,12 @@ const UPPER_BOUNDS = new Set([
1744
2404
  if (s.type === "integer") {
1745
2405
  const handle = defineAnnotatedType().designType("number").tags("number");
1746
2406
  handle.annotate("expect.int", true);
1747
- if (typeof s.minimum === "number") handle.annotate("expect.min", { minValue: s.minimum });
1748
- if (typeof s.maximum === "number") handle.annotate("expect.max", { maxValue: s.maximum });
2407
+ annotateNumberBounds(handle, s);
1749
2408
  return handle.$type;
1750
2409
  }
1751
2410
  if (s.type === "number") {
1752
2411
  const handle = defineAnnotatedType().designType("number").tags("number");
1753
- if (typeof s.minimum === "number") handle.annotate("expect.min", { minValue: s.minimum });
1754
- if (typeof s.maximum === "number") handle.annotate("expect.max", { maxValue: s.maximum });
2412
+ annotateNumberBounds(handle, s);
1755
2413
  return handle.$type;
1756
2414
  }
1757
2415
  if (s.type === "boolean") return defineAnnotatedType().designType("boolean").tags("boolean").$type;
@@ -1761,6 +2419,18 @@ const UPPER_BOUNDS = new Set([
1761
2419
  return convert(schema);
1762
2420
  }
1763
2421
  /**
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 });
2432
+ }
2433
+ /**
1764
2434
  * Merges multiple annotated types into a combined schema map with shared `$defs`.
1765
2435
  *
1766
2436
  * Each type must have an `id`. The returned `schemas` object contains individual
@@ -1789,87 +2459,4 @@ const UPPER_BOUNDS = new Set([
1789
2459
  }
1790
2460
 
1791
2461
  //#endregion
1792
- Object.defineProperty(exports, 'Validator', {
1793
- enumerable: true,
1794
- get: function () {
1795
- return Validator;
1796
- }
1797
- });
1798
- Object.defineProperty(exports, 'ValidatorError', {
1799
- enumerable: true,
1800
- get: function () {
1801
- return ValidatorError;
1802
- }
1803
- });
1804
- Object.defineProperty(exports, 'annotate', {
1805
- enumerable: true,
1806
- get: function () {
1807
- return annotate;
1808
- }
1809
- });
1810
- Object.defineProperty(exports, 'buildJsonSchema', {
1811
- enumerable: true,
1812
- get: function () {
1813
- return buildJsonSchema;
1814
- }
1815
- });
1816
- Object.defineProperty(exports, 'cloneRefProp', {
1817
- enumerable: true,
1818
- get: function () {
1819
- return cloneRefProp;
1820
- }
1821
- });
1822
- Object.defineProperty(exports, 'createAnnotatedTypeNode', {
1823
- enumerable: true,
1824
- get: function () {
1825
- return createAnnotatedTypeNode;
1826
- }
1827
- });
1828
- Object.defineProperty(exports, 'defineAnnotatedType', {
1829
- enumerable: true,
1830
- get: function () {
1831
- return defineAnnotatedType;
1832
- }
1833
- });
1834
- Object.defineProperty(exports, 'detectDiscriminator', {
1835
- enumerable: true,
1836
- get: function () {
1837
- return detectDiscriminator;
1838
- }
1839
- });
1840
- Object.defineProperty(exports, 'forAnnotatedType', {
1841
- enumerable: true,
1842
- get: function () {
1843
- return forAnnotatedType;
1844
- }
1845
- });
1846
- Object.defineProperty(exports, 'fromJsonSchema', {
1847
- enumerable: true,
1848
- get: function () {
1849
- return fromJsonSchema;
1850
- }
1851
- });
1852
- Object.defineProperty(exports, 'isAnnotatedType', {
1853
- enumerable: true,
1854
- get: function () {
1855
- return isAnnotatedType;
1856
- }
1857
- });
1858
- Object.defineProperty(exports, 'isAnnotatedTypeOfPrimitive', {
1859
- enumerable: true,
1860
- get: function () {
1861
- return isAnnotatedTypeOfPrimitive;
1862
- }
1863
- });
1864
- Object.defineProperty(exports, 'isPhantomType', {
1865
- enumerable: true,
1866
- get: function () {
1867
- return isPhantomType;
1868
- }
1869
- });
1870
- Object.defineProperty(exports, 'mergeJsonSchemas', {
1871
- enumerable: true,
1872
- get: function () {
1873
- return mergeJsonSchemas;
1874
- }
1875
- });
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 };