@atscript/core 0.1.32 → 0.1.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -99,6 +99,7 @@ else this.annotationsCounter.set(name, 1);
99
99
  }
100
100
  define(node) {
101
101
  this.definition = node;
102
+ node.ownerNode = this;
102
103
  return this;
103
104
  }
104
105
  get def() {
@@ -152,6 +153,7 @@ else this.annotationsCounter.set(name, 1);
152
153
  _define_property$15(this, "annotations", void 0);
153
154
  _define_property$15(this, "annotationsCounter", void 0);
154
155
  _define_property$15(this, "__typeId", void 0);
156
+ _define_property$15(this, "ownerNode", void 0);
155
157
  _define_property$15(this, "_documentation", void 0);
156
158
  this.entity = entity;
157
159
  this.isGroup = false;
@@ -695,10 +697,12 @@ var SemanticStructureNode = class extends SemanticGroup {
695
697
  * Shortcut to set props, used as utility
696
698
  */ setProps(props$1) {
697
699
  this.nodes = props$1;
698
- for (const prop of props$1) this.props.set(prop.id, prop);
700
+ for (const prop of props$1) {
701
+ prop.ownerNode = this;
702
+ this.props.set(prop.id, prop);
703
+ }
699
704
  }
700
705
  registerAtDocument(doc) {
701
- super.registerAtDocument(doc);
702
706
  const block$2 = this.token("identifier");
703
707
  block$2.blockType = "structure";
704
708
  doc.blocksIndex.add(block$2);
@@ -721,8 +725,10 @@ var SemanticStructureNode = class extends SemanticGroup {
721
725
  doc.registerMessage(token, "Non-prop node");
722
726
  continue;
723
727
  }
728
+ node.ownerNode = this;
724
729
  this.props.set(name, node);
725
730
  }
731
+ super.registerAtDocument(doc);
726
732
  }
727
733
  addVirtualProp(opts) {
728
734
  const token = opts.refToken || this.token("identifier");
@@ -750,6 +756,7 @@ var SemanticStructureNode = class extends SemanticGroup {
750
756
  }
751
757
  prop.define(ref$1);
752
758
  } else prop.define(opts.type);
759
+ prop.ownerNode = this;
753
760
  this.nodes.push(prop);
754
761
  this.props.set(opts.name, prop);
755
762
  }
@@ -2735,14 +2742,14 @@ else {
2735
2742
  this.blocksIndex.add(block$2);
2736
2743
  block$2.blockType = "import";
2737
2744
  block$2.fromPath = from.text;
2745
+ this.tokensIndex.add(from);
2746
+ from.fromPath = from.text;
2738
2747
  imports.forEach((t) => {
2739
2748
  t.imported = true;
2740
2749
  t.fromPath = from.text;
2741
2750
  this.registerDefinition(t, true);
2742
2751
  this.tokensIndex.add(t);
2743
- this.tokensIndex.add(from);
2744
2752
  this.importedDefs.set(t.text, from);
2745
- from.fromPath = from.text;
2746
2753
  });
2747
2754
  }
