@atscript/typescript 0.1.110 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/utils.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { Y as invalidateCompiledValidators, a as forAnnotatedType, c as createAnnotatedTypeNode, d as defineAnnotatedType, f as isAnnotatedType, g as ValidatorError, h as Validator, i as mergeJsonSchemas, l as createMetadataMap, m as isPhantomType, n as detectDiscriminator, o as annotate, p as isAnnotatedTypeOfPrimitive, r as fromJsonSchema, s as cloneRefProp, t as buildJsonSchema, u as createObjectTypeDef, v as registerCompiledCheck } from "./json-schema-BG1SEcjI.mjs";
1
+ import { A as statelessRegExp, B as VALIDATOR_KEYS, C as isAnnotatedTypeOfPrimitive, D as ValidatorError, E as Validator, F as watchLayer, H as boundOf, I as invalidateCompiledValidators, L as metadataWriteCount, M as $nr, N as LayerMap, O as registerCompiledCheck, P as metaEmpty, R as touched, S as isAnnotatedType, T as propAtChain, V as arrayKeyProps, _ as annotate, a as $f, b as createObjectTypeDef, c as $ps, d as appliedBlockModules, f as pendingStatements, g as enterCut, h as cutKey, i as $end, j as $ak, k as jsonSchemaPattern, l as $q, m as cutAs, n as $alias, o as $fc, r as $blk, s as $ft, t as uniqueName, u as $sh, v as createAnnotatedTypeNode, w as isPhantomType, x as defineAnnotatedType, y as createMetadataMap, z as DECIMAL_RE } from "./unique-name-hg1CyPIs.mjs";
2
2
 
3
3
  //#region packages/typescript/src/runtime/coerce.ts
