@atscript/core 0.2.3 → 0.2.4

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/index.cjs CHANGED
@@ -664,6 +664,17 @@ const text$1 = (val) => new Token({
664
664
  return specifier[0] !== "." && specifier[0] !== "/";
665
665
  }
666
666
  /**
667
+ * The import path of an `.as` import as atscript resolves it: without a trailing `.as` extension.
668
+ * `.as` imports may name a file with or without its extension (`'./user'`, `'./user.as'`,
669
+ * `'my-lib/models.as'`); both spellings resolve to the same module. A bare package name
670
+ * (`'my-lib'`, no subpath) is kept as written.
671
+ */ function withoutAsExtension(specifier) {
672
+ if (!specifier.endsWith(".as")) return specifier;
673
+ const slash = specifier.lastIndexOf("/");
674
+ if (specifier.slice(slash + 1) === ".as" || isBareSpecifier(specifier) && parseBareSpecifier(specifier).subpath === ".") return specifier;
675
+ return specifier.slice(0, -3);
676
+ }
677
+ /**
667
678
  * Returns true if the document ID is a bare specifier placeholder.
668
679
  */ function isBareId(id) {
669
680
  return id.startsWith("bare:");
@@ -770,6 +781,7 @@ const resolveCache = /* @__PURE__ */ new Map();
770
781
  * @param fromDir Absolute directory of the importing file
771
782
  * @returns Resolved absolute file path, or undefined if not found
772
783
  */ async function resolveBareSpecifier(specifier, fromDir) {
784
+ specifier = withoutAsExtension(specifier);
773
785
  const cacheKey = `${fromDir}\0${specifier}`;
774
786
  if (resolveCache.has(cacheKey)) return resolveCache.get(cacheKey);
775
787
  const result = await _resolveBareSpecifier(specifier, fromDir);
@@ -815,16 +827,17 @@ async function _resolveBareSpecifier(specifier, fromDir) {
815
827
  //#endregion
816
828
  //#region packages/core/src/parser/utils.ts
817
829
  /** {@link resolveAtscriptFromPath} by document id and import path (a pure function of both). */ const resolvedFromPaths = /* @__PURE__ */ new Map();
818
- function resolveAtscriptFromPath(from, id) {
830
+ function resolveAtscriptFromPath(written, id) {
819
831
  let byFrom = resolvedFromPaths.get(id);
820
832
  if (!byFrom) {
821
833
  byFrom = /* @__PURE__ */ new Map();
822
834
  resolvedFromPaths.set(id, byFrom);
823
835
  }
824
- let resolved = byFrom.get(from);
836
+ let resolved = byFrom.get(written);
825
837
  if (resolved === void 0) {
838
+ const from = withoutAsExtension(written);
826
839
  resolved = isBareSpecifier(from) ? `bare:${from}.as` : `file://${path.default.join(fileUriToPath(id).split("/").slice(0, -1).join("/"), from)}.as`;
827
- byFrom.set(from, resolved);
840
+ byFrom.set(written, resolved);
828
841
  }
829
842
  return resolved;
830
843
  }
@@ -1293,6 +1306,10 @@ function _define_property$9(obj, key, value) {
1293
1306
  else obj[key] = value;
1294
1307
  return obj;
1295
1308
  }
1309
+ /**
1310
+ * The built-in annotation of `annotate` blocks that removes another annotation from the node
1311
+ * (`@annotate.reset 'expect.pattern'`): a directive, never written as metadata.
1312
+ */ const ANNOTATE_RESET = "annotate.reset";
1296
1313
  /** Whether an annotation argument type is written in backticks (`query`, `expr`, `order`). */ function isBacktickArgType(type) {
1297
1314
  return type === "query" || type === "expr" || type === "order";
1298
1315
  }
@@ -1311,7 +1328,7 @@ var AnnotationSpec = class {
1311
1328
  return this.arguments.map((arg, index) => {
1312
1329
  const placeholderIndex = index + 1;
1313
1330
  const defaultValue = this.getDefaultValueForType(arg.name, arg.type);
1314
- const quote = arg.type === "string" ? `'` : isBacktickArgType(arg.type) ? "`" : "";
1331
+ const quote = arg.type === "string" || arg.type === "value" ? `'` : isBacktickArgType(arg.type) ? "`" : "";
1315
1332
  return `${quote}\${${placeholderIndex}:${defaultValue}}${quote}`;
1316
1333
  }).join(", ");
1317
1334
  }
@@ -1321,6 +1338,7 @@ var AnnotationSpec = class {
1321
1338
  case "number": return tokenType === "number" ? void 0 : "number expected.";
1322
1339
  case "boolean": return tokenType === "identifier" ? void 0 : "boolean expected.";
1323
1340
  case "ref": return tokenType === "identifier" ? void 0 : "type reference expected.";
1341
+ case "value": return tokenType === "text" || tokenType === "number" || tokenType === "identifier" ? void 0 : "string, number or boolean expected.";
1324
1342
  case "query":
1325
1343
  case "expr":
1326
1344
  case "order": return tokenType === "query" ? void 0 : BACKTICK_TYPE_MESSAGES[type];
@@ -1377,7 +1395,7 @@ var AnnotationSpec = class {
1377
1395
  });
1378
1396
  continue;
1379
1397
  }
1380
- const values = argSpec.type === "boolean" ? ["true", "false"] : argSpec.values;
1398
+ const values = argSpec.type === "boolean" || argSpec.type === "value" && tokenType === "identifier" ? ["true", "false"] : argSpec.values;
1381
1399
  if (values && !values.includes(valueText)) messages.push({
1382
1400
  severity: 1,
1383
1401
  message: `${mainToken.text} at argument #${i + 1} ("${argSpec.name}") must be one of [${values.join(", ")}]`,
@@ -1426,10 +1444,33 @@ var AnnotationSpec = class {
1426
1444
  messages.push(...this.validateTargetType(def, mainToken.range, defDoc) || []);
1427
1445
  }
1428
1446
  }
1447
+ messages.push(...this.validateValueArgs(mainToken, args, doc));
1429
1448
  if (this.config.validate) messages.push(...this.config.validate(mainToken, args, doc) || []);
1430
1449
  return messages.length > 0 ? messages : void 0;
1431
1450
  }
1432
1451
  /**
1452
+ * `value` arguments written as a number or a boolean must fit the annotated field's type: a
1453
+ * number literal a field that holds numbers, a boolean literal one that holds booleans (a
1454
+ * union: one of its members; `unknown`: any). A string is accepted for any field.
1455
+ */ validateValueArgs(mainToken, args, doc) {
1456
+ const messages = [];
1457
+ const specArgs = this.arguments;
1458
+ let kinds = null;
1459
+ for (let i = 0; i < args.length && i < specArgs.length; i++) {
1460
+ const token = args[i];
1461
+ const kind = token.type === "number" ? "number" : token.type === "identifier" ? "boolean" : void 0;
1462
+ if (specArgs[i].type !== "value" || !kind) continue;
1463
+ if (kinds === null) kinds = annotatedValueKinds(mainToken, doc);
1464
+ if (!kinds) return messages;
1465
+ if (!literalFits(kind, kinds)) messages.push({
1466
+ severity: 1,
1467
+ message: `${mainToken.text} at argument #${i + 1} ("${specArgs[i].name}"): a ${kind} does not fit the field's type (${[...kinds].join(" | ") || "unknown"}).`,
1468
+ range: token.range
1469
+ });
1470
+ }
1471
+ return messages;
1472
+ }
1473
+ /**
1433
1474
  * Checks an already-resolved target node against this annotation's `defType`
1434
1475
  * guard (e.g. `@expect.minLength` requires `string | array`). Returns a
1435
1476
  * diagnostic when the type doesn't match, or `undefined` when it matches or no
@@ -1462,9 +1503,9 @@ var AnnotationSpec = class {
1462
1503
  const a = this.arguments[index];
1463
1504
  if (a) {
1464
1505
  const values = a.values ? `\n\nValues:\n${a.values.join(", ")}` : "";
1465
- return `### \`${a.name}${a.optional ? "?" : ""}: ${a.type}\`\n\n${a.description}${values}`;
1506
+ return `### \`${a.name}${a.optional ? "?" : ""}: ${argTypeLabel(a)}\`\n\n${a.description}${values}`;
1466
1507
  }
1467
- } else return `### ${index} ${this.arguments.map((a) => `\`${a.name}${a.optional ? "?" : ""}: ${a.type}\``).join(", ")}\n\n${this.config.description}`;
1508
+ } else return `### ${index} ${this.arguments.map((a) => `\`${a.name}${a.optional ? "?" : ""}: ${argTypeLabel(a)}\``).join(", ")}\n\n${this.config.description}`;
1468
1509
  }
1469
1510
  getDefaultValueForType(name, type) {
1470
1511
  switch (type) {
@@ -1475,6 +1516,7 @@ var AnnotationSpec = class {
1475
1516
  case "query": return "field = value";
1476
1517
  case "expr": return "field + 1";
1477
1518
  case "order": return "field asc";
1519
+ case "value": return name;
1478
1520
  default: return "";
1479
1521
  }
1480
1522
  }
@@ -1485,6 +1527,9 @@ var AnnotationSpec = class {
1485
1527
  this.__is_annotation_spec = true;
1486
1528
  }
1487
1529
  };
1530
+ /** An argument's type as the docs show it (`value`: the literals it takes). */ function argTypeLabel(a) {
1531
+ return a.type === "value" ? "string | number | boolean" : a.type;
1532
+ }
1488
1533
  function isAnnotationSpec(a) {
1489
1534
  return Boolean(a) && a.__is_annotation_spec;
1490
1535
  }
@@ -1508,6 +1553,29 @@ function isAnnotationSpec(a) {
1508
1553
  };
1509
1554
  walk(tree);
1510
1555
  }
1556
+ /**
1557
+ * Where annotation `spec` holds user-facing text (arguments flagged `userText`): `true` — its
1558
+ * value itself (a spec with one argument, not a list: the value is the string; for a `multiple`
1559
+ * annotation, each value); a list — those fields of its value object (a spec with an argument
1560
+ * list). `undefined`: no user-facing text.
1561
+ */ function userTextFields(spec) {
1562
+ const arg = spec.config.argument;
1563
+ if (!arg) return;
1564
+ if (!Array.isArray(arg)) return arg.userText ? true : void 0;
1565
+ const fields = arg.filter((a) => a.userText).map((a) => a.name);
1566
+ return fields.length > 0 ? fields : void 0;
1567
+ }
1568
+ /**
1569
+ * Every annotation of `tree` (core and plugins) holding user-facing text, by full name (see
1570
+ * {@link userTextFields}): what i18n tooling extracts and a translator translates.
1571
+ */ function userTextAnnotations(tree) {
1572
+ const out = /* @__PURE__ */ new Map();
1573
+ forEachAnnotationSpec(tree, (name, spec) => {
1574
+ const fields = userTextFields(spec);
1575
+ if (fields) out.set(name, fields);
1576
+ });
1577
+ return out;
1578
+ }
1511
1579
  function resolveAnnotation(name, annotationsTree) {
1512
1580
  const parts = name.split(".");
1513
1581
  let current = annotationsTree;
@@ -1526,11 +1594,14 @@ function resolveAnnotation(name, annotationsTree) {
1526
1594
  return defType.includes(describeNode(def));
1527
1595
  }
1528
1596
  /** The `defType` vocabulary name of a resolved node (`string`, `object`, `union`, `array`, …). */ function describeNode(def) {
1529
- if (isPrimitive(def)) return def.type || "unknown";
1597
+ if (isPrimitive(def)) return def.type === "any" ? "unknown" : def.type || "unknown";
1530
1598
  if (isInterface(def) || isStructure(def)) return "object";
1531
1599
  if (isGroup(def) && def.entity !== "tuple") return def.op === "&" ? "intersection" : "union";
1532
1600
  return def?.entity || "unknown";
1533
1601
  }
1602
+ /** A `|` group (not a tuple, an inline object `{ … }` or a `&` group). */ function isUnionGroup(node) {
1603
+ return node?.entity === "group" && node.op !== "&";
1604
+ }
1534
1605
  /** Walks a `|` union (flattening nested unions and union aliases), resolving member refs. */ function walkUnionMembers(def, doc, cb, seen = /* @__PURE__ */ new Set()) {
1535
1606
  if (seen.has(def)) return;
1536
1607
  seen.add(def);
@@ -1542,7 +1613,7 @@ function resolveAnnotation(name, annotationsTree) {
1542
1613
  member = unwound?.def;
1543
1614
  memberDoc = unwound?.doc || doc;
1544
1615
  }
1545
- if (isGroup(member) && member.entity !== "tuple" && member.op !== "&") walkUnionMembers(member, memberDoc, cb, seen);
1616
+ if (isUnionGroup(member)) walkUnionMembers(member, memberDoc, cb, seen);
1546
1617
  else cb(member);
1547
1618
  }
1548
1619
  }
@@ -1569,7 +1640,7 @@ function describeUnionMembers(def, doc) {
1569
1640
  * const ok = members ? members.length > 0 && members.every(isWanted) : isWanted(def)
1570
1641
  * ```
1571
1642
  */ function nonNullishMembers(def, doc) {
1572
- if (!isGroup(def) || def.entity === "tuple" || def.op === "&") return;
1643
+ if (!isUnionGroup(def)) return;
1573
1644
  const members = [];
1574
1645
  walkUnionMembers(def, doc, (m) => {
1575
1646
  if (m && !isNullishPrimitive(m)) members.push(m);
@@ -1577,6 +1648,73 @@ function describeUnionMembers(def, doc) {
1577
1648
  return members;
1578
1649
  }
1579
1650
  /**
1651
+ * The resolved type of the field (or type) an annotation is written on: an inline prop's, the
1652
+ * prop an `annotate` block entry names, an `annotate` block's target. `undefined` when it does
1653
+ * not resolve (reported elsewhere).
1654
+ */ function annotatedFieldType(mainToken, doc) {
1655
+ const parent = mainToken.parentNode;
1656
+ if (!parent) return;
1657
+ const at = parent.entity === "annotate" ? doc.unwindType(parent.targetName) : doc.annotatedDefinition(parent);
1658
+ if (!at?.def) return;
1659
+ if (isRef(at.def)) {
1660
+ const unwound = at.doc.unwindRef(at.def);
1661
+ return unwound?.def ? {
1662
+ def: unwound.def,
1663
+ doc: unwound.doc
1664
+ } : void 0;
1665
+ }
1666
+ return {
1667
+ def: at.def,
1668
+ doc: at.doc
1669
+ };
1670
+ }
1671
+ /**
1672
+ * The scalar kinds a resolved type holds (`string`, `number`, `boolean`, `decimal`; `unknown`:
1673
+ * any value), through references and aliases: a union's members' (not `null` / `undefined`), a
1674
+ * scalar merge's kinds every member has (`unknown` takes no part: `unknown & number` is a
1675
+ * number), a literal's.
1676
+ */ function valueKinds(def, doc, seen = /* @__PURE__ */ new Set()) {
1677
+ let node = def;
1678
+ let at = doc;
1679
+ while (node && isGroup(node) && !node.op && node.unwrap().length === 1) node = node.unwrap()[0];
1680
+ if (isRef(node)) {
1681
+ const unwound = at.unwindRef(node);
1682
+ node = unwound?.def;
1683
+ at = unwound?.doc ?? at;
1684
+ }
1685
+ if (!node || seen.has(node)) return /* @__PURE__ */ new Set();
1686
+ seen.add(node);
1687
+ if (node.entity === "const") return new Set([node.token("identifier")?.type === "number" ? "number" : "string"]);
1688
+ if (isGroup(node) && node.entity !== "tuple" && node.op === "&") {
1689
+ let out;
1690
+ for (const m of node.unwrap()) {
1691
+ const ks = valueKinds(m, at, seen);
1692
+ if (ks.size === 1 && ks.has("unknown")) continue;
1693
+ out = out ? new Set([...out].filter((k) => ks.has(k))) : ks;
1694
+ }
1695
+ return out ?? new Set(["unknown"]);
1696
+ }
1697
+ const members = nonNullishMembers(node, at);
1698
+ if (members) {
1699
+ const out = /* @__PURE__ */ new Set();
1700
+ for (const m of members) for (const k of valueKinds(m, at, seen)) out.add(k);
1701
+ return out;
1702
+ }
1703
+ return new Set([describeNode(node)]);
1704
+ }
1705
+ /**
1706
+ * The scalar kinds the field (or type) annotation `mainToken` is written on holds (see
1707
+ * `valueKinds`): `string`, `number`, `boolean`, `decimal`, `unknown` (any value), or another
1708
+ * kind name (`object`, `array`, …). `undefined` when the field does not resolve. Code generators
1709
+ * use it for `value` arguments: a number literal on a `decimal` field is written as its string.
1710
+ */ function annotatedValueKinds(mainToken, doc) {
1711
+ const target = annotatedFieldType(mainToken, doc);
1712
+ return target ? valueKinds(target.def, target.doc) : void 0;
1713
+ }
1714
+ /** Whether a literal of `kind` (`number`, `boolean`) fits a field of `kinds` (see `valueKinds`). */ function literalFits(kind, kinds) {
1715
+ return kinds.has("unknown") || kinds.has(kind) || kind === "number" && kinds.has("decimal");
1716
+ }
1717
+ /**
1580
1718
  * The node type an `annotate` block's top-level annotations apply to: its target's (`interface`
1581
1719
  * or `type`; through an `annotate … as` alias, the alias's target's). `undefined` while the
1582
1720
  * target does not resolve (reported elsewhere).
@@ -4200,6 +4338,11 @@ var TSeverity = /* @__PURE__ */ function(TSeverity) {
4200
4338
  const UNION_IN_RECURSIVE_MERGE = "union members are not supported in recursive merges; split with named types";
4201
4339
  const MERGE_TOO_COMPLEX = "merge too complex: split it with named types";
4202
4340
  /** Why scalars (or an object and a scalar) merge to `never`. */ const NOTHING_IN_COMMON = "values with nothing in common";
4341
+ /**
4342
+ * Why a merge of `unknown` (any value) with an object, an array or `null` is refused: TypeScript
4343
+ * reads `unknown & X` as `X`, a merge of values would be `never` (a compile error, not a
4344
+ * validator rejecting what the `.d.ts` accepts).
4345
+ */ const OPAQUE_MERGE = "\"unknown\" cannot be merged with an object, an array or null";
4203
4346
  /** A type written as an operand of its own merge (`type X = A & X`). */ const SELF_OPERAND = "a type cannot be an operand of its own merge; recurse through a field instead";
4204
4347
  /** A db entity whose flattening reaches a web of mutually recursive merges. */ const FLATTEN_WEB = "flattening this type reaches mutually recursive merges; split it with named types";
4205
4348
  /**
@@ -4207,6 +4350,8 @@ const MERGE_TOO_COMPLEX = "merge too complex: split it with named types";
4207
4350
  * itself splits (MODEL §15 SELF-SPLIT): where it lands depends on the positions it decides.
4208
4351
  */ const SELF_SPLIT = "A block's path can't cross the type path it splits.";
4209
4352
  const isBranch = (s) => s.startsWith("|");
4353
+ /** A shape of the `unknown` primitive (any value). */ const isAnyShape = (s) => s.k === "scalar" && s.any === true;
4354
+ /** Merge refusals reported as errors, never dropped as a `never` branch. */ const refused = (reason) => reason === MERGE_TOO_COMPLEX || reason === OPAQUE_MERGE;
4210
4355
  /** A step that is a prop's name (not a union branch, an in-place merge operand or an element). */ const isNameStep = (s) => !s.startsWith("|") && !s.startsWith("&") && s !== "[]";
4211
4356
  /** A written `null`. */ const isNull = (x) => x.k === "scalar" && isPrimitive(x.node) && x.node.key === "null";
4212
4357
  /** A shape that is, or has a branch that is, an array. */ const holdsArray = (s) => s?.k === "arr" || s?.k === "uni" && s.items.some(holdsArray);
@@ -6411,7 +6556,12 @@ function fieldLoc(s) {
6411
6556
  }
6412
6557
  shape0(t) {
6413
6558
  switch (t.k) {
6414
- case "scalar": return isPrimitive(t.node) && t.node.key === "null" ? { k: "mixed" } : { k: "scalar" };
6559
+ case "scalar":
6560
+ if (!isPrimitive(t.node)) return { k: "scalar" };
6561
+ return t.node.key === "null" ? { k: "mixed" } : t.node.type === "any" ? {
6562
+ k: "scalar",
6563
+ any: true
6564
+ } : { k: "scalar" };
6415
6565
  case "tup": {
6416
6566
  const items = t.items.map((i) => this.shape(i));
6417
6567
  if (!items.every((s) => s.k === "scalar" || s.k === "never")) return { k: "mixed" };
@@ -6423,6 +6573,10 @@ function fieldLoc(s) {
6423
6573
  case "uni": {
6424
6574
  if (t.struct) return this.shape(structExpr(t));
6425
6575
  const ss = t.items.map((i) => this.shape(i));
6576
+ if (ss.some(isAnyShape)) return {
6577
+ k: "scalar",
6578
+ any: true
6579
+ };
6426
6580
  if (ss.every((s) => s.k === "scalar" || s.k === "never")) return ss.every((s) => s.k === "never") ? {
6427
6581
  k: "never",
6428
6582
  reason: "union"
@@ -6490,13 +6644,17 @@ function fieldLoc(s) {
6490
6644
  * algebra: disjoint scalars are `never`), a single union operand of objects distributes.
6491
6645
  */ combine(ss, ends) {
6492
6646
  if (ss.length === 1) return ss[0];
6647
+ if (ss.some(isAnyShape) && !ss.every((s) => s.k === "scalar" || s.k === "never")) return {
6648
+ k: "never",
6649
+ reason: OPAQUE_MERGE
6650
+ };
6493
6651
  const tuple = ends.length === ss.length ? this.tupleShape(ends) : void 0;
6494
6652
  if (tuple) return tuple;
6495
6653
  if (ss.some((s) => s.k === "mixed")) {
6496
6654
  if (ends.length === ss.length && ends.some(isNull) && ends.every((e) => isNull(e) || this.nullable(e))) return { k: "scalar" };
6497
6655
  const leaves = ends.length === ss.length ? this.mixedLeaves(ss, ends) : void 0;
6498
6656
  const product = leaves && this.productShape(leaves.ss, leaves.ends);
6499
- if (product?.k === "never" && product.reason === MERGE_TOO_COMPLEX) return product;
6657
+ if (product?.k === "never" && refused(product.reason)) return product;
6500
6658
  return product?.k === "never" ? {
6501
6659
  k: "never",
6502
6660
  reason: NOTHING_IN_COMMON
@@ -6567,6 +6725,7 @@ function fieldLoc(s) {
6567
6725
  }
6568
6726
  const es = pick.map((p) => p.e);
6569
6727
  const c = this.combine(pick.map((p) => p.s), es.every(Boolean) ? es : []);
6728
+ if (c.k === "never" && c.reason === OPAQUE_MERGE) return c;
6570
6729
  if (c.k !== "never" && c.k !== "mixed") out.push(c);
6571
6730
  }
6572
6731
  if (out.length === 0) return {
@@ -8286,12 +8445,12 @@ var AtscriptDoc = class AtscriptDoc {
8286
8445
  * them to its target's metadata: an `append` annotation adds its values after the existing
8287
8446
  * ones, any other replaces them.
8288
8447
  */ overlayAnnotations(base, overlay) {
8289
- const replaced = /* @__PURE__ */ new Set();
8448
+ const replaced = resetNames(overlay) ?? /* @__PURE__ */ new Set();
8290
8449
  for (const a of overlay) {
8291
8450
  const spec = this.resolveAnnotation(a.name);
8292
8451
  if (!(spec?.config.multiple && spec.config.mergeStrategy === "append")) replaced.add(a.name);
8293
8452
  }
8294
- return [...(base ?? []).filter((a) => !replaced.has(a.name)), ...overlay];
8453
+ return [...(base ?? []).filter((a) => a.name === ANNOTATE_RESET || !replaced.has(a.name)), ...overlay];
8295
8454
  }
8296
8455
  /**
8297
8456
  * What declaration `decl` (of this document) is defined as — an alias's, its target's (an
@@ -8660,7 +8819,7 @@ var AtscriptDoc = class AtscriptDoc {
8660
8819
  */ evalAnnotationsForNode(givenNode, own = givenNode.annotations, blocks = false) {
8661
8820
  if (isAnnotate(givenNode) && !givenNode.isMutating) {
8662
8821
  const target = this.getDeclarationOwnerNode(givenNode.targetName);
8663
- return this.mergeNodesAnnotations(target?.node && target.node !== givenNode ? target.doc.evalAnnotationsForNode(target.node, annotationsOf(target.node, blocks), blocks) : void 0, own);
8822
+ return stripResets(this.mergeNodesAnnotations(target?.node && target.node !== givenNode ? target.doc.evalAnnotationsForNode(target.node, annotationsOf(target.node, blocks), blocks) : void 0, own, true));
8664
8823
  }
8665
8824
  return this.evalAnnotationsForDefinition(givenNode.getDefinition(), own, givenNode, blocks);
8666
8825
  }
@@ -8689,24 +8848,24 @@ var AtscriptDoc = class AtscriptDoc {
8689
8848
  for (const chainNode of chainNodes) {
8690
8849
  if (chainNode === unwound?.def) continue;
8691
8850
  const anns = chainNode === unwound?.node && fieldAnns ? fieldAnns : annotationsOf(chainNode, blocks);
8692
- right = this.mergeNodesAnnotations(this.filterPassedWhenReferred(anns, viaProp), right);
8851
+ right = this.mergeNodesAnnotations(this.filterPassedWhenReferred(anns, viaProp), right, true);
8693
8852
  }
8694
8853
  def = unwound?.def || def;
8695
8854
  }
8696
8855
  if (def) {
8697
8856
  const merged = this.mergeIntersection(def);
8698
8857
  if (merged !== def && isRef(merged)) {
8699
- right = this.mergeNodesAnnotations(merged.annotations, right);
8858
+ right = this.mergeNodesAnnotations(merged.annotations, right, true);
8700
8859
  def = merged;
8701
8860
  continue;
8702
8861
  }
8703
8862
  const written = unparenthesized(def);
8704
8863
  const own = isIntersection(written) ? this.intersectionAnnotations(written, blocks).map((p) => p.an) : refDef ? annotationsOf(merged, blocks) : merged.annotations;
8705
- right = this.mergeNodesAnnotations(refDef ? this.filterPassedWhenReferred(own, viaProp) : own, right);
8864
+ right = this.mergeNodesAnnotations(refDef ? this.filterPassedWhenReferred(own, viaProp) : own, right, true);
8706
8865
  }
8707
8866
  break;
8708
8867
  }
8709
- return right;
8868
+ return stripResets(right);
8710
8869
  }
8711
8870
  /**
8712
8871
  * The annotations of the field chain reference `ref` names (its node `node`), with the blocks:
@@ -8916,7 +9075,7 @@ var AtscriptDoc = class AtscriptDoc {
8916
9075
  const idToken = prop.token("identifier");
8917
9076
  if (idToken) cloned.saveToken(idToken, "identifier");
8918
9077
  if (newDef) cloned.define(newDef);
8919
- cloned.annotations = group.own.length === 0 ? prop.annotations : this.mergeNodesAnnotations(prop.annotations, group.own);
9078
+ cloned.annotations = group.own.length === 0 ? prop.annotations : this.mergeNodesAnnotations(prop.annotations, group.own, true);
8920
9079
  const optionalToken = prop.token("optional");
8921
9080
  if (optionalToken) cloned.saveToken(optionalToken, "optional");
8922
9081
  newProps.push(cloned);
@@ -9539,6 +9698,11 @@ var AtscriptDoc = class AtscriptDoc {
9539
9698
  message: MERGE_TOO_COMPLEX,
9540
9699
  range: token.range
9541
9700
  });
9701
+ else if (token && reason === OPAQUE_MERGE) messages.push({
9702
+ severity: TSeverity.Error,
9703
+ message: `${OPAQUE_MERGE}${path.length > 0 ? ` at "${decl.name}.${path.join(".")}"` : ` in "${decl.name}"`}: write the other type alone`,
9704
+ range: token.range
9705
+ });
9542
9706
  else if (token) messages.push({
9543
9707
  severity: TSeverity.Warning,
9544
9708
  message: `Intersection of ${reason} cannot be merged${path.length > 0 ? ` at "${decl.name}.${path.join(".")}"` : ` in "${decl.name}"`}; the type resolves to never`,
@@ -10114,14 +10278,29 @@ var AtscriptDoc = class AtscriptDoc {
10114
10278
  add(group);
10115
10279
  return out;
10116
10280
  }
10117
- mergeNodesAnnotations(left, right) {
10281
+ /**
10282
+ * Annotations `right` over `left`: right's win, `append` ones of both kept (left's after).
10283
+ *
10284
+ * `layered`: `right` is a node's and `left` what the node is layered over (the type it
10285
+ * references, an `as` copy's target) — right's `@annotate.reset 'x'` drop left's x, and the
10286
+ * resets of both stay, for the layers further below (see {@link stripResets}). Else they are
10287
+ * siblings (the members of a merge): a reset applies within its member's own layers only, and
10288
+ * is left out.
10289
+ */ mergeNodesAnnotations(left, right, layered = false) {
10118
10290
  const annotations = [];
10119
10291
  const savedAnnotations = /* @__PURE__ */ new Set();
10292
+ const hidden = layered ? resetNames(right) : void 0;
10120
10293
  for (const a of right || []) {
10294
+ if (a.name === ANNOTATE_RESET && !layered) continue;
10121
10295
  annotations.push(a);
10122
10296
  savedAnnotations.add(a.name);
10123
10297
  }
10124
10298
  for (const a of left || []) {
10299
+ if (a.name === ANNOTATE_RESET) {
10300
+ if (layered) annotations.push(a);
10301
+ continue;
10302
+ }
10303
+ if (hidden?.has(a.name)) continue;
10125
10304
  const spec = this.resolveAnnotation(a.name);
10126
10305
  if (spec && spec.config.multiple && spec.config.mergeStrategy === "append" || !savedAnnotations.has(a.name)) annotations.push(a);
10127
10306
  }
@@ -10330,6 +10509,72 @@ const zeroRange = {
10330
10509
  for (const t of decl.referredIdentifiers) out.add(t);
10331
10510
  return out;
10332
10511
  }
10512
+ /** The annotation names `@annotate.reset` entries of `anns` reset; `undefined`: none. */ function resetNames(anns) {
10513
+ let out;
10514
+ for (const a of anns ?? []) if (a.name === ANNOTATE_RESET && a.args[0]?.type === "text") (out ?? (out = /* @__PURE__ */ new Set())).add(a.args[0].text);
10515
+ return out;
10516
+ }
10517
+ /**
10518
+ * `anns` without their `@annotate.reset` entries: a node's annotations once the resets applied to
10519
+ * the layers below it (see `AtscriptDoc.mergeNodesAnnotations`).
10520
+ */ function stripResets(anns) {
10521
+ return anns?.some((a) => a.name === ANNOTATE_RESET) ? anns.filter((a) => a.name !== ANNOTATE_RESET) : anns;
10522
+ }
10523
+
10524
+ //#endregion
10525
+ //#region packages/core/src/defaults/annotate-annotations.ts
10526
+ /** Whether `name` is in the `annotate` namespace: a directive of `annotate` blocks, never metadata. */ function isAnnotateDirective(name) {
10527
+ return name.startsWith("annotate.");
10528
+ }
10529
+ /** The annotations of the `annotate` namespace: directives of `annotate` blocks, not metadata. */ const annotateAnnotations = { reset: new AnnotationSpec({
10530
+ description: annotationExample("Removes an annotation the annotated field or type would otherwise carry — declared on it, inherited from the type it references (`email: Email`, a primitive like `string.email`), from the target of an `annotate … as` copy, or written by a lower-ranked `annotate` block. Allowed only in `annotate` blocks (mutating and `annotate … as`), on an entry or at the top of the block (the type itself). The block's own value of that annotation applies over the reset; any other value does not. Repeat it to reset several annotations.", "annotate User as PublicUser {", " @annotate.reset 'expect.pattern'", " @expect.pattern '^[a-z]+$'", " login", "", " @annotate.reset 'meta.sensitive'", " token", "}"),
10531
+ multiple: true,
10532
+ argument: {
10533
+ name: "annotation",
10534
+ type: "string",
10535
+ description: "The full name of the annotation to remove, without `@` (`expect.pattern`, `meta.label`).",
10536
+ valueScope: (_token, doc) => annotationNames(doc.config.annotations)
10537
+ },
10538
+ validate(token, args, doc) {
10539
+ const messages = [];
10540
+ const parent = token.parentNode;
10541
+ const id = parent && isRef(parent) ? parent.token("identifier") : void 0;
10542
+ if (!(!!parent && isAnnotate(parent) || !!id && !!doc.annotateBlockAt(id.range.start.line, id.range.start.character))) messages.push({
10543
+ severity: TSeverity.Error,
10544
+ message: "@annotate.reset is allowed only in annotate blocks",
10545
+ range: token.range
10546
+ });
10547
+ const name = args[0]?.type === "text" ? args[0].text : void 0;
10548
+ if (name === void 0) return messages;
10549
+ if (isAnnotateDirective(name) || name === "annotate") messages.push({
10550
+ severity: TSeverity.Error,
10551
+ message: `"${name}" is not metadata: it cannot be reset`,
10552
+ range: args[0].range
10553
+ });
10554
+ else if (!doc.resolveAnnotation(name)) {
10555
+ const unknown = doc.config.unknownAnnotation;
10556
+ if (unknown !== "allow") messages.push({
10557
+ severity: unknown === "warn" ? TSeverity.Warning : TSeverity.Error,
10558
+ message: `Unknown annotation "@${name}"`,
10559
+ range: args[0].range
10560
+ });
10561
+ }
10562
+ return messages;
10563
+ }
10564
+ }) };
10565
+ /** The full names of the metadata annotations of `tree` (completion of `@annotate.reset`). */ function annotationNames(tree) {
10566
+ const out = [];
10567
+ forEachAnnotationSpec(tree ?? {}, (name, spec) => {
10568
+ if (!isAnnotateDirective(name)) {
10569
+ const doc = spec.config.description;
10570
+ out.push({
10571
+ value: name,
10572
+ documentation: doc
10573
+ });
10574
+ }
10575
+ });
10576
+ return out;
10577
+ }
10333
10578
 
10334
10579
  //#endregion
10335
10580
  //#region packages/core/src/defaults/emit-annotations.ts
@@ -10367,6 +10612,13 @@ const emitAnnotations = {
10367
10612
  //#endregion
10368
10613
  //#region packages/core/src/defaults/expect-annotations.ts
10369
10614
  const NULLABLE_NOTE = "Also allowed on a nullable field (`T | null`, `T | undefined`): `null` passes, any other value must satisfy the constraint.";
10615
+ /** The optional message argument of a constraint annotation. */ const MESSAGE_ARG = {
10616
+ name: "message",
10617
+ optional: true,
10618
+ type: "string",
10619
+ description: "Optional error message to display if the validation fails.",
10620
+ userText: true
10621
+ };
10370
10622
  /** Whether `flags` are flags of a JS regular expression. */ function validFlags(flags) {
10371
10623
  try {
10372
10624
  new RegExp("", flags);
@@ -10395,12 +10647,40 @@ const NULLABLE_NOTE = "Also allowed on a nullable field (`T | null`, `T | undefi
10395
10647
  name: argName,
10396
10648
  type: "number",
10397
10649
  description: argDescription
10398
- }, {
10399
- name: "message",
10400
- optional: true,
10401
- type: "string",
10402
- description: "Optional error message to display if the validation fails."
10403
- }]
10650
+ }, MESSAGE_ARG]
10651
+ });
10652
+ }
10653
+ /** Whether `text` (a number argument) is a non-negative integer. */ function isCount(text) {
10654
+ return /^\d+$/.test(text);
10655
+ }
10656
+ /**
10657
+ * `@expect.minKeys` / `maxKeys`: a key count (a non-negative integer) plus an optional message.
10658
+ * `@expect.maxKeys` also checks it is not below the node's `@expect.minKeys`.
10659
+ */ function keyCountSpec(bound, example, argDescription, min) {
10660
+ return new AnnotationSpec({
10661
+ description: annotationExample(`${`Validates that an object has ${bound} this many keys: the keys it keeps (with unknown properties ignored, every own key; else the declared and pattern-matched ones).`} ${NULLABLE_NOTE}`, ...example),
10662
+ defType: ["object"],
10663
+ argument: [{
10664
+ name: "count",
10665
+ type: "number",
10666
+ description: argDescription
10667
+ }, MESSAGE_ARG],
10668
+ validate(mainToken, args) {
10669
+ const count = args[0];
10670
+ if (!count || count.type !== "number") return [];
10671
+ if (!isCount(count.text)) return [{
10672
+ message: `${mainToken.text} expects a non-negative integer`,
10673
+ range: count.range,
10674
+ severity: 1
10675
+ }];
10676
+ const lower = min ? mainToken.parentNode?.annotations?.find((a) => a.name === min)?.args[0] : void 0;
10677
+ if (lower && isCount(lower.text) && Number(lower.text) > Number(count.text)) return [{
10678
+ message: `${mainToken.text} is below @${min} (${lower.text})`,
10679
+ range: count.range,
10680
+ severity: 1
10681
+ }];
10682
+ return [];
10683
+ }
10404
10684
  });
10405
10685
  }
