@atscript/core 0.1.33 → 0.1.35

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.mjs CHANGED
@@ -3,7 +3,7 @@ import { readFile, readdir } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
5
  import { rolldown } from "rolldown";
6
- import { BasicNode } from "@prostojs/parser";
6
+ import { Node, printTree } from "@prostojs/parser";
7
7
  import path$1 from "path";
8
8
  import { URL } from "url";
9
9
  import { defu } from "defu";
@@ -11,7 +11,7 @@ import { mkdir, writeFile } from "fs/promises";
11
11
  import { glob } from "glob";
12
12
 
13
13
  //#region packages/core/src/parser/nodes/semantic-node.ts
14
- function _define_property$15(obj, key, value) {
14
+ function _define_property$16(obj, key, value) {
15
15
  if (key in obj) Object.defineProperty(obj, key, {
16
16
  value,
17
17
  enumerable: true,
@@ -75,6 +75,7 @@ else this.annotationsCounter.set(name, 1);
75
75
  }
76
76
  define(node) {
77
77
  this.definition = node;
78
+ node.ownerNode = this;
78
79
  return this;
79
80
  }
80
81
  get def() {
@@ -121,14 +122,15 @@ else this.annotationsCounter.set(name, 1);
121
122
  return this.definition;
122
123
  }
123
124
  constructor(entity) {
124
- _define_property$15(this, "entity", void 0);
125
- _define_property$15(this, "tokens", void 0);
126
- _define_property$15(this, "isGroup", void 0);
127
- _define_property$15(this, "definition", void 0);
128
- _define_property$15(this, "annotations", void 0);
129
- _define_property$15(this, "annotationsCounter", void 0);
130
- _define_property$15(this, "__typeId", void 0);
131
- _define_property$15(this, "_documentation", void 0);
125
+ _define_property$16(this, "entity", void 0);
126
+ _define_property$16(this, "tokens", void 0);
127
+ _define_property$16(this, "isGroup", void 0);
128
+ _define_property$16(this, "definition", void 0);
129
+ _define_property$16(this, "annotations", void 0);
130
+ _define_property$16(this, "annotationsCounter", void 0);
131
+ _define_property$16(this, "__typeId", void 0);
132
+ _define_property$16(this, "ownerNode", void 0);
133
+ _define_property$16(this, "_documentation", void 0);
132
134
  this.entity = entity;
133
135
  this.isGroup = false;
134
136
  }
@@ -225,7 +227,7 @@ var SemanticConstNode = class extends SemanticNode {
225
227
 
226
228
  //#endregion
227
229
  //#region packages/core/src/parser/nodes/group-node.ts
228
- function _define_property$14(obj, key, value) {
230
+ function _define_property$15(obj, key, value) {
229
231
  if (key in obj) Object.defineProperty(obj, key, {
230
232
  value,
231
233
  enumerable: true,
@@ -270,7 +272,7 @@ var SemanticGroup = class extends SemanticNode {
270
272
  return s;
271
273
  }
272
274
  constructor(nodes = [], operator) {
273
- super("group"), _define_property$14(this, "nodes", void 0), _define_property$14(this, "operator", void 0), _define_property$14(this, "isGroup", void 0), this.nodes = nodes, this.operator = operator, this.isGroup = true;
275
+ super("group"), _define_property$15(this, "nodes", void 0), _define_property$15(this, "operator", void 0), _define_property$15(this, "isGroup", void 0), this.nodes = nodes, this.operator = operator, this.isGroup = true;
274
276
  }
275
277
  };
276
278
 
@@ -292,7 +294,7 @@ var SemanticImportNode = class extends SemanticNode {
292
294
 
293
295
  //#endregion
294
296
  //#region packages/core/src/parser/nodes/interface-node.ts
295
- function _define_property$13(obj, key, value) {
297
+ function _define_property$14(obj, key, value) {
296
298
  if (key in obj) Object.defineProperty(obj, key, {
297
299
  value,
298
300
  enumerable: true,
@@ -340,13 +342,13 @@ var SemanticInterfaceNode = class extends SemanticNode {
340
342
  return s;
341
343
  }
342
344
  constructor() {
343
- super("interface"), _define_property$13(this, "_extendsTokens", []);
345
+ super("interface"), _define_property$14(this, "_extendsTokens", []);
344
346
  }
345
347
  };
346
348
 
347
349
  //#endregion
348
350
  //#region packages/core/src/parser/token.ts
349
- function _define_property$12(obj, key, value) {
351
+ function _define_property$13(obj, key, value) {
350
352
  if (key in obj) Object.defineProperty(obj, key, {
351
353
  value,
352
354
  enumerable: true,
@@ -392,43 +394,46 @@ var Token = class Token {
392
394
  return this._data.type === "annotation";
393
395
  }
394
396
  constructor(_data) {
395
- _define_property$12(this, "_data", void 0);
397
+ _define_property$13(this, "_data", void 0);
396
398
  /**
397
399
  * Set this to file path (e.g. "./src/file.as") for path token in import statement
398
- */ _define_property$12(this, "fromPath", void 0);
400
+ */ _define_property$13(this, "fromPath", void 0);
399
401
  /**
400
402
  * All definitions that exported must be marked with this flag
401
- */ _define_property$12(this, "exported", void 0);
403
+ */ _define_property$13(this, "exported", void 0);
402
404
  /**
403
405
  * All the definitions must be marked with this flag
404
- */ _define_property$12(this, "isDefinition", void 0);
406
+ */ _define_property$13(this, "isDefinition", void 0);
405
407
  /**
406
408
  * All the references must be marked with this flag
407
- */ _define_property$12(this, "isReference", void 0);
409
+ */ _define_property$13(this, "isReference", void 0);
408
410
  /**
409
411
  * All the import tokens must be marked with this flag
410
- */ _define_property$12(this, "imported", void 0);
412
+ */ _define_property$13(this, "imported", void 0);
411
413
  /**
412
414
  * Refs chained via . or ["propName"] are marked with this flag
413
- */ _define_property$12(this, "isChain", void 0);
415
+ */ _define_property$13(this, "isChain", void 0);
414
416
  /**
415
417
  * Prop patterns ([*] or [regexp]) are storing patterns here
416
- */ _define_property$12(this, "pattern", void 0);
417
- _define_property$12(this, "parentNode", void 0);
418
+ */ _define_property$13(this, "pattern", void 0);
419
+ _define_property$13(this, "parentNode", void 0);
418
420
  /**
419
421
  * Only for annotation arguments: reference to their annotation token
420
- */ _define_property$12(this, "annotationRef", void 0);
421
- _define_property$12(this, "index", void 0);
422
+ */ _define_property$13(this, "annotationRef", void 0);
423
+ _define_property$13(this, "index", void 0);
422
424
  /**
423
425
  * Block type
424
- */ _define_property$12(this, "blockType", void 0);
426
+ */ _define_property$13(this, "blockType", void 0);
427
+ /**
428
+ * Parsed query expression tree (for query-type annotation arguments)
429
+ */ _define_property$13(this, "queryNode", void 0);
425
430
  this._data = _data;
426
431
  }
427
432
  };
428
433
 
429
434
  //#endregion
430
435
  //#region packages/core/src/parser/nodes/primitive-node.ts
431
- function _define_property$11(obj, key, value) {
436
+ function _define_property$12(obj, key, value) {
432
437
  if (key in obj) Object.defineProperty(obj, key, {
433
438
  value,
434
439
  enumerable: true,
@@ -477,7 +482,7 @@ else if (value.length > 0) this.annotations.push(toAnnotationTokens(name, value[
477
482
  return indent + s.split("\n").join(`\n${indent}`);
478
483
  }
479
484
  constructor(_id, config, parentKey = "", annotationTree) {
480
- super("primitive"), _define_property$11(this, "_id", void 0), _define_property$11(this, "config", void 0), _define_property$11(this, "parentKey", void 0), _define_property$11(this, "annotationTree", void 0), _define_property$11(this, "type", void 0), _define_property$11(this, "props", void 0), _define_property$11(this, "tags", void 0), this._id = _id, this.config = config, this.parentKey = parentKey, this.annotationTree = annotationTree;
485
+ super("primitive"), _define_property$12(this, "_id", void 0), _define_property$12(this, "config", void 0), _define_property$12(this, "parentKey", void 0), _define_property$12(this, "annotationTree", void 0), _define_property$12(this, "type", void 0), _define_property$12(this, "props", void 0), _define_property$12(this, "tags", void 0), this._id = _id, this.config = config, this.parentKey = parentKey, this.annotationTree = annotationTree;
481
486
  this.props = new Map();
482
487
  this.tags = new Set([_id, ...config?.tags || []]);
483
488
  for (const [ext, def] of Object.entries(config.extensions || {})) {
@@ -598,7 +603,7 @@ var SemanticPropNode = class extends SemanticNode {
598
603
 
599
604
  //#endregion
600
605
  //#region packages/core/src/parser/nodes/ref-node.ts
601
- function _define_property$10(obj, key, value) {
606
+ function _define_property$11(obj, key, value) {
602
607
  if (key in obj) Object.defineProperty(obj, key, {
603
608
  value,
604
609
  enumerable: true,
@@ -650,13 +655,13 @@ var SemanticRefNode = class extends SemanticNode {
650
655
  return indent + s.split("\n").join(`\n${indent}`);
651
656
  }
652
657
  constructor() {
653
- super("ref"), _define_property$10(this, "_chain", []), _define_property$10(this, "_dots", []);
658
+ super("ref"), _define_property$11(this, "_chain", []), _define_property$11(this, "_dots", []);
654
659
  }
655
660
  };
656
661
 
657
662
  //#endregion
658
663
  //#region packages/core/src/parser/nodes/structure-node.ts
659
- function _define_property$9(obj, key, value) {
664
+ function _define_property$10(obj, key, value) {
660
665
  if (key in obj) Object.defineProperty(obj, key, {
661
666
  value,
662
667
  enumerable: true,
@@ -671,10 +676,12 @@ var SemanticStructureNode = class extends SemanticGroup {
671
676
  * Shortcut to set props, used as utility
672
677
  */ setProps(props$1) {
673
678
  this.nodes = props$1;
674
- for (const prop of props$1) this.props.set(prop.id, prop);
679
+ for (const prop of props$1) {
680
+ prop.ownerNode = this;
681
+ this.props.set(prop.id, prop);
682
+ }
675
683
  }
676
684
  registerAtDocument(doc) {
677
- super.registerAtDocument(doc);
678
685
  const block$2 = this.token("identifier");
679
686
  block$2.blockType = "structure";
680
687
  doc.blocksIndex.add(block$2);
@@ -697,8 +704,10 @@ var SemanticStructureNode = class extends SemanticGroup {
697
704
  doc.registerMessage(token, "Non-prop node");
698
705
  continue;
699
706
  }
707
+ node.ownerNode = this;
700
708
  this.props.set(name, node);
701
709
  }
710
+ super.registerAtDocument(doc);
702
711
  }
703
712
  addVirtualProp(opts) {
704
713
  const token = opts.refToken || this.token("identifier");
@@ -726,11 +735,12 @@ var SemanticStructureNode = class extends SemanticGroup {
726
735
  }
727
736
  prop.define(ref$1);
728
737
  } else prop.define(opts.type);
738
+ prop.ownerNode = this;
729
739
  this.nodes.push(prop);
730
740
  this.props.set(opts.name, prop);
731
741
  }
732
742
  constructor() {
733
- super(), _define_property$9(this, "props", new Map());
743
+ super(), _define_property$10(this, "props", new Map());
734
744
  this.entity = "structure";
735
745
  }
736
746
  };
@@ -763,6 +773,84 @@ var SemanticTypeNode = class extends SemanticNode {
763
773
  }
764
774
  };
765
775
 
776
+ //#endregion
777
+ //#region packages/core/src/parser/nodes/query-nodes.ts
778
+ function _define_property$9(obj, key, value) {
779
+ if (key in obj) Object.defineProperty(obj, key, {
780
+ value,
781
+ enumerable: true,
782
+ configurable: true,
783
+ writable: true
784
+ });
785
+ else obj[key] = value;
786
+ return obj;
787
+ }
788
+ var SemanticQueryNode = class extends SemanticNode {
789
+ registerAtDocument(doc) {
790
+ this.propagateQueryArgToken(this.expression);
791
+ this.expression.registerAtDocument(doc);
792
+ }
793
+ propagateQueryArgToken(expr) {
794
+ if ("left" in expr) {
795
+ expr.left.queryArgToken = this.sourceToken;
796
+ const right = expr.right;
797
+ if (right && "fieldRef" in right) right.queryArgToken = this.sourceToken;
798
+ } else if ("operands" in expr) for (const operand of expr.operands) this.propagateQueryArgToken(operand);
799
+ }
800
+ constructor() {
801
+ super("query"), _define_property$9(this, "expression", void 0), _define_property$9(this, "sourceToken", void 0);
802
+ }
803
+ };
804
+ var SemanticQueryLogicalNode = class extends SemanticNode {
805
+ registerAtDocument(doc) {
806
+ for (const operand of this.operands) operand.registerAtDocument(doc);
807
+ }
808
+ constructor() {
809
+ super("query-logical"), _define_property$9(this, "operator", void 0), _define_property$9(this, "operands", void 0);
810
+ }
811
+ };
812
+ var SemanticQueryComparisonNode = class extends SemanticNode {
813
+ registerAtDocument(doc) {
814
+ this.left.registerAtDocument(doc);
815
+ this.right?.registerAtDocument(doc);
816
+ }
817
+ constructor() {
818
+ super("query-comparison"), _define_property$9(this, "left", void 0), _define_property$9(this, "operator", void 0), _define_property$9(this, "right", void 0);
819
+ }
820
+ };
821
+ var SemanticQueryFieldRefNode = class extends SemanticNode {
822
+ registerAtDocument(doc) {
823
+ if (this.typeRef) {
824
+ this.typeRef.isReference = true;
825
+ this.typeRef.parentNode = this;
826
+ doc.referred.push(this.typeRef);
827
+ doc.tokensIndex.add(this.typeRef);
828
+ }
829
+ this.fieldRef.parentNode = this;
830
+ doc.tokensIndex.add(this.fieldRef);
831
+ doc.queryFieldRefs.push(this);
832
+ }
833
+ constructor() {
834
+ super("query-field-ref"), _define_property$9(this, "typeRef", void 0), _define_property$9(this, "fieldRef", void 0), _define_property$9(this, "queryArgToken", void 0);
835
+ }
836
+ };
837
+ var SemanticQueryValueNode = class extends SemanticNode {
838
+ registerAtDocument(doc) {
839
+ doc.tokensIndex.add(this.valueToken);
840
+ }
841
+ constructor() {
842
+ super("query-value"), _define_property$9(this, "valueToken", void 0);
843
+ }
844
+ };
845
+ var SemanticQueryValueListNode = class extends SemanticNode {
846
+ registerAtDocument(doc) {
847
+ for (const v of this.values) v.registerAtDocument(doc);
848
+ }
849
+ constructor() {
850
+ super("query-value-list"), _define_property$9(this, "values", void 0);
851
+ }
852
+ };
853
+
766
854
  //#endregion
767
855
  //#region packages/core/src/parser/nodes/index.ts
768
856
  const $n = {
@@ -815,6 +903,15 @@ function isPrimitive(node) {
815
903
  function isAnnotate(node) {
816
904
  return node?.entity === "annotate";
817
905
  }
906
+ function isQueryLogical(node) {
907
+ return node?.operands !== undefined;
908
+ }
909
+ function isQueryComparison(node) {
910
+ return node?.left !== undefined;
911
+ }
912
+ function isQueryFieldRef(node) {
913
+ return node?.fieldRef !== undefined;
914
+ }
818
915
 
819
916
  //#endregion
820
917
  //#region packages/core/src/annotations/annotation-spec.ts
@@ -838,7 +935,7 @@ var AnnotationSpec = class {
838
935
  return this.arguments.map((arg, index) => {
839
936
  const placeholderIndex = index + 1;
840
937
  const defaultValue = this.getDefaultValueForType(arg.name, arg.type);
841
- const quote = arg.type === "string" ? `'` : "";
938
+ const quote = arg.type === "string" ? `'` : arg.type === "query" ? "`" : "";
842
939
  return `${quote}\${${placeholderIndex}:${defaultValue}}${quote}`;
843
940
  }).join(", ");
844
941
  }
@@ -847,6 +944,8 @@ var AnnotationSpec = class {
847
944
  case "string": return tokenType === "text" ? undefined : "string expected.";
848
945
  case "number": return tokenType === "number" ? undefined : "number expected.";
849
946
  case "boolean": return tokenType === "identifier" ? undefined : "boolean expected.";
947
+ case "ref": return tokenType === "identifier" ? undefined : "type reference expected.";
948
+ case "query": return tokenType === "query" ? undefined : "query expression expected (use backticks).";
850
949
  default: return `unknown type "${type$1}".`;
851
950
  }
852
951
  }
@@ -939,6 +1038,8 @@ else if (isGroup(def) && def.entity !== "tuple") defEntity = def.op === "&" ? "i
939
1038
  case "string": return name;
940
1039
  case "number": return "0";
941
1040
  case "boolean": return "true";
1041
+ case "ref": return "TypeName";
1042
+ case "query": return "field = value";
942
1043
  default: return "";
943
1044
  }
944
1045
  }
@@ -956,10 +1057,13 @@ function resolveAnnotation(name, annotationsTree) {
956
1057
  const parts = name.split(".");
957
1058
  let current = annotationsTree;
958
1059
  for (const part of parts) {
1060
+ if (part === "$self") return undefined;
959
1061
  if (!current || isAnnotationSpec(current)) return undefined;
960
1062
  current = current[part];
961
1063
  }
962
- return isAnnotationSpec(current) ? current : undefined;
1064
+ if (isAnnotationSpec(current)) return current;
1065
+ if (current && !isAnnotationSpec(current) && current.$self) return current.$self;
1066
+ return undefined;
963
1067
  }
964
1068
 
965
1069
  //#endregion
@@ -1076,6 +1180,204 @@ else if (SUPPORTED_TS_CONFIG_FORMATS.includes(ext)) {
1076
1180
  }
1077
1181
  }
1078
1182
 
1183
+ //#endregion
1184
+ //#region packages/core/src/defaults/db-query-lsp.ts
1185
+ function getQueryScope(queryArgToken, doc) {
1186
+ const annotationRef = queryArgToken.annotationRef;
1187
+ if (!annotationRef) return undefined;
1188
+ const owner = queryArgToken.parentNode;
1189
+ if (!owner) return undefined;
1190
+ const annotationName = annotationRef.text.slice(1);
1191
+ if (annotationName === "db.view.filter") return getViewFilterScope(owner);
1192
+ if (annotationName === "db.view.joins") return getViewJoinsScope(owner, queryArgToken);
1193
+ if (annotationName === "db.rel.filter") return getRelFilterScope(owner);
1194
+ return undefined;
1195
+ }
1196
+ function getViewFilterScope(owner) {
1197
+ const forAnnotations = owner.annotations?.filter((a) => a.name === "db.view.for");
1198
+ const entryTypeName = forAnnotations?.[0]?.args[0]?.text;
1199
+ if (!entryTypeName) return undefined;
1200
+ const allowedTypes = [entryTypeName];
1201
+ const joinsAnnotations = owner.annotations?.filter((a) => a.name === "db.view.joins");
1202
+ if (joinsAnnotations) {
1203
+ for (const join of joinsAnnotations) if (join.args[0]) allowedTypes.push(join.args[0].text);
1204
+ }
1205
+ return {
1206
+ allowedTypes,
1207
+ unqualifiedTarget: entryTypeName
1208
+ };
1209
+ }
1210
+ function getViewJoinsScope(owner, queryArgToken) {
1211
+ const forAnnotations = owner.annotations?.filter((a) => a.name === "db.view.for");
1212
+ const entryTypeName = forAnnotations?.[0]?.args[0]?.text;
1213
+ if (!entryTypeName) return undefined;
1214
+ const joinsAnnotation = owner.annotations?.find((a) => a.name === "db.view.joins" && a.args.includes(queryArgToken));
1215
+ const joinTargetName = joinsAnnotation?.args[0]?.text;
1216
+ if (!joinTargetName) return undefined;
1217
+ return {
1218
+ allowedTypes: [joinTargetName, entryTypeName],
1219
+ unqualifiedTarget: entryTypeName
1220
+ };
1221
+ }
1222
+ function getRelFilterScope(owner) {
1223
+ let def = owner.getDefinition();
1224
+ if (isArray(def)) def = def?.getDefinition();
1225
+ if (!isRef(def)) return undefined;
1226
+ const targetTypeName = def.id;
1227
+ const allowedTypes = [targetTypeName];
1228
+ const viaAnnotation = owner.annotations?.find((a) => a.name === "db.rel.via");
1229
+ if (viaAnnotation?.args[0]) allowedTypes.push(viaAnnotation.args[0].text);
1230
+ return {
1231
+ allowedTypes,
1232
+ unqualifiedTarget: targetTypeName
1233
+ };
1234
+ }
1235
+ function resolveQueryFieldRef(fieldRefNode, doc, scope) {
1236
+ const typeName = fieldRefNode.typeRef?.text ?? scope.unqualifiedTarget;
1237
+ if (!typeName) return undefined;
1238
+ const fieldPath = fieldRefNode.fieldRef.text;
1239
+ const chain = fieldPath.split(".");
1240
+ const parentChain = chain.slice(0, -1);
1241
+ const parentUnwound = doc.unwindType(typeName, parentChain);
1242
+ if (!parentUnwound?.def) return undefined;
1243
+ const unwound = doc.unwindType(typeName, chain);
1244
+ if (!unwound?.node) return undefined;
1245
+ const prop = unwound.node;
1246
+ return {
1247
+ targetUri: parentUnwound.doc.id,
1248
+ doc: parentUnwound.doc,
1249
+ prop
1250
+ };
1251
+ }
1252
+ function getFieldsForType(doc, typeName) {
1253
+ const unwound = doc.unwindType(typeName);
1254
+ if (!unwound?.def) return [];
1255
+ let def = doc.mergeIntersection(unwound.def);
1256
+ if (isInterface(def)) {
1257
+ const resolved = doc.resolveInterfaceExtends(def);
1258
+ if (resolved) def = resolved;
1259
+ else def = def.getDefinition() || def;
1260
+ }
1261
+ if (isStructure(def) || isInterface(def)) return Array.from(def.props.values());
1262
+ return [];
1263
+ }
1264
+ function getQueryCompletionScope(queryArgToken, doc) {
1265
+ const scope = getQueryScope(queryArgToken, doc);
1266
+ if (!scope) return undefined;
1267
+ return {
1268
+ typeNames: scope.allowedTypes,
1269
+ unqualifiedTarget: scope.unqualifiedTarget,
1270
+ getFields: (typeName) => getFieldsForType(doc, typeName)
1271
+ };
1272
+ }
1273
+ const SYMBOLIC_OPS$1 = new Set([
1274
+ "=",
1275
+ "!=",
1276
+ ">",
1277
+ ">=",
1278
+ "<",
1279
+ "<="
1280
+ ]);
1281
+ const KEYWORD_OPS = new Set([
1282
+ "in",
1283
+ "matches",
1284
+ "exists"
1285
+ ]);
1286
+ const LOGICAL_KEYWORDS = new Set([
1287
+ "and",
1288
+ "or",
1289
+ "not"
1290
+ ]);
1291
+ const VALUE_KEYWORDS$1 = new Set([
1292
+ "true",
1293
+ "false",
1294
+ "null",
1295
+ "undefined"
1296
+ ]);
1297
+ function analyzeQueryCursorContext(textBeforeCursor) {
1298
+ const trimmed = textBeforeCursor.trimEnd();
1299
+ const hasTrailingSpace = textBeforeCursor.length > trimmed.length;
1300
+ if (trimmed.length === 0) return { type: "field-start" };
1301
+ if (trimmed.endsWith(".")) {
1302
+ const before = trimmed.slice(0, -1).trimEnd();
1303
+ const match = /(\w+)$/u.exec(before);
1304
+ if (match) return {
1305
+ type: "after-dot",
1306
+ typeName: match[1]
1307
+ };
1308
+ return { type: "field-start" };
1309
+ }
1310
+ const tokens$1 = tokenizeQueryText(trimmed);
1311
+ if (tokens$1.length === 0) return { type: "field-start" };
1312
+ const last = tokens$1[tokens$1.length - 1];
1313
+ if (LOGICAL_KEYWORDS.has(last) || last === "(") return { type: "field-start" };
1314
+ if (SYMBOLIC_OPS$1.has(last)) return { type: "after-operator" };
1315
+ if (last === "in" || last === "matches") return { type: "after-operator" };
1316
+ if (last === "exists") return { type: "after-comparison" };
1317
+ if (VALUE_KEYWORDS$1.has(last)) return { type: "after-comparison" };
1318
+ if (/^['"]/.test(last) || /^\d/.test(last)) return { type: "after-comparison" };
1319
+ if (tokens$1.length >= 2) {
1320
+ const prev = tokens$1[tokens$1.length - 2];
1321
+ if (SYMBOLIC_OPS$1.has(prev) || KEYWORD_OPS.has(prev)) return { type: "after-comparison" };
1322
+ }
1323
+ if (/^\w+$/u.test(last)) {
1324
+ if (!hasTrailingSpace) return { type: "field-start" };
1325
+ return { type: "after-field" };
1326
+ }
1327
+ return { type: "field-start" };
1328
+ }
1329
+ /**
1330
+ * Simple tokenizer for query text — splits into identifiers, operators, and punctuation.
1331
+ * Does NOT need to handle all edge cases; just enough for cursor context analysis.
1332
+ */ function tokenizeQueryText(text$2) {
1333
+ const tokens$1 = [];
1334
+ let i = 0;
1335
+ while (i < text$2.length) {
1336
+ if (/\s/.test(text$2[i])) {
1337
+ i++;
1338
+ continue;
1339
+ }
1340
+ if (text$2[i] === "'" || text$2[i] === "\"") {
1341
+ const quote = text$2[i];
1342
+ let j = i + 1;
1343
+ while (j < text$2.length && text$2[j] !== quote) {
1344
+ if (text$2[j] === "\\") j++;
1345
+ j++;
1346
+ }
1347
+ tokens$1.push(text$2.slice(i, j + 1));
1348
+ i = j + 1;
1349
+ continue;
1350
+ }
1351
+ if (i + 1 < text$2.length) {
1352
+ const two = text$2.slice(i, i + 2);
1353
+ if (two === "!=" || two === ">=" || two === "<=") {
1354
+ tokens$1.push(two);
1355
+ i += 2;
1356
+ continue;
1357
+ }
1358
+ }
1359
+ if ("=><(),".includes(text$2[i])) {
1360
+ tokens$1.push(text$2[i]);
1361
+ i++;
1362
+ continue;
1363
+ }
1364
+ if (text$2[i] === ".") {
1365
+ tokens$1.push(".");
1366
+ i++;
1367
+ continue;
1368
+ }
1369
+ if (/[\w]/u.test(text$2[i])) {
1370
+ let j = i;
1371
+ while (j < text$2.length && /[\w]/u.test(text$2[j])) j++;
1372
+ tokens$1.push(text$2.slice(i, j));
1373
+ i = j;
1374
+ continue;
1375
+ }
1376
+ i++;
1377
+ }
1378
+ return tokens$1;
1379
+ }
1380
+
1079
1381
  //#endregion
1080
1382
  //#region packages/core/src/parser/id-registry.ts
1081
1383
  function _define_property$7(obj, key, value) {
@@ -1266,40 +1568,21 @@ var NodeIterator = class NodeIterator {
1266
1568
  }
1267
1569
  };
1268
1570
 
1269
- //#endregion
1270
- //#region packages/core/src/parser/utils.ts
1271
- function toVsCodeRange(start, end, startOffset = 0, endOffset = 0) {
1272
- return {
1273
- start: {
1274
- line: start.row - 1,
1275
- character: start.col + startOffset
1276
- },
1277
- end: {
1278
- line: end.row - 1,
1279
- character: end.col + endOffset
1280
- }
1281
- };
1282
- }
1283
- function resolveAtscriptFromPath(from, id) {
1284
- return `file://${path$1.join(id.slice(7).split("/").slice(0, -1).join("/"), from)}.as`;
1285
- }
1286
- function getRelPath(fromUri, toUri) {
1287
- const fromPath = new URL(fromUri).pathname;
1288
- const toPath = new URL(toUri).pathname;
1289
- const relPath = path$1.relative(path$1.dirname(fromPath), toPath);
1290
- const { dir, name } = path$1.parse(relPath);
1291
- const prefix = dir.startsWith("..") ? "" : "./";
1292
- return `${prefix}${dir ? `${dir}/` : ""}${name}`;
1293
- }
1294
-
1295
1571
  //#endregion
1296
1572
  //#region packages/core/src/tokenizer/tokens/a-identifier.token.ts
1297
- const AIdentifierToken = new BasicNode({
1298
- icon: "@",
1299
- tokens: [RegExp("@[\\p{ID_Continue}$.]*", "u"), RegExp("[^\\p{ID_Continue}$.]", "u")],
1300
- tokenOE: "-eject"
1301
- }).mapContent("text", "join-clear").onMatch((context) => {
1302
- context.customData.type = "annotation";
1573
+ const AIdentifierToken = new Node({
1574
+ name: "annotation",
1575
+ start: { token: RegExp("@[\\p{ID_Continue}$.]*", "u") },
1576
+ end: {
1577
+ token: RegExp("[^\\p{ID_Continue}$.]", "u"),
1578
+ eject: true
1579
+ },
1580
+ eofClose: true,
1581
+ data: {
1582
+ type: "annotation",
1583
+ text: ""
1584
+ },
1585
+ mapContent: "text"
1303
1586
  });
1304
1587
 
1305
1588
  //#endregion
@@ -1309,33 +1592,59 @@ const pairs = {
1309
1592
  "(": ")",
1310
1593
  "[": "]"
1311
1594
  };
1312
- const BlockToken = new BasicNode({
1313
- label: "block",
1314
- icon: "→",
1315
- tokens: [RegExp("(?<text>[([{])", "u"), (context) => pairs[context.getCustomData().text] || ""],
1316
- tokenOE: "omit-omit",
1317
- skipToken: /\s/u
1318
- }).onMatch((context) => {
1319
- context.customData.type = "block";
1595
+ const BlockToken = new Node({
1596
+ name: "block",
1597
+ start: {
1598
+ token: RegExp("(?<text>[([{])", "u"),
1599
+ omit: true
1600
+ },
1601
+ end: {
1602
+ token: (ctx) => pairs[ctx.node.data.text] || "",
1603
+ omit: true
1604
+ },
1605
+ skip: /\s/u,
1606
+ eofClose: true,
1607
+ data: {
1608
+ type: "block",
1609
+ text: ""
1610
+ }
1320
1611
  });
1321
1612
 
1322
1613
  //#endregion
1323
1614
  //#region packages/core/src/tokenizer/tokens/comment.token.ts
1324
- const inline = new BasicNode({
1325
- label: "inline-comment",
1326
- icon: "“",
1327
- tokens: ["//", /$/mu],
1328
- tokenOE: "omit-omit"
1329
- }).mapContent("text", "join-clear").popsAtEOFSource(true).onMatch((context) => {
1330
- context.customData.type = "comment";
1615
+ const inline = new Node({
1616
+ name: "inline-comment",
1617
+ start: {
1618
+ token: "//",
1619
+ omit: true
1620
+ },
1621
+ end: {
1622
+ token: /$/mu,
1623
+ omit: true
1624
+ },
1625
+ eofClose: true,
1626
+ data: {
1627
+ type: "comment",
1628
+ text: ""
1629
+ },
1630
+ mapContent: "text"
1331
1631
  });
1332
- const block$1 = new BasicNode({
1333
- label: "block-comment",
1334
- icon: "“",
1335
- tokens: ["/*", "*/"],
1336
- tokenOE: "omit-omit"
1337
- }).mapContent("text", "join-clear").popsAtEOFSource(true).onMatch((context) => {
1338
- context.customData.type = "comment";
1632
+ const block$1 = new Node({
1633
+ name: "block-comment",
1634
+ start: {
1635
+ token: "/*",
1636
+ omit: true
1637
+ },
1638
+ end: {
1639
+ token: "*/",
1640
+ omit: true
1641
+ },
1642
+ eofClose: true,
1643
+ data: {
1644
+ type: "comment",
1645
+ text: ""
1646
+ },
1647
+ mapContent: "text"
1339
1648
  });
1340
1649
  const commentNodes = {
1341
1650
  inline,
@@ -1345,58 +1654,141 @@ const commentNodes = {
1345
1654
 
1346
1655
  //#endregion
1347
1656
  //#region packages/core/src/tokenizer/tokens/identifier.token.ts
1348
- const IdentifierToken = new BasicNode({
1349
- icon: "I",
1350
- tokens: [RegExp("[\\p{ID_Start}$_][\\p{ID_Continue}$]*", "u"), RegExp("[^\\p{ID_Continue}$]", "u")],
1351
- tokenOE: "consume-eject"
1352
- }).mapContent("text", "join-clear").onMatch((context) => {
1353
- context.customData.type = "identifier";
1657
+ const IdentifierToken = new Node({
1658
+ name: "identifier",
1659
+ start: { token: RegExp("[\\p{ID_Start}$_][\\p{ID_Continue}$]*", "u") },
1660
+ end: {
1661
+ token: RegExp("[^\\p{ID_Continue}$]", "u"),
1662
+ eject: true
1663
+ },
1664
+ eofClose: true,
1665
+ data: {
1666
+ type: "identifier",
1667
+ text: ""
1668
+ },
1669
+ mapContent: "text"
1354
1670
  });
1355
1671
 
1356
1672
  //#endregion
1357
1673
  //#region packages/core/src/tokenizer/tokens/number.token.ts
1358
- const NumberToken = new BasicNode({
1359
- icon: "N",
1360
- tokens: [/[-+]?(?:\d*\.\d+|\d+)(?:[eE][-+]?\d+)?/u, /[^\d]/u],
1361
- tokenOE: "-eject"
1362
- }).mapContent("text", "join-clear").onMatch((context) => {
1363
- context.customData.type = "number";
1674
+ const NumberToken = new Node({
1675
+ name: "number",
1676
+ start: { token: /[-+]?(?:\d*\.\d+|\d+)(?:[eE][-+]?\d+)?/u },
1677
+ end: {
1678
+ token: /[^\d]/u,
1679
+ eject: true
1680
+ },
1681
+ eofClose: true,
1682
+ data: {
1683
+ type: "number",
1684
+ text: ""
1685
+ },
1686
+ mapContent: "text"
1364
1687
  });
1365
1688
 
1366
1689
  //#endregion
1367
1690
  //#region packages/core/src/tokenizer/tokens/punctuation.token.ts
1368
- const PunctuationToken = new BasicNode({
1369
- tokens: [RegExp("(?<text>[\\n!&+,./:;=?|])", "u"), ""],
1370
- tokenOE: "omit-omit",
1371
- icon: "..."
1372
- }).onMatch((context) => {
1373
- context.customData.type = "punctuation";
1691
+ const PunctuationToken = new Node({
1692
+ name: "punctuation",
1693
+ start: {
1694
+ token: RegExp("(?<text>[\\n!&+,./:;=?|])", "u"),
1695
+ omit: true
1696
+ },
1697
+ end: {
1698
+ token: "",
1699
+ omit: true
1700
+ },
1701
+ eofClose: true,
1702
+ data: {
1703
+ type: "punctuation",
1704
+ text: ""
1705
+ }
1706
+ });
1707
+
1708
+ //#endregion
1709
+ //#region packages/core/src/tokenizer/tokens/query-operator.token.ts
1710
+ const QueryOperatorToken = new Node({
1711
+ name: "punctuation",
1712
+ start: {
1713
+ token: RegExp("(?<text>!=|>=|<=|[=><])", "u"),
1714
+ omit: true
1715
+ },
1716
+ end: {
1717
+ token: "",
1718
+ omit: true
1719
+ },
1720
+ eofClose: true,
1721
+ data: {
1722
+ type: "punctuation",
1723
+ text: ""
1724
+ }
1725
+ });
1726
+
1727
+ //#endregion
1728
+ //#region packages/core/src/tokenizer/tokens/query.token.ts
1729
+ const QueryToken = new Node({
1730
+ name: "query",
1731
+ start: {
1732
+ token: /`/u,
1733
+ omit: true
1734
+ },
1735
+ end: {
1736
+ token: /`/u,
1737
+ omit: true
1738
+ },
1739
+ skip: /\s/u,
1740
+ eofClose: true,
1741
+ data: {
1742
+ type: "query",
1743
+ text: ""
1744
+ }
1374
1745
  });
1375
1746
 
1376
1747
  //#endregion
1377
1748
  //#region packages/core/src/tokenizer/tokens/regexp.token.ts
1378
1749
  const REGEXP_LITERAL_RE = /\/(?![/*])(?:\\.|\[.*?]|[^/\\\n\r[])*\/[dgimsuy]*/;
1379
- const RegExpToken = new BasicNode({
1380
- label: "regexp",
1381
- icon: "RG",
1382
- tokens: [REGEXP_LITERAL_RE, ""],
1383
- tokenOE: "omit-omit"
1384
- }).onMatch((ctx) => {
1385
- ctx.customData.type = "regexp";
1386
- ctx.customData.text = ctx.matched[0];
1750
+ const RegExpToken = new Node({
1751
+ name: "regexp",
1752
+ start: {
1753
+ token: REGEXP_LITERAL_RE,
1754
+ omit: true
1755
+ },
1756
+ end: {
1757
+ token: "",
1758
+ omit: true
1759
+ },
1760
+ eofClose: true,
1761
+ data: {
1762
+ type: "regexp",
1763
+ text: ""
1764
+ }
1765
+ }).onOpen((node, match) => {
1766
+ node.data.text = match?.text ?? "";
1387
1767
  });
1388
1768
 
1389
1769
  //#endregion
1390
1770
  //#region packages/core/src/tokenizer/tokens/text.node.ts
1391
- const TextToken = new BasicNode({
1392
- icon: "T",
1393
- tokens: [RegExp("(?<quote>[\"'])", "u"), (context) => new RegExp(`(?<end>${context.getCustomData().quote || ""}|\\n)`)],
1394
- backSlash: "-ignore",
1395
- tokenOE: "omit-omit"
1396
- }).mapContent("text", "join-clear").onMatch((context) => {
1397
- context.customData.type = "text";
1398
- }).onPop((context) => {
1399
- context.customData.multiline = context.customData.end === "\n";
1771
+ const TextToken = new Node({
1772
+ name: "text",
1773
+ start: {
1774
+ token: RegExp("(?<quote>[\"'])", "u"),
1775
+ omit: true
1776
+ },
1777
+ end: {
1778
+ token: (ctx) => new RegExp(`(?<end>${ctx.node.data.quote || ""}|\\n)`),
1779
+ omit: true,
1780
+ backslash: true
1781
+ },
1782
+ eofClose: true,
1783
+ data: {
1784
+ type: "text",
1785
+ quote: "",
1786
+ end: "",
1787
+ text: ""
1788
+ },
1789
+ mapContent: "text"
1790
+ }).onClose((node) => {
1791
+ node.data.multiline = node.data.end === "\n";
1400
1792
  });
1401
1793
 
1402
1794
  //#endregion
@@ -1412,31 +1804,55 @@ const tokens = {
1412
1804
  number: NumberToken,
1413
1805
  text: TextToken,
1414
1806
  regexp: RegExpToken,
1807
+ query: QueryToken,
1415
1808
  root: undefined
1416
1809
  };
1417
- const root = new BasicNode({
1418
- label: "root",
1419
- skipToken: /\s/u
1420
- }).addRecognizes(...tokens.comments, tokens.block, tokens.aIdentifier, tokens.identifier, tokens.text, tokens.number, tokens.punctuation);
1421
- tokens.root = root;
1422
- BlockToken.addRecognizes(tokens.regexp, ...tokens.comments, tokens.block, tokens.aIdentifier, tokens.identifier, tokens.text, tokens.number, tokens.punctuation);
1423
- const mapContent = (content) => content.map((item) => {
1424
- if (typeof item === "string") return {
1425
- type: "unknown",
1426
- text: item
1427
- };
1428
- const data = item.getCustomData();
1429
- data.getRange = () => toVsCodeRange(item.startPos, item.endPos, data.startOffset, data.endOffset);
1430
- return data;
1810
+ const root = new Node({
1811
+ name: "root",
1812
+ skip: /\s/u,
1813
+ eofClose: true,
1814
+ recognizes: [
1815
+ ...commentNodes.all,
1816
+ BlockToken,
1817
+ QueryToken,
1818
+ AIdentifierToken,
1819
+ IdentifierToken,
1820
+ TextToken,
1821
+ NumberToken,
1822
+ PunctuationToken
1823
+ ]
1431
1824
  });
1432
- for (const node of Object.values(tokens)) if (node instanceof BasicNode) node.popsAtEOFSource(true).mapContent("children", mapContent);
1825
+ tokens.root = root;
1826
+ BlockToken.recognize(RegExpToken, ...commentNodes.all, BlockToken, QueryToken, AIdentifierToken, IdentifierToken, TextToken, NumberToken, PunctuationToken);
1827
+ QueryToken.recognize(RegExpToken, QueryOperatorToken, BlockToken, IdentifierToken, TextToken, NumberToken, PunctuationToken);
1828
+ function extractTokens(node) {
1829
+ return node.content.map((item) => {
1830
+ if (typeof item === "string") return {
1831
+ type: "unknown",
1832
+ text: item
1833
+ };
1834
+ const data = item.data;
1835
+ data.getRange = () => ({
1836
+ start: {
1837
+ line: item.start.line - 1,
1838
+ character: item.start.column - 1 + (data.startOffset ?? 0)
1839
+ },
1840
+ end: {
1841
+ line: item.end.line - 1,
1842
+ character: item.end.column - 1 + (data.endOffset ?? 0)
1843
+ }
1844
+ });
1845
+ data.children = extractTokens(item);
1846
+ return data;
1847
+ });
1848
+ }
1433
1849
 
1434
1850
  //#endregion
1435
1851
  //#region packages/core/src/tokenizer/index.ts
1436
1852
  function tokenize(source, debug = false) {
1437
- const tokens$1 = root.parse(source);
1438
- if (debug) console.log(tokens$1.toTree());
1439
- return mapContent(tokens$1.content);
1853
+ const result = root.parse(source);
1854
+ if (debug) console.log(printTree(result));
1855
+ return extractTokens(result);
1440
1856
  }
1441
1857
 
1442
1858
  //#endregion
@@ -1692,67 +2108,359 @@ else if (isOperator && !(node instanceof Token)) throw new Error(`Unexpected tok
1692
2108
  }
1693
2109
 
1694
2110
  //#endregion
1695
- //#region packages/core/src/parser/pipes/special.pipe.ts
1696
- function refWithChain() {
1697
- const s = {
1698
- id: { node: "identifier" },
1699
- dot: {
1700
- node: "punctuation",
1701
- text: "."
1702
- },
1703
- block: {
1704
- node: "block",
1705
- text: "["
1706
- },
1707
- end: {
1708
- node: "punctuation",
1709
- text: ";"
2111
+ //#region packages/core/src/parser/pipes/query.pipe.ts
2112
+ const SYMBOLIC_OPS = new Set([
2113
+ "=",
2114
+ "!=",
2115
+ ">",
2116
+ ">=",
2117
+ "<",
2118
+ "<="
2119
+ ]);
2120
+ const VALUE_KEYWORDS = new Set([
2121
+ "true",
2122
+ "false",
2123
+ "null",
2124
+ "undefined"
2125
+ ]);
2126
+ function parseQueryExpression(children, messages, sourceToken) {
2127
+ if (children.length === 0) return undefined;
2128
+ const ni = new NodeIterator(children, messages);
2129
+ ni.move();
2130
+ const expr = parseOrExpr(ni, messages);
2131
+ if (!expr) return undefined;
2132
+ if (ni.$) messages.push({
2133
+ severity: 1,
2134
+ message: `Unexpected token in query expression: "${ni.$.text}"`,
2135
+ range: ni.$.getRange?.() ?? {
2136
+ start: {
2137
+ line: 0,
2138
+ character: 0
2139
+ },
2140
+ end: {
2141
+ line: 0,
2142
+ character: 0
2143
+ }
1710
2144
  }
1711
- };
1712
- return { handler(ni, target) {
1713
- ni.skip(["\n"]);
1714
- if (!ni.$) return false;
1715
- if (ni.satisfies(s.id)) {
1716
- ni.accepted();
1717
- target.node.saveToken(new Token(ni.$), "identifier");
1718
- } else return false;
2145
+ });
2146
+ const node = new SemanticQueryNode();
2147
+ node.expression = expr;
2148
+ node.sourceToken = sourceToken;
2149
+ return node;
2150
+ }
2151
+ function parseOrExpr(ni, messages) {
2152
+ const left = parseAndExpr(ni, messages);
2153
+ if (!left) return undefined;
2154
+ const operands = [left];
2155
+ while (ni.$?.type === "identifier" && ni.$.text === "or") {
1719
2156
  ni.move();
1720
- if (ni.fork().skip(["\n"]).satisfies(s.end)) {
1721
- ni.skip(["\n", ";"]);
1722
- return true;
2157
+ const right = parseAndExpr(ni, messages);
2158
+ if (!right) {
2159
+ pushError(ni, messages, "Expected expression after \"or\"");
2160
+ break;
1723
2161
  }
1724
- const fork = ni.fork();
1725
- let isDot = fork.skip(["\n"]).satisfies(s.dot);
1726
- let isBlock = fork.satisfies(s.block);
1727
- while (fork.$ && (isDot || isBlock)) {
1728
- if (isBlock) if (fork.$.children?.length === 0) {
1729
- while (isBlock && fork.$.children?.length === 0) {
1730
- target.node = new SemanticArrayNode().wrap(target.node, new Token(fork.$));
1731
- fork.move();
1732
- fork.skip(["\n", ";"]);
1733
- isBlock = fork.satisfies(s.block);
1734
- }
1735
- ni.unfork(fork);
1736
- return true;
1737
- } else if (fork.$.children?.length === 1 && fork.$.children[0].type === "text") {
1738
- if (isRef(target.node)) target.node.addChain(new Token(fork.$.children[0]));
1739
- } else return true;
1740
- else {
1741
- fork.skip(["\n"]);
1742
- if (fork.next().satisfies(s.id)) {
1743
- if (isRef(target.node)) target.node.addDot(new Token(fork.$));
1744
- fork.move();
1745
- if (isRef(target.node) && fork.$) target.node.addChain(new Token(fork.$));
1746
- } else {
1747
- if (isRef(target.node)) target.node.addDot(new Token(fork.$));
1748
- fork.unexpected();
1749
- fork.move(1);
1750
- fork.unexpected();
1751
- ni.unfork(fork);
1752
- ni.move();
1753
- ni.skip([";", "\n"]);
1754
- return true;
1755
- }
2162
+ operands.push(right);
2163
+ }
2164
+ if (operands.length === 1) return operands[0];
2165
+ const node = new SemanticQueryLogicalNode();
2166
+ node.operator = "or";
2167
+ node.operands = operands;
2168
+ return node;
2169
+ }
2170
+ function parseAndExpr(ni, messages) {
2171
+ const left = parseUnaryExpr(ni, messages);
2172
+ if (!left) return undefined;
2173
+ const operands = [left];
2174
+ while (ni.$?.type === "identifier" && ni.$.text === "and") {
2175
+ ni.move();
2176
+ const right = parseUnaryExpr(ni, messages);
2177
+ if (!right) {
2178
+ pushError(ni, messages, "Expected expression after \"and\"");
2179
+ break;
2180
+ }
2181
+ operands.push(right);
2182
+ }
2183
+ if (operands.length === 1) return operands[0];
2184
+ const node = new SemanticQueryLogicalNode();
2185
+ node.operator = "and";
2186
+ node.operands = operands;
2187
+ return node;
2188
+ }
2189
+ function parseUnaryExpr(ni, messages) {
2190
+ if (ni.$?.type === "identifier" && ni.$.text === "not") {
2191
+ ni.move();
2192
+ const operand = parseUnaryExpr(ni, messages);
2193
+ if (!operand) {
2194
+ pushError(ni, messages, "Expected expression after \"not\"");
2195
+ return undefined;
2196
+ }
2197
+ const node = new SemanticQueryLogicalNode();
2198
+ node.operator = "not";
2199
+ node.operands = [operand];
2200
+ return node;
2201
+ }
2202
+ if (ni.$?.type === "block" && ni.$.text === "(") {
2203
+ const blockChildren = ni.$.children || [];
2204
+ ni.move();
2205
+ if (blockChildren.length === 0) {
2206
+ pushError(ni, messages, "Empty parenthesized expression");
2207
+ return undefined;
2208
+ }
2209
+ const subNi = new NodeIterator(blockChildren, messages);
2210
+ subNi.move();
2211
+ const expr = parseOrExpr(subNi, messages);
2212
+ if (subNi.$) pushError(subNi, messages, `Unexpected token in parenthesized expression: "${subNi.$.text}"`);
2213
+ return expr;
2214
+ }
2215
+ return parseComparison(ni, messages);
2216
+ }
2217
+ function parseComparison(ni, messages) {
2218
+ const left = parseFieldRef(ni, messages);
2219
+ if (!left) return undefined;
2220
+ if (ni.$?.type === "punctuation" && SYMBOLIC_OPS.has(ni.$.text)) {
2221
+ const opText = ni.$.text;
2222
+ ni.move();
2223
+ const right = parseValueOrFieldRef(ni, messages);
2224
+ if (!right) {
2225
+ pushError(ni, messages, `Expected value or field reference after "${opText}"`);
2226
+ return undefined;
2227
+ }
2228
+ const node = new SemanticQueryComparisonNode();
2229
+ node.left = left;
2230
+ node.operator = opText;
2231
+ node.right = right;
2232
+ return node;
2233
+ }
2234
+ if (ni.$?.type === "identifier") {
2235
+ const opText = ni.$.text;
2236
+ if (opText === "in") {
2237
+ ni.move();
2238
+ const right = parseValueList(ni, messages);
2239
+ if (!right) return undefined;
2240
+ const node = new SemanticQueryComparisonNode();
2241
+ node.left = left;
2242
+ node.operator = "in";
2243
+ node.right = right;
2244
+ return node;
2245
+ }
2246
+ if (opText === "matches") {
2247
+ ni.move();
2248
+ const right = parseValueOrFieldRef(ni, messages);
2249
+ if (!right) {
2250
+ pushError(ni, messages, "Expected value after \"matches\"");
2251
+ return undefined;
2252
+ }
2253
+ const node = new SemanticQueryComparisonNode();
2254
+ node.left = left;
2255
+ node.operator = "matches";
2256
+ node.right = right;
2257
+ return node;
2258
+ }
2259
+ if (opText === "exists") {
2260
+ ni.move();
2261
+ const node = new SemanticQueryComparisonNode();
2262
+ node.left = left;
2263
+ node.operator = "exists";
2264
+ return node;
2265
+ }
2266
+ if (opText === "not") return parseNotComparison(ni, messages, left);
2267
+ pushError(ni, messages, `Unknown operator "${opText}"`);
2268
+ return undefined;
2269
+ }
2270
+ pushError(ni, messages, "Expected operator after field reference");
2271
+ return undefined;
2272
+ }
2273
+ function parseNotComparison(ni, messages, left) {
2274
+ ni.move();
2275
+ if (ni.$?.type === "identifier" && ni.$.text === "in") {
2276
+ ni.move();
2277
+ const right = parseValueList(ni, messages);
2278
+ if (!right) return undefined;
2279
+ const node = new SemanticQueryComparisonNode();
2280
+ node.left = left;
2281
+ node.operator = "not in";
2282
+ node.right = right;
2283
+ return node;
2284
+ }
2285
+ if (ni.$?.type === "identifier" && ni.$.text === "exists") {
2286
+ ni.move();
2287
+ const node = new SemanticQueryComparisonNode();
2288
+ node.left = left;
2289
+ node.operator = "not exists";
2290
+ return node;
2291
+ }
2292
+ pushError(ni, messages, "Expected \"in\" or \"exists\" after \"not\"");
2293
+ return undefined;
2294
+ }
2295
+ function parseFieldRef(ni, messages) {
2296
+ if (ni.$?.type !== "identifier") {
2297
+ pushError(ni, messages, "Expected field reference");
2298
+ return undefined;
2299
+ }
2300
+ const firstToken = new Token(ni.$);
2301
+ ni.move();
2302
+ if (ni.$?.type === "punctuation" && ni.$.text === ".") {
2303
+ ni.move();
2304
+ if (ni.$?.type === "identifier") {
2305
+ const secondToken = new Token(ni.$);
2306
+ ni.move();
2307
+ let fieldText = secondToken.text;
2308
+ while (ni.$?.type === "punctuation" && ni.$.text === ".") {
2309
+ ni.move();
2310
+ if (ni.$?.type === "identifier") {
2311
+ fieldText += `.${ni.$.text}`;
2312
+ ni.move();
2313
+ } else {
2314
+ pushError(ni, messages, "Expected identifier after \".\"");
2315
+ break;
2316
+ }
2317
+ }
2318
+ const node$2 = new SemanticQueryFieldRefNode();
2319
+ node$2.typeRef = firstToken;
2320
+ if (fieldText !== secondToken.text) node$2.fieldRef = secondToken.clone({ text: fieldText });
2321
+ else node$2.fieldRef = secondToken;
2322
+ return node$2;
2323
+ }
2324
+ pushError(ni, messages, "Expected identifier after \".\"");
2325
+ const node$1 = new SemanticQueryFieldRefNode();
2326
+ node$1.fieldRef = firstToken;
2327
+ return node$1;
2328
+ }
2329
+ const node = new SemanticQueryFieldRefNode();
2330
+ node.fieldRef = firstToken;
2331
+ return node;
2332
+ }
2333
+ function parseValueOrFieldRef(ni, messages) {
2334
+ if (!ni.$) return undefined;
2335
+ if (ni.$.type === "text" || ni.$.type === "number" || ni.$.type === "regexp") return parseValue(ni, messages);
2336
+ if (ni.$.type === "identifier") {
2337
+ if (VALUE_KEYWORDS.has(ni.$.text)) return parseValue(ni, messages);
2338
+ return parseFieldRef(ni, messages);
2339
+ }
2340
+ pushError(ni, messages, "Expected value or field reference");
2341
+ return undefined;
2342
+ }
2343
+ function parseValue(ni, messages) {
2344
+ if (!ni.$) {
2345
+ pushError(ni, messages, "Expected value");
2346
+ return undefined;
2347
+ }
2348
+ const token = ni.$;
2349
+ if (token.type === "text" || token.type === "number" || token.type === "regexp" || token.type === "identifier" && VALUE_KEYWORDS.has(token.text)) {
2350
+ const node = new SemanticQueryValueNode();
2351
+ node.valueToken = new Token(token);
2352
+ ni.move();
2353
+ return node;
2354
+ }
2355
+ pushError(ni, messages, `Unexpected token "${token.text}" where value expected`);
2356
+ return undefined;
2357
+ }
2358
+ function parseValueList(ni, messages) {
2359
+ if (ni.$?.type === "block" && ni.$.text === "(") {
2360
+ const blockChildren = ni.$.children || [];
2361
+ ni.move();
2362
+ const values = [];
2363
+ if (blockChildren.length === 0) {
2364
+ pushError(ni, messages, "Empty value list in \"in\" expression");
2365
+ return undefined;
2366
+ }
2367
+ const subNi = new NodeIterator(blockChildren, messages);
2368
+ subNi.move();
2369
+ const first = parseValue(subNi, messages);
2370
+ if (first) values.push(first);
2371
+ while (subNi.$?.type === "punctuation" && subNi.$.text === ",") {
2372
+ subNi.move();
2373
+ const v = parseValue(subNi, messages);
2374
+ if (v) values.push(v);
2375
+ }
2376
+ if (subNi.$) pushError(subNi, messages, `Unexpected token in value list: "${subNi.$.text}"`);
2377
+ const node = new SemanticQueryValueListNode();
2378
+ node.values = values;
2379
+ return node;
2380
+ }
2381
+ pushError(ni, messages, "Expected parenthesized value list after \"in\"");
2382
+ return undefined;
2383
+ }
2384
+ function pushError(ni, messages, message) {
2385
+ const range = ni.$?.getRange?.() ?? {
2386
+ start: {
2387
+ line: 0,
2388
+ character: 0
2389
+ },
2390
+ end: {
2391
+ line: 0,
2392
+ character: 0
2393
+ }
2394
+ };
2395
+ messages.push({
2396
+ severity: 1,
2397
+ message,
2398
+ range
2399
+ });
2400
+ }
2401
+
2402
+ //#endregion
2403
+ //#region packages/core/src/parser/pipes/special.pipe.ts
2404
+ function refWithChain() {
2405
+ const s = {
2406
+ id: { node: "identifier" },
2407
+ dot: {
2408
+ node: "punctuation",
2409
+ text: "."
2410
+ },
2411
+ block: {
2412
+ node: "block",
2413
+ text: "["
2414
+ },
2415
+ end: {
2416
+ node: "punctuation",
2417
+ text: ";"
2418
+ }
2419
+ };
2420
+ return { handler(ni, target) {
2421
+ ni.skip(["\n"]);
2422
+ if (!ni.$) return false;
2423
+ if (ni.satisfies(s.id)) {
2424
+ ni.accepted();
2425
+ target.node.saveToken(new Token(ni.$), "identifier");
2426
+ } else return false;
2427
+ ni.move();
2428
+ if (ni.fork().skip(["\n"]).satisfies(s.end)) {
2429
+ ni.skip(["\n", ";"]);
2430
+ return true;
2431
+ }
2432
+ const fork = ni.fork();
2433
+ let isDot = fork.skip(["\n"]).satisfies(s.dot);
2434
+ let isBlock = fork.satisfies(s.block);
2435
+ while (fork.$ && (isDot || isBlock)) {
2436
+ if (isBlock) if (fork.$.children?.length === 0) {
2437
+ while (isBlock && fork.$.children?.length === 0) {
2438
+ target.node = new SemanticArrayNode().wrap(target.node, new Token(fork.$));
2439
+ fork.move();
2440
+ fork.skip(["\n", ";"]);
2441
+ isBlock = fork.satisfies(s.block);
2442
+ }
2443
+ ni.unfork(fork);
2444
+ return true;
2445
+ } else if (fork.$.children?.length === 1 && fork.$.children[0].type === "text") {
2446
+ if (isRef(target.node)) target.node.addChain(new Token(fork.$.children[0]));
2447
+ } else return true;
2448
+ else {
2449
+ fork.skip(["\n"]);
2450
+ if (fork.next().satisfies(s.id)) {
2451
+ if (isRef(target.node)) target.node.addDot(new Token(fork.$));
2452
+ fork.move();
2453
+ if (isRef(target.node) && fork.$) target.node.addChain(new Token(fork.$));
2454
+ } else {
2455
+ if (isRef(target.node)) target.node.addDot(new Token(fork.$));
2456
+ fork.unexpected();
2457
+ fork.move(1);
2458
+ fork.unexpected();
2459
+ ni.unfork(fork);
2460
+ ni.move();
2461
+ ni.skip([";", "\n"]);
2462
+ return true;
2463
+ }
1756
2464
  }
1757
2465
  fork.move();
1758
2466
  ni.unfork(fork);
@@ -1769,15 +2477,25 @@ else {
1769
2477
  function annotations() {
1770
2478
  const opts = {
1771
2479
  annotation: { node: "annotation" },
1772
- argument: [{ node: ["number", "text"] }, {
1773
- node: "identifier",
1774
- text: [
1775
- "true",
1776
- "false",
1777
- "undefined",
1778
- "null"
1779
- ]
1780
- }],
2480
+ argument: [
2481
+ { node: ["number", "text"] },
2482
+ {
2483
+ node: "identifier",
2484
+ text: [
2485
+ "true",
2486
+ "false",
2487
+ "undefined",
2488
+ "null"
2489
+ ]
2490
+ },
2491
+ { node: "identifier" },
2492
+ { node: "query" }
2493
+ ],
2494
+ dot: {
2495
+ node: "punctuation",
2496
+ text: "."
2497
+ },
2498
+ ident: { node: "identifier" },
1781
2499
  comma: {
1782
2500
  node: "punctuation",
1783
2501
  text: ","
@@ -1799,9 +2517,30 @@ function annotations() {
1799
2517
  ni.move();
1800
2518
  }
1801
2519
  while (ni.satisfies(...opts.argument)) {
1802
- addArgument(new Token(ni.$));
2520
+ let argToken = new Token(ni.$);
1803
2521
  ni.accepted();
1804
2522
  ni.move();
2523
+ if (argToken.type === "identifier" && ![
2524
+ "true",
2525
+ "false",
2526
+ "undefined",
2527
+ "null"
2528
+ ].includes(argToken.text)) {
2529
+ let chainText = argToken.text;
2530
+ while (ni.satisfies(opts.dot) && ni.next()?.satisfies(opts.ident)) {
2531
+ ni.accepted();
2532
+ ni.move();
2533
+ chainText += `.${ni.$.text}`;
2534
+ ni.accepted();
2535
+ ni.move();
2536
+ }
2537
+ if (chainText !== argToken.text) argToken = argToken.clone({ text: chainText });
2538
+ }
2539
+ if (argToken.type === "query") {
2540
+ const queryNode = parseQueryExpression(argToken.children, ni.messages, argToken);
2541
+ if (queryNode) argToken.queryNode = queryNode;
2542
+ }
2543
+ addArgument(argToken);
1805
2544
  if (ni.satisfies(opts.comma)) {
1806
2545
  ni.accepted();
1807
2546
  ni.move();
@@ -2132,6 +2871,20 @@ var TSeverity = /*#__PURE__*/ function(TSeverity$1) {
2132
2871
  return TSeverity$1;
2133
2872
  }({});
2134
2873
 
2874
+ //#endregion
2875
+ //#region packages/core/src/parser/utils.ts
2876
+ function resolveAtscriptFromPath(from, id) {
2877
+ return `file://${path$1.join(id.slice(7).split("/").slice(0, -1).join("/"), from)}.as`;
2878
+ }
2879
+ function getRelPath(fromUri, toUri) {
2880
+ const fromPath = new URL(fromUri).pathname;
2881
+ const toPath = new URL(toUri).pathname;
2882
+ const relPath = path$1.relative(path$1.dirname(fromPath), toPath);
2883
+ const { dir, name } = path$1.parse(relPath);
2884
+ const prefix = dir.startsWith("..") ? "" : "./";
2885
+ return `${prefix}${dir ? `${dir}/` : ""}${name}`;
2886
+ }
2887
+
2135
2888
  //#endregion
2136
2889
  //#region packages/core/src/token-index/blocks-index.ts
2137
2890
  function _define_property$5(obj, key, value) {
@@ -2254,7 +3007,11 @@ var TokensIndex = class {
2254
3007
  */ at(line, character) {
2255
3008
  const tokens$1 = this.tokensMap[line];
2256
3009
  if (!tokens$1) return undefined;
2257
- return Array.from(tokens$1).find((t) => t.range.start.character <= character && t.range.end.character >= character);
3010
+ let best;
3011
+ for (const t of tokens$1) if (t.range.start.character <= character && t.range.end.character >= character) {
3012
+ if (!best || t.range.start.character > best.range.start.character || t.range.start.character === best.range.start.character && t.range.end.character < best.range.end.character) best = t;
3013
+ }
3014
+ return best;
2258
3015
  }
2259
3016
  /**
2260
3017
  * Retrieves either the token at the specified (line, character), or if none exists,
@@ -2356,6 +3113,7 @@ var AtscriptDoc = class {
2356
3113
  this.importedDefs.clear();
2357
3114
  this.messages = [];
2358
3115
  this.referred = [];
3116
+ this.queryFieldRefs = [];
2359
3117
  this.imports.clear();
2360
3118
  this._allMessages = undefined;
2361
3119
  this.tokensIndex = new TokensIndex();
@@ -2384,6 +3142,23 @@ var AtscriptDoc = class {
2384
3142
  this.registerMessages(annotationSpec.validate(mainToken, args || [], this));
2385
3143
  annotationSpec.modify(mainToken, args || [], this);
2386
3144
  this.resolvedAnnotations.push(mainToken);
3145
+ const specArgs = annotationSpec.arguments;
3146
+ for (let i = 0; i < (args?.length ?? 0); i++) {
3147
+ const argSpec = specArgs[i];
3148
+ if (argSpec?.type === "ref" && args?.[i]) {
3149
+ const refToken = args[i];
3150
+ const dotIdx = refToken.text.indexOf(".");
3151
+ if (dotIdx > 0) {
3152
+ const typeToken = refToken.clone({ text: refToken.text.slice(0, dotIdx) });
3153
+ typeToken.isReference = true;
3154
+ this.referred.push(typeToken);
3155
+ } else {
3156
+ refToken.isReference = true;
3157
+ this.referred.push(refToken);
3158
+ }
3159
+ }
3160
+ if (argSpec?.type === "query" && args?.[i]?.queryNode) args[i].queryNode.registerAtDocument(this);
3161
+ }
2387
3162
  } else {
2388
3163
  let severity = 0;
2389
3164
  switch (this.config.unknownAnnotation) {
@@ -2591,6 +3366,17 @@ else {
2591
3366
  });
2592
3367
  }
2593
3368
  }
3369
+ for (const qfr of doc.queryFieldRefs) {
3370
+ if (!qfr.queryArgToken || qfr.fieldRef.text !== propName$1) continue;
3371
+ const scope = getQueryScope(qfr.queryArgToken, doc);
3372
+ if (!scope) continue;
3373
+ const resolvedTypeName = qfr.typeRef?.text ?? scope.unqualifiedTarget;
3374
+ if (resolvedTypeName === parentName) refs.push({
3375
+ uri,
3376
+ range: qfr.fieldRef.range,
3377
+ token: qfr.fieldRef
3378
+ });
3379
+ }
2594
3380
  };
2595
3381
  searchDoc(this, this.id);
2596
3382
  const parentDefToken = this.registry.definitions.get(parentName);
@@ -2602,7 +3388,23 @@ else {
2602
3388
  }
2603
3389
  }
2604
3390
  return refs;
2605
- } else {
3391
+ }
3392
+ if (isQueryFieldRef(token.parentNode) && token === token.parentNode.fieldRef) {
3393
+ const fieldRefNode = token.parentNode;
3394
+ const queryArgToken = fieldRefNode.queryArgToken;
3395
+ if (queryArgToken) {
3396
+ const scope = getQueryScope(queryArgToken, this);
3397
+ if (scope) {
3398
+ const resolved = resolveQueryFieldRef(fieldRefNode, this, scope);
3399
+ if (resolved?.prop) {
3400
+ const propToken = resolved.prop.token("identifier");
3401
+ if (propToken) return resolved.doc.usageListFor(propToken);
3402
+ }
3403
+ }
3404
+ }
3405
+ return undefined;
3406
+ }
3407
+ {
2606
3408
  const defForToken = this.getDefinitionFor(token);
2607
3409
  if (defForToken?.token?.isDefinition && defForToken.doc) return defForToken.doc.usageListFor(defForToken.token);
2608
3410
  }
@@ -2676,6 +3478,37 @@ else {
2676
3478
  }];
2677
3479
  return undefined;
2678
3480
  }
3481
+ if (isQueryFieldRef(token.parentNode)) {
3482
+ const fieldRefNode = token.parentNode;
3483
+ const queryArgToken = fieldRefNode.queryArgToken;
3484
+ if (queryArgToken) {
3485
+ const scope = getQueryScope(queryArgToken, this);
3486
+ if (scope) {
3487
+ if (token === fieldRefNode.typeRef) {
3488
+ const result = this.getDefinitionFor(token);
3489
+ return result ? [{
3490
+ targetUri: result.uri,
3491
+ targetRange: result.token?.range ?? zeroRange,
3492
+ targetSelectionRange: result.token?.range ?? zeroRange,
3493
+ originSelectionRange: token.range
3494
+ }] : undefined;
3495
+ }
3496
+ if (token === fieldRefNode.fieldRef) {
3497
+ const resolved = resolveQueryFieldRef(fieldRefNode, this, scope);
3498
+ if (resolved?.prop) {
3499
+ const propToken = resolved.prop.token("identifier");
3500
+ return [{
3501
+ targetUri: resolved.targetUri,
3502
+ targetRange: propToken?.range ?? zeroRange,
3503
+ targetSelectionRange: propToken?.range ?? zeroRange,
3504
+ originSelectionRange: token.range
3505
+ }];
3506
+ }
3507
+ }
3508
+ }
3509
+ }
3510
+ return undefined;
3511
+ }
2679
3512
  if (isProp(token.parentNode)) return [{
2680
3513
  targetUri: this.id,
2681
3514
  targetRange: token.range,
@@ -3132,6 +3965,9 @@ else {
3132
3965
  * List of tokens that refer to some type or interface
3133
3966
  */ _define_property$3(this, "referred", void 0);
3134
3967
  /**
3968
+ * List of query field ref nodes (for find-references support)
3969
+ */ _define_property$3(this, "queryFieldRefs", void 0);
3970
+ /**
3135
3971
  * Map of dependencies (documents) by URI
3136
3972
  */ _define_property$3(this, "dependenciesMap", void 0);
3137
3973
  _define_property$3(this, "nodes", void 0);
@@ -3153,6 +3989,7 @@ else {
3153
3989
  this.dependencies = new Set();
3154
3990
  this.dependants = new Set();
3155
3991
  this.referred = [];
3992
+ this.queryFieldRefs = [];
3156
3993
  this.dependenciesMap = new Map();
3157
3994
  this.nodes = [];
3158
3995
  this._text = "";
@@ -3183,47 +4020,307 @@ function createSyntheticRef(name) {
3183
4020
  return ref$1;
3184
4021
  }
3185
4022
 
4023
+ //#endregion
4024
+ //#region packages/core/src/defaults/db-utils.ts
4025
+ function validateRefArgument(token, doc, options) {
4026
+ const messages = [];
4027
+ const text$2 = token.text;
4028
+ const [typeName, ...chain] = text$2.split(".");
4029
+ const decl = doc.getDeclarationOwnerNode(typeName);
4030
+ if (!decl) {
4031
+ const regDef = doc.registry.definitions.get(typeName);
4032
+ if (regDef?.imported) return messages;
4033
+ messages.push({
4034
+ severity: 1,
4035
+ message: `Unknown type '${typeName}'.`,
4036
+ range: token.range
4037
+ });
4038
+ return messages;
4039
+ }
4040
+ if (chain.length > 0) {
4041
+ const unwound = doc.unwindType(typeName, chain);
4042
+ if (!unwound) {
4043
+ messages.push({
4044
+ severity: 1,
4045
+ message: `Field '${chain.join(".")}' does not exist on type '${typeName}'.`,
4046
+ range: token.range
4047
+ });
4048
+ return messages;
4049
+ }
4050
+ }
4051
+ if (options?.requireDbTable && decl.node) {
4052
+ const hasDbTable = decl.node.countAnnotations("db.table") > 0;
4053
+ if (!hasDbTable) messages.push({
4054
+ severity: 1,
4055
+ message: `Type '${typeName}' must have @db.table annotation.`,
4056
+ range: token.range
4057
+ });
4058
+ }
4059
+ return messages;
4060
+ }
4061
+ function findFKFieldsPointingTo(doc, iface, targetTypeName, alias) {
4062
+ const results = [];
4063
+ let struct;
4064
+ if (isInterface(iface) && iface.hasExtends) {
4065
+ const resolved = doc.resolveInterfaceExtends(iface);
4066
+ if (resolved && isStructure(resolved)) struct = resolved;
4067
+ }
4068
+ if (!struct) struct = isStructure(iface) ? iface : isInterface(iface) && isStructure(iface.getDefinition()) ? iface.getDefinition() : undefined;
4069
+ if (!struct) return results;
4070
+ for (const [name, prop] of struct.props) {
4071
+ if (prop.countAnnotations("db.rel.FK") === 0) continue;
4072
+ const def = prop.getDefinition();
4073
+ if (!def || !isRef(def)) continue;
4074
+ const ref$1 = def;
4075
+ if (!ref$1.hasChain) continue;
4076
+ const refTypeName = ref$1.id;
4077
+ const refField = ref$1.chain.map((c) => c.text).join(".");
4078
+ if (refTypeName !== targetTypeName) continue;
4079
+ if (alias !== undefined) {
4080
+ const fkAnnotations = prop.annotations?.filter((a) => a.name === "db.rel.FK");
4081
+ const hasMatchingAlias = fkAnnotations?.some((a) => a.args.length > 0 && a.args[0].text === alias);
4082
+ if (!hasMatchingAlias) continue;
4083
+ }
4084
+ results.push({
4085
+ name,
4086
+ prop,
4087
+ chainRef: {
4088
+ type: refTypeName,
4089
+ field: refField
4090
+ }
4091
+ });
4092
+ }
4093
+ return results;
4094
+ }
4095
+ const viewAnnotationNames = [
4096
+ "db.view",
4097
+ "db.view.for",
4098
+ "db.view.joins",
4099
+ "db.view.filter",
4100
+ "db.view.materialized"
4101
+ ];
4102
+ function hasAnyViewAnnotation(node) {
4103
+ return viewAnnotationNames.some((name) => node.countAnnotations(name) > 0);
4104
+ }
4105
+ function validateQueryScope(queryToken, allowedTypes, unqualifiedTarget, doc) {
4106
+ const errors = [];
4107
+ const queryNode = queryToken.queryNode;
4108
+ if (!queryNode) return errors;
4109
+ function walkFieldRef(ref$1) {
4110
+ if (ref$1.typeRef) {
4111
+ const typeName = ref$1.typeRef.text;
4112
+ if (!allowedTypes.includes(typeName)) errors.push({
4113
+ message: `Query references '${typeName}' which is not in scope — expected ${allowedTypes.map((t) => `'${t}'`).join(" or ")}`,
4114
+ severity: 1,
4115
+ range: ref$1.typeRef.range
4116
+ });
4117
+ } else if (unqualifiedTarget === null) errors.push({
4118
+ message: `Unqualified field reference '${ref$1.fieldRef.text}' — use qualified form (e.g., Type.${ref$1.fieldRef.text})`,
4119
+ severity: 1,
4120
+ range: ref$1.fieldRef.range
4121
+ });
4122
+ else {
4123
+ const unwound = doc.unwindType(unqualifiedTarget);
4124
+ if (unwound) {
4125
+ const targetDef = unwound.def;
4126
+ if (isInterface(targetDef) || isStructure(targetDef)) {
4127
+ const struct = isInterface(targetDef) ? targetDef.getDefinition() : targetDef;
4128
+ if (struct && isStructure(struct) && !struct.props.has(ref$1.fieldRef.text)) errors.push({
4129
+ message: `Field '${ref$1.fieldRef.text}' does not exist on '${unqualifiedTarget}'`,
4130
+ severity: 1,
4131
+ range: ref$1.fieldRef.range
4132
+ });
4133
+ }
4134
+ }
4135
+ }
4136
+ }
4137
+ function walkExpr(expr) {
4138
+ if (isQueryLogical(expr)) for (const operand of expr.operands) walkExpr(operand);
4139
+ else if (isQueryComparison(expr)) {
4140
+ walkFieldRef(expr.left);
4141
+ if (expr.right && "fieldRef" in expr.right) walkFieldRef(expr.right);
4142
+ }
4143
+ }
4144
+ walkExpr(queryNode.expression);
4145
+ return errors;
4146
+ }
4147
+
3186
4148
  //#endregion
3187
4149
  //#region packages/core/src/defaults/db-annotations.ts
3188
- const dbAnnotations = {
3189
- patch: { strategy: new AnnotationSpec({
3190
- description: "Defines the **patching strategy** for updating nested objects.\n\n- **\"replace\"** → The field or object will be **fully replaced**.\n- **\"merge\"** → The field or object will be **merged recursively** (applies only to objects, not arrays).\n\n**Example:**\n```atscript\n@db.patch.strategy \"merge\"\nsettings: {\n notifications: boolean\n preferences: {\n theme: string\n }\n}\n```\n",
4150
+ /**
4151
+ * Traverse from annotation token → prop → structure → interface
4152
+ * to check if the parent interface has @db.table.
4153
+ */ function getDbTableOwner(token) {
4154
+ const field = token.parentNode;
4155
+ const struct = field.ownerNode;
4156
+ if (!struct || !isStructure(struct)) return undefined;
4157
+ const iface = struct.ownerNode;
4158
+ return iface && isInterface(iface) ? iface : struct;
4159
+ }
4160
+ /**
4161
+ * Get the parent structure node from an annotation token.
4162
+ */ function getParentStruct(token) {
4163
+ const field = token.parentNode;
4164
+ const struct = field.ownerNode;
4165
+ return struct && isStructure(struct) ? struct : undefined;
4166
+ }
4167
+ /**
4168
+ * Get the parent interface name (for error messages and cross-type resolution).
4169
+ */ function getParentTypeName(token) {
4170
+ const struct = getParentStruct(token);
4171
+ if (!struct) return undefined;
4172
+ const iface = struct.ownerNode;
4173
+ return iface && isInterface(iface) ? iface.id : struct.id;
4174
+ }
4175
+ /**
4176
+ * Extract target type name from a navigational field definition.
4177
+ * Unwraps arrays (e.g., `Post[]` → `Post`).
4178
+ */ function getNavTargetTypeName(field) {
4179
+ let def = field.getDefinition();
4180
+ if (isArray(def)) def = def?.getDefinition();
4181
+ if (isRef(def)) return def.id;
4182
+ return undefined;
4183
+ }
4184
+ /**
4185
+ * Get the alias argument from an annotation on a field.
4186
+ */ function getAnnotationAlias(prop, annotationName) {
4187
+ const annotations$1 = prop.annotations?.filter((a) => a.name === annotationName);
4188
+ if (!annotations$1 || annotations$1.length === 0) return undefined;
4189
+ return annotations$1[0].args.length > 0 ? annotations$1[0].args[0].text : undefined;
4190
+ }
4191
+ /**
4192
+ * Factory for @db.rel.onDelete / @db.rel.onUpdate — identical validation logic,
4193
+ * only the annotation name and description verb differ.
4194
+ */ function refActionAnnotation(name) {
4195
+ return new AnnotationSpec({
4196
+ description: `Referential action when the target ${name === "onDelete" ? "row is deleted" : "key is updated"}. Only valid on @db.rel.FK fields.\n\n` + "**Example:**\n" + "```atscript\n" + "@db.rel.FK\n" + `@db.rel.${name} "cascade"\n` + "authorId: User.id\n" + "```\n",
3191
4197
  nodeType: ["prop"],
3192
- multiple: false,
3193
4198
  argument: {
3194
- name: "strategy",
4199
+ name: "action",
3195
4200
  type: "string",
3196
- description: "The **patch strategy** for this field: `\"replace\"` (default) or `\"merge\"`.",
3197
- values: ["replace", "merge"]
4201
+ values: [
4202
+ "cascade",
4203
+ "restrict",
4204
+ "noAction",
4205
+ "setNull",
4206
+ "setDefault"
4207
+ ],
4208
+ description: "Referential action: \"cascade\", \"restrict\", \"noAction\", \"setNull\", or \"setDefault\"."
3198
4209
  },
3199
4210
  validate(token, args, doc) {
3200
- const field = token.parentNode;
3201
4211
  const errors = [];
3202
- const definition$1 = field.getDefinition();
3203
- if (!definition$1) return errors;
3204
- let wrongType = false;
3205
- if (isRef(definition$1)) {
3206
- const def = doc.unwindType(definition$1.id, definition$1.chain)?.def;
3207
- if (!isStructure(def) && !isInterface(def) && !isArray(def)) wrongType = true;
3208
- } else if (!isStructure(definition$1) && !isInterface(definition$1) && !isArray(definition$1)) wrongType = true;
3209
- if (wrongType) errors.push({
3210
- message: `@db.patch.strategy requires a field of type object or array`,
4212
+ const field = token.parentNode;
4213
+ if (field.countAnnotations("db.rel.FK") === 0) errors.push({
4214
+ message: `@db.rel.${name} is only valid on @db.rel.FK fields`,
3211
4215
  severity: 1,
3212
4216
  range: token.range
3213
4217
  });
3214
- return errors;
3215
- }
3216
- }) },
3217
- table: new AnnotationSpec({
3218
- description: "Marks an interface as a database-persisted entity (table in SQL, collection in MongoDB). If the name argument is omitted, the adapter derives the table name from the interface name.\n\n**Example:**\n```atscript\n@db.table \"users\"\nexport interface User { ... }\n```\n",
3219
- nodeType: ["interface"],
4218
+ if (args[0]) {
4219
+ const action = args[0].text;
4220
+ if (action === "setNull" && !field.has("optional")) errors.push({
4221
+ message: `@db.rel.${name} "setNull" requires the FK field to be optional (?)`,
4222
+ severity: 1,
4223
+ range: token.range
4224
+ });
4225
+ if (action === "setDefault" && field.countAnnotations("db.default") === 0 && field.countAnnotations("db.default.fn") === 0) errors.push({
4226
+ message: `@db.rel.${name} "setDefault" but no @db.default.* annotation — field will have no fallback value`,
4227
+ severity: 2,
4228
+ range: token.range
4229
+ });
4230
+ }
4231
+ const fkAlias = getAnnotationAlias(field, "db.rel.FK");
4232
+ if (fkAlias) {
4233
+ const struct = getParentStruct(token);
4234
+ if (struct) {
4235
+ const annotationName = `db.rel.${name}`;
4236
+ let count = 0;
4237
+ for (const [, prop] of struct.props) {
4238
+ if (prop.countAnnotations("db.rel.FK") === 0) continue;
4239
+ if (prop.countAnnotations(annotationName) === 0) continue;
4240
+ const propFkAlias = getAnnotationAlias(prop, "db.rel.FK");
4241
+ if (propFkAlias === fkAlias) count++;
4242
+ }
4243
+ if (count > 1) errors.push({
4244
+ message: `Composite FK '${fkAlias}' has @db.rel.${name} on multiple fields — declare it on exactly one`,
4245
+ severity: 1,
4246
+ range: token.range
4247
+ });
4248
+ }
4249
+ }
4250
+ return errors;
4251
+ }
4252
+ });
4253
+ }
4254
+ const dbAnnotations = {
4255
+ patch: { strategy: new AnnotationSpec({
4256
+ description: "Defines the **patching strategy** for updating nested objects.\n\n- **\"replace\"** → The field or object will be **fully replaced**.\n- **\"merge\"** → The field or object will be **merged recursively** (applies only to objects, not arrays).\n\n**Example:**\n```atscript\n@db.patch.strategy \"merge\"\nsettings: {\n notifications: boolean\n preferences: {\n theme: string\n }\n}\n```\n",
4257
+ nodeType: ["prop"],
4258
+ multiple: false,
3220
4259
  argument: {
3221
- optional: true,
3222
- name: "name",
4260
+ name: "strategy",
3223
4261
  type: "string",
3224
- description: "Table/collection name. If omitted, derived from interface name."
4262
+ description: "The **patch strategy** for this field: `\"replace\"` (default) or `\"merge\"`.",
4263
+ values: ["replace", "merge"]
4264
+ },
4265
+ validate(token, args, doc) {
4266
+ const field = token.parentNode;
4267
+ const errors = [];
4268
+ const definition$1 = field.getDefinition();
4269
+ if (!definition$1) return errors;
4270
+ let wrongType = false;
4271
+ if (isRef(definition$1)) {
4272
+ const def = doc.unwindType(definition$1.id, definition$1.chain)?.def;
4273
+ if (!isStructure(def) && !isInterface(def) && !isArray(def)) wrongType = true;
4274
+ } else if (!isStructure(definition$1) && !isInterface(definition$1) && !isArray(definition$1)) wrongType = true;
4275
+ if (wrongType) errors.push({
4276
+ message: `@db.patch.strategy requires a field of type object or array`,
4277
+ severity: 1,
4278
+ range: token.range
4279
+ });
4280
+ return errors;
3225
4281
  }
3226
- }),
4282
+ }) },
4283
+ table: {
4284
+ $self: new AnnotationSpec({
4285
+ description: "Marks an interface as a database-persisted entity (table in SQL, collection in MongoDB). If the name argument is omitted, the adapter derives the table name from the interface name.\n\n**Example:**\n```atscript\n@db.table \"users\"\nexport interface User { ... }\n```\n",
4286
+ nodeType: ["interface"],
4287
+ argument: {
4288
+ optional: true,
4289
+ name: "name",
4290
+ type: "string",
4291
+ description: "Table/collection name. If omitted, derived from interface name."
4292
+ },
4293
+ validate(token, _args, _doc) {
4294
+ const errors = [];
4295
+ const owner = token.parentNode;
4296
+ if (hasAnyViewAnnotation(owner)) errors.push({
4297
+ message: "An interface cannot be both a @db.table and a @db.view",
4298
+ severity: 1,
4299
+ range: token.range
4300
+ });
4301
+ return errors;
4302
+ }
4303
+ }),
4304
+ renamed: new AnnotationSpec({
4305
+ description: "Specifies the previous table name for table rename migration. The sync engine generates ALTER TABLE RENAME instead of drop+create.\n\n**Example:**\n```atscript\n@db.table \"app_users\"\n@db.table.renamed \"users\"\nexport interface User { ... }\n```\n",
4306
+ nodeType: ["interface"],
4307
+ argument: {
4308
+ name: "oldName",
4309
+ type: "string",
4310
+ description: "The previous table/collection name."
4311
+ },
4312
+ validate(token, _args, _doc) {
4313
+ const errors = [];
4314
+ const owner = token.parentNode;
4315
+ if (owner.countAnnotations("db.table") === 0) errors.push({
4316
+ message: "@db.table.renamed requires @db.table on the same interface",
4317
+ severity: 1,
4318
+ range: token.range
4319
+ });
4320
+ return errors;
4321
+ }
4322
+ })
4323
+ },
3227
4324
  schema: new AnnotationSpec({
3228
4325
  description: "Assigns the entity to a database schema/namespace.\n\n**Example:**\n```atscript\n@db.table \"users\"\n@db.schema \"auth\"\nexport interface User { ... }\n```\n",
3229
4326
  nodeType: ["interface"],
@@ -3282,18 +4379,29 @@ const dbAnnotations = {
3282
4379
  }]
3283
4380
  })
3284
4381
  },
3285
- column: new AnnotationSpec({
3286
- description: "Overrides the physical column/document-field name in the database.\n\n**Example:**\n```atscript\n@db.column \"first_name\"\nfirstName: string\n```\n",
3287
- nodeType: ["prop"],
3288
- argument: {
3289
- name: "name",
3290
- type: "string",
3291
- description: "The actual column/field name in the DB."
3292
- }
3293
- }),
4382
+ column: {
4383
+ $self: new AnnotationSpec({
4384
+ description: "Overrides the physical column name in the database. For nested (flattened) fields, the parent prefix is still prepended automatically.\n\n**Example:**\n```atscript\n@db.column \"first_name\"\nfirstName: string\n// → physical column: first_name\n\n// Nested:\naddress: {\n @db.column \"zip_code\"\n zip: string\n}\n// → physical column: address__zip_code\n```\n",
4385
+ nodeType: ["prop"],
4386
+ argument: {
4387
+ name: "name",
4388
+ type: "string",
4389
+ description: "The column/field name (without parent prefix for nested fields)."
4390
+ }
4391
+ }),
4392
+ renamed: new AnnotationSpec({
4393
+ description: "Specifies the previous local field name for column rename migration. The sync engine generates ALTER TABLE RENAME COLUMN instead of drop+add.\n\n**Example:**\n```atscript\n@db.column.renamed \"zip\"\npostalCode: string\n// Renames address__zip → address__postalCode\n```\n",
4394
+ nodeType: ["prop"],
4395
+ argument: {
4396
+ name: "oldName",
4397
+ type: "string",
4398
+ description: "The old local field name (parent prefix is reconstructed automatically)."
4399
+ }
4400
+ })
4401
+ },
3294
4402
  default: {
3295
- value: new AnnotationSpec({
3296
- description: "Sets a static DB-level default value (used in DDL DEFAULT clause). For string fields the value is used as-is; for other types it is parsed as JSON.\n\n**Example:**\n```atscript\n@db.default.value \"active\"\nstatus: string\n```\n",
4403
+ $self: new AnnotationSpec({
4404
+ description: "Sets a static DB-level default value (used in DDL DEFAULT clause). For string fields the value is used as-is; for other types it is parsed as JSON.\n\n**Example:**\n```atscript\n@db.default \"active\"\nstatus: string\n```\n",
3297
4405
  nodeType: ["prop"],
3298
4406
  argument: {
3299
4407
  name: "value",
@@ -3387,7 +4495,538 @@ else if (fnName === "now" && !["number", "string"].includes(baseType)) errors.pu
3387
4495
  });
3388
4496
  return errors;
3389
4497
  }
3390
- })
4498
+ }),
4499
+ sync: { method: new AnnotationSpec({
4500
+ description: "Controls how the sync engine handles structural changes that cannot be applied via ALTER TABLE.\n\n- `\"recreate\"` — lossless: create temp table, copy data, drop old, rename.\n- `\"drop\"` — lossy: drop table entirely and create from scratch.\n\nWithout this annotation, structural changes fail with an error requiring manual intervention.\n\n**Example:**\n```atscript\n@db.sync.method \"drop\"\ninterface Logs { ... }\n```\n",
4501
+ nodeType: ["interface"],
4502
+ argument: {
4503
+ name: "method",
4504
+ type: "string",
4505
+ description: "Sync method: \"drop\" (lossy) or \"recreate\" (lossless with data copy).",
4506
+ values: ["drop", "recreate"]
4507
+ }
4508
+ }) },
4509
+ rel: {
4510
+ FK: new AnnotationSpec({
4511
+ description: "Declares a foreign key constraint on this field. The field must use a chain reference type (e.g., `User.id`) to specify the FK target.\n\n**Example:**\n```atscript\n@db.rel.FK\nauthorId: User.id\n\n// With alias (required when multiple FKs point to the same type)\n@db.rel.FK \"author\"\nauthorId: User.id\n```\n",
4512
+ nodeType: ["prop"],
4513
+ argument: {
4514
+ optional: true,
4515
+ name: "alias",
4516
+ type: "string",
4517
+ description: "Alias for pairing with @db.rel.to. Required when multiple FKs point to the same target type."
4518
+ },
4519
+ validate(token, args, doc) {
4520
+ const errors = [];
4521
+ const field = token.parentNode;
4522
+ const alias = args[0]?.text;
4523
+ const owner = getDbTableOwner(token);
4524
+ if (!owner || owner.countAnnotations("db.table") === 0) errors.push({
4525
+ message: "@db.rel.FK is only valid on fields of a @db.table interface",
4526
+ severity: 1,
4527
+ range: token.range
4528
+ });
4529
+ if (field.countAnnotations("db.rel.to") > 0 || field.countAnnotations("db.rel.from") > 0) errors.push({
4530
+ message: "A field cannot be both a foreign key and a navigational property",
4531
+ severity: 1,
4532
+ range: token.range
4533
+ });
4534
+ const definition$1 = field.getDefinition();
4535
+ if (!definition$1 || !isRef(definition$1) || !definition$1.hasChain) {
4536
+ errors.push({
4537
+ message: `@db.rel.FK requires a chain reference type (e.g. User.id), got scalar type`,
4538
+ severity: 1,
4539
+ range: token.range
4540
+ });
4541
+ return errors;
4542
+ }
4543
+ const ref$1 = definition$1;
4544
+ const refTypeName = ref$1.id;
4545
+ const chainFields = ref$1.chain.map((c) => c.text);
4546
+ const targetUnwound = doc.unwindType(refTypeName);
4547
+ if (targetUnwound) {
4548
+ const targetDef = targetUnwound.def;
4549
+ if (isInterface(targetDef) || isStructure(targetDef)) {
4550
+ const struct = isInterface(targetDef) ? targetDef.getDefinition() : targetDef;
4551
+ if (struct && isStructure(struct) && chainFields.length > 0) {
4552
+ const targetProp = struct.props.get(chainFields[0]);
4553
+ if (targetProp) {
4554
+ if (targetProp.countAnnotations("meta.id") === 0 && targetProp.countAnnotations("db.index.unique") === 0) errors.push({
4555
+ message: `@db.rel.FK target '${refTypeName}.${chainFields.join(".")}' is not a primary key (@meta.id) or unique (@db.index.unique) field`,
4556
+ severity: 1,
4557
+ range: token.range
4558
+ });
4559
+ const propDef = targetProp.getDefinition();
4560
+ if (propDef && isRef(propDef)) {
4561
+ const propUnwound = targetUnwound.doc.unwindType(propDef.id, propDef.chain);
4562
+ if (propUnwound && !isPrimitive(propUnwound.def)) errors.push({
4563
+ message: `Foreign key field must resolve to a scalar type (number, string, etc.), got '${propDef.id}'`,
4564
+ severity: 1,
4565
+ range: token.range
4566
+ });
4567
+ } else if (propDef && !isPrimitive(propDef)) errors.push({
4568
+ message: `Foreign key field must resolve to a scalar type (number, string, etc.)`,
4569
+ severity: 1,
4570
+ range: token.range
4571
+ });
4572
+ }
4573
+ }
4574
+ }
4575
+ }
4576
+ if (!alias) {
4577
+ const struct = getParentStruct(token);
4578
+ if (struct) {
4579
+ let sameTargetCount = 0;
4580
+ for (const [, prop] of struct.props) {
4581
+ if (prop.countAnnotations("db.rel.FK") === 0) continue;
4582
+ const def = prop.getDefinition();
4583
+ if (!def || !isRef(def)) continue;
4584
+ const r = def;
4585
+ if (!r.hasChain) continue;
4586
+ if (r.id === refTypeName) {
4587
+ const fkAnnotations = prop.annotations?.filter((a) => a.name === "db.rel.FK");
4588
+ const hasAlias = fkAnnotations?.some((a) => a.args.length > 0);
4589
+ if (!hasAlias) sameTargetCount++;
4590
+ }
4591
+ }
4592
+ if (sameTargetCount > 1) errors.push({
4593
+ message: `Multiple @db.rel.FK fields resolve to type '${refTypeName}' — add alias to disambiguate`,
4594
+ severity: 1,
4595
+ range: token.range
4596
+ });
4597
+ }
4598
+ }
4599
+ return errors;
4600
+ }
4601
+ }),
4602
+ to: new AnnotationSpec({
4603
+ description: "Forward navigational property — the FK is on **this** interface. The compiler resolves the matching @db.rel.FK by target type or alias.\n\n**Example:**\n```atscript\n@db.rel.to\nauthor?: User\n\n// With alias\n@db.rel.to \"author\"\nauthor?: User\n```\n",
4604
+ nodeType: ["prop"],
4605
+ argument: {
4606
+ optional: true,
4607
+ name: "alias",
4608
+ type: "string",
4609
+ description: "Match a local @db.rel.FK by alias."
4610
+ },
4611
+ validate(token, args, doc) {
4612
+ const errors = [];
4613
+ const field = token.parentNode;
4614
+ const alias = args[0]?.text;
4615
+ const owner = getDbTableOwner(token);
4616
+ if (!owner || owner.countAnnotations("db.table") === 0) errors.push({
4617
+ message: "@db.rel.to is only valid on fields of a @db.table interface",
4618
+ severity: 1,
4619
+ range: token.range
4620
+ });
4621
+ if (field.countAnnotations("db.rel.FK") > 0) errors.push({
4622
+ message: "A field cannot be both a foreign key and a navigational property",
4623
+ severity: 1,
4624
+ range: token.range
4625
+ });
4626
+ const targetTypeName = getNavTargetTypeName(field);
4627
+ if (!targetTypeName) return errors;
4628
+ const unwound = doc.unwindType(targetTypeName);
4629
+ if (unwound) {
4630
+ const targetDef = unwound.def;
4631
+ const targetNode = isInterface(targetDef) ? targetDef : undefined;
4632
+ if (!targetNode || targetNode.countAnnotations("db.table") === 0) errors.push({
4633
+ message: `@db.rel.to target '${targetTypeName}' is not a @db.table entity`,
4634
+ severity: 1,
4635
+ range: token.range
4636
+ });
4637
+ }
4638
+ const fieldDef = field.getDefinition();
4639
+ if (fieldDef && fieldDef.entity === "group" && fieldDef.op === "|") errors.push({
4640
+ message: "@db.rel.to does not support union types — use separate relations",
4641
+ severity: 1,
4642
+ range: token.range
4643
+ });
4644
+ const struct = getParentStruct(token);
4645
+ if (struct) {
4646
+ const fieldName = field.id;
4647
+ for (const [name, prop] of struct.props) {
4648
+ if (name === fieldName) continue;
4649
+ if (prop.countAnnotations("db.rel.to") === 0) continue;
4650
+ const propAlias = getAnnotationAlias(prop, "db.rel.to");
4651
+ if ((alias || undefined) === (propAlias || undefined)) {
4652
+ const otherTarget = getNavTargetTypeName(prop);
4653
+ if (otherTarget === targetTypeName) {
4654
+ errors.push({
4655
+ message: `Duplicate @db.rel.to '${alias || targetTypeName}' — only one forward navigational property per alias`,
4656
+ severity: 1,
4657
+ range: token.range
4658
+ });
4659
+ break;
4660
+ }
4661
+ }
4662
+ }
4663
+ if (alias) {
4664
+ const matches = findFKFieldsPointingTo(doc, struct, targetTypeName, alias);
4665
+ if (matches.length === 0) errors.push({
4666
+ message: `No @db.rel.FK '${alias}' found on this interface`,
4667
+ severity: 1,
4668
+ range: token.range
4669
+ });
4670
+ } else {
4671
+ const matches = findFKFieldsPointingTo(doc, struct, targetTypeName);
4672
+ if (matches.length === 0) errors.push({
4673
+ message: `No @db.rel.FK on this interface points to '${targetTypeName}' — did you mean @db.rel.from?`,
4674
+ severity: 1,
4675
+ range: token.range
4676
+ });
4677
+ else if (matches.length > 1) errors.push({
4678
+ message: `Multiple @db.rel.FK fields point to '${targetTypeName}' — add alias to disambiguate`,
4679
+ severity: 1,
4680
+ range: token.range
4681
+ });
4682
+ }
4683
+ }
4684
+ return errors;
4685
+ }
4686
+ }),
4687
+ from: new AnnotationSpec({
4688
+ description: "Inverse navigational property — the FK is on the **target** interface, pointing back to this one.\n\n**Example:**\n```atscript\n@db.rel.from\nposts: Post[]\n\n// With alias\n@db.rel.from \"original\"\ncomments: Comment[]\n```\n",
4689
+ nodeType: ["prop"],
4690
+ argument: {
4691
+ optional: true,
4692
+ name: "alias",
4693
+ type: "string",
4694
+ description: "Match a @db.rel.FK on the target interface by alias."
4695
+ },
4696
+ validate(token, args, doc) {
4697
+ const errors = [];
4698
+ const field = token.parentNode;
4699
+ const alias = args[0]?.text;
4700
+ const owner = getDbTableOwner(token);
4701
+ if (!owner || owner.countAnnotations("db.table") === 0) errors.push({
4702
+ message: "@db.rel.from is only valid on fields of a @db.table interface",
4703
+ severity: 1,
4704
+ range: token.range
4705
+ });
4706
+ if (field.countAnnotations("db.rel.FK") > 0) errors.push({
4707
+ message: "A field cannot be both a foreign key and a navigational property",
4708
+ severity: 1,
4709
+ range: token.range
4710
+ });
4711
+ const targetTypeName = getNavTargetTypeName(field);
4712
+ if (!targetTypeName) return errors;
4713
+ const unwound = doc.unwindType(targetTypeName);
4714
+ if (!unwound) return errors;
4715
+ const targetDef = unwound.def;
4716
+ const targetDoc = unwound.doc;
4717
+ if (!isInterface(targetDef) || targetDef.countAnnotations("db.table") === 0) {
4718
+ errors.push({
4719
+ message: `@db.rel.from target '${targetTypeName}' is not a @db.table entity`,
4720
+ severity: 1,
4721
+ range: token.range
4722
+ });
4723
+ return errors;
4724
+ }
4725
+ const struct = getParentStruct(token);
4726
+ if (struct) {
4727
+ const fieldName = field.id;
4728
+ for (const [name, prop] of struct.props) {
4729
+ if (name === fieldName) continue;
4730
+ if (prop.countAnnotations("db.rel.from") === 0) continue;
4731
+ const propAlias = getAnnotationAlias(prop, "db.rel.from");
4732
+ if ((alias || undefined) === (propAlias || undefined)) {
4733
+ const otherTarget = getNavTargetTypeName(prop);
4734
+ if (otherTarget === targetTypeName) {
4735
+ errors.push({
4736
+ message: `Duplicate @db.rel.from '${alias || targetTypeName}' — only one inverse navigational property per alias`,
4737
+ severity: 1,
4738
+ range: token.range
4739
+ });
4740
+ break;
4741
+ }
4742
+ }
4743
+ }
4744
+ }
4745
+ const thisTypeName = getParentTypeName(token);
4746
+ if (!thisTypeName) return errors;
4747
+ const matches = findFKFieldsPointingTo(targetDoc, targetDef, thisTypeName, alias);
4748
+ if (alias) {
4749
+ if (matches.length === 0) errors.push({
4750
+ message: `No @db.rel.FK '${alias}' found on '${targetTypeName}'`,
4751
+ severity: 1,
4752
+ range: token.range
4753
+ });
4754
+ } else if (matches.length === 0) errors.push({
4755
+ message: `No @db.rel.FK on '${targetTypeName}' points to '${thisTypeName}'`,
4756
+ severity: 1,
4757
+ range: token.range
4758
+ });
4759
+ else if (matches.length > 1) errors.push({
4760
+ message: `'${targetTypeName}' has multiple @db.rel.FK fields pointing to '${thisTypeName}' — add alias`,
4761
+ severity: 1,
4762
+ range: token.range
4763
+ });
4764
+ const fieldDef = field.getDefinition();
4765
+ if (!isArray(fieldDef) && matches.length === 1) {
4766
+ const fkProp = matches[0].prop;
4767
+ if (fkProp.countAnnotations("db.index.unique") === 0) errors.push({
4768
+ message: `@db.rel.from '${field.id}' has singular type '${targetTypeName}' (1:1) but the FK on '${targetTypeName}' is not @db.index.unique — did you mean '${targetTypeName}[]' (1:N)?`,
4769
+ severity: 2,
4770
+ range: token.range
4771
+ });
4772
+ }
4773
+ return errors;
4774
+ }
4775
+ }),
4776
+ onDelete: refActionAnnotation("onDelete"),
4777
+ onUpdate: refActionAnnotation("onUpdate"),
4778
+ via: new AnnotationSpec({
4779
+ description: "Declares a many-to-many navigational property through an explicit junction table. `@db.rel.via` is self-sufficient — no `@db.rel.from` pairing is needed.\n\n**Example:**\n```atscript\n@db.rel.via PostTag\ntags: Tag[]\n```\n",
4780
+ nodeType: ["prop"],
4781
+ argument: {
4782
+ name: "junction",
4783
+ type: "ref",
4784
+ description: "The junction table type (must have @db.table and @db.rel.FK fields pointing to both sides)."
4785
+ },
4786
+ validate(token, args, doc) {
4787
+ const errors = [];
4788
+ const field = token.parentNode;
4789
+ if (field.countAnnotations("db.rel.to") > 0 || field.countAnnotations("db.rel.from") > 0) errors.push({
4790
+ message: "@db.rel.via is self-sufficient — cannot be combined with @db.rel.to or @db.rel.from",
4791
+ severity: 1,
4792
+ range: token.range
4793
+ });
4794
+ const definition$1 = field.getDefinition();
4795
+ if (!isArray(definition$1)) errors.push({
4796
+ message: "@db.rel.via requires an array type (e.g. Tag[])",
4797
+ severity: 1,
4798
+ range: token.range
4799
+ });
4800
+ if (!args[0]) return errors;
4801
+ const junctionName = args[0].text;
4802
+ errors.push(...validateRefArgument(args[0], doc, { requireDbTable: true }));
4803
+ if (errors.length > 0) return errors;
4804
+ const junctionUnwound = doc.unwindType(junctionName);
4805
+ if (!junctionUnwound) return errors;
4806
+ const junctionDef = junctionUnwound.def;
4807
+ if (!isInterface(junctionDef)) return errors;
4808
+ const thisTypeName = getParentTypeName(token);
4809
+ const targetTypeName = getNavTargetTypeName(field);
4810
+ if (!thisTypeName || !targetTypeName) return errors;
4811
+ const fksToThis = findFKFieldsPointingTo(junctionUnwound.doc, junctionDef, thisTypeName);
4812
+ if (fksToThis.length === 0) errors.push({
4813
+ message: `Junction '${junctionName}' has no @db.rel.FK pointing to '${thisTypeName}'`,
4814
+ severity: 1,
4815
+ range: args[0].range
4816
+ });
4817
+ else if (fksToThis.length > 1) errors.push({
4818
+ message: `Junction '${junctionName}' has multiple @db.rel.FK pointing to '${thisTypeName}' — not supported`,
4819
+ severity: 1,
4820
+ range: args[0].range
4821
+ });
4822
+ if (targetTypeName !== thisTypeName) {
4823
+ const fksToTarget = findFKFieldsPointingTo(junctionUnwound.doc, junctionDef, targetTypeName);
4824
+ if (fksToTarget.length === 0) errors.push({
4825
+ message: `Junction '${junctionName}' has no @db.rel.FK pointing to '${targetTypeName}'`,
4826
+ severity: 1,
4827
+ range: args[0].range
4828
+ });
4829
+ else if (fksToTarget.length > 1) errors.push({
4830
+ message: `Junction '${junctionName}' has multiple @db.rel.FK pointing to '${targetTypeName}' — not supported`,
4831
+ severity: 1,
4832
+ range: args[0].range
4833
+ });
4834
+ }
4835
+ return errors;
4836
+ }
4837
+ }),
4838
+ filter: new AnnotationSpec({
4839
+ description: "Applies a filter to a navigational property, restricting which related records are loaded.\n\n**Example:**\n```atscript\n@db.rel.from\n@db.rel.filter `Post.published = true`\npublishedPosts: Post[]\n```\n",
4840
+ nodeType: ["prop"],
4841
+ argument: {
4842
+ name: "condition",
4843
+ type: "query",
4844
+ description: "Filter expression restricting which related records are loaded."
4845
+ },
4846
+ validate(token, args, doc) {
4847
+ const errors = [];
4848
+ const field = token.parentNode;
4849
+ const hasTo = field.countAnnotations("db.rel.to") > 0;
4850
+ const hasFrom = field.countAnnotations("db.rel.from") > 0;
4851
+ const hasVia = field.countAnnotations("db.rel.via") > 0;
4852
+ if (!hasTo && !hasFrom && !hasVia) {
4853
+ errors.push({
4854
+ message: "@db.rel.filter is only valid on navigational fields (@db.rel.to, @db.rel.from, or @db.rel.via)",
4855
+ severity: 1,
4856
+ range: token.range
4857
+ });
4858
+ return errors;
4859
+ }
4860
+ if (!args[0]?.queryNode) return errors;
4861
+ const targetTypeName = getNavTargetTypeName(field);
4862
+ if (!targetTypeName) return errors;
4863
+ const allowedTypes = [targetTypeName];
4864
+ if (hasVia) {
4865
+ const viaAnnotations = field.annotations?.filter((a) => a.name === "db.rel.via");
4866
+ if (viaAnnotations?.[0]?.args[0]) allowedTypes.push(viaAnnotations[0].args[0].text);
4867
+ }
4868
+ errors.push(...validateQueryScope(args[0], allowedTypes, targetTypeName, doc));
4869
+ return errors;
4870
+ }
4871
+ })
4872
+ },
4873
+ view: {
4874
+ $self: new AnnotationSpec({
4875
+ description: "Marks an interface as a **database view**. Optionally takes a view name argument.\n\n**Example:**\n```atscript\n@db.view \"active_premium_users\"\n@db.view.for User\nexport interface ActivePremiumUser { ... }\n```\n",
4876
+ nodeType: ["interface"],
4877
+ argument: {
4878
+ optional: true,
4879
+ name: "name",
4880
+ type: "string",
4881
+ description: "The view name in the database. If omitted, derived from the interface name."
4882
+ },
4883
+ validate(token, _args, _doc) {
4884
+ const errors = [];
4885
+ const owner = token.parentNode;
4886
+ if (owner.countAnnotations("db.table") > 0) errors.push({
4887
+ message: "An interface cannot be both a @db.table and a @db.view",
4888
+ severity: 1,
4889
+ range: token.range
4890
+ });
4891
+ return errors;
4892
+ }
4893
+ }),
4894
+ for: new AnnotationSpec({
4895
+ description: "Specifies the entry/primary table for a computed view. Required for views that map fields via chain refs.\n\n**Example:**\n```atscript\n@db.view.for Order\n@db.view.filter `Order.status = 'active'`\nexport interface ActiveOrderDetails { ... }\n```\n",
4896
+ nodeType: ["interface"],
4897
+ argument: {
4898
+ name: "entry",
4899
+ type: "ref",
4900
+ description: "The primary/entry table type (must have @db.table)."
4901
+ },
4902
+ validate(token, args, doc) {
4903
+ const errors = [];
4904
+ const owner = token.parentNode;
4905
+ if (owner.countAnnotations("db.table") > 0) errors.push({
4906
+ message: "An interface cannot be both a @db.table and a @db.view",
4907
+ severity: 1,
4908
+ range: token.range
4909
+ });
4910
+ if (args[0]) errors.push(...validateRefArgument(args[0], doc, { requireDbTable: true }));
4911
+ return errors;
4912
+ }
4913
+ }),
4914
+ joins: new AnnotationSpec({
4915
+ description: "Declares an explicit join for a view. Use when no `@db.rel.*` path exists between the entry table and the target.\n\n**Example:**\n```atscript\n@db.view.for Order\n@db.view.joins Warehouse, `Warehouse.regionId = Order.regionId`\nexport interface OrderWarehouse { ... }\n```\n",
4916
+ nodeType: ["interface"],
4917
+ multiple: true,
4918
+ mergeStrategy: "append",
4919
+ argument: [{
4920
+ name: "target",
4921
+ type: "ref",
4922
+ description: "The table type to join (must have @db.table)."
4923
+ }, {
4924
+ name: "condition",
4925
+ type: "query",
4926
+ description: "Join condition expression."
4927
+ }],
4928
+ validate(token, args, doc) {
4929
+ const errors = [];
4930
+ const owner = token.parentNode;
4931
+ if (!hasAnyViewAnnotation(owner) && !args[0]) {
4932
+ errors.push({
4933
+ message: "@db.view.joins is only valid on @db.view interfaces",
4934
+ severity: 1,
4935
+ range: token.range
4936
+ });
4937
+ return errors;
4938
+ }
4939
+ if (args[0]) errors.push(...validateRefArgument(args[0], doc, { requireDbTable: true }));
4940
+ const forAnnotations = owner.annotations?.filter((a) => a.name === "db.view.for");
4941
+ const entryTypeName = forAnnotations?.[0]?.args[0]?.text;
4942
+ if (!entryTypeName) {
4943
+ errors.push({
4944
+ message: "@db.view.joins requires @db.view.for to identify the entry table",
4945
+ severity: 1,
4946
+ range: token.range
4947
+ });
4948
+ return errors;
4949
+ }
4950
+ if (args[1]?.queryNode && args[0]) {
4951
+ const joinTargetName = args[0].text;
4952
+ errors.push(...validateQueryScope(args[1], [joinTargetName, entryTypeName], entryTypeName, doc));
4953
+ }
4954
+ return errors;
4955
+ }
4956
+ }),
4957
+ filter: new AnnotationSpec({
4958
+ description: "WHERE clause for a view, filtering which rows are included.\n\n**Example:**\n```atscript\n@db.view.for User\n@db.view.filter `User.status = 'active' and User.age >= 18`\nexport interface ActiveUser { ... }\n```\n",
4959
+ nodeType: ["interface"],
4960
+ argument: {
4961
+ name: "condition",
4962
+ type: "query",
4963
+ description: "Filter expression for the view WHERE clause."
4964
+ },
4965
+ validate(token, args, doc) {
4966
+ const errors = [];
4967
+ const owner = token.parentNode;
4968
+ if (!hasAnyViewAnnotation(owner) && !args[0]) {
4969
+ errors.push({
4970
+ message: "@db.view.filter is only valid on @db.view interfaces",
4971
+ severity: 1,
4972
+ range: token.range
4973
+ });
4974
+ return errors;
4975
+ }
4976
+ if (!args[0]?.queryNode) return errors;
4977
+ const forAnnotations = owner.annotations?.filter((a) => a.name === "db.view.for");
4978
+ const entryTypeName = forAnnotations?.[0]?.args[0]?.text;
4979
+ if (!entryTypeName) {
4980
+ errors.push({
4981
+ message: "@db.view.filter requires @db.view.for to identify the entry table",
4982
+ severity: 1,
4983
+ range: token.range
4984
+ });
4985
+ return errors;
4986
+ }
4987
+ const allowedTypes = [entryTypeName];
4988
+ const joinsAnnotations = owner.annotations?.filter((a) => a.name === "db.view.joins");
4989
+ if (joinsAnnotations) {
4990
+ for (const join of joinsAnnotations) if (join.args[0]) allowedTypes.push(join.args[0].text);
4991
+ }
4992
+ errors.push(...validateQueryScope(args[0], allowedTypes, entryTypeName, doc));
4993
+ return errors;
4994
+ }
4995
+ }),
4996
+ materialized: new AnnotationSpec({
4997
+ description: "Marks a view as materialized (precomputed, stored on disk). Supported by PostgreSQL, CockroachDB, Oracle, SQL Server (indexed views), Snowflake. MongoDB supports on-demand materialized views via $merge/$out. Not applicable to MySQL or SQLite.\n\n**Example:**\n```atscript\n@db.view.materialized\n@db.view.for User\n@db.view.filter `User.status = 'active'`\nexport interface ActiveUsers { ... }\n```\n",
4998
+ nodeType: ["interface"],
4999
+ validate(token, _args, _doc) {
5000
+ const errors = [];
5001
+ const owner = token.parentNode;
5002
+ if (!hasAnyViewAnnotation(owner)) errors.push({
5003
+ message: "@db.view.materialized is only valid on @db.view interfaces",
5004
+ severity: 1,
5005
+ range: token.range
5006
+ });
5007
+ return errors;
5008
+ }
5009
+ }),
5010
+ renamed: new AnnotationSpec({
5011
+ description: "Specifies the previous view name for view rename migration. The sync engine drops the old view and creates the new one.\n\n**Example:**\n```atscript\n@db.view \"active_premium_users\"\n@db.view.renamed \"active_users\"\n@db.view.for User\nexport interface ActivePremiumUser { ... }\n```\n",
5012
+ nodeType: ["interface"],
5013
+ argument: {
5014
+ name: "oldName",
5015
+ type: "string",
5016
+ description: "The previous view name."
5017
+ },
5018
+ validate(token, _args, _doc) {
5019
+ const errors = [];
5020
+ const owner = token.parentNode;
5021
+ if (!hasAnyViewAnnotation(owner)) errors.push({
5022
+ message: "@db.view.renamed requires @db.view on the same interface",
5023
+ severity: 1,
5024
+ range: token.range
5025
+ });
5026
+ return errors;
5027
+ }
5028
+ })
5029
+ }
3391
5030
  };
3392
5031
 
3393
5032
  //#endregion
@@ -4086,8 +5725,12 @@ var PluginManager = class {
4086
5725
  return this._loopInAnnotationsSpec(annotations$1, cb);
4087
5726
  }
4088
5727
  _loopInAnnotationsSpec(annotations$1, cb, prefix) {
4089
- for (const [key, value] of Object.entries(annotations$1)) if (isAnnotationSpec(value)) cb(prefix ? `${prefix}.${key}` : key, value);
5728
+ if (annotations$1.$self && prefix) cb(prefix, annotations$1.$self);
5729
+ for (const [key, value] of Object.entries(annotations$1)) {
5730
+ if (key === "$self") continue;
5731
+ if (isAnnotationSpec(value)) cb(prefix ? `${prefix}.${key}` : key, value);
4090
5732
  else this._loopInAnnotationsSpec(value, cb, prefix ? `${prefix}.${key}` : key);
5733
+ }
4091
5734
  }
4092
5735
  constructor(cfg) {
4093
5736
  _define_property$2(this, "cfg", void 0);
@@ -4126,6 +5769,11 @@ var AtscriptRepo = class {
4126
5769
  return new Set(tags);
4127
5770
  }
4128
5771
  async getUsedAnnotations() {
5772
+ const ANNOTATION_TYPE_MAP = {
5773
+ ref: "import(\"@atscript/typescript/utils\").AtscriptRef",
5774
+ query: "import(\"@atscript/typescript/utils\").AtscriptQueryNode"
5775
+ };
5776
+ const mapArgType = (t) => ANNOTATION_TYPE_MAP[t] || t;
4129
5777
  const manager = await this.getSharedPluginManager();
4130
5778
  const annotations$1 = {};
4131
5779
  if (manager) await manager.loopInAnnotationsSpec((name, spec) => {
@@ -4137,12 +5785,12 @@ var AtscriptRepo = class {
4137
5785
  props: {}
4138
5786
  };
4139
5787
  for (const a of spec.arguments) o.props[a.name] = {
4140
- type: a.type,
5788
+ type: mapArgType(a.type),
4141
5789
  optional: a.optional
4142
5790
  };
4143
5791
  types.push(o);
4144
5792
  } else if (spec.config.argument) types.push({
4145
- type: spec.config.argument.type,
5793
+ type: mapArgType(spec.config.argument.type),
4146
5794
  optional: spec.config.argument.optional
4147
5795
  });
4148
5796
  else types.push({ type: "boolean" });
@@ -4283,34 +5931,28 @@ else types.push({ type: "boolean" });
4283
5931
  async checkImport(atscript, from, imports, checked) {
4284
5932
  const forId = resolveAtscriptFromPath(from.text, atscript.id);
4285
5933
  if (forId === atscript.id) {
4286
- const messages = atscript.getDiagMessages();
4287
- messages.push({
5934
+ atscript.registerMessages([{
4288
5935
  severity: 1,
4289
5936
  message: "\"import\" cannot import itself",
4290
5937
  range: from.range
4291
- });
5938
+ }]);
4292
5939
  return;
4293
5940
  }
4294
- const errors = [];
4295
5941
  let external;
4296
5942
  try {
4297
5943
  external = await this.openDocument(forId);
4298
5944
  await this.checkImports(external, checked);
4299
- for (const token of imports) if (!external.exports.has(token.text)) errors.push({
5945
+ for (const token of imports) if (!external.exports.has(token.text)) atscript.registerMessages([{
4300
5946
  severity: 1,
4301
5947
  message: `"${from.text}" has no exported member "${token.text}"`,
4302
5948
  range: token.range
4303
- });
5949
+ }]);
4304
5950
  } catch (error) {
4305
- errors.push({
5951
+ atscript.registerMessages([{
4306
5952
  severity: 1,
4307
5953
  message: `"${from.text}" not found`,
4308
5954
  range: from.range
4309
- });
4310
- }
4311
- if (errors.length > 0) {
4312
- const messages = atscript.getDiagMessages();
4313
- messages.push(...errors);
5955
+ }]);
4314
5956
  }
4315
5957
  return external;
4316
5958
  }
@@ -4371,7 +6013,9 @@ else {
4371
6013
  }
4372
6014
  const documents = [];
4373
6015
  for (const entry of entries) documents.push(await repo.openDocument(`file://${entry}`));
4374
- return new BuildRepo(rootDir, repo, documents.filter(Boolean));
6016
+ const docs = documents.filter(Boolean);
6017
+ for (const doc of docs) await repo.checkDoc(doc);
6018
+ return new BuildRepo(rootDir, repo, docs);
4375
6019
  }
4376
6020
  var BuildRepo = class {
4377
6021
  getDoc(id) {
@@ -4379,10 +6023,7 @@ var BuildRepo = class {
4379
6023
  }
4380
6024
  async diagnostics() {
4381
6025
  const docMessages = new Map();
4382
- for (const document of this.docs) {
4383
- await this.repo.checkDoc(document);
4384
- docMessages.set(document.id, document.getDiagMessages());
4385
- }
6026
+ for (const document of this.docs) docMessages.set(document.id, document.getDiagMessages());
4386
6027
  return docMessages;
4387
6028
  }
4388
6029
  async generate(config, docs = this.docs) {
@@ -4425,14 +6066,14 @@ var BuildRepo = class {
4425
6066
 
4426
6067
  //#endregion
4427
6068
  //#region packages/core/src/flatten.ts
4428
- function flattenInterfaceNode(doc, node) {
6069
+ function flattenInterfaceNode(doc, node, options) {
4429
6070
  const flatMap = new Map();
4430
6071
  const stack = new Set();
4431
6072
  let struct;
4432
6073
  if (node.hasExtends) struct = doc.resolveInterfaceExtends(node);
4433
6074
  if (!struct) struct = node.getDefinition();
4434
6075
  if (!struct || !isStructure(struct)) return flatMap;
4435
- walkStructure(doc, struct, "", false, flatMap, stack);
6076
+ walkStructure(doc, struct, "", false, flatMap, stack, options);
4436
6077
  return flatMap;
4437
6078
  }
4438
6079
  /**
@@ -4447,6 +6088,10 @@ function flattenInterfaceNode(doc, node) {
4447
6088
  if (!prop.annotations) return false;
4448
6089
  return prop.annotations.some((a) => a.name === "db.json");
4449
6090
  }
6091
+ function hasNavPropAnnotation(prop) {
6092
+ if (!prop.annotations) return false;
6093
+ return prop.annotations.some((a) => a.name === "db.rel.to" || a.name === "db.rel.from" || a.name === "db.rel.via");
6094
+ }
4450
6095
  function isPhantomNode(doc, def) {
4451
6096
  if (!def) return false;
4452
6097
  if (isPrimitive(def) && def.config.type === "phantom") return true;
@@ -4495,11 +6140,12 @@ function addToFlatMap(flatMap, path$2, descriptor) {
4495
6140
  });
4496
6141
  } else flatMap.set(path$2, descriptor);
4497
6142
  }
4498
- function walkStructure(doc, struct, prefix, parentOptional, flatMap, stack) {
6143
+ function walkStructure(doc, struct, prefix, parentOptional, flatMap, stack, options) {
4499
6144
  for (const [name, prop] of struct.props) {
4500
6145
  if (prop.token("identifier")?.pattern) continue;
4501
6146
  const propDef = prop.getDefinition();
4502
6147
  if (isPhantomNode(doc, propDef)) continue;
6148
+ if (options?.skipNavProps && hasNavPropAnnotation(prop)) continue;
4503
6149
  const path$2 = prefix ? `${prefix}.${name}` : name;
4504
6150
  const optional = parentOptional || !!prop.token("optional");
4505
6151
  const dbJson = hasDbJsonAnnotation(prop);
@@ -4532,10 +6178,10 @@ function walkStructure(doc, struct, prefix, parentOptional, flatMap, stack) {
4532
6178
  });
4533
6179
  continue;
4534
6180
  }
4535
- walkNode(resolved.doc, resolved.def, path$2, optional, prop, flatMap, stack);
6181
+ walkNode(resolved.doc, resolved.def, path$2, optional, prop, flatMap, stack, options);
4536
6182
  }
4537
6183
  }
4538
- function walkNode(doc, def, path$2, optional, propNode, flatMap, stack) {
6184
+ function walkNode(doc, def, path$2, optional, propNode, flatMap, stack, options) {
4539
6185
  if (stack.has(def)) {
4540
6186
  addToFlatMap(flatMap, path$2, {
4541
6187
  def,
@@ -4555,7 +6201,7 @@ function walkNode(doc, def, path$2, optional, propNode, flatMap, stack) {
4555
6201
  propNode,
4556
6202
  intermediate: true
4557
6203
  });
4558
- walkStructure(doc, def, path$2, optional, flatMap, stack);
6204
+ walkStructure(doc, def, path$2, optional, flatMap, stack, options);
4559
6205
  } else if (isArray(def)) {
4560
6206
  const elementDef = def.getDefinition();
4561
6207
  const resolvedElement = elementDef ? resolveNode(doc, elementDef) : undefined;
@@ -4568,7 +6214,7 @@ function walkNode(doc, def, path$2, optional, propNode, flatMap, stack) {
4568
6214
  propNode,
4569
6215
  intermediate: true
4570
6216
  });
4571
- walkArrayElement(doc, def, path$2, optional, flatMap, stack);
6217
+ walkArrayElement(doc, def, path$2, optional, flatMap, stack, options);
4572
6218
  } else addToFlatMap(flatMap, path$2, {
4573
6219
  def,
4574
6220
  doc,
@@ -4587,7 +6233,7 @@ function walkNode(doc, def, path$2, optional, propNode, flatMap, stack) {
4587
6233
  propNode,
4588
6234
  intermediate: true
4589
6235
  });
4590
- walkStructure(doc, merged, path$2, optional, flatMap, stack);
6236
+ walkStructure(doc, merged, path$2, optional, flatMap, stack, options);
4591
6237
  } else addToFlatMap(flatMap, path$2, {
4592
6238
  def,
4593
6239
  doc,
@@ -4619,7 +6265,7 @@ else addToFlatMap(flatMap, path$2, {
4619
6265
  });
4620
6266
  for (const branch of branches) {
4621
6267
  const resolved = resolveNode(doc, branch);
4622
- if (resolved) walkBranch(resolved.doc, resolved.def, path$2, optional, flatMap, stack);
6268
+ if (resolved) walkBranch(resolved.doc, resolved.def, path$2, optional, flatMap, stack, options);
4623
6269
  }
4624
6270
  } else addToFlatMap(flatMap, path$2, {
4625
6271
  def,
@@ -4643,30 +6289,30 @@ else addToFlatMap(flatMap, path$2, {
4643
6289
  stack.delete(def);
4644
6290
  }
4645
6291
  }
4646
- function walkArrayElement(doc, arrayNode, prefix, parentOptional, flatMap, stack) {
6292
+ function walkArrayElement(doc, arrayNode, prefix, parentOptional, flatMap, stack, options) {
4647
6293
  const elementDef = arrayNode.getDefinition();
4648
6294
  if (!elementDef) return;
4649
6295
  const resolved = resolveNode(doc, elementDef);
4650
6296
  if (!resolved) return;
4651
- walkBranch(resolved.doc, resolved.def, prefix, parentOptional, flatMap, stack);
6297
+ walkBranch(resolved.doc, resolved.def, prefix, parentOptional, flatMap, stack, options);
4652
6298
  }
4653
6299
  /**
4654
6300
  * Walks a branch (union branch or array element) to collect sub-paths.
4655
6301
  * Does NOT add an entry for the branch itself — the parent already did that.
4656
- */ function walkBranch(doc, def, prefix, parentOptional, flatMap, stack) {
4657
- if (isStructure(def)) walkStructure(doc, def, prefix, parentOptional, flatMap, stack);
4658
- else if (isArray(def)) walkArrayElement(doc, def, prefix, parentOptional, flatMap, stack);
6302
+ */ function walkBranch(doc, def, prefix, parentOptional, flatMap, stack, options) {
6303
+ if (isStructure(def)) walkStructure(doc, def, prefix, parentOptional, flatMap, stack, options);
6304
+ else if (isArray(def)) walkArrayElement(doc, def, prefix, parentOptional, flatMap, stack, options);
4659
6305
  else if (isGroup(def) && def.entity !== "structure") {
4660
6306
  const group$1 = def;
4661
6307
  if (group$1.op === "&") {
4662
6308
  const merged = doc.mergeIntersection(def);
4663
- if (isStructure(merged)) walkStructure(doc, merged, prefix, parentOptional, flatMap, stack);
6309
+ if (isStructure(merged)) walkStructure(doc, merged, prefix, parentOptional, flatMap, stack, options);
4664
6310
  } else if (group$1.op === "|") for (const branch of group$1.unwrap()) {
4665
6311
  const resolved = resolveNode(doc, branch);
4666
- if (resolved) walkBranch(resolved.doc, resolved.def, prefix, parentOptional, flatMap, stack);
6312
+ if (resolved) walkBranch(resolved.doc, resolved.def, prefix, parentOptional, flatMap, stack, options);
4667
6313
  }
4668
6314
  }
4669
6315
  }
4670
6316
 
4671
6317
  //#endregion
4672
- export { $n, AnnotationSpec, AtscriptDoc, AtscriptRepo, BuildRepo, DEFAULT_FORMAT, PluginManager, SemanticAnnotateNode, SemanticArrayNode, SemanticConstNode, SemanticGroup, SemanticImportNode, SemanticInterfaceNode, SemanticNode, SemanticPrimitiveNode, SemanticPropNode, SemanticRefNode, SemanticStructureNode, SemanticTupleNode, SemanticTypeNode, Token, build, createAtscriptPlugin, defineConfig, flattenInterfaceNode, getRelPath, isAnnotate, isAnnotationSpec, isArray, isConst, isGroup, isImport, isInterface, isPhantomNode, isPrimitive, isProp, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, resolveAnnotation, resolveAtscriptFromPath, resolveConfigFile };
6318
+ export { $n, AnnotationSpec, AtscriptDoc, AtscriptRepo, BuildRepo, DEFAULT_FORMAT, PluginManager, SemanticAnnotateNode, SemanticArrayNode, SemanticConstNode, SemanticGroup, SemanticImportNode, SemanticInterfaceNode, SemanticNode, SemanticPrimitiveNode, SemanticPropNode, SemanticQueryComparisonNode, SemanticQueryFieldRefNode, SemanticQueryLogicalNode, SemanticQueryNode, SemanticQueryValueListNode, SemanticQueryValueNode, SemanticRefNode, SemanticStructureNode, SemanticTupleNode, SemanticTypeNode, Token, analyzeQueryCursorContext, build, createAtscriptPlugin, defineConfig, findFKFieldsPointingTo, flattenInterfaceNode, getFieldsForType, getQueryCompletionScope, getQueryScope, getRelPath, hasNavPropAnnotation, isAnnotate, isAnnotationSpec, isArray, isConst, isGroup, isImport, isInterface, isPhantomNode, isPrimitive, isProp, isQueryComparison, isQueryFieldRef, isQueryLogical, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, resolveAnnotation, resolveAtscriptFromPath, resolveConfigFile, resolveQueryFieldRef, validateRefArgument };