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