@atscript/typescript 0.2.5 → 0.2.6

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_user_text = require('./user-text-Dl8FNKLL.cjs');
2
+ const require_user_text = require('./user-text-BvyErcKK.cjs');
3
3
 
4
4
  //#region packages/typescript/src/runtime/copy-on-change.ts
5
5
  /**
@@ -85,122 +85,49 @@ const require_user_text = require('./user-text-Dl8FNKLL.cjs');
85
85
  else out[key] = value;
86
86
  }
87
87
 
88
- //#endregion
89
- //#region packages/typescript/src/runtime/coerce.ts
90
- /**
91
- * Coerces string-transport input (route params, query strings) toward the
92
- * scalar shapes an annotated type expects.
93
- *
94
- * Pure and non-throwing: when a value can't be coerced it is returned
95
- * untouched, leaving the {@link Validator} to report the proper error.
96
- * Coercion converts representation only — constraint checks (`@expect.int`,
97
- * `@expect.min`, patterns) remain the validator's job.
98
- *
99
- * Rules:
100
- * - Strings targeting `number` are trimmed and parsed via `Number()`; only
101
- * finite results are accepted.
102
- * - Strings targeting `boolean` accept `"true"/"1"` and `"false"/"0"`.
103
- * - Unions try each branch in declared order; the first successful parse wins.
104
- * - Objects recurse into props when the input is a plain object (covers
105
- * `@Query()` DTOs where every field arrives as a string).
106
- * - Arrays and tuples coerce items; intersections apply each member in order.
107
- * - `string` / `decimal` targets never change string input.
108
- *
109
- * @example
110
- * ```ts
111
- * coerceForType(KafkaOffset, '42') // → 42
112
- * coerceForType(KafkaOffset, 'abc') // → 'abc' (validator reports the error)
113
- * ```
114
- */ function coerceForType(def, value) {
115
- const result = coerce(def, value);
116
- return result === NO_MATCH ? value : result;
117
- }
118
- /**
119
- * Coerces a single scalar value toward a design type, using the same rules
120
- * as {@link coerceForType}. Returns the input untouched when it can't coerce.
121
- * Useful when only a design type is known (e.g. `design:paramtypes` fallbacks).
122
- */ function coerceScalar(designType, value) {
123
- const result = scalar(designType, value);
124
- return result === NO_MATCH ? value : result;
125
- }
126
- /** Returns the coerced value, or NO_MATCH when the value can't fit this node. */ function coerce(def, value) {
127
- if (value === void 0 || value === null) return def.optional === true ? value : NO_MATCH;
128
- const type = def.type;
129
- switch (type.kind) {
130
- case "": {
131
- const final = type;
132
- if (final.designType === "phantom") return value;
133
- const result = scalar(final.designType, value);
134
- if (result !== NO_MATCH && final.value !== void 0 && result !== final.value) return NO_MATCH;
135
- return result;
136
- }
137
- case "object":
138
- if (!isPlainObject$1(value)) return NO_MATCH;
139
- return mapProps(type, value, coerceChild, void 0);
140
- case "array": return Array.isArray(value) ? mapItems(value, type.of, coerceChild, void 0) : NO_MATCH;
141
- case "tuple": {
142
- const items = type.items;
143
- return Array.isArray(value) && value.length === items.length ? mapItems(value, items, coerceChild, void 0) : NO_MATCH;
144
- }
145
- case "union":
146
- for (const item of type.items) {
147
- const result = coerce(item, value);
148
- if (result !== NO_MATCH) return result;
149
- }
150
- return NO_MATCH;
151
- case "intersection": {
152
- let current = value;
153
- for (const item of type.items) {
154
- const result = coerce(item, current);
155
- if (result === NO_MATCH) return NO_MATCH;
156
- current = result;
157
- }
158
- return current;
159
- }
160
- default: throw new Error(`Unknown type kind "${type.kind}"`);
161
- }
162
- }
163
- function scalar(designType, value) {
164
- switch (designType) {
165
- case "string":
166
- case "decimal": return typeof value === "string" ? value : NO_MATCH;
167
- case "number":
168
- if (typeof value === "number") return value;
169
- if (typeof value === "string") {
170
- const trimmed = value.trim();
171
- if (trimmed.length > 0) {
172
- const parsed = Number(trimmed);
173
- if (Number.isFinite(parsed)) return parsed;
174
- }
175
- }
176
- return NO_MATCH;
177
- case "boolean":
178
- if (typeof value === "boolean") return value;
179
- if (value === "true" || value === "1") return true;
180
- if (value === "false" || value === "0") return false;
181
- return NO_MATCH;
182
- case "object": return typeof value === "object" ? value : NO_MATCH;
183
- case "any":
184
- case "phantom": return value;
185
- default: return NO_MATCH;
186
- }
187
- }
188
- /** A prop / item: its coerced value, else the value as it is (copy-on-change, see `mapProps`). */ function coerceChild(def, input) {
189
- const result = coerce(def, input);
190
- return result === NO_MATCH ? input : result;
191
- }
192
-
193
88
  //#endregion