10406
10686
  const expectAnnotations = {
@@ -10411,12 +10691,7 @@ const expectAnnotations = {
10411
10691
  name: "length",
10412
10692
  type: "number",
10413
10693
  description: "The minimum length of the string or array."
10414
- }, {
10415
- name: "message",
10416
- optional: true,
10417
- type: "string",
10418
- description: "Optional error message to display if the validation fails."
10419
- }]
10694
+ }, MESSAGE_ARG]
10420
10695
  }),
10421
10696
  maxLength: new AnnotationSpec({
10422
10697
  description: annotationExample(`Validates that a string or array has a maximum length. ${NULLABLE_NOTE}`, "@expect.maxLength 5", "name: string"),
@@ -10425,12 +10700,7 @@ const expectAnnotations = {
10425
10700
  name: "length",
10426
10701
  type: "number",
10427
10702
  description: "The maximum length of the string or array."
10428
- }, {
10429
- name: "message",
10430
- optional: true,
10431
- type: "string",
10432
- description: "Optional error message to display if the validation fails."
10433
- }]
10703
+ }, MESSAGE_ARG]
10434
10704
  }),
10435
10705
  min: numberBoundSpec("Validates that a number is greater than or equal to a minimum value.", ["@expect.min 18", "age: number"], "minValue", "The minimum value."),