4
4
  /**
@@ -53,7 +53,7 @@ import { Y as invalidateCompiledValidators, a as forAnnotatedType, c as createAn
53
53
  return result;
54
54
  }
55
55
  case "object":
56
- if (!isPlainObject(value)) return NO_MATCH;
56
+ if (!isPlainObject$1(value)) return NO_MATCH;
57
57
  return coerceProps(def, value);
58
58
  case "array": return Array.isArray(value) ? coerceItems(value, type.of) : NO_MATCH;
59
59
  case "tuple": {
@@ -150,12 +150,865 @@ function scalar(designType, value) {
150
150
  }
151
151
  return out ?? value;
152
152
  }
153
- function isPlainObject(value) {
153
+ function isPlainObject$1(value) {
154
154
  if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
155
155
  const proto = Object.getPrototypeOf(value);
156
156
  return proto === Object.prototype || proto === null;
157
157
  }
158
158
 
159
+ //#endregion
160
+ //#region packages/typescript/src/runtime/traverse.ts
161
+ /**
162
+ * Type-safe dispatch over `TAtscriptAnnotatedType` by its `type.kind`.
163
+ *
164
+ * Provides the common `switch (def.type.kind)` pattern used by
165
+ * the validator, JSON-schema builder, and serializer.
166
+ * Each caller supplies its own handlers that control recursion.
167
+ *
168
+ * When a `phantom` handler is provided, phantom types (`designType === 'phantom'`)
169
+ * are dispatched to it instead of `final`. This allows consumers to skip or
170
+ * handle phantom props without polluting their `final` handler.
171
+ */ function forAnnotatedType(def, handlers) {
172
+ switch (def.type.kind) {
173
+ case "": {
174
+ const typed = def;
175
+ if (handlers.phantom && typed.type.designType === "phantom") return handlers.phantom(typed);
176
+ return handlers.final(typed);
177
+ }
178
+ case "object": return handlers.object(def);
179
+ case "array": return handlers.array(def);
180
+ case "union": return handlers.union(def);
181
+ case "intersection": return handlers.intersection(def);
182
+ case "tuple": return handlers.tuple(def);
183
+ default: throw new Error(`Unknown type kind "${def.type.kind}"`);
184
+ }
185
+ }
186
+ /**
187
+ * Runs `walk`, and every child walk it yields, on an explicit stack: the depth of the tree costs
188
+ * heap, never the call stack (a 3000-deep chain of types serializes / deserializes / builds its
189
+ * data). A throw ends the whole walk.
190
+ */ function runWalk(walk) {
191
+ const stack = [walk];
192
+ let input;
193
+ for (;;) {
194
+ const step = stack.at(-1).next(input);
195
+ if (step.done) {
196
+ stack.pop();
197
+ if (stack.length === 0) return step.value;
198
+ input = step.value;
199
+ } else {
200
+ stack.push(step.value);
201
+ input = void 0;
202
+ }
203
+ }
204
+ }
205
+
206
+ //#endregion
207
+ //#region packages/typescript/src/runtime/json-schema.ts
208
+ /**
209
+ * Detects a discriminator property across union items.
210
+ *
211
+ * Scans all items for object-typed members that share a common property
212
+ * with distinct const/literal values. If exactly one such property exists,
213
+ * it is returned as the discriminator. Returns `null` when no qualifying
214
+ * property exists, or when more than one does (ambiguous).
215
+ */ function detectDiscriminator(items) {
216
+ if (items.length < 2) return null;
217
+ for (const item of items) if (item.type.kind !== "object") return null;
218
+ const firstObj = items[0].type;
219
+ const candidates = [];
220
+ for (const [propName, propType] of firstObj.props.entries()) if (propType.type.kind === "" && propType.type.value !== void 0) candidates.push(propName);
221
+ let result = null;
222
+ for (const candidate of candidates) {
223
+ const values = /* @__PURE__ */ new Set();
224
+ const indexMapping = {};
225
+ let valid = true;
226
+ for (let i = 0; i < items.length; i++) {
227
+ const prop = items[i].type.props.get(candidate);
228
+ if (!prop || prop.type.kind !== "" || prop.type.value === void 0) {
229
+ valid = false;
230
+ break;
231
+ }
232
+ const val = prop.type.value;
233
+ if (values.has(val)) {
234
+ valid = false;
235
+ break;
236
+ }
237
+ values.add(val);
238
+ indexMapping[String(val)] = i;
239
+ }
240
+ if (valid) {
241
+ if (result) return null;
242
+ result = {
243
+ propertyName: candidate,
244
+ indexMapping
245
+ };
246
+ }
247
+ }
248
+ return result;
249
+ }
250
+ /**
251
+ * Builds a JSON Schema from an {@link TAtscriptAnnotatedType}.
252
+ *
253
+ * Translates the atscript type structure and validation metadata
254
+ * (min/max, patterns, integer constraints, etc.) into a standard JSON Schema.
255
+ *
256
+ * @example
257
+ * ```ts
258
+ * import { buildJsonSchema } from '@atscript/typescript'
259
+ *
260
+ * const schema = buildJsonSchema(MyInterface)
261
+ * // { type: 'object', properties: { ... }, required: [...] }
262
+ * ```
263
+ *
264
+ * @param type - The annotated type to convert.
265
+ * @returns A JSON Schema object.
266
+ */ function buildJsonSchema(type) {
267
+ /**
268
+ * `$defs` entries by type def (identity): named objects (always extracted) and types found
269
+ * recursive (`type Json = string | Json[]`), with the name each asks for (its id). Names are
270
+ * given once all are known (see `nameDefs`), so references are filled in at the end.
271
+ */ const defs = /* @__PURE__ */ new Map();
272
+ /** References to `$defs` entries, filled in by `nameDefs`: `[holder, key, type def]`. */ const refs = [];
273
+ /** A `$ref` to the `$defs` entry of `typeDef`. */ /** The `$ref` schemas (filled in at the end: empty until then). */ const refSchemas = /* @__PURE__ */ new WeakSet();
274
+ const ref = (typeDef) => {
275
+ const schema = {};
276
+ refs.push([
277
+ schema,
278
+ "$ref",
279
+ typeDef
280
+ ]);
281
+ refSchemas.add(schema);
282
+ return schema;
283
+ };
284
+ /**
285
+ * An optional prop's schema: the validator accepts `null` for an optional prop (like a
286
+ * missing one), so its schema accepts `null` too — `type: [t, 'null']` for a schema of one
287
+ * `type` (its other keywords apply to that type only), else `anyOf: [schema, null]`.
288
+ */ const nullable = (schema) => {
289
+ if (acceptsNull(schema, refSchemas)) return schema;
290
+ if (typeof schema.type === "string" && !("const" in schema) && !schema.enum) return {
291
+ ...schema,
292
+ type: [schema.type, "null"]
293
+ };
294
+ if (Object.keys(schema).length === 1 && Array.isArray(schema.anyOf)) return { anyOf: [...schema.anyOf, { type: "null" }] };
295
+ return { anyOf: [schema, { type: "null" }] };
296
+ };
297
+ /**
298
+ * Non-primitive type defs being built: `true` once re-entered (recursive). A named object
299
+ * starts afresh: recursion through it ends at its `$ref`.
300
+ */ let building = /* @__PURE__ */ new Map();
301
+ /**
302
+ * Per type def, a node without metadata standing in for a declaration no reference leads
303
+ * to (see `ownDef`).
304
+ */ const standIns = /* @__PURE__ */ new Map();
305
+ const standIn = (def) => {
306
+ let node = standIns.get(def.type);
307
+ if (!node) {
308
+ node = {
309
+ ...def,
310
+ metadata: /* @__PURE__ */ new Map(),
311
+ optional: void 0
312
+ };
313
+ standIns.set(def.type, node);
314
+ }
315
+ return node;
316
+ };
317
+ /** References being inlined with their own constraints (see `refTo`). */ const inlining = /* @__PURE__ */ new Set();
318
+ /** The types without an id the tree holds in several places (see `sharedDefs`). */ const shared = sharedDefs(type);
319
+ /** Reserves a `$defs` entry for `typeDef`, asking for name `base` (`named`: a type's id). */ const reserve = (typeDef, base, named = false) => {
320
+ defs.set(typeDef, {
321
+ base,
322
+ schema: {},
323
+ named
324
+ });
325
+ return typeDef;
326
+ };
327
+ /**
328
+ * A reference to `$defs[name]`, built from `own` (the type's own metadata, see `ownDef`).
329
+ * A reference whose constraints differ (`@expect.maxLength 3 a: Json`) is inlined with
330
+ * them instead, its recursion referring to the shared definition.
331
+ */ function* refTo(typeDef, def, own) {
332
+ if (def === own || inlining.has(def) || sameConstraints(def, own)) return ref(typeDef);
333
+ inlining.add(def);
334
+ const schema = yield buildDef(def);
335
+ inlining.delete(def);
336
+ return schema;
337
+ }
338
+ function* buildObject(d) {
339
+ const properties = {};
340
+ const required = [];
341
+ for (const [key, val] of d.type.props.entries()) {
342
+ if (isPhantomType(val)) continue;
343
+ if (val.optional) {
344
+ const schema = yield build(val);
345
+ properties[key] = val.metadata.get("meta.required") ? schema : nullable(schema);
346
+ } else {
347
+ properties[key] = yield build(val);
348
+ required.push(key);
349
+ }
350
+ }
351
+ const schema = {
352
+ type: "object",
353
+ properties
354
+ };
355
+ if (required.length > 0) schema.required = required;
356
+ const patterns = d.type.propsPatterns;
357
+ if (patterns.length > 0) {
358
+ const built = [];
359
+ for (const p of patterns) built.push([p.pattern, yield build(p.def)]);
360
+ schema.patternProperties = patternProperties(built, Object.keys(properties));
361
+ }
362
+ return schema;
363
+ }
364
+ /** Whether the root is being built (its own node met again below it is a reference). */ let rootEntered = false;
365
+ /** The schema of `def` (an explicit-stack walk, see `runWalk`: no recursion per level). */ function* build(def) {
366
+ const typeDef = def.type;
367
+ if (typeDef.kind === "") return yield buildDef(def);
368
+ const atRoot = def === type && !rootEntered;
369
+ rootEntered = true;
370
+ if (def.id && typeDef.kind === "object" && !atRoot) {
371
+ if (!defs.has(typeDef)) {
372
+ reserve(typeDef, def.id, true);
373
+ const outer = building;
374
+ building = /* @__PURE__ */ new Map();
375
+ defs.get(typeDef).schema = yield buildObject(def);
376
+ building = outer;
377
+ }
378
+ return ref(typeDef);
379
+ }
380
+ if (defs.has(typeDef)) return yield refTo(typeDef, def, shared.get(typeDef)?.first ?? ownOf(def));
381
+ const repeated = atRoot ? void 0 : shared.get(typeDef);
382
+ if (repeated && repeated.count > 1) {
383
+ reserve(typeDef, repeated.key);
384
+ const outer = building;
385
+ building = /* @__PURE__ */ new Map();
386
+ inlining.add(repeated.first);
387
+ defs.get(typeDef).schema = yield buildDef(repeated.first);
388
+ inlining.delete(repeated.first);
389
+ building = outer;
390
+ return yield refTo(typeDef, def, repeated.first);
391
+ }
392
+ if (building.has(typeDef)) {
393
+ building.set(typeDef, true);
394
+ const own = ownOf(def);
395
+ return yield refTo(reserve(typeDef, own.id ?? "Recursive", own.id !== void 0), def, own);
396
+ }
397
+ building.set(typeDef, false);
398
+ inlining.add(def);
399
+ const schema = yield buildDef(def);
400
+ inlining.delete(def);
401
+ const recursive = building.get(typeDef);
402
+ building.delete(typeDef);
403
+ if (!recursive) return schema;
404
+ const own = ownOf(def);
405
+ const same = def === own || sameConstraints(def, own);
406
+ defs.get(typeDef).schema = same ? schema : yield buildDef(own);
407
+ return def === type || !same ? schema : ref(typeDef);
408
+ }
409
+ /** The node carrying `def`'s type's own metadata (see `ownDef`), memoized per node. */ const owners = /* @__PURE__ */ new Map();
410
+ const ownOf = (def) => {
411
+ let own = owners.get(def);
412
+ if (!own) {
413
+ own = ownDef(def, type) ?? standIn(def);
414
+ owners.set(def, own);
415
+ }
416
+ return own;
417
+ };
418
+ /** The schema of `def`'s own type (see {@link build}). */ function* buildDef(def) {
419
+ const meta = def.metadata;
420
+ const all = function* (items) {
421
+ const out = [];
422
+ for (const item of items) out.push(yield build(item));
423
+ return out;
424
+ };
425
+ const kind = def.type.kind;
426
+ if (kind === "object") return yield buildObject(def);
427
+ if (kind === "array") {
428
+ const d = def;
429
+ const schema = {
430
+ type: "array",
431
+ items: yield build(d.type.of)
432
+ };
433
+ applyArrayConstraints(schema, meta, d.type.of);
434
+ return schema;
435
+ }
436
+ if (kind === "union" || kind === "intersection" || kind === "tuple") {
437
+ const items = def.type.items;
438
+ const built = yield all(items);
439
+ if (kind === "intersection") return { allOf: built };
440
+ if (kind === "tuple") return {
441
+ type: "array",
442
+ items: built,
443
+ additionalItems: false,
444
+ minItems: items.length,
445
+ maxItems: items.length
446
+ };
447
+ const disc = detectDiscriminator(items);
448
+ if (disc) {
449
+ const mapping = {};
450
+ for (const [val, idx] of Object.entries(disc.indexMapping)) {
451
+ const itemType = items[idx].type;
452
+ if (defs.has(itemType)) refs.push([
453
+ mapping,
454
+ val,
455
+ itemType
456
+ ]);
457
+ else mapping[val] = `#/oneOf/${idx}`;
458
+ }
459
+ return {
460
+ oneOf: built,
461
+ discriminator: {
462
+ propertyName: disc.propertyName,
463
+ mapping
464
+ }
465
+ };
466
+ }
467
+ if (!metaEmpty(meta)) applyUnionConstraints(built, meta, items);
468
+ return { anyOf: built };
469
+ }
470
+ return forAnnotatedType(def, {
471
+ phantom() {
472
+ return {};
473
+ },
474
+ final(d) {
475
+ if (d.type.designType === "never") return { not: {} };
476
+ const schema = {};
477
+ if (d.type.value !== void 0) schema.const = d.type.value;
478
+ if (d.type.designType && d.type.designType !== "any") {
479
+ const dt = d.type.designType;
480
+ schema.type = dt === "undefined" ? "null" : dt === "decimal" ? "string" : dt;
481
+ }
482
+ if (d.type.designType === "decimal" && d.type.value === void 0) schema.pattern = DECIMAL_RE.source;
483
+ applyScalarConstraints(schema, meta);
484
+ return schema;
485
+ },
486
+ object: unreachable,
487
+ array: unreachable,
488
+ union: unreachable,
489
+ intersection: unreachable,
490
+ tuple: unreachable
491
+ });
492
+ }
493
+ const schema = runWalk(build(type));
494
+ if (defs.size === 0) return schema;
495
+ const same = sameDefs(defs, refs);
496
+ for (const typeDef of defs.keys()) if (same.get(typeDef) !== typeDef) defs.delete(typeDef);
497
+ const names = nameDefs(defs);
498
+ for (const [holder, key, typeDef] of refs) holder[key] = `#/$defs/${names.get(same.get(typeDef))}`;
499
+ return {
500
+ ...schema,
501
+ $defs: Object.fromEntries([...defs].map(([typeDef, d]) => [names.get(typeDef), d.schema]))
502
+ };
503
+ }
504
+ /**
505
+ * The `$defs` entry each one is the same as (itself, or an earlier one): entries without a name
506
+ * of their own (a merge reached at several places, a recursion of types without an id) whose
507
+ * schemas are the same once their references are — the coarsest such partition (refined from
508
+ * one class until stable), so a recursion written out at several places is one entry. A named
509
+ * entry is only itself. `refs` are the references the schemas hold (filled in afterwards).
510
+ */ function sameDefs(defs, refs) {
511
+ const entries = [...defs.keys()];
512
+ const index = new Map(entries.map((typeDef, i) => [typeDef, i]));
513
+ /** The references each holder holds, by key: their entries' numbers. */ const held = /* @__PURE__ */ new Map();
514
+ for (const [holder, key, typeDef] of refs) {
515
+ let keys = held.get(holder);
516
+ if (!keys) {
517
+ keys = /* @__PURE__ */ new Map();
518
+ held.set(holder, keys);
519
+ }
520
+ keys.set(key, index.get(typeDef));
521
+ }
522
+ let classes = entries.map((typeDef, i) => defs.get(typeDef).named ? i + 1 : 0);
523
+ const targets = entries.map(() => []);
524
+ const texts = entries.map((typeDef, i) => JSON.stringify(defs.get(typeDef).schema, (key, value) => {
525
+ if (!value || typeof value !== "object") return value;
526
+ if (Array.isArray(value)) return key === "required" ? [...value].sort() : value;
527
+ const keys = held.get(value);
528
+ const out = keys ? {
529
+ ...value,
530
+ "\0": [...keys.keys()]
531
+ } : value;
532
+ if (keys) targets[i].push(...keys.values());
533
+ return Object.fromEntries(Object.keys(out).sort().map((k) => [k, out[k]]));
534
+ }));
535
+ const textIds = /* @__PURE__ */ new Map();
536
+ const shapes = texts.map((text) => {
537
+ let id = textIds.get(text);
538
+ if (id === void 0) {
539
+ id = textIds.size;
540
+ textIds.set(text, id);
541
+ }
542
+ return id;
543
+ });
544
+ const signature = (i) => `${classes[i]}:${shapes[i]}:${targets[i].map((j) => classes[j]).join(",")}`;
545
+ for (let count = new Set(classes).size;;) {
546
+ const signatures = /* @__PURE__ */ new Map();
547
+ classes = entries.map((_, i) => {
548
+ const s = signature(i);
549
+ let c = signatures.get(s);
550
+ if (c === void 0) {
551
+ c = signatures.size;
552
+ signatures.set(s, c);
553
+ }
554
+ return c;
555
+ });
556
+ if (signatures.size === count) break;
557
+ count = signatures.size;
558
+ }
559
+ const first = /* @__PURE__ */ new Map();
560
+ const out = /* @__PURE__ */ new Map();
561
+ entries.forEach((typeDef, i) => {
562
+ if (!first.has(classes[i])) first.set(classes[i], typeDef);
563
+ out.set(typeDef, first.get(classes[i]));
564
+ });
565
+ return out;
566
+ }
567
+ /**
568
+ * `$defs` names: the name each entry asks for, unless an earlier entry asks for it too — then
569
+ * the first free `<name>_<n>` that no entry asks for (a type named `Helper_1` keeps its name).
570
+ */ function nameDefs(defs) {
571
+ const asked = new Set([...defs.values()].map((d) => d.base));
572
+ const taken = /* @__PURE__ */ new Set();
573
+ const names = /* @__PURE__ */ new Map();
574
+ for (const [typeDef, { base }] of defs) {
575
+ const name = uniqueName(base, (n) => taken.has(n) || n !== base && asked.has(n), "_");
576
+ taken.add(name);
577
+ names.set(typeDef, name);
578
+ }
579
+ return names;
580
+ }
581
+ /**
582
+ * The node carrying a type's own metadata: following references (a chained one through the
583
+ * props it names) to the declaration that shares the type def — a reference also carries its
584
+ * own annotations. `def` itself for the root; `undefined` when `def` is a use whose declaration
585
+ * is unknown (no `ref`, e.g. a deserialized type): its metadata may be the use's own.
586
+ */ function ownDef(def, root) {
587
+ if (def === root) return def;
588
+ let own = def;
589
+ for (const seen = /* @__PURE__ */ new Set(); own !== root && own.ref && !seen.has(own);) {
590
+ seen.add(own);
591
+ const ref = own.ref.type();
592
+ const target = isAnnotatedType(ref) ? propAtChain(ref, own.ref.field ? own.ref.field.split(".") : []) : void 0;
593
+ if (!isAnnotatedType(target) || target.type !== def.type) break;
594
+ own = target;
595
+ }
596
+ return own === def && !def.ref ? void 0 : own;
597
+ }
598
+ /**
599
+ * The non-primitive types without an id `root`'s tree holds in more than one place (by type
600
+ * def), with the first node holding each and the prop it was found under (the `$defs` name it
601
+ * asks for). Named objects are extracted anyway (their bodies counted once).
602
+ */ function sharedDefs(root) {
603
+ const out = /* @__PURE__ */ new Map();
604
+ const walked = /* @__PURE__ */ new Set();
605
+ /** The types being walked (a type met again among them is recursive: named so). */ const walking = /* @__PURE__ */ new Set();
606
+ /** Pending visits, last first (`leave`: a type's children are done). */ const stack = [{
607
+ node: root,
608
+ key: "Shared"
609
+ }];
610
+ for (let step = stack.pop(); step; step = stack.pop()) {
611
+ if ("leave" in step) {
612
+ walking.delete(step.leave);
613
+ continue;
614
+ }
615
+ const { node, key } = step;
616
+ const type = node?.type;
617
+ if (!node || !type || type.kind === "") continue;
618
+ if (!node.id && node !== root) {
619
+ const known = out.get(type);
620
+ if (known) {
621
+ known.count++;
622
+ if (walking.has(type)) known.key = "Recursive";
623
+ continue;
624
+ }
625
+ out.set(type, {
626
+ count: 1,
627
+ first: node,
628
+ key
629
+ });
630
+ }
631
+ if (walked.has(type)) continue;
632
+ walked.add(type);
633
+ walking.add(type);
634
+ const children = [];
635
+ if (type.kind === "object") {
636
+ for (const [k, prop] of type.props) children.push({
637
+ node: prop,
638
+ key: k
639
+ });
640
+ for (const { def } of type.propsPatterns) children.push({
641
+ node: def,
642
+ key
643
+ });
644
+ } else if (type.kind === "array") children.push({
645
+ node: type.of,
646
+ key
647
+ });
648
+ else for (const item of type.items) children.push({
649
+ node: item,
650
+ key
651
+ });
652
+ stack.push({ leave: type });
653
+ for (let c = children.length - 1; c >= 0; c--) stack.push(children[c]);
654
+ }
655
+ return out;
656
+ }
657
+ /** A `forAnnotatedType` handler for kinds handled before it. */ function unreachable() {
658
+ throw new Error("unreachable");
659
+ }
660
+ function withoutUniqueItems(meta) {
661
+ if (!meta.get("expect.array.uniqueItems")) return meta;
662
+ const copy = new Map(meta);
663
+ copy.delete("expect.array.uniqueItems");
664
+ return copy;
665
+ }
666
+ /**
667
+ * The `patternProperties` of an object's pattern props (`[/^k/]: T`): the validator checks a key
668
+ * against them when the object declares no prop of that name, so each pattern excludes the
669
+ * declared names (`^(?!(?:a|b)$)[\s\S]*?(?:pattern)`); a pattern written twice accepts what
670
+ * either prop accepts. (A key matching several different patterns passes one of them in the
671
+ * validator, all of them in JSON Schema: see the JSON Schema guide.)
672
+ */ function patternProperties(patterns, declared) {
673
+ const exclude = declared.length > 0 ? `^(?!(?:${declared.map((n) => n.replaceAll(/[\\^$.*+?()[\]{}|/]/g, "\\$&")).join("|")})$)[\\s\\S]*?` : "";
674
+ const out = {};
675
+ for (const [regex, schema] of patterns) {
676
+ const pattern = jsonSchemaPattern(regex.source, regex.flags);
677
+ const key = exclude ? `${exclude}(?:${pattern})` : pattern;
678
+ const taken = out[key];
679
+ out[key] = taken ? { anyOf: [...Object.keys(taken).length === 1 && taken.anyOf ? taken.anyOf : [taken], schema] } : schema;
680
+ }
681
+ return out;
682
+ }
683
+ /** Whether `schema` accepts `null` as it is (`{}`, a `null` type or value, a union with one). */ function acceptsNull(schema, refs) {
684
+ if (refs.has(schema)) return false;
685
+ if (Object.keys(schema).length === 0) return true;
686
+ if ("const" in schema) return schema.const === null;
687
+ if (schema.enum) return schema.enum.includes(null);
688
+ if (schema.type !== void 0) return schema.type === "null" || Array.isArray(schema.type) && schema.type.includes("null");
689
+ return Array.isArray(schema.anyOf) && schema.anyOf.some((s) => acceptsNull(s, refs));
690
+ }
691
+ /** `a` and `b` carry the same schema constraints. */ function sameConstraints(a, b) {
692
+ return a.metadata === b.metadata || VALIDATOR_KEYS.every((key) => {
693
+ const x = a.metadata.get(key);
694
+ const y = b.metadata.get(key);
695
+ return x === y || JSON.stringify(x) === JSON.stringify(y);
696
+ });
697
+ }
698
+ /**
699
+ * `@expect.minLength` / `maxLength` → `minItems` / `maxItems` on an array schema, and
700
+ * `@expect.array.uniqueItems` → `uniqueItems` unless the items are objects with
701
+ * `@expect.array.key` props (unique by those props: JSON Schema compares whole items).
702
+ */ function applyArrayConstraints(schema, meta, of) {
703
+ if (meta.get("expect.array.uniqueItems") && arrayKeyProps(of).length === 0) schema.uniqueItems = true;
704
+ const minLength = meta.get("expect.minLength");
705
+ if (minLength !== void 0) schema.minItems = boundOf(minLength, "length");
706
+ const maxLength = meta.get("expect.maxLength");
707
+ if (maxLength !== void 0) schema.maxItems = boundOf(maxLength, "length");
708
+ }
709
+ /** String / number constraints on a scalar schema whose `type` is already set. */ function applyScalarConstraints(schema, meta) {
710
+ if (schema.type === "number" && meta.get("expect.int")) schema.type = "integer";
711
+ if (schema.type === "string") {
712
+ if (meta.get("meta.required")) schema.minLength = 1;
713
+ const minLength = meta.get("expect.minLength");
714
+ if (minLength !== void 0) schema.minLength = boundOf(minLength, "length");
715
+ const maxLength = meta.get("expect.maxLength");
716
+ if (maxLength !== void 0) schema.maxLength = boundOf(maxLength, "length");
717
+ const patterns = (meta.get("expect.pattern") ?? []).map((p) => jsonSchemaPattern(p.pattern, p.flags));
718
+ if (meta.get("meta.required")) patterns.push("\\S");
719
+ if (schema.pattern !== void 0) {
720
+ patterns.unshift(schema.pattern);
721
+ delete schema.pattern;
722
+ }
723
+ if (patterns.length === 1 && !schema.allOf) schema.pattern = patterns[0];
724
+ else if (patterns.length > 0) schema.allOf = (schema.allOf || []).concat(patterns.map((pattern) => ({ pattern })));
725
+ }
726
+ if (schema.type === "boolean" && meta.get("meta.required")) schema.const = true;
727
+ if (schema.type === "number" || schema.type === "integer") {
728
+ const min = meta.get("expect.min");
729
+ if (min !== void 0) schema.minimum = boundOf(min, "minValue");
730
+ const max = meta.get("expect.max");
731
+ if (max !== void 0) schema.maximum = boundOf(max, "maxValue");
732
+ const exMin = meta.get("expect.exclusiveMin");
733
+ if (exMin !== void 0) schema.exclusiveMinimum = boundOf(exMin, "exclusiveMinValue");
734
+ const exMax = meta.get("expect.exclusiveMax");
735
+ if (exMax !== void 0) schema.exclusiveMaximum = boundOf(exMax, "exclusiveMaxValue");
736
+ }
737
+ }
738
+ const LOWER_BOUNDS = new Set([
739
+ "minimum",
740
+ "exclusiveMinimum",
741
+ "minLength",
742
+ "minItems"
743
+ ]);
744
+ const UPPER_BOUNDS = new Set([
745
+ "maximum",
746
+ "exclusiveMaximum",
747
+ "maxLength",
748
+ "maxItems"
749
+ ]);
750
+ /**
751
+ * Puts union-level constraints onto the matching `anyOf` members (numbers, strings,
752
+ * arrays; nested `anyOf` members recursively). When a member already has the same
753
+ * bound, the stricter one wins; patterns accumulate.
754
+ */ function applyUnionConstraints(members, meta, types) {
755
+ for (const [i, member] of members.entries()) {
756
+ const memberType = types?.[i];
757
+ if (Array.isArray(member.anyOf)) {
758
+ applyUnionConstraints(member.anyOf, meta, memberType?.type.kind === "union" ? memberType.type.items : void 0);
759
+ continue;
760
+ }
761
+ if (member.const !== void 0) continue;
762
+ const type = member.type;
763
+ const extra = { type };
764
+ if (type === "array") {
765
+ const of = memberType?.type.kind === "array" ? memberType.type.of : void 0;
766
+ applyArrayConstraints(extra, of ? meta : withoutUniqueItems(meta), of);
767
+ } else if (type === "string" || type === "number" || type === "integer") applyScalarConstraints(extra, meta);
768
+ else continue;
769
+ if (extra.type === "integer") member.type = "integer";
770
+ for (const [key, value] of Object.entries(extra)) {
771
+ if (key === "type") continue;
772
+ if (key === "pattern" || key === "allOf") {
773
+ const patterns = key === "pattern" ? [{ pattern: value }] : value;
774
+ if (member.pattern === void 0 && key === "pattern" && !member.allOf) member.pattern = value;
775
+ else member.allOf = (member.allOf || []).concat(patterns);
776
+ } else if (member[key] === void 0) member[key] = value;
777
+ else if (LOWER_BOUNDS.has(key)) member[key] = Math.max(member[key], value);
778
+ else if (UPPER_BOUNDS.has(key)) member[key] = Math.min(member[key], value);
779
+ }
780
+ }
781
+ }
782
+ /**
783
+ * Converts a JSON Schema object into a {@link TAtscriptAnnotatedType}.
784
+ *
785
+ * This is the inverse of {@link buildJsonSchema}. A round-trip
786
+ * `buildJsonSchema(fromJsonSchema(schema))` preserves structure and constraints.
787
+ *
788
+ * Supports the JSON Schema subset produced by `buildJsonSchema` plus
789
+ * common extensions like `oneOf` (treated as union) and `enum` (union of literals).
790
+ *
791
+ * @example
792
+ * ```ts
793
+ * import { fromJsonSchema } from '@atscript/typescript'
794
+ *
795
+ * const type = fromJsonSchema({ type: 'object', properties: { name: { type: 'string' } }, required: ['name'] })
796
+ * type.validator().validate({ name: 'Alice' }) // passes
797
+ * ```
798
+ *
799
+ * @param schema - A JSON Schema object.
800
+ * @returns An annotated type with full validator support.
801
+ */ function fromJsonSchema(schema) {
802
+ const defsSource = schema.$defs || schema.definitions || {};
803
+ const resolved = /* @__PURE__ */ new Map();
804
+ const convert = (s) => {
805
+ if (!s || Object.keys(s).length === 0) return defineAnnotatedType().designType("any").$type;
806
+ if (s.$ref) {
807
+ const refName = s.$ref.replace(/^#\/(\$defs|definitions)\//, "");
808
+ if (resolved.has(refName)) return resolved.get(refName);
809
+ if (defsSource[refName]) {
810
+ const placeholder = defineAnnotatedType().designType("any").$type;
811
+ resolved.set(refName, placeholder);
812
+ const type = convert(defsSource[refName]);
813
+ resolved.set(refName, type);
814
+ return type;
815
+ }
816
+ throw new Error(`Unresolvable $ref: ${s.$ref}`);
817
+ }
818
+ if ("const" in s) {
819
+ const val = s.const;
820
+ const dt = val === null ? "null" : typeof val;
821
+ return defineAnnotatedType().designType(dt).value(val).$type;
822
+ }
823
+ if (s.enum) {
824
+ const handle = defineAnnotatedType("union");
825
+ for (const val of s.enum) {
826
+ const dt = val === null ? "null" : typeof val;
827
+ handle.item(defineAnnotatedType().designType(dt).value(val).$type);
828
+ }
829
+ return handle.$type;
830
+ }
831
+ if (s.anyOf) {
832
+ const handle = defineAnnotatedType("union");
833
+ for (const item of s.anyOf) handle.item(convert(item));
834
+ return handle.$type;
835
+ }
836
+ if (s.oneOf) {
837
+ const handle = defineAnnotatedType("union");
838
+ for (const item of s.oneOf) handle.item(convert(item));
839
+ return handle.$type;
840
+ }
841
+ if (s.allOf && !s.type) {
842
+ const handle = defineAnnotatedType("intersection");
843
+ for (const item of s.allOf) handle.item(convert(item));
844
+ return handle.$type;
845
+ }
846
+ if (Array.isArray(s.type)) {
847
+ const handle = defineAnnotatedType("union");
848
+ for (const t of s.type) handle.item(convert({
849
+ ...s,
850
+ type: t
851
+ }));
852
+ return handle.$type;
853
+ }
854
+ if (s.type === "object") {
855
+ const handle = defineAnnotatedType("object");
856
+ const required = new Set(s.required || []);
857
+ if (s.properties) for (const [key, propSchema] of Object.entries(s.properties)) {
858
+ const optional = !required.has(key);
859
+ const propType = convert(optional ? withoutNullType(propSchema) : propSchema);
860
+ if (optional) propType.optional = true;
861
+ handle.prop(key, propType);
862
+ }
863
+ for (const [pattern, propSchema] of Object.entries(s.patternProperties ?? {})) handle.propPattern(compilePattern(pattern), convert(propSchema));
864
+ return handle.$type;
865
+ }
866
+ if (s.type === "array") {
867
+ if (Array.isArray(s.items)) {
868
+ const handle = defineAnnotatedType("tuple");
869
+ for (const item of s.items) handle.item(convert(item));
870
+ return handle.$type;
871
+ }
872
+ const itemType = s.items ? convert(s.items) : defineAnnotatedType().designType("any").$type;
873
+ const handle = defineAnnotatedType("array").of(itemType);
874
+ if (typeof s.minItems === "number") handle.annotate("expect.minLength", { length: s.minItems });
875
+ if (typeof s.maxItems === "number") handle.annotate("expect.maxLength", { length: s.maxItems });
876
+ return handle.$type;
877
+ }
878
+ if (s.type === "string") {
879
+ const handle = defineAnnotatedType().designType("string").tags("string");
880
+ if (typeof s.minLength === "number") handle.annotate("expect.minLength", { length: s.minLength });
881
+ if (typeof s.maxLength === "number") handle.annotate("expect.maxLength", { length: s.maxLength });
882
+ if (s.pattern) handle.annotate("expect.pattern", { pattern: s.pattern }, true);
883
+ if (s.allOf) {
884
+ for (const item of s.allOf) if (item.pattern) handle.annotate("expect.pattern", { pattern: item.pattern }, true);
885
+ }
886
+ return handle.$type;
887
+ }
888
+ if (s.type === "integer") {
889
+ const handle = defineAnnotatedType().designType("number").tags("number");
890
+ handle.annotate("expect.int", true);
891
+ annotateNumberBounds(handle, s);
892
+ return handle.$type;
893
+ }
894
+ if (s.type === "number") {
895
+ const handle = defineAnnotatedType().designType("number").tags("number");
896
+ annotateNumberBounds(handle, s);
897
+ return handle.$type;
898
+ }
899
+ if (s.type === "boolean") return defineAnnotatedType().designType("boolean").tags("boolean").$type;
900
+ if (s.type === "null") return defineAnnotatedType().designType("null").tags("null").$type;
901
+ return defineAnnotatedType().designType("any").$type;
902
+ };
903
+ return convert(schema);
904
+ }
905
+ /** A JSON Schema pattern as a regex (compiled with `u`, like ajv; without when it must). */ function compilePattern(pattern) {
906
+ try {
907
+ return new RegExp(pattern, "u");
908
+ } catch {
909
+ return new RegExp(pattern);
910
+ }
911
+ }
912
+ /**
913
+ * An optional prop's schema without the `null` its `type` lists (`buildJsonSchema` adds it: an
914
+ * optional prop passes `null`), so the prop round-trips as `p?: T`.
915
+ */ function withoutNullType(s) {
916
+ if (!Array.isArray(s.type) || !s.type.includes("null") || s.type.length < 2) return s;
917
+ const types = s.type.filter((t) => t !== "null");
918
+ return {
919
+ ...s,
920
+ type: types.length === 1 ? types[0] : types
921
+ };
922
+ }
923
+ /**
924
+ * Maps `minimum` / `maximum` / `exclusiveMinimum` / `exclusiveMaximum` onto
925
+ * `@expect.min` / `max` / `exclusiveMin` / `exclusiveMax`. Also reads the draft-4 form,
926
+ * where `exclusiveMinimum: true` makes `minimum` exclusive.
927
+ */ function annotateNumberBounds(handle, s) {
928
+ if (typeof s.minimum === "number") if (s.exclusiveMinimum === true) handle.annotate("expect.exclusiveMin", { exclusiveMinValue: s.minimum });
929
+ else handle.annotate("expect.min", { minValue: s.minimum });
930
+ if (typeof s.maximum === "number") if (s.exclusiveMaximum === true) handle.annotate("expect.exclusiveMax", { exclusiveMaxValue: s.maximum });
931
+ else handle.annotate("expect.max", { maxValue: s.maximum });
932
+ if (typeof s.exclusiveMinimum === "number") handle.annotate("expect.exclusiveMin", { exclusiveMinValue: s.exclusiveMinimum });
933
+ if (typeof s.exclusiveMaximum === "number") handle.annotate("expect.exclusiveMax", { exclusiveMaxValue: s.exclusiveMaximum });
934
+ }
935
+ /**
936
+ * Merges multiple annotated types into a combined schema map with shared `$defs`.
937
+ *
938
+ * Each type must have an `id`. The returned `schemas` object contains individual
939
+ * schemas keyed by type id, and `$defs` contains all shared type definitions
940
+ * deduplicated across schemas: a definition equal to one already merged (the same schema,
941
+ * its references leading to equal definitions) is shared; a different one asking for a name
942
+ * already taken (two types named alike) gets the next free `<name>_<n>`, and the references
943
+ * to it are renamed.
944
+ *
945
+ * @param types - Array of annotated types, each with an `id`.
946
+ * @returns An object with `schemas` (keyed by id) and shared `$defs`.
947
+ */ function mergeJsonSchemas(types) {
948
+ const mergedDefs = {};
949
+ const schemas = {};
950
+ for (const type of types) {
951
+ const name = type.id;
952
+ if (!name) throw new Error("mergeJsonSchemas: all types must have an id");
953
+ const { $defs: defs, ...schema } = buildJsonSchema(type);
954
+ if (!defs) {
955
+ schemas[name] = schema;
956
+ continue;
957
+ }
958
+ const local = defs;
959
+ /** The merged name of each of this schema's `$defs` entries. */ const renamed = /* @__PURE__ */ new Map();
960
+ for (const defName of Object.keys(local)) {
961
+ const family = defName.replace(/_\d+$/, "");
962
+ const same = Object.keys(mergedDefs).find((merged) => merged.replace(/_\d+$/, "") === family && sameSchema(local[defName], local, mergedDefs[merged], mergedDefs, /* @__PURE__ */ new Set()));
963
+ renamed.set(defName, same ?? (defName in mergedDefs || [...renamed.values()].includes(defName) ? uniqueName(family, (n) => n in mergedDefs || [...renamed.values()].includes(n), "_") : defName));
964
+ }
965
+ for (const [defName, merged] of renamed) if (!(merged in mergedDefs)) mergedDefs[merged] = renameRefs(local[defName], renamed);
966
+ schemas[name] = renameRefs(schema, renamed);
967
+ }
968
+ return {
969
+ schemas,
970
+ $defs: mergedDefs
971
+ };
972
+ }
973
+ const DEF_REF = /^#\/\$defs\/(.+)$/;
974
+ /** The `$defs` entry a reference string names (`#/$defs/<name>`), if it is one. */ function defRef(value) {
975
+ return typeof value === "string" ? DEF_REF.exec(value)?.[1] : void 0;
976
+ }
977
+ /** What `holder[key]` is, `holder` being a `part`. */ function partOf(part, key) {
978
+ if (part === "mapping" || key === "$ref") return "ref";
979
+ if (part === "discriminator" && key === "mapping") return "mapping";
980
+ return key === "discriminator" ? "discriminator" : "schema";
981
+ }
982
+ /**
983
+ * Whether `a` (in a schema with `$defs` `defsA`) and `b` (with `defsB`) are the same schema:
984
+ * equal, their references (`$ref`, discriminator mappings) leading to the same schemas.
985
+ * `assumed`: the pairs of entries being compared (a recursive one is the same unless shown
986
+ * otherwise).
987
+ */ function sameSchema(a, defsA, b, defsB, assumed, part = "schema") {
988
+ const refA = part === "ref" ? defRef(a) : void 0;
989
+ const refB = part === "ref" ? defRef(b) : void 0;
990
+ if (refA !== void 0 || refB !== void 0) {
991
+ if (refA === void 0 || refB === void 0) return false;
992
+ const pair = `${refA}\u0000${refB}`;
993
+ if (assumed.has(pair)) return true;
994
+ assumed.add(pair);
995
+ return sameSchema(defsA[refA], defsA, defsB[refB], defsB, assumed);
996
+ }
997
+ if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, i) => sameSchema(item, defsA, b[i], defsB, assumed));
998
+ if (!a || !b || typeof a !== "object" || typeof b !== "object") return a === b;
999
+ const keysA = Object.keys(a);
1000
+ return keysA.length === Object.keys(b).length && keysA.every((key) => Object.hasOwn(b, key) && sameSchema(a[key], defsA, b[key], defsB, assumed, partOf(part, key)));
1001
+ }
1002
+ /** `schema` with its references to `$defs` entries renamed by `renamed` (a copy). */ function renameRefs(schema, renamed, part = "schema") {
1003
+ const target = part === "ref" ? defRef(schema) : void 0;
1004
+ if (target !== void 0) return `#/$defs/${renamed.get(target) ?? target}`;
1005
+ if (Array.isArray(schema)) return schema.map((item) => renameRefs(item, renamed));
1006
+ if (!schema || typeof schema !== "object") return schema;
1007
+ const out = {};
1008
+ for (const [key, value] of Object.entries(schema)) out[key] = renameRefs(value, renamed, partOf(part, key));
1009
+ return out;
1010
+ }
1011
+
159
1012
  //#endregion
