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