10436
10706
  max: numberBoundSpec("Validates that a number is less than or equal to a maximum value.", ["@expect.max 10", "count: number"], "maxValue", "The maximum value."),
@@ -10438,7 +10708,20 @@ const expectAnnotations = {
10438
10708
  exclusiveMax: numberBoundSpec("Validates that a number is strictly less than a value (the value itself is rejected).", ["@expect.exclusiveMax 1", "ratio: number"], "exclusiveMaxValue", "The exclusive upper bound (the value must be less than this)."),
10439
10709
  int: new AnnotationSpec({
10440
10710
  description: annotationExample(`Validates that a number is an integer (no decimal places). ${NULLABLE_NOTE}`, "@expect.int", "age: number"),
10441
- defType: ["number"]
10711
+ defType: ["number"],
10712
+ argument: [MESSAGE_ARG]
10713
+ }),
10714
+ minKeys: keyCountSpec("at least", ["@expect.minKeys 1", "labels: { [*]: string }"], "The minimum number of keys."),
10715
+ maxKeys: keyCountSpec("at most", ["@expect.maxKeys 20", "labels: { [*]: string }"], "The maximum number of keys.", "expect.minKeys"),
10716
+ message: new AnnotationSpec({
10717
+ description: annotationExample("Custom error message for a type mismatch: wrong type (a non-finite number, a malformed decimal), not the literal (or not one of a literal union's values), no union branch, unknown discriminator, wrong tuple length. Constraint failures keep their own messages (`@expect.minLength` …, `@meta.required`).", "@expect.message 'Choose a valid status'", "status: 'active' | 'blocked'"),
10718
+ nodeType: ["prop", "type"],
10719
+ argument: {
10720
+ name: "message",
10721
+ type: "string",
10722
+ description: "The error message.",
10723
+ userText: true
10724
+ }
10442
10725
  }),
10443
10726
  pattern: new AnnotationSpec({
10444
10727
  description: annotationExample(`Validates that a string matches a specific pattern. ${NULLABLE_NOTE}`, "@expect.pattern \"[a-z]+\", \"u\"", "name: string"),
@@ -10523,12 +10806,7 @@ const expectAnnotations = {
10523
10806
  ],
10524
10807
  description: "Optional flags for the regular expression."
10525
10808
  },
10526
- {
10527
- name: "message",
10528
- optional: true,
10529
- type: "string",
10530
- description: "Optional error message to display if the validation fails."
10531
- }
10809
+ MESSAGE_ARG
10532
10810
  ],
10533
10811
  validate(mainToken, args) {
10534
10812
  if (args[0]) {
@@ -10557,7 +10835,8 @@ const expectAnnotations = {
10557
10835
  name: "message",
10558
10836
  optional: true,
10559
10837
  type: "string",
10560
- description: "Optional custom error message when duplicate items are found."
10838
+ description: "Optional custom error message when duplicate items are found.",
10839
+ userText: true
10561
10840
  }],
10562
10841
  validate(token, args, doc) {
10563
10842
  const field = token.parentNode;
@@ -10588,7 +10867,8 @@ const expectAnnotations = {
10588
10867
  name: "message",
10589
10868
  optional: true,
10590
10869
  type: "string",
10591
- description: "Optional custom error message (used by @expect.array.uniqueItems when checking key-based uniqueness)."
10870
+ description: "Optional custom error message (used by @expect.array.uniqueItems when checking key-based uniqueness).",
10871
+ userText: true
10592
10872
  }],
10593
10873
  validate(token, args, doc) {
10594
10874
  const field = token.parentNode;
@@ -10624,7 +10904,8 @@ const metaAnnotations = {
10624
10904
  argument: {
10625
10905
  name: "text",
10626
10906
  type: "string",
10627
- description: "The label to be used for this field or entity."
10907
+ description: "The label to be used for this field or entity.",
10908
+ userText: true
10628
10909
  }
10629
10910
  }),
10630
10911
  id: new AnnotationSpec({
@@ -10637,7 +10918,8 @@ const metaAnnotations = {
10637
10918
  argument: {
10638
10919
  name: "text",
10639
10920
  type: "string",
10640
- description: "Detailed description for this field or entity."
10921
+ description: "Detailed description for this field or entity.",
10922
+ userText: true
10641
10923
  }
10642
10924
  }),
10643
10925
  documentation: new AnnotationSpec({
@@ -10667,7 +10949,8 @@ const metaAnnotations = {
10667
10949
  name: "message",
10668
10950
  optional: true,
10669
10951
  type: "string",
10670
- description: "Optional error message to display if the validation fails."
10952
+ description: "Optional error message to display if the validation fails.",
10953
+ userText: true
10671
10954
  }],
10672
10955
  passedWhenReferred: false
10673
10956
  }),
@@ -10932,6 +11215,10 @@ const primitives = {
10932
11215
  type: "void",
10933
11216
  documentation: "Represents no value."
10934
11217
  },
11218
+ unknown: {
11219
+ type: "any",
11220
+ documentation: "Any value (an opaque value: JSON data of any shape). Not checked by the validator; JSON Schema `{}`; TypeScript `unknown`."
11221
+ },
10935
11222
  phantom: {
10936
11223
  type: "phantom",
10937
11224
  documentation: "Phantom type. Does not affect the data type, validation, or schema. Discoverable via runtime type traversal."
@@ -10946,7 +11233,8 @@ function getDefaultAtscriptConfig() {
10946
11233
  annotations: {
10947
11234
  meta: { ...metaAnnotations },
10948
11235
  expect: { ...expectAnnotations },
10949
- emit: { ...emitAnnotations }
11236
+ emit: { ...emitAnnotations },
11237
+ annotate: { ...annotateAnnotations }
10950
11238
  }
10951
11239
  };
10952
11240
  }
@@ -11108,12 +11396,14 @@ var AtscriptRepo = class {
11108
11396
  ref: "import(\"@atscript/typescript/utils\").AtscriptRef",
11109
11397
  query: "import(\"@atscript/typescript/utils\").AtscriptQueryNode",
11110
11398
  expr: "import(\"@atscript/typescript/utils\").AtscriptExprNode",
11111
- order: "import(\"@atscript/typescript/utils\").AtscriptOrderItem[]"
11399
+ order: "import(\"@atscript/typescript/utils\").AtscriptOrderItem[]",
11400
+ value: "string | number | boolean"
11112
11401
  };
11113
11402
  const mapArgType = (t) => ANNOTATION_TYPE_MAP[t] || t;
11114
11403
  const manager = await this.getSharedPluginManager();
11115
11404
  const annotations = {};
11116
11405
  if (manager) await manager.loopInAnnotationsSpec((name, spec) => {
11406
+ if (isAnnotateDirective(name)) return;
11117
11407
  const types = [];
11118
11408
  const multiple = !!spec.config.multiple;
11119
11409
  if (Array.isArray(spec.config.argument)) {
@@ -11141,7 +11431,7 @@ var AtscriptRepo = class {
11141
11431
  for (const doc of Array.from(this.atscripts.values())) {
11142
11432
  const awaited = await doc;
11143
11433
  for (const { name, token, args } of awaited.annotations) {
11144
- if (annotations[name]?.fromSpec) continue;
11434
+ if (annotations[name]?.fromSpec || isAnnotateDirective(name)) continue;
11145
11435
  if (!annotations[name]) annotations[name] = {
11146
11436
  multiple: false,
11147
11437
  fromSpec: false,
@@ -11491,6 +11781,7 @@ let tmpSeq = 0;
11491
11781
 
11492
11782
  //#endregion
11493
11783
  exports.$n = $n;
11784
+ exports.ANNOTATE_RESET = ANNOTATE_RESET;
11494
11785
  exports.AnnotationSpec = AnnotationSpec;
11495
11786
  exports.AtscriptDoc = AtscriptDoc;
11496
11787
  exports.AtscriptRepo = AtscriptRepo;
@@ -11503,6 +11794,7 @@ exports.MERGE_CAP = MERGE_CAP;
11503
11794
  exports.MERGE_TOO_COMPLEX = MERGE_TOO_COMPLEX;
11504
11795
  exports.NAV_PROP_ANNOTATIONS = NAV_PROP_ANNOTATIONS;
11505
11796
  exports.NOTHING_IN_COMMON = NOTHING_IN_COMMON;
11797
+ exports.OPAQUE_MERGE = OPAQUE_MERGE;
11506
11798
  exports.PRODUCT_CAP = PRODUCT_CAP;
11507
11799
  exports.PluginManager = PluginManager;
11508
11800
  exports.SELF_OPERAND = SELF_OPERAND;
@@ -11537,6 +11829,7 @@ exports.Token = Token;
11537
11829
  exports.UNION_IN_RECURSIVE_MERGE = UNION_IN_RECURSIVE_MERGE;
11538
11830
  exports.analyzeQueryCursorContext = analyzeQueryCursorContext;
11539
11831
  exports.andExprs = andExprs;
11832
+ exports.annotatedValueKinds = annotatedValueKinds;
11540
11833
  exports.annotationExample = annotationExample;
11541
11834
  exports.baseSlot = baseSlot;
11542
11835
  exports.blockDependencies = blockDependencies;
@@ -11605,4 +11898,7 @@ exports.resolveFieldRefAt = resolveFieldRefAt;
11605
11898
  exports.resolveFieldRefsAt = resolveFieldRefsAt;
11606
11899
  exports.resolveQueryFieldRef = resolveQueryFieldRef;
11607
11900
  exports.unshell = unshell;
11608
- exports.unwoundFields = unwoundFields;
11901
+ exports.unwoundFields = unwoundFields;
11902
+ exports.userTextAnnotations = userTextAnnotations;
11903
+ exports.userTextFields = userTextFields;
11904
+ exports.withoutAsExtension = withoutAsExtension;