160
1013
  //#region packages/typescript/src/runtime/default-value.ts
161
1014
  /**
@@ -212,6 +1065,11 @@ function isPlainObject(value) {
212
1065
  }
213
1066
  }
214
1067
  /**
1068
+ * What {@link build} returns for a type it does not build: a recursive type reached again, or a
1069
+ * type holding one where a value is required (a required prop, a tuple item, an intersection
1070
+ * member) — its value would have to hold its ancestor's again.
1071
+ */ const STOPPED = Symbol("stopped");
1072
+ /**
215
1073
  * Creates a data object from an ATScript annotated type definition.
216
1074
  *
217
1075
  * Supports five modes:
@@ -229,48 +1087,91 @@ function isPlainObject(value) {
229
1087
  * @param opts - Options controlling value resolution mode.
230
1088
  * @returns A value conforming to the type's shape.
231
1089
  */ function createDataFromAnnotatedType(type, opts) {
232
- return build(type, "", opts?.mode);
1090
+ const data = runWalk(build(type, "", opts?.mode, {
1091
+ path: void 0,
1092
+ lenient: false
1093
+ }));
1094
+ return built(data === STOPPED ? runWalk(build(type, "", opts?.mode, {
1095
+ path: void 0,
1096
+ lenient: true
1097
+ })) : data);
233
1098
  }