2748
2755
  nextTypeId() {
@@ -2811,7 +2818,7 @@ else {
2811
2818
  getUnusedTokens() {
2812
2819
  const refSet = new Set(this.referred.filter((r) => !r.imported).map((r) => r.text));
2813
2820
  const tokens$1 = [];
2814
- for (const [key, token] of Array.from(this.registry.definitions.entries())) if (!refSet.has(key) && !this.exports.has(key)) tokens$1.push(token);
2821
+ for (const [key, token] of this.registry.definitions) if (!refSet.has(key) && !this.exports.has(key)) tokens$1.push(token);
2815
2822
  return tokens$1;
2816
2823
  }
2817
2824
  renderDiagMessage(m, addSourceLinses = false, colors = false) {
@@ -2865,7 +2872,7 @@ else {
2865
2872
  l: lines[n - 1],
2866
2873
  i: n - 1
2867
2874
  }
2868
- ].filter(Boolean);
2875
+ ].filter((r) => r.l !== undefined);
2869
2876
  const nl = String(n).length + 1;
2870
2877
  for (const { l, i } of renderLines) {
2871
2878
  const prefix = `${c.dim + c.cyan}${`0${i}`.slice(-nl)} | ${c.reset}`;
@@ -3062,13 +3069,7 @@ else {
3062
3069
  if (!left || !right) return [_left, _right];
3063
3070
  if (isPrimitive(left) && isPrimitive(right)) {
3064
3071
  if (left.config.type === right.config.type) return [left];
3065
- const never$1 = new SemanticRefNode();
3066
- never$1.saveToken(new Token({
3067
- text: "never",
3068
- type: "identifier",
3069
- getRange: () => zeroRange
3070
- }), "identifier");
3071
- return [never$1];
3072
+ return [createSyntheticRef("never")];
3072
3073
  }
3073
3074
  if ((isStructure(left) || isInterface(left)) && (isStructure(right) || isInterface(right))) {
3074
3075
  const mergedProps = [];
@@ -3086,15 +3087,7 @@ else {
3086
3087
  }
3087
3088
  const prop = new SemanticPropNode();
3088
3089
  prop.saveToken((leftProp || rightProp).token("identifier"), "identifier");
3089
- if (isPrimitive(mergedDef)) {
3090
- const name = mergedDef.id;
3091
- mergedDef = new SemanticRefNode();
3092
- mergedDef.saveToken(new Token({
3093
- text: name,
3094
- type: "identifier",
3095
- getRange: () => zeroRange
3096
- }), "identifier");
3097
- }
3090
+ if (isPrimitive(mergedDef)) mergedDef = createSyntheticRef(mergedDef.id);
3098
3091
  prop.define(mergedDef);
3099
3092
  prop.annotations = this.mergeNodesAnnotations(leftProp?.annotations, rightProp?.annotations);
3100
3093
  const oldProps = [leftProp, rightProp].filter(Boolean);
@@ -3108,17 +3101,10 @@ else {
3108
3101
  }
3109
3102
  const mergedStructure = new SemanticStructureNode();
3110
3103
  mergedStructure.setProps(mergedProps);
3111
- this.resolveAnnotation;
3112
3104
  mergedStructure.annotations = this.mergeNodesAnnotations(left.annotations, right.annotations);
3113
3105
  return [mergedStructure];
3114
3106
  }
3115
- const never = new SemanticRefNode();
3116
- never.saveToken(new Token({
3117
- text: "never",
3118
- type: "identifier",
3119
- getRange: () => zeroRange
3120
- }), "identifier");
3121
- return [never];
3107
+ return [createSyntheticRef("never")];
3122
3108
  }
3123
3109
  /**
3124
3110
  * Merges two arrays of annotation tokens, ensuring that annotations from the
@@ -3218,9 +3204,159 @@ const zeroRange = {
3218
3204
  character: 0
3219
3205
  }
3220
3206
  };
3207
+ function createSyntheticRef(name) {
3208
+ const ref$1 = new SemanticRefNode();
3209
+ ref$1.saveToken(new Token({
3210
+ text: name,
3211
+ type: "identifier",
3212
+ getRange: () => zeroRange
3213
+ }), "identifier");
3214
+ return ref$1;
3215
+ }
3216
+
3217
+ //#endregion
3218
+ //#region packages/core/src/defaults/db-utils.ts
3219
+ function findFKFieldsPointingTo(doc, iface, targetTypeName, alias) {
3220
+ const results = [];
3221
+ let struct;
3222
+ if (isInterface(iface) && iface.hasExtends) {
3223
+ const resolved = doc.resolveInterfaceExtends(iface);
3224
+ if (resolved && isStructure(resolved)) struct = resolved;
3225
+ }
3226
+ if (!struct) struct = isStructure(iface) ? iface : isInterface(iface) && isStructure(iface.getDefinition()) ? iface.getDefinition() : undefined;
3227
+ if (!struct) return results;
3228
+ for (const [name, prop] of struct.props) {
3229
+ if (prop.countAnnotations("db.rel.FK") === 0) continue;
3230
+ const def = prop.getDefinition();
3231
+ if (!def || !isRef(def)) continue;
3232
+ const ref$1 = def;
3233
+ if (!ref$1.hasChain) continue;
3234
+ const refTypeName = ref$1.id;
3235
+ const refField = ref$1.chain.map((c) => c.text).join(".");
3236
+ if (refTypeName !== targetTypeName) continue;
3237
+ if (alias !== undefined) {
3238
+ const fkAnnotations = prop.annotations?.filter((a) => a.name === "db.rel.FK");
3239
+ const hasMatchingAlias = fkAnnotations?.some((a) => a.args.length > 0 && a.args[0].text === alias);
3240
+ if (!hasMatchingAlias) continue;
3241
+ }
3242
+ results.push({
3243
+ name,
3244
+ prop,
3245
+ chainRef: {
3246
+ type: refTypeName,
3247
+ field: refField
3248
+ }
3249
+ });
3250
+ }
3251
+ return results;
3252
+ }
3221
3253
 
3222
3254
  //#endregion
3223
3255
  //#region packages/core/src/defaults/db-annotations.ts
3256
+ /**
3257
+ * Traverse from annotation token → prop → structure → interface
3258
+ * to check if the parent interface has @db.table.
3259
+ */ function getDbTableOwner(token) {
3260
+ const field = token.parentNode;
3261
+ const struct = field.ownerNode;
3262
+ if (!struct || !isStructure(struct)) return undefined;
3263
+ const iface = struct.ownerNode;
3264
+ return iface && isInterface(iface) ? iface : struct;
3265
+ }
3266
+ /**
3267
+ * Get the parent structure node from an annotation token.
3268
+ */ function getParentStruct(token) {
3269
+ const field = token.parentNode;
3270
+ const struct = field.ownerNode;
3271
+ return struct && isStructure(struct) ? struct : undefined;
3272
+ }
3273
+ /**
3274
+ * Get the parent interface name (for error messages and cross-type resolution).
3275
+ */ function getParentTypeName(token) {
3276
+ const struct = getParentStruct(token);
3277
+ if (!struct) return undefined;
3278
+ const iface = struct.ownerNode;
3279
+ return iface && isInterface(iface) ? iface.id : struct.id;
3280
+ }
3281
+ /**
3282
+ * Extract target type name from a navigational field definition.
3283
+ * Unwraps arrays (e.g., `Post[]` → `Post`).
3284
+ */ function getNavTargetTypeName(field) {
3285
+ let def = field.getDefinition();
3286
+ if (isArray(def)) def = def?.getDefinition();
3287
+ if (isRef(def)) return def.id;
3288
+ return undefined;
3289
+ }
3290
+ /**
3291
+ * Get the alias argument from an annotation on a field.
3292
+ */ function getAnnotationAlias(prop, annotationName) {
3293
+ const annotations$1 = prop.annotations?.filter((a) => a.name === annotationName);
3294
+ if (!annotations$1 || annotations$1.length === 0) return undefined;
3295
+ return annotations$1[0].args.length > 0 ? annotations$1[0].args[0].text : undefined;
3296
+ }
3297
+ /**
3298
+ * Factory for @db.rel.onDelete / @db.rel.onUpdate — identical validation logic,
3299
+ * only the annotation name and description verb differ.
3300
+ */ function refActionAnnotation(name) {
3301
+ return new AnnotationSpec({
3302
+ 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",
3303
+ nodeType: ["prop"],
3304
+ argument: {
3305
+ name: "action",
3306
+ type: "string",
3307
+ values: [
3308
+ "cascade",
3309
+ "restrict",
3310
+ "noAction",
3311
+ "setNull",
3312
+ "setDefault"
3313
+ ],
3314
+ description: "Referential action: \"cascade\", \"restrict\", \"noAction\", \"setNull\", or \"setDefault\"."
3315
+ },
3316
+ validate(token, args, doc) {
3317
+ const errors = [];
3318
+ const field = token.parentNode;
3319
+ if (field.countAnnotations("db.rel.FK") === 0) errors.push({
3320
+ message: `@db.rel.${name} is only valid on @db.rel.FK fields`,
3321
+ severity: 1,
3322
+ range: token.range
3323
+ });
3324
+ if (args[0]) {
3325
+ const action = args[0].text;
3326
+ if (action === "setNull" && !field.has("optional")) errors.push({
3327
+ message: `@db.rel.${name} "setNull" requires the FK field to be optional (?)`,
3328
+ severity: 1,
3329
+ range: token.range
3330
+ });
3331
+ if (action === "setDefault" && field.countAnnotations("db.default.value") === 0 && field.countAnnotations("db.default.fn") === 0) errors.push({
3332
+ message: `@db.rel.${name} "setDefault" but no @db.default.* annotation — field will have no fallback value`,
3333
+ severity: 2,
3334
+ range: token.range
3335
+ });
3336
+ }
3337
+ const fkAlias = getAnnotationAlias(field, "db.rel.FK");
3338
+ if (fkAlias) {
3339
+ const struct = getParentStruct(token);
3340
+ if (struct) {
3341
+ const annotationName = `db.rel.${name}`;
3342
+ let count = 0;
3343
+ for (const [, prop] of struct.props) {
3344
+ if (prop.countAnnotations("db.rel.FK") === 0) continue;
3345
+ if (prop.countAnnotations(annotationName) === 0) continue;
3346
+ const propFkAlias = getAnnotationAlias(prop, "db.rel.FK");
3347
+ if (propFkAlias === fkAlias) count++;
3348
+ }
3349
+ if (count > 1) errors.push({
3350
+ message: `Composite FK '${fkAlias}' has @db.rel.${name} on multiple fields — declare it on exactly one`,
3351
+ severity: 1,
3352
+ range: token.range
3353
+ });
3354
+ }
3355
+ }
3356
+ return errors;
3357
+ }
3358
+ });
3359
+ }
3224
3360
  const dbAnnotations = {
3225
3361
  patch: { strategy: new AnnotationSpec({
3226
3362
  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",
@@ -3423,7 +3559,277 @@ else if (fnName === "now" && !["number", "string"].includes(baseType)) errors.pu
3423
3559
  });
3424
3560
  return errors;
3425
3561
  }
3426
- })
3562
+ }),
3563
+ rel: {
3564
+ FK: new AnnotationSpec({
3565
+ 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",
3566
+ nodeType: ["prop"],
3567
+ argument: {
3568
+ optional: true,
3569
+ name: "alias",
3570
+ type: "string",
3571
+ description: "Alias for pairing with @db.rel.to. Required when multiple FKs point to the same target type."
3572
+ },
3573
+ validate(token, args, doc) {
3574
+ const errors = [];
3575
+ const field = token.parentNode;
3576
+ const alias = args[0]?.text;
3577
+ const owner = getDbTableOwner(token);
3578
+ if (!owner || owner.countAnnotations("db.table") === 0) errors.push({
3579
+ message: "@db.rel.FK is only valid on fields of a @db.table interface",
3580
+ severity: 1,
3581
+ range: token.range
3582
+ });
3583
+ if (field.countAnnotations("db.rel.to") > 0 || field.countAnnotations("db.rel.from") > 0) errors.push({
3584
+ message: "A field cannot be both a foreign key and a navigational property",
3585
+ severity: 1,
3586
+ range: token.range
3587
+ });
3588
+ const definition$1 = field.getDefinition();
3589
+ if (!definition$1 || !isRef(definition$1) || !definition$1.hasChain) {
3590
+ errors.push({
3591
+ message: `@db.rel.FK requires a chain reference type (e.g. User.id), got scalar type`,
3592
+ severity: 1,
3593
+ range: token.range
3594
+ });
3595
+ return errors;
3596
+ }
3597
+ const ref$1 = definition$1;
3598
+ const refTypeName = ref$1.id;
3599
+ const chainFields = ref$1.chain.map((c) => c.text);
3600
+ const targetUnwound = doc.unwindType(refTypeName);
3601
+ if (targetUnwound) {
3602
+ const targetDef = targetUnwound.def;
3603
+ if (isInterface(targetDef) || isStructure(targetDef)) {
3604
+ const struct = isInterface(targetDef) ? targetDef.getDefinition() : targetDef;
3605
+ if (struct && isStructure(struct) && chainFields.length > 0) {
3606
+ const targetProp = struct.props.get(chainFields[0]);
3607
+ if (targetProp) {
3608
+ if (targetProp.countAnnotations("meta.id") === 0 && targetProp.countAnnotations("db.index.unique") === 0) errors.push({
3609
+ message: `@db.rel.FK target '${refTypeName}.${chainFields.join(".")}' is not a primary key (@meta.id) or unique (@db.index.unique) field`,
3610
+ severity: 1,
3611
+ range: token.range
3612
+ });
3613
+ const propDef = targetProp.getDefinition();
3614
+ if (propDef && isRef(propDef)) {
3615
+ const propUnwound = targetUnwound.doc.unwindType(propDef.id, propDef.chain);
3616
+ if (propUnwound && !isPrimitive(propUnwound.def)) errors.push({
3617
+ message: `Foreign key field must resolve to a scalar type (number, string, etc.), got '${propDef.id}'`,
3618
+ severity: 1,
3619
+ range: token.range
3620
+ });
3621
+ } else if (propDef && !isPrimitive(propDef)) errors.push({
3622
+ message: `Foreign key field must resolve to a scalar type (number, string, etc.)`,
3623
+ severity: 1,
3624
+ range: token.range
3625
+ });
3626
+ }
3627
+ }
3628
+ }
3629
+ }
3630
+ if (!alias) {
3631
+ const struct = getParentStruct(token);
3632
+ if (struct) {
3633
+ let sameTargetCount = 0;
3634
+ for (const [, prop] of struct.props) {
3635
+ if (prop.countAnnotations("db.rel.FK") === 0) continue;
3636
+ const def = prop.getDefinition();
3637
+ if (!def || !isRef(def)) continue;
3638
+ const r = def;
3639
+ if (!r.hasChain) continue;
3640
+ if (r.id === refTypeName) {
3641
+ const fkAnnotations = prop.annotations?.filter((a) => a.name === "db.rel.FK");
3642
+ const hasAlias = fkAnnotations?.some((a) => a.args.length > 0);
3643
+ if (!hasAlias) sameTargetCount++;
3644
+ }
3645
+ }
3646
+ if (sameTargetCount > 1) errors.push({
3647
+ message: `Multiple @db.rel.FK fields resolve to type '${refTypeName}' — add alias to disambiguate`,
3648
+ severity: 1,
3649
+ range: token.range
3650
+ });
3651
+ }
3652
+ }
3653
+ return errors;
3654
+ }
3655
+ }),
3656
+ to: new AnnotationSpec({
3657
+ 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",
3658
+ nodeType: ["prop"],
3659
+ argument: {
3660
+ optional: true,
3661
+ name: "alias",
3662
+ type: "string",
3663
+ description: "Match a local @db.rel.FK by alias."
3664
+ },
3665
+ validate(token, args, doc) {
3666
+ const errors = [];
3667
+ const field = token.parentNode;
3668
+ const alias = args[0]?.text;
3669
+ const owner = getDbTableOwner(token);
3670
+ if (!owner || owner.countAnnotations("db.table") === 0) errors.push({
3671
+ message: "@db.rel.to is only valid on fields of a @db.table interface",
3672
+ severity: 1,
3673
+ range: token.range
3674
+ });
3675
+ if (field.countAnnotations("db.rel.FK") > 0) errors.push({
3676
+ message: "A field cannot be both a foreign key and a navigational property",
3677
+ severity: 1,
3678
+ range: token.range
3679
+ });
3680
+ const targetTypeName = getNavTargetTypeName(field);
3681
+ if (!targetTypeName) return errors;
3682
+ const unwound = doc.unwindType(targetTypeName);
3683
+ if (unwound) {
3684
+ const targetDef = unwound.def;
3685
+ const targetNode = isInterface(targetDef) ? targetDef : undefined;
3686
+ if (!targetNode || targetNode.countAnnotations("db.table") === 0) errors.push({
3687
+ message: `@db.rel.to target '${targetTypeName}' is not a @db.table entity`,
3688
+ severity: 1,
3689
+ range: token.range
3690
+ });
3691
+ }
3692
+ const fieldDef = field.getDefinition();
3693
+ if (fieldDef && fieldDef.entity === "group" && fieldDef.op === "|") errors.push({
3694
+ message: "@db.rel.to does not support union types — use separate relations",
3695
+ severity: 1,
3696
+ range: token.range
3697
+ });
3698
+ const struct = getParentStruct(token);
3699
+ if (struct) {
3700
+ const fieldName = field.id;
3701
+ for (const [name, prop] of struct.props) {
3702
+ if (name === fieldName) continue;
3703
+ if (prop.countAnnotations("db.rel.to") === 0) continue;
3704
+ const propAlias = getAnnotationAlias(prop, "db.rel.to");
3705
+ if ((alias || undefined) === (propAlias || undefined)) {
3706
+ const otherTarget = getNavTargetTypeName(prop);
3707
+ if (otherTarget === targetTypeName) {
3708
+ errors.push({
3709
+ message: `Duplicate @db.rel.to '${alias || targetTypeName}' — only one forward navigational property per alias`,
3710
+ severity: 1,
3711
+ range: token.range
3712
+ });
3713
+ break;
3714
+ }
3715
+ }
3716
+ }
3717
+ if (alias) {
3718
+ const matches = findFKFieldsPointingTo(doc, struct, targetTypeName, alias);
3719
+ if (matches.length === 0) errors.push({
3720
+ message: `No @db.rel.FK '${alias}' found on this interface`,
3721
+ severity: 1,
3722
+ range: token.range
3723
+ });
3724
+ } else {
3725
+ const matches = findFKFieldsPointingTo(doc, struct, targetTypeName);
3726
+ if (matches.length === 0) errors.push({
3727
+ message: `No @db.rel.FK on this interface points to '${targetTypeName}' — did you mean @db.rel.from?`,
3728
+ severity: 1,
3729
+ range: token.range
3730
+ });
3731
+ else if (matches.length > 1) errors.push({
3732
+ message: `Multiple @db.rel.FK fields point to '${targetTypeName}' — add alias to disambiguate`,
3733
+ severity: 1,
3734
+ range: token.range
3735
+ });
3736
+ }
3737
+ }
3738
+ return errors;
3739
+ }
3740
+ }),
3741
+ from: new AnnotationSpec({
3742
+ 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",
3743
+ nodeType: ["prop"],
3744
+ argument: {
3745
+ optional: true,
3746
+ name: "alias",
3747
+ type: "string",
3748
+ description: "Match a @db.rel.FK on the target interface by alias."
3749
+ },
3750
+ validate(token, args, doc) {
3751
+ const errors = [];
3752
+ const field = token.parentNode;
3753
+ const alias = args[0]?.text;
3754
+ const owner = getDbTableOwner(token);
3755
+ if (!owner || owner.countAnnotations("db.table") === 0) errors.push({
3756
+ message: "@db.rel.from is only valid on fields of a @db.table interface",
3757
+ severity: 1,
3758
+ range: token.range
3759
+ });
3760
+ if (field.countAnnotations("db.rel.FK") > 0) errors.push({
3761
+ message: "A field cannot be both a foreign key and a navigational property",
3762
+ severity: 1,
3763
+ range: token.range
3764
+ });
3765
+ const targetTypeName = getNavTargetTypeName(field);
3766
+ if (!targetTypeName) return errors;
3767
+ const unwound = doc.unwindType(targetTypeName);
3768
+ if (!unwound) return errors;
3769
+ const targetDef = unwound.def;
3770
+ const targetDoc = unwound.doc;
3771
+ if (!isInterface(targetDef) || targetDef.countAnnotations("db.table") === 0) {
3772
+ errors.push({
3773
+ message: `@db.rel.from target '${targetTypeName}' is not a @db.table entity`,
3774
+ severity: 1,
3775
+ range: token.range
3776
+ });
3777
+ return errors;
3778
+ }
3779
+ const struct = getParentStruct(token);
3780
+ if (struct) {
3781
+ const fieldName = field.id;
3782
+ for (const [name, prop] of struct.props) {
3783
+ if (name === fieldName) continue;
3784
+ if (prop.countAnnotations("db.rel.from") === 0) continue;
3785
+ const propAlias = getAnnotationAlias(prop, "db.rel.from");
3786
+ if ((alias || undefined) === (propAlias || undefined)) {
3787
+ const otherTarget = getNavTargetTypeName(prop);
3788
+ if (otherTarget === targetTypeName) {
3789
+ errors.push({
3790
+ message: `Duplicate @db.rel.from '${alias || targetTypeName}' — only one inverse navigational property per alias`,
3791
+ severity: 1,
3792
+ range: token.range
3793
+ });
3794
+ break;
3795
+ }
3796
+ }
3797
+ }
3798
+ }
3799
+ const thisTypeName = getParentTypeName(token);
3800
+ if (!thisTypeName) return errors;
3801
+ const matches = findFKFieldsPointingTo(targetDoc, targetDef, thisTypeName, alias);
3802
+ if (alias) {
3803
+ if (matches.length === 0) errors.push({
3804
+ message: `No @db.rel.FK '${alias}' found on '${targetTypeName}'`,
3805
+ severity: 1,
3806
+ range: token.range
3807
+ });
3808
+ } else if (matches.length === 0) errors.push({
3809
+ message: `No @db.rel.FK on '${targetTypeName}' points to '${thisTypeName}'`,
3810
+ severity: 1,
3811
+ range: token.range
3812
+ });
3813
+ else if (matches.length > 1) errors.push({
3814
+ message: `'${targetTypeName}' has multiple @db.rel.FK fields pointing to '${thisTypeName}' — add alias`,
3815
+ severity: 1,
3816
+ range: token.range
3817
+ });
3818
+ const fieldDef = field.getDefinition();
3819
+ if (!isArray(fieldDef) && matches.length === 1) {
3820
+ const fkProp = matches[0].prop;
3821
+ if (fkProp.countAnnotations("db.index.unique") === 0) errors.push({
3822
+ 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)?`,
3823
+ severity: 2,
3824
+ range: token.range
3825
+ });
3826
+ }
3827
+ return errors;
3828
+ }
3829
+ }),
3830
+ onDelete: refActionAnnotation("onDelete"),
3831
+ onUpdate: refActionAnnotation("onUpdate")
3832
+ }
3427
3833
  };
3428
3834
 
3429
3835
  //#endregion
@@ -4064,31 +4470,22 @@ var PluginManager = class {
4064
4470
  const raw = await this.config();
4065
4471
  this._docConfig = {};
4066
4472
  if (raw?.primitives) {
4067
- this._docConfig.primitives = this._docConfig.primitives || new Map();
4473
+ this._docConfig.primitives = new Map();
4068
4474
  for (const [key, value] of Object.entries(raw.primitives)) this._docConfig.primitives.set(key, new SemanticPrimitiveNode(key, value, "", raw.annotations));
4069
4475
  }
4070
- if (raw?.annotations) {
4071
- this._docConfig.annotations = this._docConfig.annotations || {};
4072
- Object.assign(this._docConfig.annotations, raw.annotations);
4073
- }
4476
+ if (raw?.annotations) this._docConfig.annotations = { ...raw.annotations };
4074
4477
  this._docConfig.unknownAnnotation = raw?.unknownAnnotation;
4075
4478
  }
4076
4479
  return this._docConfig;
4077
4480
  }
4078
4481
  async config(config = this.cfg) {
4079
4482
  if (!this._config) {
4080
- const processed = new Set();
4081
4483
  config = (0, defu.defu)(config, getDefaultAtscriptConfig());
4082
- const filtered = this.plugins.filter((plugin) => !processed.has(plugin.name));
4083
- let i = 0;
4084
- while (processed.size !== filtered.length) {
4085
- i++;
4086
- for (const plugin of filtered) {
4087
- if (processed.has(plugin.name)) continue;
4088
- config = (0, defu.defu)(await plugin.config?.(config), config);
4089
- processed.add(plugin.name);
4090
- }
4091
- if (i > 100) throw new Error(`Too many iterations in config`);
4484
+ const seen = new Set();
4485
+ for (const plugin of this.plugins) {
4486
+ if (seen.has(plugin.name)) continue;
4487
+ seen.add(plugin.name);
4488
+ config = (0, defu.defu)(await plugin.config?.(config), config);
4092
4489
  }
4093
4490
  this._config = config;
4094
4491
  }
@@ -4096,28 +4493,28 @@ var PluginManager = class {
4096
4493
  }
4097
4494
  async resolve(id) {
4098
4495
  let newId = id;
4099
- for (const plugin of this.plugins) if (plugin.resolve) newId = await plugin.resolve(id);
4496
+ for (const plugin of this.plugins) if (plugin.resolve) newId = await plugin.resolve(newId) ?? newId;
4100
4497
  return newId;
4101
4498
  }
4102
4499
  async load(id) {
4103
4500
  const filePath = id.startsWith("file://") ? id.slice(7) : id;
4104
4501
  for (const plugin of this.plugins) if (plugin.load) {
4105
- const content$1 = await plugin.load(id);
4106
- if (content$1) return content$1;
4502
+ const content = await plugin.load(id);
4503
+ if (content) return content;
4107
4504
  }
4108
- const content = await (0, node_fs_promises.readFile)(filePath, "utf8");
4109
- return content.toString();
4505
+ return (0, node_fs_promises.readFile)(filePath, "utf8");
4110
4506
  }
4111
4507
  async onDocument(doc) {
4112
4508
  for (const plugin of this.plugins) if (plugin.onDocument) await plugin.onDocument(doc);
4113
4509
  }
4114
4510
  async render(doc, format) {
4511
+ const source = doc.id.startsWith("file://") ? doc.id.slice(7) : doc.id;
4115
4512
  const files = [];
4116
4513
  for (const plugin of this.plugins) if (plugin.render) {
4117
4514
  const newFiles = await plugin.render(doc, format);
4118
4515
  if (newFiles?.length > 0) files.push(...newFiles.map((f) => ({
4119
4516
  ...f,
4120
- source: doc.id.startsWith("file://") ? doc.id.slice(7) : doc.id
4517
+ source
4121
4518
  })));
4122
4519
  }
4123
4520
  return files;
@@ -4251,17 +4648,16 @@ else types.push({ type: "boolean" });
4251
4648
  }
4252
4649
  const configFile = await resolveConfigFile(id, this.root);
4253
4650
  if (configFile) {
4254
- const globalPathToConfig = configFile;
4255
- if (!this.configFiles.has(globalPathToConfig)) {
4651
+ if (!this.configFiles.has(configFile)) {
4256
4652
  const rawConfigPromise = loadConfig(configFile, this.configFormat);
4257
- this.configFiles.set(globalPathToConfig, rawConfigPromise);
4653
+ this.configFiles.set(configFile, rawConfigPromise);
4258
4654
  }
4259
- const rawConfig = await this.configFiles.get(globalPathToConfig);
4655
+ const rawConfig = await this.configFiles.get(configFile);
4260
4656
  if (!rawConfig.rootDir) rawConfig.rootDir = node_path.default.dirname(configFile);
4261
4657
  const manager = new PluginManager(rawConfig);
4262
4658
  await manager.getDocConfig();
4263
4659
  return {
4264
- file: globalPathToConfig,
4660
+ file: configFile,
4265
4661
  manager,
4266
4662
  dependants: new Set()
4267
4663
  };
@@ -4288,10 +4684,13 @@ else types.push({ type: "boolean" });
4288
4684
  async openDocument(id, text$2) {
4289
4685
  let atscript = this.atscripts.get(id);
4290
4686
  if (atscript) {
4291
- if (text$2) atscript.then((d) => {
4292
- d.update(text$2);
4293
- return d;
4294
- });
4687
+ if (text$2) {
4688
+ atscript = atscript.then((d) => {
4689
+ d.update(text$2);
4690
+ return d;
4691
+ });
4692
+ this.atscripts.set(id, atscript);
4693
+ }
4295
4694
  } else {
4296
4695
  atscript = this._openDocument(id, text$2);
4297
4696
  atscript.catch(() => {
@@ -4736,6 +5135,7 @@ exports.Token = Token
4736
5135
  exports.build = build
4737
5136
  exports.createAtscriptPlugin = createAtscriptPlugin
4738
5137
  exports.defineConfig = defineConfig
5138
+ exports.findFKFieldsPointingTo = findFKFieldsPointingTo
4739
5139
  exports.flattenInterfaceNode = flattenInterfaceNode
4740
5140
  exports.getRelPath = getRelPath
4741
5141
  exports.isAnnotate = isAnnotate