194
89
  //#region packages/typescript/src/runtime/normalize.ts
195
90
  const TRIM = 1;
196
91
  const LOWERCASE = 2;
197
92
  const UPPERCASE = 4;
198
93
  /**
199
- * Whether each node's subtree has normalizers: valid until the next metadata write or
200
- * `invalidateCompiledValidators()` (checked by {@link normalizeForType}).
94
+ * Whether each node's subtree has normalizers: valid until the next type tree write (metadata or
95
+ * shape) or `invalidateCompiledValidators()` (checked by {@link normalizeForType}).
201
96
  */ let reach = /* @__PURE__ */ new WeakMap();
202
97
  let stampWrites = -1;
203
- let stampEpoch = -1;
98
+ function newJudges(opts) {
99
+ const root = {
100
+ ...opts,
101
+ errorLimit: 1
102
+ };
103
+ delete root.translate;
104
+ if (root.unknownProps === "strip") root.unknownProps = "ignore";
105
+ const judge = {
106
+ opts: root,
107
+ validators: /* @__PURE__ */ new WeakMap()
108
+ };
109
+ return {
110
+ root: judge,
111
+ nested: root.partial === true ? {
112
+ opts: {
113
+ ...root,
114
+ partial: false
115
+ },
116
+ validators: /* @__PURE__ */ new WeakMap()
117
+ } : judge
118
+ };
119
+ }
120
+ const DEFAULT_JUDGES = newJudges({});
121
+ /** The judges by the options object passed (the same options: the same validators). */ const judgesByOpts = /* @__PURE__ */ new WeakMap();
122
+ function judgesFor(opts) {
123
+ if (!opts) return DEFAULT_JUDGES;
124
+ let found = judgesByOpts.get(opts);
125
+ if (!found) {
126
+ found = newJudges(opts);
127
+ judgesByOpts.set(opts, found);
128
+ }
129
+ return found;
130
+ }
204
131
  /**
205
132
  * Normalizes input toward the string forms an annotated type declares with `@normalize.trim`,
206
133
  * `@normalize.lowercase` and `@normalize.uppercase`.
@@ -221,9 +148,11 @@ let stampEpoch = -1;
221
148
  * `detectDiscriminator`) uses the branch the value's discriminator names;
222
149
  * - otherwise every branch that can take the value is tried (a literal branch can take a string
223
150
  * only when the normalized string equals its literal): when they all give the same result it
224
- * is used; when they differ, the branches whose result their own validator accepts (default
225
- * options) are kept, and the result is used when they agree; else the value is returned
226
- * untouched (ambiguous).
151
+ * is used; when they differ, the branches whose result their own validator accepts are kept,
152
+ * and the result is used when they agree; else the value is returned untouched (ambiguous).
153
+ * The branch validators take `opts` — pass the options the result will be validated with
154
+ * (`partial`, `unknownProps`, …) so a branch is judged as the validator will judge it; default
155
+ * options when omitted. (`unknownProps: 'strip'` judges as `'ignore'`: nothing is stripped.)
227
156
  *
228
157
  * The intended flow is `coerceForType` → `normalizeForType` → `validate`.
229
158
  *
@@ -231,17 +160,21 @@ let stampEpoch = -1;
231
160
  * ```ts
232
161
  * // @normalize.trim @normalize.lowercase email: string.email
233
162
  * normalizeForType(User, { email: ' Ann@Example.COM ' }) // → { email: 'ann@example.com' }
163
+ * // judged as a partial update will be validated
164
+ * normalizeForType(Patch, body, { partial: true })
234
165
  * ```
235
- */ function normalizeForType(def, value) {
236
- const writes = require_user_text.metadataWriteCount();
237
- const epoch = require_user_text.currentEpoch();
238
- if (writes !== stampWrites || epoch !== stampEpoch) {
166
+ */ function normalizeForType(def, value, opts) {
167
+ const writes = require_user_text.typeWriteCount();
168
+ if (writes !== stampWrites) {
239
169
  stampWrites = writes;
240
- stampEpoch = epoch;
241
170
  reach = /* @__PURE__ */ new WeakMap();
242
171
  }
243
172
  if (!hasNormalizers(def)) return value;
244
- const result = normalize(def, value, 0, /* @__PURE__ */ new Map());
173
+ const result = normalize(def, value, 0, {
174
+ memo: /* @__PURE__ */ new Map(),
175
+ root: value,
176
+ opts
177
+ });
245
178
  return result === NO_MATCH ? value : result;
246
179
  }
247
180
  /** The nodes `def`'s value walk can enter (props, pattern props, items, elements). */ function childrenOf(def) {
@@ -306,7 +239,7 @@ let stampEpoch = -1;
306
239
  if (meta.get("normalize.uppercase")) flags |= UPPERCASE;
307
240
  return flags;
308
241
  }
309
- function applyFlags(value, flags) {
242
+ /** `value` with normalizer `flags` applied, in their fixed order (see {@link flagsOf}). */ function applyFlags(value, flags) {
310
243
  let out = value;
311
244
  if (flags & TRIM) out = out.trim();
312
245
  if (flags & LOWERCASE) out = out.toLowerCase();
@@ -320,37 +253,37 @@ function applyFlags(value, flags) {
320
253
  * Objects and unions are memoized per call by input object: a recursive union without a
321
254
  * discriminator is tried for every branch at every level, which without it is exponential in
322
255
  * the depth of the value.
323
- */ function normalize(def, value, inherited, memo) {
256
+ */ function normalize(def, value, inherited, walk) {
324
257
  if (value === void 0 || value === null) return value;
325
- if (inherited === 0 && !hasNormalizers(def)) return takes(def, value) ? value : NO_MATCH;
258
+ if (inherited === 0 && !hasNormalizers(def)) return takes$1(def, value) ? value : NO_MATCH;
326
259
  const type = def.type;
327
260
  switch (type.kind) {
328
261
  case "": {
329
262
  const out = typeof value === "string" && type.designType === "string" ? applyFlags(value, flagsOf(def, inherited)) : value;
330
- return takes(def, out) ? out : NO_MATCH;
263
+ return takes$1(def, out) ? out : NO_MATCH;
331
264
  }
332
265
  case "object": {
333
266
  if (!isPlainObject$1(value)) return NO_MATCH;
334
- const entries = entriesOf(memo, value);
335
- return recall(entries, type, 0) ?? remember(entries, type, 0, mapProps(type, value, normalizeProp, memo));
267
+ const entries = entriesOf(walk.memo, value);
268
+ return recall(entries, type, 0) ?? remember(entries, type, 0, mapProps(type, value, normalizeProp, walk));
336
269
  }
337
- case "array": return Array.isArray(value) ? mapItems(value, type.of, normalizeItem, memo) : NO_MATCH;
270
+ case "array": return Array.isArray(value) ? mapItems(value, type.of, normalizeItem, walk) : NO_MATCH;
338
271
  case "tuple": {
339
272
  const items = type.items;
340
- return Array.isArray(value) && value.length === items.length ? mapItems(value, items, normalizeItem, memo) : NO_MATCH;
273
+ return Array.isArray(value) && value.length === items.length ? mapItems(value, items, normalizeItem, walk) : NO_MATCH;
341
274
  }
342
275
  case "union": {
343
276
  const flags = flagsOf(def, inherited);
344
277
  const items = type.items;
345
- if (typeof value !== "object") return normalizeUnion(items, value, flags, memo);
346
- const entries = entriesOf(memo, value);
347
- return recall(entries, type, flags) ?? remember(entries, type, flags, normalizeUnion(items, value, flags, memo));
278
+ if (typeof value !== "object") return normalizeUnion(items, value, flags, walk);
279
+ const entries = entriesOf(walk.memo, value);
280
+ return recall(entries, type, flags) ?? remember(entries, type, flags, normalizeUnion(items, value, flags, walk));
348
281
  }
349
282
  case "intersection": {
350
283
  const flags = flagsOf(def, inherited);
351
284
  let current = value;
352
285
  for (const item of type.items) {
353
- const result = normalize(item, current, flags, memo);
286
+ const result = normalize(item, current, flags, walk);
354
287
  if (result === NO_MATCH) return NO_MATCH;
355
288
  current = result;
356
289
  }
@@ -378,20 +311,47 @@ function applyFlags(value, flags) {
378
311
  ]);
379
312
  return result;
380
313
  }
381
- /** An array / tuple item: its normalized value, else the value as it is. */ function normalizeItem(def, input, memo) {
314
+ /** An array / tuple item: its normalized value, else the value as it is. */ function normalizeItem(def, input, walk) {
382
315
  if (!hasNormalizers(def)) return input;
383
- const result = normalize(def, input, 0, memo);
316
+ const result = normalize(def, input, 0, walk);
384
317
  return result === NO_MATCH ? input : result;
385
318
  }
386
319
  /**
387
320
  * A prop: as {@link normalizeItem}, but NO_MATCH (the object is not this type) when a literal prop
388
- * (`kind: 'cat'`) holds another value.
389
- */ function normalizeProp(def, input, memo) {
390
- const out = normalizeItem(def, input, memo);
391
- if (out === input && def.type.kind === "" && def.type.value !== void 0 && input !== def.type.value && input !== void 0 && input !== null) return NO_MATCH;
321
+ * (`kind: 'cat'`, `kind: 'cat' | null`, see {@link literalNodes}) holds another value.
322
+ */ function normalizeProp(def, input, walk) {
323
+ const out = normalizeItem(def, input, walk);
324
+ if (out === input && input !== void 0 && input !== null) {
325
+ const literals = literalNodes(def);
326
+ if (literals && !literals.some((l) => l.node.type.value === input)) return NO_MATCH;
327
+ }
392
328
  return out;
393
329
  }
394
- /** Whether `def` can take `value` by its kind alone (see {@link normalize}). */ function takes(def, value) {
330
+ /**
331
+ * The literals a literal prop can hold: `def` itself when it is a literal (`kind: 'cat'`), the
332
+ * literals of a union of literals, `null` and `undefined` (`kind: 'cat' | null`, nested unions and
333
+ * aliases too); `undefined` for any other type. Each with the normalizers of the nodes on its way
334
+ * (a union's apply to its members). A literal prop holding another value tells that an object is
335
+ * not of its type, for normalization and coercion alike (see `coerce.ts`).
336
+ */ function literalNodes(def, inherited = 0) {
337
+ const type = def.type;
338
+ if (type.kind === "") return type.value === void 0 ? void 0 : [{
339
+ node: def,
340
+ flags: flagsOf(def, inherited)
341
+ }];
342
+ if (type.kind !== "union") return;
343
+ const flags = flagsOf(def, inherited);
344
+ const out = [];
345
+ for (const item of type.items) {
346
+ const designType = item.type.designType;
347
+ if (item.type.kind === "" && (designType === "null" || designType === "undefined")) continue;
348
+ const inner = literalNodes(item, flags);
349
+ if (!inner) return;
350
+ out.push(...inner);
351
+ }
352
+ return out.length > 0 ? out : void 0;
353
+ }
354
+ /** Whether `def` can take `value` by its kind alone (see {@link normalize}). */ function takes$1(def, value) {
395
355
  const type = def.type;
396
356
  switch (type.kind) {
397
357
  case "": {
@@ -410,8 +370,8 @@ function applyFlags(value, flags) {
410
370
  case "object": return isPlainObject$1(value);
411
371
  case "array": return Array.isArray(value);
412
372
  case "tuple": return Array.isArray(value) && value.length === type.items.length;
413
- case "union": return type.items.some((item) => takes(item, value));
414
- case "intersection": return type.items.every((item) => takes(item, value));
373
+ case "union": return type.items.some((item) => takes$1(item, value));
374
+ case "intersection": return type.items.every((item) => takes$1(item, value));
415
375
  default: return false;
416
376
  }
417
377
  }
@@ -419,19 +379,19 @@ function applyFlags(value, flags) {
419
379
  * A union: the branch a discriminator names, else the one result every branch that can take
420
380
  * the value agrees on — or, when they differ, the one result of the branches whose validator
421
381
  * accepts their result (NO_MATCH when none can take the value or it stays ambiguous).
422
- */ function normalizeUnion(items, value, flags, memo) {
382
+ */ function normalizeUnion(items, value, flags, walk) {
423
383
  if (isPlainObject$1(value)) {
424
384
  const disc = require_user_text.unionDiscriminator(items);
425
385
  if (disc) {
426
386
  const tag = value[disc.property];
427
- for (const [index, literal] of disc.branches) if (literal === tag) return normalize(items[index], value, flags, memo);
387
+ for (const [index, literal] of disc.branches) if (literal === tag) return normalize(items[index], value, flags, walk);
428
388
  }
429
389
  }
430
390
  let first = NO_MATCH;
431
391
  let firstItem;
432
392
  let rest;
433
393
  for (const item of items) {
434
- const out = normalize(item, value, flags, memo);
394
+ const out = normalize(item, value, flags, walk);
435
395
  if (out === NO_MATCH) continue;
436
396
  if (first === NO_MATCH) {
437
397
  first = out;
@@ -440,23 +400,21 @@ function applyFlags(value, flags) {
440
400
  }
441
401
  if (!rest || rest.every(([, out]) => sameValue(out, first))) return first;
442
402
  rest.unshift([firstItem, first]);
403
+ const judges = judgesFor(walk.opts);
404
+ const judge = value === walk.root ? judges.root : judges.nested;
443
405
  let accepted = NO_MATCH;
444
406
  for (const [item, out] of rest) {
445
- if (!branchValidator(item).validate(out, true)) continue;
407
+ if (!branchValidator(judge, item).validate(out, true)) continue;
446
408
  if (accepted === NO_MATCH) accepted = out;
447
409
  else if (!sameValue(accepted, out)) return NO_MATCH;
448
410
  }
449
411
  return accepted;
450
412
  }
451
- /**
452
- * Each union branch's validator (default options; one error is enough to reject a result),
453
- * judging its own normalized result.
454
- */ const branchValidators = /* @__PURE__ */ new WeakMap();
455
- function branchValidator(def) {
456
- let validator = branchValidators.get(def);
413
+ /** Union branch `def`'s validator, judging its own normalized result (see {@link TJudges}). */ function branchValidator(judge, def) {
414
+ let validator = judge.validators.get(def);
457
415
  if (!validator) {
458
- validator = new require_user_text.Validator(def, { errorLimit: 1 });
459
- branchValidators.set(def, validator);
416
+ validator = new require_user_text.Validator(def, judge.opts);
417
+ judge.validators.set(def, validator);
460
418
  }
461
419
  return validator;
462
420
  }
@@ -470,6 +428,210 @@ function branchValidator(def) {
470
428
  return false;
471
429
  }
472
430
 
431
+ //#endregion
432
+ //#region packages/typescript/src/runtime/coerce.ts
433
+ /**
434
+ * Coerces string-transport input (route params, query strings) toward the
435
+ * scalar shapes an annotated type expects.
436
+ *
437
+ * Pure and non-throwing: when a value can't be coerced it is returned
438
+ * untouched, leaving the {@link Validator} to report the proper error.
439
+ * Coercion converts representation only — constraint checks (`@expect.int`,
440
+ * `@expect.min`, patterns) remain the validator's job.
441
+ *
442
+ * Rules:
443
+ * - Strings targeting `number` are trimmed and parsed via `Number()`; only
444
+ * finite results are accepted.
445
+ * - Strings targeting `boolean` accept `"true"/"1"` and `"false"/"0"`.
446
+ * - Unions pick one branch and coerce the value against it only (linear, no
447
+ * backtracking). A scalar branch takes what it parses; an object (tuple)
448
+ * branch takes a plain object (an array of its length) unless a literal
449
+ * property (item) — `kind: 'cat'`, `kind: 'cat' | null` — holds a value that
450
+ * does not coerce to it, a string compared after the normalizers of the
451
+ * literal and of the unions it is in. An object takes the branch its
452
+ * discriminator names (as the validator does: the literal itself first, else
453
+ * `"2"` names a `2` literal), else the first whose shape it has (required
454
+ * props present, no undeclared key), else the first that takes it. When no
455
+ * branch takes the value, it is returned untouched.
456
+ * - Objects recurse into props when the input is a plain object (covers
457
+ * `@Query()` DTOs where every field arrives as a string), whatever their
458
+ * literal props hold unless tried as a union branch.
459
+ * - Arrays and tuples coerce items; intersections apply each member in order.
460
+ * - `string` / `decimal` targets never change string input.
461
+ *
462
+ * @example
463
+ * ```ts
464
+ * coerceForType(KafkaOffset, '42') // → 42
465
+ * coerceForType(KafkaOffset, 'abc') // → 'abc' (validator reports the error)
466
+ * ```
467
+ */ function coerceForType(def, value) {
468
+ const result = coerce(def, value);
469
+ return result === NO_MATCH ? value : result;
470
+ }
471
+ /**
472
+ * Coerces a single scalar value toward a design type, using the same rules
473
+ * as {@link coerceForType}. Returns the input untouched when it can't coerce.
474
+ * Useful when only a design type is known (e.g. `design:paramtypes` fallbacks).
475
+ */ function coerceScalar(designType, value) {
476
+ const result = scalar(designType, value);
477
+ return result === NO_MATCH ? value : result;
478
+ }
479
+ /** Returns the coerced value, or NO_MATCH when the value can't fit this node. */ function coerce(def, value) {
480
+ if (value === void 0 || value === null) return def.optional === true ? value : NO_MATCH;
481
+ const type = def.type;
482
+ switch (type.kind) {
483
+ case "": {
484
+ const final = type;
485
+ if (final.designType === "phantom") return value;
486
+ const result = scalar(final.designType, value);
487
+ if (result !== NO_MATCH && final.value !== void 0 && result !== final.value) return NO_MATCH;
488
+ return result;
489
+ }
490
+ case "object":
491
+ if (!isPlainObject$1(value)) return NO_MATCH;
492
+ return mapProps(type, value, coerceChild, void 0);
493
+ case "array": return Array.isArray(value) ? mapItems(value, type.of, coerceChild, void 0) : NO_MATCH;
494
+ case "tuple": {
495
+ const items = type.items;
496
+ return Array.isArray(value) && value.length === items.length ? mapItems(value, items, coerceChild, void 0) : NO_MATCH;
497
+ }
498
+ case "union": {
499
+ const branch = branchOf(type.items, value);
500
+ return branch ? coerce(branch, value) : NO_MATCH;
501
+ }
502
+ case "intersection": {
503
+ let current = value;
504
+ for (const item of type.items) {
505
+ const result = coerce(item, current);
506
+ if (result === NO_MATCH) return NO_MATCH;
507
+ current = result;
508
+ }
509
+ return current;
510
+ }
511
+ default: throw new Error(`Unknown type kind "${type.kind}"`);
512
+ }
513
+ }
514
+ function scalar(designType, value) {
515
+ switch (designType) {
516
+ case "string":
517
+ case "decimal": return typeof value === "string" ? value : NO_MATCH;
518
+ case "number":
519
+ if (typeof value === "number") return value;
520
+ if (typeof value === "string") {
521
+ const trimmed = value.trim();
522
+ if (trimmed.length > 0) {
523
+ const parsed = Number(trimmed);
524
+ if (Number.isFinite(parsed)) return parsed;
525
+ }
526
+ }
527
+ return NO_MATCH;
528
+ case "boolean":
529
+ if (typeof value === "boolean") return value;
530
+ if (value === "true" || value === "1") return true;
531
+ if (value === "false" || value === "0") return false;
532
+ return NO_MATCH;
533
+ case "object": return typeof value === "object" ? value : NO_MATCH;
534
+ case "any":
535
+ case "phantom": return value;
536
+ default: return NO_MATCH;
537
+ }
538
+ }
539
+ /**
540
+ * The branch of union `items` that takes `value` (see {@link takes}): the one an object's
541
+ * discriminator names; else, for an object, the first that takes it and whose shape it has (see
542
+ * {@link fits}); else the first that takes it, in declared order (a partial patch); `undefined`
543
+ * when none does.
544
+ */ function branchOf(items, value) {
545
+ let first;
546
+ if (isPlainObject$1(value)) {
547
+ const named = discriminatedBranch(items, value);
548
+ if (named && takes(named, value)) return named;
549
+ for (const item of items) if (takes(item, value)) {
550
+ if (fits(item, value)) return item;
551
+ first ?? (first = item);
552
+ }
553
+ return first;
554
+ }
555
+ return items.find((item) => takes(item, value));
556
+ }
557
+ /**
558
+ * Whether object `value` has the shape of branch `def`, by its own keys alone: every required
559
+ * prop is one of them, and each of them is a prop (or matches a prop pattern) of the branch. A
560
+ * union: one of its branches; a branch that is not an object (nor an intersection of objects)
561
+ * has any shape.
562
+ */ function fits(def, value) {
563
+ if (def.type.kind === "union") return def.type.items.some((item) => fits(item, value));
564
+ const objects = [];
565
+ if (!objectsOf(def, objects)) return true;
566
+ for (const o of objects) for (const [key, prop] of o.props) if (!prop.optional && !Object.hasOwn(value, key)) return false;
567
+ return Object.keys(value).every((key) => objects.some((o) => o.props.has(key) || o.propsPatterns.some((p) => p.pattern.test(key))));
568
+ }
569
+ /** Collects the objects `def` is (an object, an intersection of objects); `false` for others. */ function objectsOf(def, out) {
570
+ const type = def.type;
571
+ if (type.kind === "object") {
572
+ out.push(type);
573
+ return true;
574
+ }
575
+ return type.kind === "intersection" && type.items.every((item) => objectsOf(item, out));
576
+ }
577
+ /**
578
+ * Whether union branch `def` takes `value`: exactly when coercing `value` against it does not
579
+ * fail (a branch taken never fails after it), decided from `value` itself — its kind, its length,
580
+ * its direct literal props and items — never from what it holds deeper. A union takes one branch
581
+ * once, so coercion is linear in the value.
582
+ */ function takes(def, value) {
583
+ if (value === void 0 || value === null) return def.optional === true;
584
+ const type = def.type;
585
+ switch (type.kind) {
586
+ case "": return coerce(def, value) !== NO_MATCH;
587
+ case "object":
588
+ if (!isPlainObject$1(value)) return false;
589
+ for (const [key, prop] of type.props) if (Object.hasOwn(value, key) && !holdsLiteral(prop, value[key])) return false;
590
+ return true;
591
+ case "array": return Array.isArray(value);
592
+ case "tuple": {
593
+ const items = type.items;
594
+ return Array.isArray(value) && value.length === items.length && items.every((item, i) => holdsLiteral(item, value[i]));
595
+ }
596
+ case "union": return type.items.some((item) => takes(item, value));
597
+ case "intersection": return type.items.every((item) => takes(item, value));
598
+ default: return false;
599
+ }
600
+ }
601
+ /**
602
+ * Whether prop (item) `def` of a union branch can hold `input`: anything, but a literal prop
603
+ * (see `literalNodes`: `kind: 'cat'`, `kind: 'cat' | null`) only a value that coerces to one of
604
+ * its literals — a string after the normalizers on the literal's way (`' Cat '` to `'cat'` with
605
+ * `@normalize.trim @normalize.lowercase`). `null` / `undefined` are left to the validator.
606
+ */ function holdsLiteral(def, input) {
607
+ if (input === void 0 || input === null) return true;
608
+ const literals = literalNodes(def);
609
+ return !literals || literals.some((literal) => coercesTo(literal, input));
610
+ }
611
+ /** Whether `input` coerces to the value of `literal` (see `holdsLiteral`). */ function coercesTo(literal, input) {
612
+ const value = typeof input === "string" ? applyFlags(input, literal.flags) : input;
613
+ return coerce(literal.node, value) !== NO_MATCH;
614
+ }
615
+ /**
616
+ * The branch of union `items` the discriminator of object `value` names: its literal itself,
617
+ * else the one its value coerces to (`"2"` names `2`, see {@link coercesTo}); `undefined` when the
618
+ * union has no discriminator or the value names no branch.
619
+ */ function discriminatedBranch(items, value) {
620
+ const disc = require_user_text.unionDiscriminator(items);
621
+ if (disc === void 0) return;
622
+ const tag = Object.hasOwn(value, disc.property) ? value[disc.property] : void 0;
623
+ if (tag === void 0 || tag === null) return;
624
+ for (const [index, literal] of disc.branches) if (literal === tag) return items[index];
625
+ for (const [index] of disc.branches) {
626
+ const prop = items[index].type.props.get(disc.property);
627
+ if (prop && holdsLiteral(prop, tag)) return items[index];
628
+ }
629
+ }
630
+ /** A prop / item: its coerced value, else the value as it is (copy-on-change, see `mapProps`). */ function coerceChild(def, input) {
631
+ const result = coerce(def, input);
632
+ return result === NO_MATCH ? input : result;
633
+ }
634
+
473
635
  //#endregion
474
636
  //#region packages/typescript/src/runtime/traverse.ts
475
637
  /**
@@ -1576,12 +1738,12 @@ function isPlainObject(value) {
1576
1738
  /** The lazy JSON schema of each type, with the metadata write count it was built at. */ const lazy = /* @__PURE__ */ new WeakMap();
1577
1739
  /**
1578
1740
  * The JSON schema of `type` built by the runtime (`jsonSchema: 'lazy'`): built once, again after
1579
- * a metadata write (a block, a runtime edit: see `metadataWrites`). Called by generated code
1580
- * (`static toJsonSchema()`), with the `jsonSchemaOptions` of the build (the same for every call
1581
- * of a type).
1741
+ * a type tree write (a block, a runtime edit of metadata or shape: see `typeWrites`). Called by
1742
+ * generated code (`static toJsonSchema()`), with the `jsonSchemaOptions` of the build (the same
1743
+ * for every call of a type).
1582
1744
  */ function lazyJsonSchema(type, opts) {
1583
1745
  const known = lazy.get(type);
1584
- const writes = require_user_text.metadataWriteCount();
1746
+ const writes = require_user_text.typeWriteCount();
1585
1747
  if (known?.writes === writes) return known.schema;
1586
1748
  const schema = buildJsonSchema(type, opts);
1587
1749
  lazy.set(type, {