234
- function build(def, path, mode) {
1099
+ /**
1100
+ * Builds the data of `def`. A recursive type stops where the path reaches it again
1101
+ * ({@link STOPPED}): an optional prop or an array item leading back is left out, a union takes a
1102
+ * branch that does not, and anything else holding it stops too.
1103
+ */ function* build(def, path, mode, walk) {
235
1104
  const resolved = resolveValue(def, path, mode);
236
1105
  if (resolved !== void 0) return resolved.value;
237
- return forAnnotatedType(def, {
238
- phantom: () => void 0,
239
- final: (d) => finalDefault(d),
240
- object: (d) => {
1106
+ const below = enterCut(walk.path, def);
1107
+ if (below === false) return STOPPED;
1108
+ return yield buildStructure(def, path, mode, {
1109
+ ...walk,
1110
+ path: below
1111
+ });
1112
+ }
1113
+ function* buildStructure(def, path, mode, walk) {
1114
+ const recursive = (node) => enterCut(walk.path, node) === false;
1115
+ const stops = (value) => value === STOPPED && !walk.lenient;
1116
+ const type = def.type;
1117
+ switch (type.kind) {
1118
+ case "": return type.designType === "phantom" ? void 0 : finalDefault(def);
1119
+ case "object": {
241
1120
  const data = {};
242
- for (const [key, prop] of d.type.props.entries()) {
1121
+ for (const [key, prop] of type.props.entries()) {
243
1122
  if (isPhantomType(prop)) continue;
244
1123
  const childPath = path ? `${path}.${key}` : key;
245
1124
  if (prop.optional) {
246
- if (mode === "example") data[key] = build(prop, childPath, mode);
247
- else {
1125
+ if (mode === "example") {
1126
+ if (!recursive(prop)) setBuilt(data, key, yield build(prop, childPath, mode, walk));
1127
+ } else {
248
1128
  const childResolved = resolveValue(prop, childPath, mode);
249
1129
  if (childResolved !== void 0) data[key] = childResolved.value;
250
1130
  }
251
1131
  continue;
252
1132
  }
253
- data[key] = build(prop, childPath, mode);
1133
+ const value = yield build(prop, childPath, mode, walk);
1134
+ if (stops(value)) return STOPPED;
1135
+ setBuilt(data, key, value);
254
1136
  }
255
1137
  return data;
256
- },
257
- array: (d) => {
258
- if (mode === "example") {
259
- const item = build(d.type.of, `${path}.0`, mode);
260
- return item !== void 0 ? [item] : [];
1138
+ }
1139
+ case "array":
1140
+ if (mode === "example" && !recursive(type.of)) {
1141
+ const item = yield build(type.of, `${path}.0`, mode, walk);
1142
+ return item !== void 0 && item !== STOPPED ? [item] : [];
261
1143
  }
262
1144
  return [];
263
- },
264
- tuple: (d) => d.type.items.map((item, i) => build(item, `${path}.${i}`, mode)),
265
- union: (d) => {
266
- const first = d.type.items[0];
267
- return first ? build(first, path, mode) : void 0;
268
- },
269
- intersection: (d) => {
270
- const first = d.type.items[0];
271
- return first ? build(first, path, mode) : void 0;
1145
+ case "tuple": {
1146
+ const items = [];
1147
+ for (const [i, item] of type.items.entries()) items.push(yield build(item, `${path}.${i}`, mode, walk));
1148
+ return items.some(stops) ? STOPPED : items.map(built);
272
1149
  }
273
- });
1150
+ case "union":
1151
+ for (const item of type.items) {
1152
+ if (recursive(item)) continue;
1153
+ const value = yield build(item, path, mode, walk);
1154
+ if (value !== STOPPED || walk.lenient) return built(value);
1155
+ }
1156
+ return walk.lenient ? void 0 : STOPPED;
1157
+ case "intersection": {
1158
+ const items = [];
1159
+ for (const item of type.items) items.push(yield build(item, path, mode, walk));
1160
+ if (items.some(stops)) return STOPPED;
1161
+ const values = items.filter((item) => item !== STOPPED);
1162
+ return values.length > 0 && values.every(isPlainObject) ? Object.assign({}, ...values) : values[0];
1163
+ }
1164
+ default: throw new Error(`Unknown type kind "${type.kind}"`);
1165
+ }
1166
+ }
1167
+ /** Sets `data[key]` unless nothing was built (see {@link STOPPED}). */ function setBuilt(data, key, value) {
1168
+ if (value !== STOPPED) data[key] = value;
1169
+ }
1170
+ /** A built value (`undefined` for {@link STOPPED}). */ function built(value) {
1171
+ return value === STOPPED ? void 0 : value;
1172
+ }
1173
+ function isPlainObject(value) {
1174
+ return typeof value === "object" && value !== null && !Array.isArray(value);
274
1175
  }
275
1176
 
276
1177
  //#endregion
@@ -282,6 +1183,45 @@ function build(def, path, mode) {
282
1183
  throw new Error(`${feature} support is disabled. To enable, set \`${option}: 'lazy'\` or \`${option}: 'bundle'\` in tsPlugin options, or add @${annotation} annotation to individual interfaces.`);
283
1184
  }
284
1185
 
1186
+ //#endregion
1187
+ //#region packages/typescript/src/runtime/bundled-schema.ts
1188
+ /** The lazy JSON schema of each type, with the metadata write count it was built at. */ const lazy = /* @__PURE__ */ new WeakMap();
1189
+ /**
1190
+ * The JSON schema of `type` built by the runtime (`jsonSchema: 'lazy'`): built once, again after
1191
+ * a metadata write (a block, a runtime edit: see `metadataWrites`). Called by generated code
1192
+ * (`static toJsonSchema()`).
1193
+ */ function lazyJsonSchema(type) {
1194
+ const known = lazy.get(type);
1195
+ const writes = metadataWriteCount();
1196
+ if (known?.writes === writes) return known.schema;
1197
+ const schema = buildJsonSchema(type);
1198
+ lazy.set(type, {
1199
+ writes,
1200
+ schema
1201
+ });
1202
+ return schema;
1203
+ }
1204
+ /** The bundled schemas of the generated types (see {@link bundledSchemaOf}). */ const bundled = /* @__PURE__ */ new WeakMap();
1205
+ /**
1206
+ * The JSON schema of `type` (`jsonSchema: 'bundle'`): the
1207
+ * bundled `literal` while the modules whose blocks applied are exactly those the build accounted
1208
+ * (`modules`, the realm's applied block modules), else the runtime's (`buildJsonSchema`). Raw
1209
+ * metadata writes are not seen (as in 0.1.110). Called by generated code.
1210
+ */ function bundledSchemaOf(type, literal, modules = []) {
1211
+ const applied = appliedBlockModules();
1212
+ const known = bundled.get(type);
1213
+ if (known?.size === applied.size) return known.schema;
1214
+ const accounted = new Set(modules);
1215
+ const same = applied.size === accounted.size && [...applied].every((m) => accounted.has(m));
1216
+ const schema = same ? literal() : buildJsonSchema(type);
1217
+ bundled.set(type, {
1218
+ size: applied.size,
1219
+ schema,
1220
+ source: same ? "bundled" : "runtime"
1221
+ });
1222
+ return schema;
1223
+ }
1224
+
285
1225
  //#endregion
286
1226
  //#region packages/typescript/src/runtime/flatten.ts
287
1227
  /**
@@ -293,117 +1233,124 @@ function build(def, path, mode) {
293
1233
  * - `'address.street'` → string type
294
1234
  * - `'address.city'` → string type
295
1235
  *
296
- * Arrays are recursed into (their element types are flattened with the same prefix).
297
- * Unions/intersections/tuples are recursed into (each branch contributes to the same path,
298
- * merging via synthetic union types when paths collide).
1236
+ * Arrays are recursed into (their element types are flattened with the same prefix). Unions,
1237
+ * tuples and intersections are recursed into (each item contributes to the same path, merging
1238
+ * via synthetic union types when paths collide). A recursive type is listed where it is reached
1239
+ * again, not expanded (the readers' recursion cut, see `cut.ts`). `onField` runs for a path once
1240
+ * its sub-paths are flattened.
299
1241
  *
300
1242
  * @param type - The root annotated type (must be an object type).
301
1243
  * @param options - Optional hooks for domain-specific processing.
302
1244
  * @returns A map of dot-separated field paths to their annotated types.
303
- */ const EMPTY_ANCESTORS = /* @__PURE__ */ new Set();
304
- function extendAncestors(ancestors, id) {
305
- if (!id || ancestors.has(id)) return ancestors;
306
- const next = new Set(ancestors);
307
- next.add(id);
308
- return next;
309
- }
310
- function flattenAnnotatedType(type, options) {
1245
+ */ function flattenAnnotatedType(type, options) {
311
1246
  const flatMap = /* @__PURE__ */ new Map();
312
1247
  const skipPhantom = !!options?.excludePhantomTypes;
1248
+ /** The walk's pending steps, last first: a type of any depth flattens without recursion. */ const tasks = [];
313
1249
  function addFieldToFlatMap(name, def) {
314
1250
  const existing = flatMap.get(name);
315
- if (existing) {
1251
+ if (existing?.__flat_union) {
1252
+ const union = existing;
1253
+ for (const [key, value] of def.metadata) union.metadata.set(key, value);
1254
+ union.type.items.push(def);
1255
+ touched(union.type);
1256
+ delete union.optional;
1257
+ } else if (existing) {
316
1258
  const flatUnion = defineAnnotatedType("union").copyMetadata(existing.metadata).copyMetadata(def.metadata);
317
- if (existing.__flat_union) existing.type.items.forEach((item) => flatUnion.item(item));
318
- else flatUnion.item(existing);
319
- flatUnion.item(def);
1259
+ flatUnion.item(existing).item(def);
320
1260
  const unionType = flatUnion.$type;
321
1261
  unionType.__flat_union = true;
322
1262
  flatMap.set(name, flatUnion.$type);
323
1263
  } else flatMap.set(name, def);
324
1264
  }
325
- function flattenArray(def, name, ancestors) {
326
- const resolvedId = def.id;
327
- if (resolvedId && ancestors.has(resolvedId)) return;
328
- let childAncestors = extendAncestors(ancestors, resolvedId);
1265
+ const fieldDone = (prefix, def) => {
1266
+ if (prefix) options?.onField?.(prefix, def, def.metadata);
1267
+ };
1268
+ /** The props of object `def` at `prefix` (`inComplex`: as array elements / union items). */ function props(def, prefix, inComplex, path) {
1269
+ const entries = [...def.type.props];
1270
+ for (let i = entries.length - 1; i >= 0; i--) {
1271
+ const [key, value] = entries[i];
1272
+ if (!(skipPhantom && isPhantomType(value))) tasks.push(() => flattenType(value, prefix ? `${prefix}.${key}` : key, inComplex, path));
1273
+ }
1274
+ }
1275
+ /** The sub-paths of array element / union item `def` at `name` (no entry of its own). */ function flattenArray(def, name, path) {
1276
+ const below = enterCut(path, def);
1277
+ if (below === false) return;
329
1278
  switch (def.type.kind) {
330
- case "object": {
331
- if (!resolvedId && def.id) {
332
- if (ancestors.has(def.id)) return;
333
- childAncestors = extendAncestors(ancestors, def.id);
334
- }
335
- const items = Array.from(def.type.props.entries());
336
- for (const [key, value] of items) {
337
- if (skipPhantom && isPhantomType(value)) continue;
338
- flattenType(value, name ? `${name}.${key}` : key, true, childAncestors);
339
- }
1279
+ case "object":
1280
+ props(def, name, true, below);
340
1281
  break;
341
- }
342
1282
  case "union":
343
1283
  case "intersection":
344
- case "tuple":
345
- for (const item of def.type.items) flattenArray(item, name, childAncestors);
1284
+ case "tuple": {
1285
+ const items = def.type.items;
1286
+ for (let i = items.length - 1; i >= 0; i--) {
1287
+ const item = items[i];
1288
+ tasks.push(() => flattenArray(item, name, below));
1289
+ }
346
1290
  break;
347
- case "array":
348
- flattenArray(def.type.of, name, childAncestors);
1291
+ }
1292
+ case "array": {
1293
+ const of = def.type.of;
1294
+ tasks.push(() => flattenArray(of, name, below));
349
1295
  break;
1296
+ }
350
1297
  default:
351
1298
  }
352
1299
  }
353
- function flattenType(def, prefix = "", inComplexTypeOrArray = false, ancestors = EMPTY_ANCESTORS) {
354
- let typeId = def.id;
355
- if (typeId && ancestors.has(typeId)) {
356
- addFieldToFlatMap(prefix || "", def);
357
- if (prefix) options?.onField?.(prefix, def, def.metadata);
1300
+ /** Flattens `def` at `prefix`, below `path`. */ function flattenType(def, prefix, inComplexTypeOrArray, path) {
1301
+ const below = enterCut(path, def);
1302
+ if (below === false) {
1303
+ addFieldToFlatMap(prefix, def);
1304
+ fieldDone(prefix, def);
358
1305
  return;
359
1306
  }
360
- let childAncestors = extendAncestors(ancestors, typeId);
361
- const kind = def.type.kind;
362
- if (!typeId && def.id) {
363
- typeId = def.id;
364
- if (ancestors.has(typeId)) {
365
- addFieldToFlatMap(prefix || "", def);
366
- if (prefix) options?.onField?.(prefix, def, def.metadata);
367
- return;
368
- }
369
- childAncestors = extendAncestors(ancestors, typeId);
370
- }
371
- switch (kind) {
1307
+ switch (def.type.kind) {
372
1308
  case "object":
373
- addFieldToFlatMap(prefix || "", def);
374
- for (const [key, value] of def.type.props.entries()) {
375
- if (skipPhantom && isPhantomType(value)) continue;
376
- flattenType(value, prefix ? `${prefix}.${key}` : key, inComplexTypeOrArray, childAncestors);
377
- }
1309
+ addFieldToFlatMap(prefix, def);
1310
+ tasks.push(() => fieldDone(prefix, def));
1311
+ props(def, prefix, inComplexTypeOrArray, below);
378
1312
  break;
379
1313
  case "array": {
380
1314
  let typeArray = def;
381
1315
  if (!inComplexTypeOrArray) {
382
- typeArray = defineAnnotatedType().refTo(def).copyMetadata(def.metadata).$type;
1316
+ typeArray = defineAnnotatedType().type(def).copyMetadata(def.metadata).$type;
383
1317
  if (def.optional) typeArray.optional = def.optional;
384
1318
  if (options?.topLevelArrayTag) typeArray.metadata.set(options.topLevelArrayTag, true);
385
1319
  }
386
- addFieldToFlatMap(prefix || "", typeArray);
387
- if (!isAnnotatedTypeOfPrimitive(typeArray.type.of)) flattenArray(typeArray.type.of, prefix, childAncestors);
1320
+ addFieldToFlatMap(prefix, typeArray);
1321
+ tasks.push(() => fieldDone(prefix, def));
1322
+ if (!isAnnotatedTypeOfPrimitive(typeArray.type.of)) {
1323
+ const of = typeArray.type.of;
1324
+ tasks.push(() => flattenArray(of, prefix, below));
1325
+ }
388
1326
  break;
389
1327
  }
390
1328
  case "intersection":
391
1329
  case "tuple":
392
- case "union":
393
- for (const item of def.type.items) flattenType(item, prefix, true, childAncestors);
394
- addFieldToFlatMap(prefix || "", def);
395
- if (def.optional) {
396
- const entry = flatMap.get(prefix || "");
397
- if (entry) entry.optional = def.optional;
1330
+ case "union": {
1331
+ tasks.push(() => {
1332
+ addFieldToFlatMap(prefix, def);
1333
+ if (def.optional) {
1334
+ const entry = flatMap.get(prefix);
1335
+ if (entry) entry.optional = def.optional;
1336
+ }
1337
+ fieldDone(prefix, def);
1338
+ });
1339
+ const items = def.type.items;
1340
+ for (let i = items.length - 1; i >= 0; i--) {
1341
+ const item = items[i];
1342
+ tasks.push(() => flattenType(item, prefix, true, below));
398
1343
  }
399
1344
  break;
1345
+ }
400
1346
  default:
401
- addFieldToFlatMap(prefix || "", def);
1347
+ addFieldToFlatMap(prefix, def);
1348
+ fieldDone(prefix, def);
402
1349
  break;
403
1350
  }
404
- if (prefix) options?.onField?.(prefix, def, def.metadata);
405
1351
  }
406
- flattenType(type);
1352
+ flattenType(type, "", false, void 0);
1353
+ for (let task = tasks.pop(); task; task = tasks.pop()) task();
407
1354
  return flatMap;
408
1355
  }
409
1356
 
@@ -438,24 +1385,37 @@ function _define_property(obj, key, value) {
438
1385
  * @param options - Optional filtering/transformation for annotations.
439
1386
  * @returns A versioned, JSON-safe representation of the type.
440
1387
  */ function serializeAnnotatedType(type, options) {
441
- const result = serializeNode(type, [], options, new Visited());
1388
+ const visited = new Visited();
1389
+ indexPayload(type, options?.refDepth ?? 0, visited);
1390
+ const result = runWalk(serializeNode(type, [], options, visited));
442
1391
  result.$v = SERIALIZE_VERSION;
443
1392
  return result;
444
1393
  }
445
1394
  /**
446
- * Named types serialized so far. `own` keeps, per id, the first node serialized under it (and
447
- * the `refDepth` it was serialized at); a later reference is compared against it, by a
448
- * fingerprint of what it carries (metadata, `optional` and `ref`), to tell a reference that adds
449
- * nothing from one whose prop annotations or FK target differ. The first node's key is computed
450
- * only when a revisit needs it, and memoized.
451
- */ let Visited = class Visited extends Set {
452
- /** Whether `def` (revisiting its id at `refDepth`) carries something other than the first node. */ differsFromFirst(def, refDepth) {
453
- const id = def.id;
454
- let first = this.firstKeys.get(id);
1395
+ * Named types serialized so far, by payload id (see {@link Visited.keyOf}). `own` keeps, per
1396
+ * id, the first node serialized under it (and the `refDepth` it was serialized at); a later
1397
+ * reference is compared against it, by a fingerprint of what it carries (metadata, `optional`
1398
+ * and `ref`), to tell a reference that adds nothing from one whose prop annotations or FK target
1399
+ * differ. The first node's fingerprint is computed only when a revisit needs it, and memoized.
1400
+ */ let Visited = class Visited {
1401
+ /**
1402
+ * The payload id of named type `def`: its id, unless a different type (another type def)
1403
+ * took it first (`Name@1`, `Name@2`, …) — distinct types never collapse onto one another.
1404
+ */ keyOf(def) {
1405
+ let key = this.keys.get(def.type);
1406
+ if (key === void 0) {
1407
+ key = uniqueName(def.id ?? ANON_ID, (k) => this.taken.has(k), "@");
1408
+ this.taken.add(key);
1409
+ this.keys.set(def.type, key);
1410
+ }
1411
+ return key;
1412
+ }
1413
+ /** Whether `def` (revisiting `key` at `refDepth`) carries something other than the first node. */ differsFromFirst(def, key, refDepth) {
1414
+ let first = this.firstKeys.get(key);
455
1415
  if (first === void 0) {
456
- const { def: firstDef, refDepth: firstDepth } = this.own.get(id);
1416
+ const { def: firstDef, refDepth: firstDepth } = this.own.get(key);
457
1417
  first = ownKey(firstDef, this, firstDepth);
458
- this.firstKeys.set(id, first);
1418
+ this.firstKeys.set(key, first);
459
1419
  }
460
1420
  return first !== ownKey(def, this, refDepth);
461
1421
  }
@@ -467,8 +1427,18 @@ function _define_property(obj, key, value) {
467
1427
  }
468
1428
  return id;
469
1429
  }
470
- constructor(...args) {
471
- super(...args), _define_property(this, "own", /* @__PURE__ */ new Map()), _define_property(this, "firstKeys", /* @__PURE__ */ new Map()), _define_property(this, "identities", /* @__PURE__ */ new WeakMap()), _define_property(this, "nextId", 0);
1430
+ constructor() {
1431
+ _define_property(this, "own", /* @__PURE__ */ new Map());
1432
+ /**
1433
+ * The nodes without an id met more than once (see `indexPayload`): serialized once, with a
1434
+ * payload id, and referenced (`$ref`, `anon`) wherever else they are.
1435
+ */ _define_property(this, "repeated", /* @__PURE__ */ new Set());
1436
+ _define_property(this, "firstKeys", /* @__PURE__ */ new Map());
1437
+ _define_property(this, "identities", /* @__PURE__ */ new WeakMap());
1438
+ _define_property(this, "nextId", 0);
1439
+ /** Payload ids by type def (see {@link keyOf}). */ _define_property(this, "keys", /* @__PURE__ */ new WeakMap());
1440
+ /** The payload ids given so far. */ _define_property(this, "taken", /* @__PURE__ */ new Set());
1441
+ /** The `cut` payload of defs (see `indexPayload`). */ _define_property(this, "cutKeys", /* @__PURE__ */ new WeakMap());
472
1442
  }
473
1443
  };
474
1444
  /**
@@ -503,16 +1473,19 @@ function _define_property(obj, key, value) {
503
1473
  const proto = Object.getPrototypeOf(value);
504
1474
  return Array.isArray(value) || proto === Object.prototype || proto === null;
505
1475
  }
506
- /** Comparison key of a resolved annotation target: its id, else its identity. */ function targetKey(target, visited) {
507
- return target.id ? `ref#${target.id}` : `ref@${visited.identity(target)}`;
1476
+ /**
1477
+ * Comparison key of a resolved annotation target: its type def's identity (two references to
1478
+ * one type compare equal; distinct types sharing an id do not).
1479
+ */ function targetKey(target, visited) {
1480
+ return `ref@${visited.identity(target.type ?? target)}`;
508
1481
  }
509
1482
  /** What a node carries of its own (metadata, optionality, FK target), as a comparison key. */ function ownKey(def, visited, refDepth) {
510
1483
  const entries = [...def.metadata.entries()].map(([k, v]) => `${JSON.stringify(k)}:${fingerprint(v, visited)}`);
511
1484
  const refTarget = refDepth > 0 ? def.ref?.type() : void 0;
512
- const ref = def.ref && refTarget ? `${refTarget.id ?? ""}.${def.ref.field}` : "";
1485
+ const ref = def.ref && refTarget ? `${targetKey(refTarget, visited)}.${def.ref.field}` : "";
513
1486
  return `${entries.join(",")}|${def.optional ? 1 : 0}|${ref}`;
514
1487
  }
515
- function serializeRef(def, options, visited) {
1488
+ function* serializeRef(def, options, visited) {
516
1489
  const refDepth = options?.refDepth ?? 0;
517
1490
  if (refDepth > 0 && def.ref) {
518
1491
  const refTarget = def.ref.type();
@@ -521,14 +1494,14 @@ function serializeRef(def, options, visited) {
521
1494
  type: refDepth < 1 && isHalfStep(refDepth) ? shallowTarget(refTarget, options, {
522
1495
  visited,
523
1496
  depth: 1
524
- }, true) : serializeNode(refTarget, [], {
1497
+ }, true) : yield serializeNode(refTarget, [], {
525
1498
  ...options,
526
1499
  refDepth: refDepth - 1
527
1500
  }, visited)
528
1501
  };
529
1502
  }
530
1503
  }
531
- function serializeNode(def, path, options, visited) {
1504
+ function* serializeNode(def, path, options, visited) {
532
1505
  const refDepth = options?.refDepth ?? 0;
533
1506
  const metadata = () => serializeMetadata(def, {
534
1507
  path,
@@ -537,104 +1510,157 @@ function serializeNode(def, path, options, visited) {
537
1510
  visited,
538
1511
  depth: 0
539
1512
  });
540
- if (def.id && visited.has(def.id)) {
541
- const differs = visited.differsFromFirst(def, refDepth);
542
- const ref = differs ? serializeRef(def, options, visited) : void 0;
543
- return {
1513
+ const key = def.id || visited.repeated.has(def.type) ? visited.keyOf(def) : void 0;
1514
+ if (key !== void 0 && visited.own.has(key)) {
1515
+ const differs = def.id !== void 0 && def.id !== visited.own.get(key).def.id || visited.differsFromFirst(def, key, refDepth);
1516
+ const ref = differs ? yield serializeRef(def, options, visited) : void 0;
1517
+ const node = {
544
1518
  type: {
545
1519
  kind: "$ref",
546
- id: def.id,
1520
+ id: key,
547
1521
  ...differs ? { own: true } : {}
548
1522
  },
549
- metadata: differs ? metadata() : {},
550
- ...def.optional ? { optional: true } : {},
551
- id: def.id,
552
- ...ref ? { ref } : {}
1523
+ metadata: differs ? metadata() : {}
553
1524
  };
1525
+ if (def.optional) node.optional = true;
1526
+ node.id = key;
1527
+ if (!def.id) node.anon = true;
1528
+ else if (key !== def.id) node.origId = def.id;
1529
+ if (ref) node.ref = ref;
1530
+ return node;
554
1531
  }
555
- if (def.id) {
556
- visited.add(def.id);
557
- visited.own.set(def.id, {
558
- def,
559
- refDepth
560
- });
561
- }
1532
+ if (key !== void 0) visited.own.set(key, {
1533
+ def,
1534
+ refDepth
1535
+ });
562
1536
  const result = {
563
- type: serializeTypeDef(def, path, options, visited),
1537
+ type: yield serializeTypeDef(def, path, options, visited),
564
1538
  metadata: metadata()
565
1539
  };
566
1540
  if (def.optional) result.optional = true;
567
- if (def.id) result.id = def.id;
568
- const ref = serializeRef(def, options, visited);
1541
+ if (key !== void 0) {
1542
+ result.id = key;
1543
+ if (!def.id) result.anon = true;
1544
+ else if (key !== def.id) result.origId = def.id;
1545
+ }
1546
+ const cutTag = visited.cutKeys.get(def.type);
1547
+ if (cutTag !== void 0) result.cut = cutTag;
1548
+ const ref = yield serializeRef(def, options, visited);
569
1549
  if (ref) result.ref = ref;
570
1550
  return result;
571
1551
  }
1552
+ /**
1553
+ * Walks the nodes the payload of `root` holds, in the order `serializeNode` writes them: its tree
1554
+ * and — `refDepth` permitting — the tree of each FK target, right after the node referencing it
1555
+ * (at one level less). `reach(node, first)` for every node met; `first` when its type is met for
1556
+ * the first time, the only time its children (and FK target) are walked — the payload writes a
1557
+ * type's tree once — except a primitive's FK target, written wherever the primitive is.
1558
+ */ function walkPayload(root, refDepth, reach) {
1559
+ const walked = /* @__PURE__ */ new Set();
1560
+ const pending = [[root, refDepth]];
1561
+ const next = [];
1562
+ while (pending.length > 0) {
1563
+ const [node, depth] = pending.pop();
1564
+ const type = node?.type;
1565
+ if (!node || !type) continue;
1566
+ const first = !walked.has(type);
1567
+ reach(node, first);
1568
+ if (first) {
1569
+ walked.add(type);
1570
+ if (type.kind === "object") {
1571
+ for (const prop of type.props.values()) next.push([prop, depth]);
1572
+ for (const { def } of type.propsPatterns) next.push([def, depth]);
1573
+ } else if (type.kind === "array") next.push([type.of, depth]);
1574
+ else if (type.kind !== "") for (const item of type.items) next.push([item, depth]);
1575
+ }
1576
+ if ((first || type.kind === "") && depth >= 1 && node.ref) next.push([node.ref.type(), depth - 1]);
1577
+ while (next.length > 0) pending.push(next.pop());
1578
+ }
1579
+ }
1580
+ /**
1581
+ * Indexes the payload of `root` (one walk, see {@link walkPayload}; decided before anything is
1582
+ * written, so a copy deserialized from the payload, which shares exactly these nodes, decides
1583
+ * alike):
1584
+ * - `visited.repeated`: the types (by def) of the nodes without an id (not primitives) the
1585
+ * payload holds in more than one place (FK targets included, so a node shared by the tree and a
1586
+ * target's tree is written once wherever it is met first): a type built from another one
1587
+ * references that one's nodes, a merge with the type itself holds its own merged prop.
1588
+ * Serialized once each (see `serializeNode`).
1589
+ * - `visited.cutKeys`: the `cut` payload (see `TSerializedAnnotatedTypeInner.cut`) of the nodes
1590
+ * without an id: the defs standing for one type to the cut (`cutKey`) get one tag, in the order
1591
+ * first met, so a copy cuts and serializes alike.
1592
+ */ function indexPayload(root, refDepth, visited) {
1593
+ const counted = /* @__PURE__ */ new Set();
1594
+ const groups = /* @__PURE__ */ new Map();
1595
+ walkPayload(root, refDepth, (node, first) => {
1596
+ const type = node.type;
1597
+ if (type.kind === "") return;
1598
+ if (counted.has(type) && !node.id) visited.repeated.add(type);
1599
+ counted.add(type);
1600
+ if (!first || node.id) return;
1601
+ const key = cutKey(node);
1602
+ const group = groups.get(key);
1603
+ if (!group) groups.set(key, [type]);
1604
+ else if (!group.includes(type)) group.push(type);
1605
+ });
1606
+ let tag = 0;
1607
+ for (const defs of groups.values()) if (defs.length > 1) {
1608
+ for (const def of defs) visited.cutKeys.set(def, tag);
1609
+ tag++;
1610
+ }
1611
+ }
1612
+ /** The payload id base of a reference without an id (see `anon`). */ const ANON_ID = "Recursive";
572
1613
  function isHalfStep(refDepth) {
573
1614
  return refDepth - Math.floor(refDepth) === .5;
574
1615
  }
575
- function serializeTypeDef(def, path, options, visited) {
576
- return forAnnotatedType(def, {
577
- phantom(d) {
578
- return {
579
- kind: "",
580
- designType: d.type.designType,
581
- tags: Array.from(d.type.tags)
582
- };
583
- },
584
- final(d) {
1616
+ function* serializeTypeDef(def, path, options, visited) {
1617
+ const type = def.type;
1618
+ switch (type.kind) {
1619
+ case "": {
585
1620
  const result = {
586
1621
  kind: "",
587
- designType: d.type.designType,
588
- tags: Array.from(d.type.tags)
1622
+ designType: type.designType,
1623
+ tags: Array.from(type.tags)
589
1624
  };
590
- if (d.type.value !== void 0) result.value = d.type.value;
1625
+ if (type.value !== void 0 && type.designType !== "phantom") result.value = type.value;
591
1626
  return result;
592
- },
593
- object(d) {
1627
+ }
1628
+ case "object": {
594
1629
  const props = {};
595
- for (const [key, val] of d.type.props.entries()) props[key] = serializeNode(val, [...path, key], options, visited);
1630
+ for (const [key, val] of type.props.entries()) props[key] = yield serializeNode(val, [...path, key], options, visited);
1631
+ const propsPatterns = [];
1632
+ for (const pp of type.propsPatterns) propsPatterns.push({
1633
+ pattern: {
1634
+ source: pp.pattern.source,
1635
+ flags: pp.pattern.flags
1636
+ },
1637
+ def: yield serializeNode(pp.def, path, options, visited)
1638
+ });
596
1639
  return {
597
1640
  kind: "object",
598
1641
  props,
599
- propsPatterns: d.type.propsPatterns.map((pp) => ({
600
- pattern: {
601
- source: pp.pattern.source,
602
- flags: pp.pattern.flags
603
- },
604
- def: serializeNode(pp.def, path, options, visited)
605
- })),
606
- tags: Array.from(d.type.tags)
607
- };
608
- },
609
- array(d) {
610
- return {
611
- kind: "array",
612
- of: serializeNode(d.type.of, path, options, visited),
613
- tags: Array.from(d.type.tags)
614
- };
615
- },
616
- union(d) {
617
- return {
618
- kind: "union",
619
- items: d.type.items.map((item) => serializeNode(item, path, options, visited)),
620
- tags: Array.from(d.type.tags)
621
- };
622
- },
623
- intersection(d) {
624
- return {
625
- kind: "intersection",
626
- items: d.type.items.map((item) => serializeNode(item, path, options, visited)),
627
- tags: Array.from(d.type.tags)
1642
+ propsPatterns,
1643
+ tags: Array.from(type.tags)
628
1644
  };
629
- },
630
- tuple(d) {
1645
+ }
1646
+ case "array": return {
1647
+ kind: "array",
1648
+ of: yield serializeNode(type.of, path, options, visited),
1649
+ tags: Array.from(type.tags)
1650
+ };
1651
+ case "union":
1652
+ case "intersection":
1653
+ case "tuple": {
1654
+ const items = [];
1655
+ for (const item of type.items) items.push(yield serializeNode(item, path, options, visited));
631
1656
  return {
632
- kind: "tuple",
633
- items: d.type.items.map((item) => serializeNode(item, path, options, visited)),
634
- tags: Array.from(d.type.tags)
1657
+ kind: type.kind,
1658
+ items,
1659
+ tags: Array.from(type.tags)
635
1660
  };
636
1661
  }
637
- });
1662
+ default: throw new Error(`Unknown type kind "${type.kind}"`);
1663
+ }
638
1664
  }
639
1665
  /**
640
1666
  * Resolves a type reference held in an annotation value: an annotated type itself (same-file
@@ -737,7 +1763,21 @@ function serializeMetadata(owner, site, options, state) {
737
1763
  * @throws If the serialized version doesn't match {@link SERIALIZE_VERSION}.
738
1764
  */ function deserializeAnnotatedType(data) {
739
1765
  if (data.$v !== SERIALIZE_VERSION) throw new Error(`Unsupported serialized type version: ${data.$v} (expected ${SERIALIZE_VERSION})`);
740
- return deserializeNode(data, /* @__PURE__ */ new Map());
1766
+ return runWalk(deserializeNode(data, /* @__PURE__ */ new Map()));
1767
+ }
1768
+ /** The anonymous type of each `cut` tag of a payload being deserialized (by its `resolved`). */ const cutTokens = /* @__PURE__ */ new WeakMap();
1769
+ /** The anonymous type `cut` tag `tag` of the payload `resolved` belongs to stands for. */ function cutToken(resolved, tag) {
1770
+ let tokens = cutTokens.get(resolved);
1771
+ if (!tokens) {
1772
+ tokens = /* @__PURE__ */ new Map();
1773
+ cutTokens.set(resolved, tokens);
1774
+ }
1775
+ let token = tokens.get(tag);
1776
+ if (!token) {
1777
+ token = {};
1778
+ tokens.set(tag, token);
1779
+ }
1780
+ return token;
741
1781
  }
742
1782
  function emptyObjectTypeDef() {
743
1783
  return createObjectTypeDef();
@@ -745,11 +1785,11 @@ function emptyObjectTypeDef() {
745
1785
  function toMetadataMap(record) {
746
1786
  return createMetadataMap(Object.entries(record));
747
1787
  }
748
- function deserializeRef(data, resolved) {
1788
+ function* deserializeRef(data, resolved) {
749
1789
  if (!data.ref) return;
750
1790
  const refTargetData = data.ref.type;
751
1791
  if ("type" in refTargetData) {
752
- const deserializedRefTarget = deserializeNode(refTargetData, resolved);
1792
+ const deserializedRefTarget = yield deserializeNode(refTargetData, resolved);
753
1793
  return {
754
1794
  type: () => deserializedRefTarget,
755
1795
  field: data.ref.field
@@ -761,15 +1801,16 @@ function deserializeRef(data, resolved) {
761
1801
  field: data.ref.field
762
1802
  };
763
1803
  }
764
- function deserializeNode(data, resolved) {
1804
+ function* deserializeNode(data, resolved) {
765
1805
  if (data.type.kind === "$ref") {
766
1806
  const { id: refId, own } = data.type;
767
1807
  const target = resolved.get(refId);
768
- if (!own) return target || createAnnotatedTypeNode(emptyObjectTypeDef(), createMetadataMap(), { id: refId });
1808
+ const id = data.anon ? void 0 : data.origId ?? target?.id ?? refId;
1809
+ if (!own) return target || createAnnotatedTypeNode(emptyObjectTypeDef(), createMetadataMap(), { id });
769
1810
  const node = createAnnotatedTypeNode(target?.type ?? emptyObjectTypeDef(), toMetadataMap(data.metadata), {
770
- id: refId,
1811
+ id,
771
1812
  optional: data.optional || void 0,
772
- ref: deserializeRef(data, resolved)
1813
+ ref: yield deserializeRef(data, resolved)
773
1814
  });
774
1815
  if (target) Object.defineProperty(node, "type", {
775
1816
  get: () => target.type,
@@ -788,12 +1829,13 @@ function deserializeNode(data, resolved) {
788
1829
  if (existing) return existing;
789
1830
  result = createAnnotatedTypeNode(emptyObjectTypeDef(), metadata, {
790
1831
  optional: data.optional || void 0,
791
- id: data.id
1832
+ id: data.anon ? void 0 : data.origId ?? data.id
792
1833
  });
793
1834
  resolved.set(data.id, result);
794
1835
  }
795
- const type = deserializeTypeDef(data.type, resolved);
796
- const ref = deserializeRef(data, resolved);
1836
+ const type = yield deserializeTypeDef(data.type, resolved);
1837
+ const ref = yield deserializeRef(data, resolved);
1838
+ if (data.cut !== void 0) cutAs(type, cutToken(resolved, data.cut));
797
1839
  if (result) {
798
1840
  result.type = type;
799
1841
  if (ref) result.ref = ref;
@@ -805,7 +1847,7 @@ function deserializeNode(data, resolved) {
805
1847
  ref
806
1848
  });
807
1849
  }
808
- function deserializeTypeDef(t, resolved) {
1850
+ function* deserializeTypeDef(t, resolved) {
809
1851
  const tags = "tags" in t ? new Set(t.tags) : /* @__PURE__ */ new Set();
810
1852
  switch (t.kind) {
811
1853
  case "": {
@@ -819,25 +1861,31 @@ function deserializeTypeDef(t, resolved) {
819
1861
  }
820
1862
  case "object": {
821
1863
  const def = createObjectTypeDef(tags);
822
- for (const [key, val] of Object.entries(t.props)) def.props.set(key, deserializeNode(val, resolved));
823
- def.propsPatterns = t.propsPatterns.map((pp) => ({
824
- pattern: new RegExp(pp.pattern.source, pp.pattern.flags),
825
- def: deserializeNode(pp.def, resolved)
826
- }));
1864
+ for (const [key, val] of Object.entries(t.props)) def.props.set(key, yield deserializeNode(val, resolved));
1865
+ const patterns = [];
1866
+ for (const pp of t.propsPatterns) patterns.push({
1867
+ pattern: statelessRegExp(new RegExp(pp.pattern.source, pp.pattern.flags)),
1868
+ def: yield deserializeNode(pp.def, resolved)
1869
+ });
1870
+ def.propsPatterns = patterns;
827
1871
  return def;
828
1872
  }
829
1873
  case "array": return {
830
1874
  kind: "array",
831
- of: deserializeNode(t.of, resolved),
1875
+ of: yield deserializeNode(t.of, resolved),
832
1876
  tags
833
1877
  };
834
1878
  case "union":
835
1879
  case "intersection":
836
- case "tuple": return {
837
- kind: t.kind,
838
- items: t.items.map((item) => deserializeNode(item, resolved)),
839
- tags
840
- };
1880
+ case "tuple": {
1881
+ const items = [];
1882
+ for (const item of t.items) items.push(yield deserializeNode(item, resolved));
1883
+ return {
1884
+ kind: t.kind,
1885
+ items,
1886
+ tags
1887
+ };
1888
+ }
841
1889
  case "$ref": {
842
1890
  const existing = resolved.get(t.id);
843
1891
  if (existing) return existing.type;
@@ -848,4 +1896,4 @@ function deserializeTypeDef(t, resolved) {
848
1896
  }
849
1897
 
850
1898
  //#endregion
851
- export { SERIALIZE_VERSION, Validator, ValidatorError, annotate, buildJsonSchema, cloneRefProp, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, flattenAnnotatedType, forAnnotatedType, fromJsonSchema, invalidateCompiledValidators, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, mergeJsonSchemas, registerCompiledCheck, serializeAnnotatedType, throwFeatureDisabled };
1899
+ export { $ak, $alias, $blk, $end, $f, $fc, $ft, $nr, $ps, $q, $sh, LayerMap, SERIALIZE_VERSION, Validator, ValidatorError, annotate, appliedBlockModules, buildJsonSchema, bundledSchemaOf, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, flattenAnnotatedType, forAnnotatedType, fromJsonSchema, invalidateCompiledValidators, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, lazyJsonSchema, mergeJsonSchemas, metaEmpty, pendingStatements, registerCompiledCheck, serializeAnnotatedType, throwFeatureDisabled, watchLayer };