@zenstackhq/language 3.0.0-beta.9 → 3.0.0

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.js CHANGED
@@ -7,16 +7,19 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
7
7
  throw Error('Dynamic require of "' + x + '" is not supported');
8
8
  });
9
9
 
10
- // src/index.ts
11
- import { isAstNode, URI as URI3 } from "langium";
12
- import { NodeFileSystem } from "langium/node";
13
- import fs3 from "fs";
14
- import path3 from "path";
15
- import { fileURLToPath as fileURLToPath2 } from "url";
10
+ // src/document.ts
11
+ import { isAstNode, TextDocument, URI as URI4 } from "langium";
12
+ import fs4 from "fs";
13
+ import path4 from "path";
14
+ import { fileURLToPath as fileURLToPath4 } from "url";
16
15
 
17
16
  // src/generated/ast.ts
18
17
  import * as langium from "langium";
19
18
  var AbstractDeclaration = "AbstractDeclaration";
19
+ function isAbstractDeclaration(item) {
20
+ return reflection.isInstance(item, AbstractDeclaration);
21
+ }
22
+ __name(isAbstractDeclaration, "isAbstractDeclaration");
20
23
  var ConfigExpr = "ConfigExpr";
21
24
  var Expression = "Expression";
22
25
  function isExpression(item) {
@@ -43,6 +46,10 @@ function isAttribute(item) {
43
46
  }
44
47
  __name(isAttribute, "isAttribute");
45
48
  var AttributeArg = "AttributeArg";
49
+ function isAttributeArg(item) {
50
+ return reflection.isInstance(item, AttributeArg);
51
+ }
52
+ __name(isAttributeArg, "isAttributeArg");
46
53
  var AttributeParam = "AttributeParam";
47
54
  var AttributeParamType = "AttributeParamType";
48
55
  var BinaryExpr = "BinaryExpr";
@@ -61,6 +68,10 @@ function isConfigArrayExpr(item) {
61
68
  }
62
69
  __name(isConfigArrayExpr, "isConfigArrayExpr");
63
70
  var ConfigField = "ConfigField";
71
+ function isConfigField(item) {
72
+ return reflection.isInstance(item, ConfigField);
73
+ }
74
+ __name(isConfigField, "isConfigField");
64
75
  var ConfigInvocationArg = "ConfigInvocationArg";
65
76
  var ConfigInvocationExpr = "ConfigInvocationExpr";
66
77
  var DataField = "DataField";
@@ -105,10 +116,22 @@ function isEnumField(item) {
105
116
  __name(isEnumField, "isEnumField");
106
117
  var FieldInitializer = "FieldInitializer";
107
118
  var FunctionDecl = "FunctionDecl";
119
+ function isFunctionDecl(item) {
120
+ return reflection.isInstance(item, FunctionDecl);
121
+ }
122
+ __name(isFunctionDecl, "isFunctionDecl");
108
123
  var FunctionParam = "FunctionParam";
109
124
  var FunctionParamType = "FunctionParamType";
110
125
  var GeneratorDecl = "GeneratorDecl";
126
+ function isGeneratorDecl(item) {
127
+ return reflection.isInstance(item, GeneratorDecl);
128
+ }
129
+ __name(isGeneratorDecl, "isGeneratorDecl");
111
130
  var InternalAttribute = "InternalAttribute";
131
+ function isInternalAttribute(item) {
132
+ return reflection.isInstance(item, InternalAttribute);
133
+ }
134
+ __name(isInternalAttribute, "isInternalAttribute");
112
135
  var InvocationExpr = "InvocationExpr";
113
136
  function isInvocationExpr(item) {
114
137
  return reflection.isInstance(item, InvocationExpr);
@@ -125,6 +148,10 @@ function isModel(item) {
125
148
  }
126
149
  __name(isModel, "isModel");
127
150
  var ModelImport = "ModelImport";
151
+ function isModelImport(item) {
152
+ return reflection.isInstance(item, ModelImport);
153
+ }
154
+ __name(isModelImport, "isModelImport");
128
155
  var NullExpr = "NullExpr";
129
156
  function isNullExpr(item) {
130
157
  return reflection.isInstance(item, NullExpr);
@@ -146,6 +173,10 @@ function isPlugin(item) {
146
173
  }
147
174
  __name(isPlugin, "isPlugin");
148
175
  var PluginField = "PluginField";
176
+ function isPluginField(item) {
177
+ return reflection.isInstance(item, PluginField);
178
+ }
179
+ __name(isPluginField, "isPluginField");
149
180
  var Procedure = "Procedure";
150
181
  var ProcedureParam = "ProcedureParam";
151
182
  var ReferenceArg = "ReferenceArg";
@@ -1012,6 +1043,26 @@ var ZModelAstReflection = class extends langium.AbstractAstReflection {
1012
1043
  };
1013
1044
  var reflection = new ZModelAstReflection();
1014
1045
 
1046
+ // src/ast.ts
1047
+ var BinaryExprOperatorPriority = {
1048
+ //LogicalExpr
1049
+ "||": 1,
1050
+ "&&": 1,
1051
+ //EqualityExpr
1052
+ "==": 2,
1053
+ "!=": 2,
1054
+ //ComparisonExpr
1055
+ ">": 3,
1056
+ "<": 3,
1057
+ ">=": 3,
1058
+ "<=": 3,
1059
+ in: 4,
1060
+ //CollectionPredicateExpr
1061
+ "^": 5,
1062
+ "?": 5,
1063
+ "!": 5
1064
+ };
1065
+
1015
1066
  // src/constants.ts
1016
1067
  var SUPPORTED_PROVIDERS = [
1017
1068
  "sqlite",
@@ -1042,8 +1093,11 @@ var ExpressionContext = /* @__PURE__ */ function(ExpressionContext2) {
1042
1093
  }({});
1043
1094
 
1044
1095
  // src/module.ts
1045
- import { inject } from "langium";
1096
+ import { DocumentState as DocumentState2, inject, URI as URI3 } from "langium";
1046
1097
  import { createDefaultModule, createDefaultSharedModule } from "langium/lsp";
1098
+ import { NodeFileSystem } from "langium/node";
1099
+ import path3 from "path";
1100
+ import { fileURLToPath as fileURLToPath3 } from "url";
1047
1101
 
1048
1102
  // src/generated/grammar.ts
1049
1103
  import { loadGrammarFromJson } from "langium";
@@ -5104,14 +5158,12 @@ var ZModelGeneratedModule = {
5104
5158
  parser: {}
5105
5159
  };
5106
5160
 
5107
- // src/validators/attribute-application-validator.ts
5108
- import { AstUtils as AstUtils2 } from "langium";
5109
- import pluralize from "pluralize";
5110
-
5111
5161
  // src/utils.ts
5112
5162
  import { AstUtils, URI } from "langium";
5113
5163
  import fs from "fs";
5164
+ import { createRequire } from "module";
5114
5165
  import path from "path";
5166
+ import { fileURLToPath, pathToFileURL } from "url";
5115
5167
  function hasAttribute(decl, name) {
5116
5168
  return !!getAttribute(decl, name);
5117
5169
  }
@@ -5215,7 +5267,7 @@ function getRecursiveBases(decl, includeDelegate = true, seen = /* @__PURE__ */
5215
5267
  ] : []
5216
5268
  ];
5217
5269
  bases.forEach((base) => {
5218
- const baseDecl = decl.$container.declarations.find((d) => isTypeDef(d) || isDataModel(d) && d.name === base.$refText);
5270
+ const baseDecl = decl.$container.declarations.find((d) => (isTypeDef(d) || isDataModel(d)) && d.name === base.$refText);
5219
5271
  if (baseDecl) {
5220
5272
  if (!includeDelegate && isDelegateModel(baseDecl)) {
5221
5273
  return;
@@ -5338,6 +5390,10 @@ function getArray(expr) {
5338
5390
  return isArrayExpr(expr) || isConfigArrayExpr(expr) ? expr.items : void 0;
5339
5391
  }
5340
5392
  __name(getArray, "getArray");
5393
+ function getAttributeArg(attr, name) {
5394
+ return attr.args.find((arg) => arg.$resolvedParam?.name === name)?.value;
5395
+ }
5396
+ __name(getAttributeArg, "getAttributeArg");
5341
5397
  function getFunctionExpressionContext(funcDecl) {
5342
5398
  const funcAllowedContext = [];
5343
5399
  const funcAttr = funcDecl.attributes.find((attr) => attr.decl.$refText === "@@@expressionContext");
@@ -5425,15 +5481,15 @@ function getAllDeclarationsIncludingImports(documents, model) {
5425
5481
  }
5426
5482
  __name(getAllDeclarationsIncludingImports, "getAllDeclarationsIncludingImports");
5427
5483
  function getAuthDecl(decls) {
5428
- let authModel = decls.find((m) => hasAttribute(m, "@@auth"));
5484
+ let authModel = decls.find((d) => hasAttribute(d, "@@auth"));
5429
5485
  if (!authModel) {
5430
- authModel = decls.find((m) => m.name === "User");
5486
+ authModel = decls.find((d) => d.name === "User");
5431
5487
  }
5432
5488
  return authModel;
5433
5489
  }
5434
5490
  __name(getAuthDecl, "getAuthDecl");
5435
5491
  function isBeforeInvocation(node) {
5436
- return isInvocationExpr(node) && node.function.ref?.name === "before" && isFromStdlib(node.function.ref);
5492
+ return isInvocationExpr(node) && node.function.ref?.name === "before";
5437
5493
  }
5438
5494
  __name(isBeforeInvocation, "isBeforeInvocation");
5439
5495
  function isCollectionPredicate(node) {
@@ -5516,13 +5572,23 @@ function getAllAttributes(decl, seen = /* @__PURE__ */ new Set()) {
5516
5572
  }
5517
5573
  if (isDataModel(decl) && decl.baseModel) {
5518
5574
  if (decl.baseModel.ref) {
5519
- attributes.push(...getAllAttributes(decl.baseModel.ref, seen));
5575
+ const attrs = getAllAttributes(decl.baseModel.ref, seen).filter((attr) => !isNonInheritableAttribute(attr));
5576
+ attributes.push(...attrs);
5520
5577
  }
5521
5578
  }
5522
5579
  attributes.push(...decl.attributes);
5523
5580
  return attributes;
5524
5581
  }
5525
5582
  __name(getAllAttributes, "getAllAttributes");
5583
+ function isNonInheritableAttribute(attr) {
5584
+ const attrName = attr.decl.ref?.name ?? attr.decl.$refText;
5585
+ return [
5586
+ "@@map",
5587
+ "@@unique",
5588
+ "@@index"
5589
+ ].includes(attrName);
5590
+ }
5591
+ __name(isNonInheritableAttribute, "isNonInheritableAttribute");
5526
5592
  function getDocument(node) {
5527
5593
  const rootNode = findRootNode(node);
5528
5594
  const result = rootNode.$document;
@@ -5532,6 +5598,71 @@ function getDocument(node) {
5532
5598
  return result;
5533
5599
  }
5534
5600
  __name(getDocument, "getDocument");
5601
+ function getPluginDocuments(model, schemaPath) {
5602
+ const result = [];
5603
+ for (const decl of model.declarations.filter(isPlugin)) {
5604
+ const providerField = decl.fields.find((f) => f.name === "provider");
5605
+ if (!providerField) {
5606
+ continue;
5607
+ }
5608
+ const provider = getLiteral(providerField.value);
5609
+ if (!provider) {
5610
+ continue;
5611
+ }
5612
+ let pluginModelFile;
5613
+ let providerPath = path.resolve(path.dirname(schemaPath), provider);
5614
+ if (fs.existsSync(providerPath)) {
5615
+ if (fs.statSync(providerPath).isDirectory()) {
5616
+ providerPath = path.join(providerPath, "index.js");
5617
+ }
5618
+ pluginModelFile = path.resolve(path.dirname(providerPath), PLUGIN_MODULE_NAME);
5619
+ if (!fs.existsSync(pluginModelFile)) {
5620
+ pluginModelFile = findUp([
5621
+ PLUGIN_MODULE_NAME
5622
+ ], path.dirname(providerPath));
5623
+ }
5624
+ }
5625
+ if (!pluginModelFile) {
5626
+ if (typeof import.meta.resolve === "function") {
5627
+ try {
5628
+ const resolvedUrl = import.meta.resolve(`${provider}/${PLUGIN_MODULE_NAME}`);
5629
+ pluginModelFile = fileURLToPath(resolvedUrl);
5630
+ } catch {
5631
+ }
5632
+ }
5633
+ }
5634
+ if (!pluginModelFile) {
5635
+ try {
5636
+ const require2 = createRequire(pathToFileURL(schemaPath));
5637
+ pluginModelFile = require2.resolve(`${provider}/${PLUGIN_MODULE_NAME}`);
5638
+ } catch {
5639
+ }
5640
+ }
5641
+ if (pluginModelFile && fs.existsSync(pluginModelFile)) {
5642
+ result.push(pluginModelFile);
5643
+ }
5644
+ }
5645
+ return result;
5646
+ }
5647
+ __name(getPluginDocuments, "getPluginDocuments");
5648
+ function findUp(names, cwd = process.cwd(), multiple = false, result = []) {
5649
+ if (!names.some((name) => !!name)) {
5650
+ return void 0;
5651
+ }
5652
+ const target = names.find((name) => fs.existsSync(path.join(cwd, name)));
5653
+ if (multiple === false && target) {
5654
+ return path.join(cwd, target);
5655
+ }
5656
+ if (target) {
5657
+ result.push(path.join(cwd, target));
5658
+ }
5659
+ const up = path.resolve(cwd, "..");
5660
+ if (up === cwd) {
5661
+ return multiple && result.length > 0 ? result : void 0;
5662
+ }
5663
+ return findUp(names, up, multiple, result);
5664
+ }
5665
+ __name(findUp, "findUp");
5535
5666
  function findRootNode(node) {
5536
5667
  while (node.$container) {
5537
5668
  node = node.$container;
@@ -5541,6 +5672,9 @@ function findRootNode(node) {
5541
5672
  __name(findRootNode, "findRootNode");
5542
5673
 
5543
5674
  // src/validators/attribute-application-validator.ts
5675
+ import { invariant } from "@zenstackhq/common-helpers";
5676
+ import { AstUtils as AstUtils2 } from "langium";
5677
+ import pluralize from "pluralize";
5544
5678
  function _ts_decorate(decorators, target, key, desc) {
5545
5679
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
5546
5680
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -5758,8 +5892,23 @@ var AttributeApplicationValidator = class {
5758
5892
  });
5759
5893
  }
5760
5894
  }
5761
- _checkUnique(attr, accept) {
5762
- const fields = attr.args[0]?.value;
5895
+ _checkId(attr, accept) {
5896
+ const dm = getContainingDataModel(attr);
5897
+ if (dm?.isView) {
5898
+ accept("error", `\`@id\` is not allowed for views`, {
5899
+ node: attr
5900
+ });
5901
+ }
5902
+ }
5903
+ _checkConstraint(attr, accept) {
5904
+ const dm = getContainingDataModel(attr);
5905
+ if (dm?.isView && (attr.decl.$refText === "@@id" || attr.decl.$refText === "@@index")) {
5906
+ accept("error", `\`${attr.decl.$refText}\` is not allowed for views`, {
5907
+ node: attr
5908
+ });
5909
+ }
5910
+ const fields = getAttributeArg(attr, "fields");
5911
+ const attrName = attr.decl.ref?.name;
5763
5912
  if (!fields) {
5764
5913
  accept("error", `expects an array of field references`, {
5765
5914
  node: attr.args[0]
@@ -5768,7 +5917,7 @@ var AttributeApplicationValidator = class {
5768
5917
  }
5769
5918
  if (isArrayExpr(fields)) {
5770
5919
  if (fields.items.length === 0) {
5771
- accept("error", `\`@@unique\` expects at least one field reference`, {
5920
+ accept("error", `\`${attrName}\` expects at least one field reference`, {
5772
5921
  node: fields
5773
5922
  });
5774
5923
  return;
@@ -5787,7 +5936,7 @@ var AttributeApplicationValidator = class {
5787
5936
  return;
5788
5937
  }
5789
5938
  if (item.target.ref.$container !== attr.$container && isDelegateModel(item.target.ref.$container)) {
5790
- accept("error", `Cannot use fields inherited from a polymorphic base model in \`@@unique\``, {
5939
+ accept("error", `Cannot use fields inherited from a polymorphic base model in \`${attrName}\``, {
5791
5940
  node: item
5792
5941
  });
5793
5942
  }
@@ -5798,6 +5947,24 @@ var AttributeApplicationValidator = class {
5798
5947
  });
5799
5948
  }
5800
5949
  }
5950
+ _checkSchema(attr, accept) {
5951
+ const schemaName = getStringLiteral(attr.args[0]?.value);
5952
+ invariant(schemaName, `@@schema expects a string literal`);
5953
+ const zmodel = AstUtils2.getContainerOfType(attr, isModel);
5954
+ const datasource = zmodel.declarations.find(isDataSource);
5955
+ if (datasource) {
5956
+ let found = false;
5957
+ const schemas = datasource.fields.find((f) => f.name === "schemas");
5958
+ if (schemas && isConfigArrayExpr(schemas.value)) {
5959
+ found = schemas.value.items.some((item) => isLiteralExpr(item) && item.value === schemaName);
5960
+ }
5961
+ if (!found) {
5962
+ accept("error", `Schema "${schemaName}" is not defined in the datasource`, {
5963
+ node: attr
5964
+ });
5965
+ }
5966
+ }
5967
+ }
5801
5968
  validatePolicyKinds(kind, candidates, attr, accept) {
5802
5969
  const items = kind.split(",").map((x) => x.trim());
5803
5970
  items.forEach((item) => {
@@ -5840,15 +6007,34 @@ _ts_decorate([
5840
6007
  _ts_metadata("design:returntype", void 0)
5841
6008
  ], AttributeApplicationValidator.prototype, "_checkValidate", null);
5842
6009
  _ts_decorate([
5843
- check("@@unique"),
6010
+ check("@id"),
6011
+ _ts_metadata("design:type", Function),
6012
+ _ts_metadata("design:paramtypes", [
6013
+ typeof AttributeApplication === "undefined" ? Object : AttributeApplication,
6014
+ typeof ValidationAcceptor === "undefined" ? Object : ValidationAcceptor
6015
+ ]),
6016
+ _ts_metadata("design:returntype", void 0)
6017
+ ], AttributeApplicationValidator.prototype, "_checkId", null);
6018
+ _ts_decorate([
5844
6019
  check("@@id"),
6020
+ check("@@index"),
6021
+ check("@@unique"),
5845
6022
  _ts_metadata("design:type", Function),
5846
6023
  _ts_metadata("design:paramtypes", [
5847
6024
  typeof AttributeApplication === "undefined" ? Object : AttributeApplication,
5848
6025
  typeof ValidationAcceptor === "undefined" ? Object : ValidationAcceptor
5849
6026
  ]),
5850
6027
  _ts_metadata("design:returntype", void 0)
5851
- ], AttributeApplicationValidator.prototype, "_checkUnique", null);
6028
+ ], AttributeApplicationValidator.prototype, "_checkConstraint", null);
6029
+ _ts_decorate([
6030
+ check("@@schema"),
6031
+ _ts_metadata("design:type", Function),
6032
+ _ts_metadata("design:paramtypes", [
6033
+ typeof AttributeApplication === "undefined" ? Object : AttributeApplication,
6034
+ typeof ValidationAcceptor === "undefined" ? Object : ValidationAcceptor
6035
+ ]),
6036
+ _ts_metadata("design:returntype", void 0)
6037
+ ], AttributeApplicationValidator.prototype, "_checkSchema", null);
5852
6038
  function assignableToAttributeParam(arg, param, attr) {
5853
6039
  const argResolvedType = arg.$resolvedType;
5854
6040
  if (!argResolvedType) {
@@ -5982,7 +6168,7 @@ var AttributeValidator = class {
5982
6168
  };
5983
6169
 
5984
6170
  // src/validators/datamodel-validator.ts
5985
- import { invariant } from "@zenstackhq/common-helpers";
6171
+ import { invariant as invariant2 } from "@zenstackhq/common-helpers";
5986
6172
  import { AstUtils as AstUtils3 } from "langium";
5987
6173
 
5988
6174
  // src/validators/common.ts
@@ -6029,7 +6215,7 @@ var DataModelValidator = class {
6029
6215
  const uniqueFields = allFields.filter((f) => f.attributes.find((attr) => attr.decl.ref?.name === "@unique"));
6030
6216
  const modelLevelIds = getModelIdFields(dm);
6031
6217
  const modelUniqueFields = getModelUniqueFields(dm);
6032
- if (idFields.length === 0 && modelLevelIds.length === 0 && uniqueFields.length === 0 && modelUniqueFields.length === 0) {
6218
+ if (!dm.isView && idFields.length === 0 && modelLevelIds.length === 0 && uniqueFields.length === 0 && modelUniqueFields.length === 0) {
6033
6219
  accept("error", "Model must have at least one unique criteria. Either mark a single field with `@id`, `@unique` or add a multi field criterion with `@@id([])` or `@@unique([])` to the model.", {
6034
6220
  node: dm
6035
6221
  });
@@ -6223,7 +6409,7 @@ var DataModelValidator = class {
6223
6409
  if (!thisRelation.valid) {
6224
6410
  return;
6225
6411
  }
6226
- if (this.isFieldInheritedFromDelegateModel(field)) {
6412
+ if (this.isFieldInheritedFromDelegateModel(field, contextModel)) {
6227
6413
  return;
6228
6414
  }
6229
6415
  if (this.isSelfRelation(field)) {
@@ -6346,14 +6532,14 @@ var DataModelValidator = class {
6346
6532
  }
6347
6533
  }
6348
6534
  // checks if the given field is inherited directly or indirectly from a delegate model
6349
- isFieldInheritedFromDelegateModel(field) {
6350
- return isDelegateModel(field.$container);
6535
+ isFieldInheritedFromDelegateModel(field, contextModel) {
6536
+ return field.$container !== contextModel && isDelegateModel(field.$container);
6351
6537
  }
6352
6538
  validateInherits(model, accept) {
6353
6539
  if (!model.baseModel) {
6354
6540
  return;
6355
6541
  }
6356
- invariant(model.baseModel.ref, "baseModel must be resolved");
6542
+ invariant2(model.baseModel.ref, "baseModel must be resolved");
6357
6543
  if (!isDelegateModel(model.baseModel.ref)) {
6358
6544
  accept("error", `Model ${model.baseModel.$refText} cannot be extended because it's not a delegate model`, {
6359
6545
  node: model,
@@ -6375,7 +6561,7 @@ var DataModelValidator = class {
6375
6561
  }
6376
6562
  seen.push(current);
6377
6563
  if (current.baseModel) {
6378
- invariant(current.baseModel.ref, "baseModel must be resolved");
6564
+ invariant2(current.baseModel.ref, "baseModel must be resolved");
6379
6565
  todo.push(current.baseModel.ref);
6380
6566
  }
6381
6567
  }
@@ -6406,7 +6592,6 @@ var DataSourceValidator = class {
6406
6592
  validateDuplicatedDeclarations(ds, ds.fields, accept);
6407
6593
  this.validateProvider(ds, accept);
6408
6594
  this.validateUrl(ds, accept);
6409
- this.validateRelationMode(ds, accept);
6410
6595
  }
6411
6596
  validateProvider(ds, accept) {
6412
6597
  const provider = ds.fields.find((f) => f.name === "provider");
@@ -6416,16 +6601,61 @@ var DataSourceValidator = class {
6416
6601
  });
6417
6602
  return;
6418
6603
  }
6419
- const value = getStringLiteral(provider.value);
6420
- if (!value) {
6604
+ const providerValue = getStringLiteral(provider.value);
6605
+ if (!providerValue) {
6421
6606
  accept("error", '"provider" must be set to a string literal', {
6422
6607
  node: provider.value
6423
6608
  });
6424
- } else if (!SUPPORTED_PROVIDERS.includes(value)) {
6425
- accept("error", `Provider "${value}" is not supported. Choose from ${SUPPORTED_PROVIDERS.map((p) => '"' + p + '"').join(" | ")}.`, {
6609
+ } else if (!SUPPORTED_PROVIDERS.includes(providerValue)) {
6610
+ accept("error", `Provider "${providerValue}" is not supported. Choose from ${SUPPORTED_PROVIDERS.map((p) => '"' + p + '"').join(" | ")}.`, {
6426
6611
  node: provider.value
6427
6612
  });
6428
6613
  }
6614
+ const defaultSchemaField = ds.fields.find((f) => f.name === "defaultSchema");
6615
+ let defaultSchemaValue;
6616
+ if (defaultSchemaField) {
6617
+ if (providerValue !== "postgresql") {
6618
+ accept("error", '"defaultSchema" is only supported for "postgresql" provider', {
6619
+ node: defaultSchemaField
6620
+ });
6621
+ }
6622
+ defaultSchemaValue = getStringLiteral(defaultSchemaField.value);
6623
+ if (!defaultSchemaValue) {
6624
+ accept("error", '"defaultSchema" must be a string literal', {
6625
+ node: defaultSchemaField.value
6626
+ });
6627
+ }
6628
+ }
6629
+ const schemasField = ds.fields.find((f) => f.name === "schemas");
6630
+ if (schemasField) {
6631
+ if (providerValue !== "postgresql") {
6632
+ accept("error", '"schemas" is only supported for "postgresql" provider', {
6633
+ node: schemasField
6634
+ });
6635
+ }
6636
+ const schemasValue = schemasField.value;
6637
+ if (!isConfigArrayExpr(schemasValue) || !schemasValue.items.every((e) => isLiteralExpr(e) && typeof getStringLiteral(e) === "string")) {
6638
+ accept("error", '"schemas" must be an array of string literals', {
6639
+ node: schemasField
6640
+ });
6641
+ } else {
6642
+ const schemasArray = schemasValue.items.map((e) => getStringLiteral(e));
6643
+ if (defaultSchemaValue) {
6644
+ if (!schemasArray.includes(defaultSchemaValue)) {
6645
+ accept("error", `"${defaultSchemaValue}" must be included in the "schemas" array`, {
6646
+ node: schemasField
6647
+ });
6648
+ }
6649
+ } else {
6650
+ const hasImplicitPublicSchema = ds.$container.declarations.some((d) => (isDataModel(d) || isEnum(d)) && !d.attributes.some((a) => a.decl.$refText === "@@schema"));
6651
+ if (hasImplicitPublicSchema && !schemasArray.includes("public")) {
6652
+ accept("error", `"public" must be included in the "schemas" array`, {
6653
+ node: schemasField
6654
+ });
6655
+ }
6656
+ }
6657
+ }
6658
+ }
6429
6659
  }
6430
6660
  validateUrl(ds, accept) {
6431
6661
  const urlField = ds.fields.find((f) => f.name === "url");
@@ -6439,20 +6669,6 @@ var DataSourceValidator = class {
6439
6669
  });
6440
6670
  }
6441
6671
  }
6442
- validateRelationMode(ds, accept) {
6443
- const field = ds.fields.find((f) => f.name === "relationMode");
6444
- if (field) {
6445
- const val = getStringLiteral(field.value);
6446
- if (!val || ![
6447
- "foreignKeys",
6448
- "prisma"
6449
- ].includes(val)) {
6450
- accept("error", '"relationMode" must be set to "foreignKeys" or "prisma"', {
6451
- node: field.value
6452
- });
6453
- }
6454
- }
6455
- }
6456
6672
  };
6457
6673
 
6458
6674
  // src/validators/enum-validator.ts
@@ -6511,6 +6727,9 @@ var ExpressionValidator = class {
6511
6727
  case "BinaryExpr":
6512
6728
  this.validateBinaryExpr(expr, accept);
6513
6729
  break;
6730
+ case "UnaryExpr":
6731
+ this.validateUnaryExpr(expr, accept);
6732
+ break;
6514
6733
  }
6515
6734
  }
6516
6735
  validateMemberAccessExpr(expr, accept) {
@@ -6652,6 +6871,13 @@ var ExpressionValidator = class {
6652
6871
  break;
6653
6872
  }
6654
6873
  }
6874
+ validateUnaryExpr(expr, accept) {
6875
+ if (expr.operand.$resolvedType && expr.operand.$resolvedType.decl !== "Boolean") {
6876
+ accept("error", `operand of "${expr.operator}" must be of Boolean type`, {
6877
+ node: expr.operand
6878
+ });
6879
+ }
6880
+ }
6655
6881
  validateCollectionPredicate(expr, accept) {
6656
6882
  if (!expr.$resolvedType) {
6657
6883
  accept("error", "collection predicate can only be used on an array of model type", {
@@ -6721,44 +6947,42 @@ var FunctionInvocationValidator = class {
6721
6947
  });
6722
6948
  return;
6723
6949
  }
6724
- if (!this.validateArgs(funcDecl, expr.args, accept)) {
6950
+ if (!this.validateArgs(funcDecl, expr, accept)) {
6725
6951
  return;
6726
6952
  }
6727
- if (isFromStdlib(funcDecl)) {
6728
- let curr = expr.$container;
6729
- let containerAttribute;
6730
- while (curr) {
6731
- if (isDataModelAttribute(curr) || isDataFieldAttribute(curr)) {
6732
- containerAttribute = curr;
6733
- break;
6734
- }
6735
- curr = curr.$container;
6953
+ let curr = expr.$container;
6954
+ let containerAttribute;
6955
+ while (curr) {
6956
+ if (isDataModelAttribute(curr) || isDataFieldAttribute(curr)) {
6957
+ containerAttribute = curr;
6958
+ break;
6736
6959
  }
6737
- const exprContext = this.getExpressionContext(containerAttribute);
6738
- const funcAllowedContext = getFunctionExpressionContext(funcDecl);
6739
- if (exprContext && !funcAllowedContext.includes(exprContext)) {
6740
- accept("error", `function "${funcDecl.name}" is not allowed in the current context: ${exprContext}`, {
6741
- node: expr
6960
+ curr = curr.$container;
6961
+ }
6962
+ const exprContext = this.getExpressionContext(containerAttribute);
6963
+ const funcAllowedContext = getFunctionExpressionContext(funcDecl);
6964
+ if (exprContext && !funcAllowedContext.includes(exprContext)) {
6965
+ accept("error", `function "${funcDecl.name}" is not allowed in the current context: ${exprContext}`, {
6966
+ node: expr
6967
+ });
6968
+ return;
6969
+ }
6970
+ const allCasing = [
6971
+ "original",
6972
+ "upper",
6973
+ "lower",
6974
+ "capitalize",
6975
+ "uncapitalize"
6976
+ ];
6977
+ if ([
6978
+ "currentModel",
6979
+ "currentOperation"
6980
+ ].includes(funcDecl.name)) {
6981
+ const arg = getLiteral(expr.args[0]?.value);
6982
+ if (arg && !allCasing.includes(arg)) {
6983
+ accept("error", `argument must be one of: ${allCasing.map((c) => '"' + c + '"').join(", ")}`, {
6984
+ node: expr.args[0]
6742
6985
  });
6743
- return;
6744
- }
6745
- const allCasing = [
6746
- "original",
6747
- "upper",
6748
- "lower",
6749
- "capitalize",
6750
- "uncapitalize"
6751
- ];
6752
- if ([
6753
- "currentModel",
6754
- "currentOperation"
6755
- ].includes(funcDecl.name)) {
6756
- const arg = getLiteral(expr.args[0]?.value);
6757
- if (arg && !allCasing.includes(arg)) {
6758
- accept("error", `argument must be one of: ${allCasing.map((c) => '"' + c + '"').join(", ")}`, {
6759
- node: expr.args[0]
6760
- });
6761
- }
6762
6986
  }
6763
6987
  }
6764
6988
  const checker = invocationCheckers.get(expr.function.$refText);
@@ -6778,18 +7002,18 @@ var FunctionInvocationValidator = class {
6778
7002
  isValidationAttribute(attr) {
6779
7003
  return !!attr.decl.ref?.attributes.some((attr2) => attr2.decl.$refText === "@@@validation");
6780
7004
  }
6781
- validateArgs(funcDecl, args, accept) {
7005
+ validateArgs(funcDecl, expr, accept) {
6782
7006
  let success = true;
6783
7007
  for (let i = 0; i < funcDecl.params.length; i++) {
6784
7008
  const param = funcDecl.params[i];
6785
7009
  if (!param) {
6786
7010
  continue;
6787
7011
  }
6788
- const arg = args[i];
7012
+ const arg = expr.args[i];
6789
7013
  if (!arg) {
6790
7014
  if (!param.optional) {
6791
7015
  accept("error", `missing argument for parameter "${param.name}"`, {
6792
- node: funcDecl
7016
+ node: expr
6793
7017
  });
6794
7018
  success = false;
6795
7019
  }
@@ -6838,6 +7062,13 @@ var FunctionInvocationValidator = class {
6838
7062
  }
6839
7063
  return true;
6840
7064
  }
7065
+ _checkAuth(expr, accept) {
7066
+ if (!expr.$resolvedType) {
7067
+ accept("error", 'cannot resolve `auth()` - make sure you have a model or type with `@auth` attribute or named "User"', {
7068
+ node: expr
7069
+ });
7070
+ }
7071
+ }
6841
7072
  _checkLength(expr, accept) {
6842
7073
  const msg = "argument must be a string or list field";
6843
7074
  const fieldArg = expr.args[0].value;
@@ -6947,6 +7178,15 @@ var FunctionInvocationValidator = class {
6947
7178
  }
6948
7179
  }
6949
7180
  };
7181
+ _ts_decorate2([
7182
+ func("auth"),
7183
+ _ts_metadata2("design:type", Function),
7184
+ _ts_metadata2("design:paramtypes", [
7185
+ typeof InvocationExpr === "undefined" ? Object : InvocationExpr,
7186
+ typeof ValidationAcceptor === "undefined" ? Object : ValidationAcceptor
7187
+ ]),
7188
+ _ts_metadata2("design:returntype", void 0)
7189
+ ], FunctionInvocationValidator.prototype, "_checkAuth", null);
6950
7190
  _ts_decorate2([
6951
7191
  func("length"),
6952
7192
  _ts_metadata2("design:type", Function),
@@ -7055,6 +7295,7 @@ function registerValidationChecks(services) {
7055
7295
  const checks = {
7056
7296
  Model: validator.checkModel,
7057
7297
  DataSource: validator.checkDataSource,
7298
+ GeneratorDecl: validator.checkGenerator,
7058
7299
  DataModel: validator.checkDataModel,
7059
7300
  TypeDef: validator.checkTypeDef,
7060
7301
  Enum: validator.checkEnum,
@@ -7080,6 +7321,11 @@ var ZModelValidator = class {
7080
7321
  checkDataSource(node, accept) {
7081
7322
  new DataSourceValidator().validate(node, accept);
7082
7323
  }
7324
+ checkGenerator(node, accept) {
7325
+ accept("warning", '"generator" is not used by ZenStack and should be removed.', {
7326
+ node
7327
+ });
7328
+ }
7083
7329
  checkDataModel(node, accept) {
7084
7330
  new DataModelValidator().validate(node, accept);
7085
7331
  }
@@ -7103,6 +7349,873 @@ var ZModelValidator = class {
7103
7349
  }
7104
7350
  };
7105
7351
 
7352
+ // src/zmodel-comment-provider.ts
7353
+ import { DefaultCommentProvider } from "langium";
7354
+ import { match as match2 } from "ts-pattern";
7355
+ var ZModelCommentProvider = class extends DefaultCommentProvider {
7356
+ static {
7357
+ __name(this, "ZModelCommentProvider");
7358
+ }
7359
+ getComment(node) {
7360
+ let comment = super.getComment(node);
7361
+ if (!comment) {
7362
+ comment = match2(node).when(isDataModel, (d) => `/**
7363
+ * Model *${d.name}*
7364
+ */`).when(isTypeDef, (d) => `/**
7365
+ * Type *${d.name}*
7366
+ */`).when(isEnum, (e) => `/**
7367
+ * Enum *${e.name}*
7368
+ */`).when(isEnumField, (f) => `/**
7369
+ * Value of enum *${f.$container?.name}*
7370
+ */`).when(isDataField, (f) => `/**
7371
+ * Field of *${f.$container?.name}*
7372
+ */`).when(isFunctionDecl, (f) => `/**
7373
+ * Function *${f.name}*
7374
+ */`).otherwise(() => "");
7375
+ }
7376
+ return comment;
7377
+ }
7378
+ };
7379
+
7380
+ // src/zmodel-completion-provider.ts
7381
+ import { DefaultCompletionProvider } from "langium/lsp";
7382
+ import fs2 from "fs";
7383
+ import { P as P2, match as match3 } from "ts-pattern";
7384
+ import { CompletionItemKind } from "vscode-languageserver";
7385
+
7386
+ // src/zmodel-code-generator.ts
7387
+ function _ts_decorate3(decorators, target, key, desc) {
7388
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
7389
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
7390
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
7391
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7392
+ }
7393
+ __name(_ts_decorate3, "_ts_decorate");
7394
+ function _ts_metadata3(k, v) {
7395
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
7396
+ }
7397
+ __name(_ts_metadata3, "_ts_metadata");
7398
+ var generationHandlers = /* @__PURE__ */ new Map();
7399
+ function gen(name) {
7400
+ return function(_target, _propertyKey, descriptor) {
7401
+ if (!generationHandlers.get(name)) {
7402
+ generationHandlers.set(name, descriptor);
7403
+ }
7404
+ return descriptor;
7405
+ };
7406
+ }
7407
+ __name(gen, "gen");
7408
+ var ZModelCodeGenerator = class {
7409
+ static {
7410
+ __name(this, "ZModelCodeGenerator");
7411
+ }
7412
+ options;
7413
+ constructor(options) {
7414
+ this.options = {
7415
+ binaryExprNumberOfSpaces: options?.binaryExprNumberOfSpaces ?? 1,
7416
+ unaryExprNumberOfSpaces: options?.unaryExprNumberOfSpaces ?? 0,
7417
+ indent: options?.indent ?? 4,
7418
+ quote: options?.quote ?? "single"
7419
+ };
7420
+ }
7421
+ /**
7422
+ * Generates ZModel source code from AST.
7423
+ */
7424
+ generate(ast) {
7425
+ const handler = generationHandlers.get(ast.$type);
7426
+ if (!handler) {
7427
+ throw new Error(`No generation handler found for ${ast.$type}`);
7428
+ }
7429
+ return handler.value.call(this, ast);
7430
+ }
7431
+ _generateModel(ast) {
7432
+ return ast.declarations.map((d) => this.generate(d)).join("\n\n");
7433
+ }
7434
+ _generateDataSource(ast) {
7435
+ return `datasource ${ast.name} {
7436
+ ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}
7437
+ }`;
7438
+ }
7439
+ _generateEnum(ast) {
7440
+ return `enum ${ast.name} {
7441
+ ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}
7442
+ }`;
7443
+ }
7444
+ _generateEnumField(ast) {
7445
+ return `${ast.name}${ast.attributes.length > 0 ? " " + ast.attributes.map((x) => this.generate(x)).join(" ") : ""}`;
7446
+ }
7447
+ _generateGenerator(ast) {
7448
+ return `generator ${ast.name} {
7449
+ ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}
7450
+ }`;
7451
+ }
7452
+ _generateConfigField(ast) {
7453
+ return `${ast.name} = ${this.generate(ast.value)}`;
7454
+ }
7455
+ _generateConfigArrayExpr(ast) {
7456
+ return `[${ast.items.map((x) => this.generate(x)).join(", ")}]`;
7457
+ }
7458
+ _generateConfigInvocationExpr(ast) {
7459
+ if (ast.args.length === 0) {
7460
+ return ast.name;
7461
+ } else {
7462
+ return `${ast.name}(${ast.args.map((x) => (x.name ? x.name + ": " : "") + this.generate(x.value)).join(", ")})`;
7463
+ }
7464
+ }
7465
+ _generatePlugin(ast) {
7466
+ return `plugin ${ast.name} {
7467
+ ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}
7468
+ }`;
7469
+ }
7470
+ _generatePluginField(ast) {
7471
+ return `${ast.name} = ${this.generate(ast.value)}`;
7472
+ }
7473
+ _generateDataModel(ast) {
7474
+ return `${ast.isView ? "view" : "model"} ${ast.name}${ast.mixins.length > 0 ? " mixes " + ast.mixins.map((x) => x.$refText).join(", ") : ""} {
7475
+ ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}${ast.attributes.length > 0 ? "\n\n" + ast.attributes.map((x) => this.indent + this.generate(x)).join("\n") : ""}
7476
+ }`;
7477
+ }
7478
+ _generateDataField(ast) {
7479
+ return `${ast.name} ${this.fieldType(ast.type)}${ast.attributes.length > 0 ? " " + ast.attributes.map((x) => this.generate(x)).join(" ") : ""}`;
7480
+ }
7481
+ fieldType(type) {
7482
+ const baseType = type.type ? type.type : type.$type == "DataFieldType" && type.unsupported ? "Unsupported(" + this.generate(type.unsupported.value) + ")" : type.reference?.$refText;
7483
+ return `${baseType}${type.array ? "[]" : ""}${type.optional ? "?" : ""}`;
7484
+ }
7485
+ _generateDataModelAttribute(ast) {
7486
+ return this.attribute(ast);
7487
+ }
7488
+ _generateDataFieldAttribute(ast) {
7489
+ return this.attribute(ast);
7490
+ }
7491
+ attribute(ast) {
7492
+ const args = ast.args.length ? `(${ast.args.map((x) => this.generate(x)).join(", ")})` : "";
7493
+ return `${ast.decl.$refText}${args}`;
7494
+ }
7495
+ _generateAttributeArg(ast) {
7496
+ if (ast.name) {
7497
+ return `${ast.name}: ${this.generate(ast.value)}`;
7498
+ } else {
7499
+ return this.generate(ast.value);
7500
+ }
7501
+ }
7502
+ _generateObjectExpr(ast) {
7503
+ return `{ ${ast.fields.map((field) => this.objectField(field)).join(", ")} }`;
7504
+ }
7505
+ objectField(field) {
7506
+ return `${field.name}: ${this.generate(field.value)}`;
7507
+ }
7508
+ _generateArrayExpr(ast) {
7509
+ return `[${ast.items.map((item) => this.generate(item)).join(", ")}]`;
7510
+ }
7511
+ _generateLiteralExpr(ast) {
7512
+ return this.options.quote === "single" ? `'${ast.value}'` : `"${ast.value}"`;
7513
+ }
7514
+ _generateNumberLiteral(ast) {
7515
+ return ast.value.toString();
7516
+ }
7517
+ _generateBooleanLiteral(ast) {
7518
+ return ast.value.toString();
7519
+ }
7520
+ _generateUnaryExpr(ast) {
7521
+ return `${ast.operator}${this.unaryExprSpace}${this.generate(ast.operand)}`;
7522
+ }
7523
+ _generateBinaryExpr(ast) {
7524
+ const operator = ast.operator;
7525
+ const isCollectionPredicate2 = this.isCollectionPredicateOperator(operator);
7526
+ const rightExpr = this.generate(ast.right);
7527
+ const { left: isLeftParenthesis, right: isRightParenthesis } = this.isParenthesesNeededForBinaryExpr(ast);
7528
+ return `${isLeftParenthesis ? "(" : ""}${this.generate(ast.left)}${isLeftParenthesis ? ")" : ""}${isCollectionPredicate2 ? "" : this.binaryExprSpace}${operator}${isCollectionPredicate2 ? "" : this.binaryExprSpace}${isRightParenthesis ? "(" : ""}${isCollectionPredicate2 ? `[${rightExpr}]` : rightExpr}${isRightParenthesis ? ")" : ""}`;
7529
+ }
7530
+ _generateReferenceExpr(ast) {
7531
+ const args = ast.args.length ? `(${ast.args.map((x) => this.generate(x)).join(", ")})` : "";
7532
+ return `${ast.target.$refText}${args}`;
7533
+ }
7534
+ _generateReferenceArg(ast) {
7535
+ return `${ast.name}:${this.generate(ast.value)}`;
7536
+ }
7537
+ _generateMemberExpr(ast) {
7538
+ return `${this.generate(ast.operand)}.${ast.member.$refText}`;
7539
+ }
7540
+ _generateInvocationExpr(ast) {
7541
+ return `${ast.function.$refText}(${ast.args.map((x) => this.argument(x)).join(", ")})`;
7542
+ }
7543
+ _generateNullExpr() {
7544
+ return "null";
7545
+ }
7546
+ _generateThisExpr() {
7547
+ return "this";
7548
+ }
7549
+ _generateAttribute(ast) {
7550
+ return `attribute ${ast.name}(${ast.params.map((x) => this.generate(x)).join(", ")})`;
7551
+ }
7552
+ _generateAttributeParam(ast) {
7553
+ return `${ast.default ? "_ " : ""}${ast.name}: ${this.generate(ast.type)}`;
7554
+ }
7555
+ _generateAttributeParamType(ast) {
7556
+ return `${ast.type ?? ast.reference?.$refText}${ast.array ? "[]" : ""}${ast.optional ? "?" : ""}`;
7557
+ }
7558
+ _generateFunctionDecl(ast) {
7559
+ return `function ${ast.name}(${ast.params.map((x) => this.generate(x)).join(", ")}) ${ast.returnType ? ": " + this.generate(ast.returnType) : ""} {}`;
7560
+ }
7561
+ _generateFunctionParam(ast) {
7562
+ return `${ast.name}: ${this.generate(ast.type)}`;
7563
+ }
7564
+ _generateFunctionParamType(ast) {
7565
+ return `${ast.type ?? ast.reference?.$refText}${ast.array ? "[]" : ""}`;
7566
+ }
7567
+ _generateTypeDef(ast) {
7568
+ return `type ${ast.name} {
7569
+ ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}${ast.attributes.length > 0 ? "\n\n" + ast.attributes.map((x) => this.indent + this.generate(x)).join("\n") : ""}
7570
+ }`;
7571
+ }
7572
+ argument(ast) {
7573
+ return this.generate(ast.value);
7574
+ }
7575
+ get binaryExprSpace() {
7576
+ return " ".repeat(this.options.binaryExprNumberOfSpaces);
7577
+ }
7578
+ get unaryExprSpace() {
7579
+ return " ".repeat(this.options.unaryExprNumberOfSpaces);
7580
+ }
7581
+ get indent() {
7582
+ return " ".repeat(this.options.indent);
7583
+ }
7584
+ isParenthesesNeededForBinaryExpr(ast) {
7585
+ const result = {
7586
+ left: false,
7587
+ right: false
7588
+ };
7589
+ const operator = ast.operator;
7590
+ const isCollectionPredicate2 = this.isCollectionPredicateOperator(operator);
7591
+ const currentPriority = BinaryExprOperatorPriority[operator];
7592
+ if (ast.left.$type === BinaryExpr && BinaryExprOperatorPriority[ast.left["operator"]] < currentPriority) {
7593
+ result.left = true;
7594
+ }
7595
+ if (!isCollectionPredicate2 && ast.right.$type === BinaryExpr && BinaryExprOperatorPriority[ast.right["operator"]] <= currentPriority) {
7596
+ result.right = true;
7597
+ }
7598
+ return result;
7599
+ }
7600
+ isCollectionPredicateOperator(op) {
7601
+ return [
7602
+ "?",
7603
+ "!",
7604
+ "^"
7605
+ ].includes(op);
7606
+ }
7607
+ };
7608
+ _ts_decorate3([
7609
+ gen(Model),
7610
+ _ts_metadata3("design:type", Function),
7611
+ _ts_metadata3("design:paramtypes", [
7612
+ typeof Model === "undefined" ? Object : Model
7613
+ ]),
7614
+ _ts_metadata3("design:returntype", void 0)
7615
+ ], ZModelCodeGenerator.prototype, "_generateModel", null);
7616
+ _ts_decorate3([
7617
+ gen(DataSource),
7618
+ _ts_metadata3("design:type", Function),
7619
+ _ts_metadata3("design:paramtypes", [
7620
+ typeof DataSource === "undefined" ? Object : DataSource
7621
+ ]),
7622
+ _ts_metadata3("design:returntype", void 0)
7623
+ ], ZModelCodeGenerator.prototype, "_generateDataSource", null);
7624
+ _ts_decorate3([
7625
+ gen(Enum),
7626
+ _ts_metadata3("design:type", Function),
7627
+ _ts_metadata3("design:paramtypes", [
7628
+ typeof Enum === "undefined" ? Object : Enum
7629
+ ]),
7630
+ _ts_metadata3("design:returntype", void 0)
7631
+ ], ZModelCodeGenerator.prototype, "_generateEnum", null);
7632
+ _ts_decorate3([
7633
+ gen(EnumField),
7634
+ _ts_metadata3("design:type", Function),
7635
+ _ts_metadata3("design:paramtypes", [
7636
+ typeof EnumField === "undefined" ? Object : EnumField
7637
+ ]),
7638
+ _ts_metadata3("design:returntype", void 0)
7639
+ ], ZModelCodeGenerator.prototype, "_generateEnumField", null);
7640
+ _ts_decorate3([
7641
+ gen(GeneratorDecl),
7642
+ _ts_metadata3("design:type", Function),
7643
+ _ts_metadata3("design:paramtypes", [
7644
+ typeof GeneratorDecl === "undefined" ? Object : GeneratorDecl
7645
+ ]),
7646
+ _ts_metadata3("design:returntype", void 0)
7647
+ ], ZModelCodeGenerator.prototype, "_generateGenerator", null);
7648
+ _ts_decorate3([
7649
+ gen(ConfigField),
7650
+ _ts_metadata3("design:type", Function),
7651
+ _ts_metadata3("design:paramtypes", [
7652
+ typeof ConfigField === "undefined" ? Object : ConfigField
7653
+ ]),
7654
+ _ts_metadata3("design:returntype", void 0)
7655
+ ], ZModelCodeGenerator.prototype, "_generateConfigField", null);
7656
+ _ts_decorate3([
7657
+ gen(ConfigArrayExpr),
7658
+ _ts_metadata3("design:type", Function),
7659
+ _ts_metadata3("design:paramtypes", [
7660
+ typeof ConfigArrayExpr === "undefined" ? Object : ConfigArrayExpr
7661
+ ]),
7662
+ _ts_metadata3("design:returntype", void 0)
7663
+ ], ZModelCodeGenerator.prototype, "_generateConfigArrayExpr", null);
7664
+ _ts_decorate3([
7665
+ gen(ConfigInvocationExpr),
7666
+ _ts_metadata3("design:type", Function),
7667
+ _ts_metadata3("design:paramtypes", [
7668
+ typeof ConfigInvocationExpr === "undefined" ? Object : ConfigInvocationExpr
7669
+ ]),
7670
+ _ts_metadata3("design:returntype", void 0)
7671
+ ], ZModelCodeGenerator.prototype, "_generateConfigInvocationExpr", null);
7672
+ _ts_decorate3([
7673
+ gen(Plugin),
7674
+ _ts_metadata3("design:type", Function),
7675
+ _ts_metadata3("design:paramtypes", [
7676
+ typeof Plugin === "undefined" ? Object : Plugin
7677
+ ]),
7678
+ _ts_metadata3("design:returntype", void 0)
7679
+ ], ZModelCodeGenerator.prototype, "_generatePlugin", null);
7680
+ _ts_decorate3([
7681
+ gen(PluginField),
7682
+ _ts_metadata3("design:type", Function),
7683
+ _ts_metadata3("design:paramtypes", [
7684
+ typeof PluginField === "undefined" ? Object : PluginField
7685
+ ]),
7686
+ _ts_metadata3("design:returntype", void 0)
7687
+ ], ZModelCodeGenerator.prototype, "_generatePluginField", null);
7688
+ _ts_decorate3([
7689
+ gen(DataModel),
7690
+ _ts_metadata3("design:type", Function),
7691
+ _ts_metadata3("design:paramtypes", [
7692
+ typeof DataModel === "undefined" ? Object : DataModel
7693
+ ]),
7694
+ _ts_metadata3("design:returntype", void 0)
7695
+ ], ZModelCodeGenerator.prototype, "_generateDataModel", null);
7696
+ _ts_decorate3([
7697
+ gen(DataField),
7698
+ _ts_metadata3("design:type", Function),
7699
+ _ts_metadata3("design:paramtypes", [
7700
+ typeof DataField === "undefined" ? Object : DataField
7701
+ ]),
7702
+ _ts_metadata3("design:returntype", void 0)
7703
+ ], ZModelCodeGenerator.prototype, "_generateDataField", null);
7704
+ _ts_decorate3([
7705
+ gen(DataModelAttribute),
7706
+ _ts_metadata3("design:type", Function),
7707
+ _ts_metadata3("design:paramtypes", [
7708
+ typeof DataModelAttribute === "undefined" ? Object : DataModelAttribute
7709
+ ]),
7710
+ _ts_metadata3("design:returntype", void 0)
7711
+ ], ZModelCodeGenerator.prototype, "_generateDataModelAttribute", null);
7712
+ _ts_decorate3([
7713
+ gen(DataFieldAttribute),
7714
+ _ts_metadata3("design:type", Function),
7715
+ _ts_metadata3("design:paramtypes", [
7716
+ typeof DataFieldAttribute === "undefined" ? Object : DataFieldAttribute
7717
+ ]),
7718
+ _ts_metadata3("design:returntype", void 0)
7719
+ ], ZModelCodeGenerator.prototype, "_generateDataFieldAttribute", null);
7720
+ _ts_decorate3([
7721
+ gen(AttributeArg),
7722
+ _ts_metadata3("design:type", Function),
7723
+ _ts_metadata3("design:paramtypes", [
7724
+ typeof AttributeArg === "undefined" ? Object : AttributeArg
7725
+ ]),
7726
+ _ts_metadata3("design:returntype", void 0)
7727
+ ], ZModelCodeGenerator.prototype, "_generateAttributeArg", null);
7728
+ _ts_decorate3([
7729
+ gen(ObjectExpr),
7730
+ _ts_metadata3("design:type", Function),
7731
+ _ts_metadata3("design:paramtypes", [
7732
+ typeof ObjectExpr === "undefined" ? Object : ObjectExpr
7733
+ ]),
7734
+ _ts_metadata3("design:returntype", void 0)
7735
+ ], ZModelCodeGenerator.prototype, "_generateObjectExpr", null);
7736
+ _ts_decorate3([
7737
+ gen(ArrayExpr),
7738
+ _ts_metadata3("design:type", Function),
7739
+ _ts_metadata3("design:paramtypes", [
7740
+ typeof ArrayExpr === "undefined" ? Object : ArrayExpr
7741
+ ]),
7742
+ _ts_metadata3("design:returntype", void 0)
7743
+ ], ZModelCodeGenerator.prototype, "_generateArrayExpr", null);
7744
+ _ts_decorate3([
7745
+ gen(StringLiteral),
7746
+ _ts_metadata3("design:type", Function),
7747
+ _ts_metadata3("design:paramtypes", [
7748
+ typeof LiteralExpr === "undefined" ? Object : LiteralExpr
7749
+ ]),
7750
+ _ts_metadata3("design:returntype", void 0)
7751
+ ], ZModelCodeGenerator.prototype, "_generateLiteralExpr", null);
7752
+ _ts_decorate3([
7753
+ gen(NumberLiteral),
7754
+ _ts_metadata3("design:type", Function),
7755
+ _ts_metadata3("design:paramtypes", [
7756
+ typeof NumberLiteral === "undefined" ? Object : NumberLiteral
7757
+ ]),
7758
+ _ts_metadata3("design:returntype", void 0)
7759
+ ], ZModelCodeGenerator.prototype, "_generateNumberLiteral", null);
7760
+ _ts_decorate3([
7761
+ gen(BooleanLiteral),
7762
+ _ts_metadata3("design:type", Function),
7763
+ _ts_metadata3("design:paramtypes", [
7764
+ typeof BooleanLiteral === "undefined" ? Object : BooleanLiteral
7765
+ ]),
7766
+ _ts_metadata3("design:returntype", void 0)
7767
+ ], ZModelCodeGenerator.prototype, "_generateBooleanLiteral", null);
7768
+ _ts_decorate3([
7769
+ gen(UnaryExpr),
7770
+ _ts_metadata3("design:type", Function),
7771
+ _ts_metadata3("design:paramtypes", [
7772
+ typeof UnaryExpr === "undefined" ? Object : UnaryExpr
7773
+ ]),
7774
+ _ts_metadata3("design:returntype", void 0)
7775
+ ], ZModelCodeGenerator.prototype, "_generateUnaryExpr", null);
7776
+ _ts_decorate3([
7777
+ gen(BinaryExpr),
7778
+ _ts_metadata3("design:type", Function),
7779
+ _ts_metadata3("design:paramtypes", [
7780
+ typeof BinaryExpr === "undefined" ? Object : BinaryExpr
7781
+ ]),
7782
+ _ts_metadata3("design:returntype", void 0)
7783
+ ], ZModelCodeGenerator.prototype, "_generateBinaryExpr", null);
7784
+ _ts_decorate3([
7785
+ gen(ReferenceExpr),
7786
+ _ts_metadata3("design:type", Function),
7787
+ _ts_metadata3("design:paramtypes", [
7788
+ typeof ReferenceExpr === "undefined" ? Object : ReferenceExpr
7789
+ ]),
7790
+ _ts_metadata3("design:returntype", void 0)
7791
+ ], ZModelCodeGenerator.prototype, "_generateReferenceExpr", null);
7792
+ _ts_decorate3([
7793
+ gen(ReferenceArg),
7794
+ _ts_metadata3("design:type", Function),
7795
+ _ts_metadata3("design:paramtypes", [
7796
+ typeof ReferenceArg === "undefined" ? Object : ReferenceArg
7797
+ ]),
7798
+ _ts_metadata3("design:returntype", void 0)
7799
+ ], ZModelCodeGenerator.prototype, "_generateReferenceArg", null);
7800
+ _ts_decorate3([
7801
+ gen(MemberAccessExpr),
7802
+ _ts_metadata3("design:type", Function),
7803
+ _ts_metadata3("design:paramtypes", [
7804
+ typeof MemberAccessExpr === "undefined" ? Object : MemberAccessExpr
7805
+ ]),
7806
+ _ts_metadata3("design:returntype", void 0)
7807
+ ], ZModelCodeGenerator.prototype, "_generateMemberExpr", null);
7808
+ _ts_decorate3([
7809
+ gen(InvocationExpr),
7810
+ _ts_metadata3("design:type", Function),
7811
+ _ts_metadata3("design:paramtypes", [
7812
+ typeof InvocationExpr === "undefined" ? Object : InvocationExpr
7813
+ ]),
7814
+ _ts_metadata3("design:returntype", void 0)
7815
+ ], ZModelCodeGenerator.prototype, "_generateInvocationExpr", null);
7816
+ _ts_decorate3([
7817
+ gen(NullExpr),
7818
+ _ts_metadata3("design:type", Function),
7819
+ _ts_metadata3("design:paramtypes", []),
7820
+ _ts_metadata3("design:returntype", void 0)
7821
+ ], ZModelCodeGenerator.prototype, "_generateNullExpr", null);
7822
+ _ts_decorate3([
7823
+ gen(ThisExpr),
7824
+ _ts_metadata3("design:type", Function),
7825
+ _ts_metadata3("design:paramtypes", []),
7826
+ _ts_metadata3("design:returntype", void 0)
7827
+ ], ZModelCodeGenerator.prototype, "_generateThisExpr", null);
7828
+ _ts_decorate3([
7829
+ gen(Attribute),
7830
+ _ts_metadata3("design:type", Function),
7831
+ _ts_metadata3("design:paramtypes", [
7832
+ typeof Attribute === "undefined" ? Object : Attribute
7833
+ ]),
7834
+ _ts_metadata3("design:returntype", void 0)
7835
+ ], ZModelCodeGenerator.prototype, "_generateAttribute", null);
7836
+ _ts_decorate3([
7837
+ gen(AttributeParam),
7838
+ _ts_metadata3("design:type", Function),
7839
+ _ts_metadata3("design:paramtypes", [
7840
+ typeof AttributeParam === "undefined" ? Object : AttributeParam
7841
+ ]),
7842
+ _ts_metadata3("design:returntype", void 0)
7843
+ ], ZModelCodeGenerator.prototype, "_generateAttributeParam", null);
7844
+ _ts_decorate3([
7845
+ gen(AttributeParamType),
7846
+ _ts_metadata3("design:type", Function),
7847
+ _ts_metadata3("design:paramtypes", [
7848
+ typeof AttributeParamType === "undefined" ? Object : AttributeParamType
7849
+ ]),
7850
+ _ts_metadata3("design:returntype", void 0)
7851
+ ], ZModelCodeGenerator.prototype, "_generateAttributeParamType", null);
7852
+ _ts_decorate3([
7853
+ gen(FunctionDecl),
7854
+ _ts_metadata3("design:type", Function),
7855
+ _ts_metadata3("design:paramtypes", [
7856
+ typeof FunctionDecl === "undefined" ? Object : FunctionDecl
7857
+ ]),
7858
+ _ts_metadata3("design:returntype", void 0)
7859
+ ], ZModelCodeGenerator.prototype, "_generateFunctionDecl", null);
7860
+ _ts_decorate3([
7861
+ gen(FunctionParam),
7862
+ _ts_metadata3("design:type", Function),
7863
+ _ts_metadata3("design:paramtypes", [
7864
+ typeof FunctionParam === "undefined" ? Object : FunctionParam
7865
+ ]),
7866
+ _ts_metadata3("design:returntype", void 0)
7867
+ ], ZModelCodeGenerator.prototype, "_generateFunctionParam", null);
7868
+ _ts_decorate3([
7869
+ gen(FunctionParamType),
7870
+ _ts_metadata3("design:type", Function),
7871
+ _ts_metadata3("design:paramtypes", [
7872
+ typeof FunctionParamType === "undefined" ? Object : FunctionParamType
7873
+ ]),
7874
+ _ts_metadata3("design:returntype", void 0)
7875
+ ], ZModelCodeGenerator.prototype, "_generateFunctionParamType", null);
7876
+ _ts_decorate3([
7877
+ gen(TypeDef),
7878
+ _ts_metadata3("design:type", Function),
7879
+ _ts_metadata3("design:paramtypes", [
7880
+ typeof TypeDef === "undefined" ? Object : TypeDef
7881
+ ]),
7882
+ _ts_metadata3("design:returntype", void 0)
7883
+ ], ZModelCodeGenerator.prototype, "_generateTypeDef", null);
7884
+
7885
+ // src/zmodel-completion-provider.ts
7886
+ var ZModelCompletionProvider = class extends DefaultCompletionProvider {
7887
+ static {
7888
+ __name(this, "ZModelCompletionProvider");
7889
+ }
7890
+ services;
7891
+ constructor(services) {
7892
+ super(services), this.services = services;
7893
+ }
7894
+ completionOptions = {
7895
+ triggerCharacters: [
7896
+ "@",
7897
+ "(",
7898
+ ",",
7899
+ "."
7900
+ ]
7901
+ };
7902
+ async getCompletion(document, params) {
7903
+ try {
7904
+ return await super.getCompletion(document, params);
7905
+ } catch (e) {
7906
+ console.error("Completion error:", e.message);
7907
+ return void 0;
7908
+ }
7909
+ }
7910
+ completionFor(context, next, acceptor) {
7911
+ if (isDataModelAttribute(context.node) || isDataFieldAttribute(context.node)) {
7912
+ const completions = this.getCompletionFromHint(context.node);
7913
+ if (completions) {
7914
+ completions.forEach((c) => acceptor(context, c));
7915
+ return;
7916
+ }
7917
+ }
7918
+ return super.completionFor(context, next, acceptor);
7919
+ }
7920
+ getCompletionFromHint(contextNode) {
7921
+ const unfilledParams = this.getUnfilledAttributeParams(contextNode);
7922
+ const nextParam = unfilledParams[0];
7923
+ if (!nextParam) {
7924
+ return void 0;
7925
+ }
7926
+ const hintAttr = getAttribute(nextParam, "@@@completionHint");
7927
+ if (hintAttr) {
7928
+ const hint = hintAttr.args[0];
7929
+ if (hint?.value) {
7930
+ if (isArrayExpr(hint.value)) {
7931
+ return hint.value.items.map((item) => {
7932
+ return {
7933
+ label: `${item.value}`,
7934
+ kind: CompletionItemKind.Value,
7935
+ detail: "Parameter",
7936
+ sortText: "0"
7937
+ };
7938
+ });
7939
+ }
7940
+ }
7941
+ }
7942
+ return void 0;
7943
+ }
7944
+ // TODO: this doesn't work when the file contains parse errors
7945
+ getUnfilledAttributeParams(contextNode) {
7946
+ try {
7947
+ const params = contextNode.decl.ref?.params;
7948
+ if (params) {
7949
+ const args = contextNode.args;
7950
+ let unfilledParams = [
7951
+ ...params
7952
+ ];
7953
+ args.forEach((arg) => {
7954
+ if (arg.name) {
7955
+ unfilledParams = unfilledParams.filter((p) => p.name !== arg.name);
7956
+ } else {
7957
+ unfilledParams.shift();
7958
+ }
7959
+ });
7960
+ return unfilledParams;
7961
+ }
7962
+ } catch {
7963
+ }
7964
+ return [];
7965
+ }
7966
+ completionForCrossReference(context, crossRef, acceptor) {
7967
+ if (crossRef.property === "member" && !isMemberAccessExpr(context.node)) {
7968
+ return;
7969
+ }
7970
+ const customAcceptor = /* @__PURE__ */ __name((context2, item) => {
7971
+ if (item.insertText?.startsWith("@@@") || item.label?.startsWith("@@@")) {
7972
+ return;
7973
+ }
7974
+ if ("nodeDescription" in item) {
7975
+ const node = this.getAstNode(item.nodeDescription);
7976
+ if (!node) {
7977
+ return;
7978
+ }
7979
+ if ((isEnum(node) || isEnumField(node)) && isFromStdlib(node)) {
7980
+ return;
7981
+ }
7982
+ if ((isDataModelAttribute(context2.node) || isDataFieldAttribute(context2.node)) && !this.filterAttributeApplicationCompletion(context2.node, node)) {
7983
+ return;
7984
+ }
7985
+ }
7986
+ acceptor(context2, item);
7987
+ }, "customAcceptor");
7988
+ return super.completionForCrossReference(context, crossRef, customAcceptor);
7989
+ }
7990
+ completionForKeyword(context, keyword, acceptor) {
7991
+ const customAcceptor = /* @__PURE__ */ __name((context2, item) => {
7992
+ if (!this.filterKeywordForContext(context2, keyword.value)) {
7993
+ return;
7994
+ }
7995
+ acceptor(context2, item);
7996
+ }, "customAcceptor");
7997
+ return super.completionForKeyword(context, keyword, customAcceptor);
7998
+ }
7999
+ filterKeywordForContext(context, keyword) {
8000
+ if (isInvocationExpr(context.node)) {
8001
+ return [
8002
+ "true",
8003
+ "false",
8004
+ "null",
8005
+ "this"
8006
+ ].includes(keyword);
8007
+ } else if (isDataModelAttribute(context.node) || isDataFieldAttribute(context.node)) {
8008
+ const exprContext = this.getAttributeContextType(context.node);
8009
+ if (exprContext === "DefaultValue") {
8010
+ return [
8011
+ "true",
8012
+ "false",
8013
+ "null"
8014
+ ].includes(keyword);
8015
+ } else {
8016
+ return [
8017
+ "true",
8018
+ "false",
8019
+ "null",
8020
+ "this"
8021
+ ].includes(keyword);
8022
+ }
8023
+ } else {
8024
+ return true;
8025
+ }
8026
+ }
8027
+ filterAttributeApplicationCompletion(contextNode, node) {
8028
+ const attrContextType = this.getAttributeContextType(contextNode);
8029
+ if (isFunctionDecl(node) && attrContextType) {
8030
+ const funcExprContextAttr = getAttribute(node, "@@@expressionContext");
8031
+ if (funcExprContextAttr && funcExprContextAttr.args[0]) {
8032
+ const arg = funcExprContextAttr.args[0];
8033
+ if (isArrayExpr(arg.value)) {
8034
+ return arg.value.items.some((item) => isEnumFieldReference(item) && item.target.$refText === attrContextType);
8035
+ }
8036
+ }
8037
+ return false;
8038
+ }
8039
+ if (isDataField(node)) {
8040
+ return attrContextType !== "DefaultValue";
8041
+ }
8042
+ return true;
8043
+ }
8044
+ getAttributeContextType(node) {
8045
+ return match3(node.decl.$refText).with("@default", () => "DefaultValue").with(P2.union("@@allow", "@allow", "@@deny", "@deny"), () => "AccessPolicy").with("@@validate", () => "ValidationRule").otherwise(() => void 0);
8046
+ }
8047
+ createReferenceCompletionItem(nodeDescription) {
8048
+ const node = this.getAstNode(nodeDescription);
8049
+ const documentation = this.getNodeDocumentation(node);
8050
+ return match3(node).when(isDataModel, () => ({
8051
+ nodeDescription,
8052
+ kind: CompletionItemKind.Class,
8053
+ detail: "Model",
8054
+ sortText: "1",
8055
+ documentation
8056
+ })).when(isTypeDef, () => ({
8057
+ nodeDescription,
8058
+ kind: CompletionItemKind.Class,
8059
+ detail: "Type",
8060
+ sortText: "1",
8061
+ documentation
8062
+ })).when(isDataField, () => ({
8063
+ nodeDescription,
8064
+ kind: CompletionItemKind.Field,
8065
+ detail: "Field",
8066
+ sortText: "0",
8067
+ documentation
8068
+ })).when(isEnum, () => ({
8069
+ nodeDescription,
8070
+ kind: CompletionItemKind.Class,
8071
+ detail: "Enum",
8072
+ sortText: "1",
8073
+ documentation
8074
+ })).when(isEnumField, (d) => {
8075
+ const container = d.$container;
8076
+ return {
8077
+ nodeDescription,
8078
+ kind: CompletionItemKind.Enum,
8079
+ detail: `Value of enum "${container.name}"`,
8080
+ sortText: "1",
8081
+ documentation
8082
+ };
8083
+ }).when(isFunctionDecl, () => ({
8084
+ nodeDescription,
8085
+ insertText: this.getFunctionInsertText(nodeDescription),
8086
+ kind: CompletionItemKind.Function,
8087
+ detail: "Function",
8088
+ sortText: "1",
8089
+ documentation
8090
+ })).when(isAttribute, () => ({
8091
+ nodeDescription,
8092
+ insertText: this.getAttributeInsertText(nodeDescription),
8093
+ kind: CompletionItemKind.Property,
8094
+ detail: "Attribute",
8095
+ sortText: "1",
8096
+ documentation
8097
+ })).otherwise(() => ({
8098
+ nodeDescription,
8099
+ kind: CompletionItemKind.Reference,
8100
+ detail: nodeDescription.type,
8101
+ sortText: "2",
8102
+ documentation
8103
+ }));
8104
+ }
8105
+ getFunctionInsertText(nodeDescription) {
8106
+ const node = this.getAstNode(nodeDescription);
8107
+ if (isFunctionDecl(node)) {
8108
+ if (node.params.some((p) => !p.optional)) {
8109
+ return nodeDescription.name;
8110
+ }
8111
+ }
8112
+ return `${nodeDescription.name}()`;
8113
+ }
8114
+ getAttributeInsertText(nodeDescription) {
8115
+ const node = this.getAstNode(nodeDescription);
8116
+ if (isAttribute(node)) {
8117
+ if (node.name === "@relation") {
8118
+ return `${nodeDescription.name}(fields: [], references: [])`;
8119
+ }
8120
+ }
8121
+ return nodeDescription.name;
8122
+ }
8123
+ getAstNode(nodeDescription) {
8124
+ let node = nodeDescription.node;
8125
+ if (!node) {
8126
+ const doc = this.getOrCreateDocumentSync(nodeDescription);
8127
+ if (!doc) {
8128
+ return void 0;
8129
+ }
8130
+ node = this.services.workspace.AstNodeLocator.getAstNode(doc.parseResult.value, nodeDescription.path);
8131
+ if (!node) {
8132
+ return void 0;
8133
+ }
8134
+ }
8135
+ return node;
8136
+ }
8137
+ getOrCreateDocumentSync(nodeDescription) {
8138
+ let doc = this.services.shared.workspace.LangiumDocuments.getDocument(nodeDescription.documentUri);
8139
+ if (!doc) {
8140
+ try {
8141
+ const content = fs2.readFileSync(nodeDescription.documentUri.fsPath, "utf-8");
8142
+ doc = this.services.shared.workspace.LangiumDocuments.createDocument(nodeDescription.documentUri, content);
8143
+ } catch {
8144
+ console.warn("Failed to read or create document:", nodeDescription.documentUri);
8145
+ return void 0;
8146
+ }
8147
+ }
8148
+ return doc;
8149
+ }
8150
+ getNodeDocumentation(node) {
8151
+ if (!node) {
8152
+ return void 0;
8153
+ }
8154
+ const md = this.commentsToMarkdown(node);
8155
+ return {
8156
+ kind: "markdown",
8157
+ value: md
8158
+ };
8159
+ }
8160
+ commentsToMarkdown(node) {
8161
+ const md = this.services.documentation.DocumentationProvider.getDocumentation(node) ?? "";
8162
+ const zModelGenerator = new ZModelCodeGenerator();
8163
+ const docs = [];
8164
+ try {
8165
+ match3(node).when(isAttribute, (attr) => {
8166
+ docs.push("```prisma", zModelGenerator.generate(attr), "```");
8167
+ }).when(isFunctionDecl, (func2) => {
8168
+ docs.push("```ts", zModelGenerator.generate(func2), "```");
8169
+ }).when(isDataModel, (model) => {
8170
+ docs.push("```prisma", `model ${model.name} { ... }`, "```");
8171
+ }).when(isEnum, (enumDecl) => {
8172
+ docs.push("```prisma", zModelGenerator.generate(enumDecl), "```");
8173
+ }).when(isDataField, (field) => {
8174
+ docs.push(`${field.name}: ${field.type.type ?? field.type.reference?.$refText}`);
8175
+ }).otherwise((ast) => {
8176
+ const name = ast.name;
8177
+ if (name) {
8178
+ docs.push(name);
8179
+ }
8180
+ });
8181
+ } catch {
8182
+ }
8183
+ if (md) {
8184
+ docs.push("___", md);
8185
+ }
8186
+ return docs.join("\n");
8187
+ }
8188
+ };
8189
+
8190
+ // src/zmodel-definition.ts
8191
+ import { DefaultDefinitionProvider } from "langium/lsp";
8192
+ import { LocationLink, Range } from "vscode-languageserver";
8193
+ var ZModelDefinitionProvider = class extends DefaultDefinitionProvider {
8194
+ static {
8195
+ __name(this, "ZModelDefinitionProvider");
8196
+ }
8197
+ documents;
8198
+ constructor(services) {
8199
+ super(services);
8200
+ this.documents = services.shared.workspace.LangiumDocuments;
8201
+ }
8202
+ collectLocationLinks(sourceCstNode, _params) {
8203
+ if (isModelImport(sourceCstNode.astNode)) {
8204
+ const importedModel = resolveImport(this.documents, sourceCstNode.astNode);
8205
+ if (importedModel?.$document) {
8206
+ const targetObject = importedModel;
8207
+ const selectionRange = this.nameProvider.getNameNode(targetObject)?.range ?? Range.create(0, 0, 0, 0);
8208
+ const previewRange = targetObject.$cstNode?.range ?? Range.create(0, 0, 0, 0);
8209
+ return [
8210
+ LocationLink.create(importedModel.$document.uri.toString(), previewRange, selectionRange, sourceCstNode.range)
8211
+ ];
8212
+ }
8213
+ return void 0;
8214
+ }
8215
+ return super.collectLocationLinks(sourceCstNode, _params);
8216
+ }
8217
+ };
8218
+
7106
8219
  // src/zmodel-document-builder.ts
7107
8220
  import { DefaultDocumentBuilder } from "langium";
7108
8221
  var ZModelDocumentBuilder = class extends DefaultDocumentBuilder {
@@ -7132,9 +8245,114 @@ var ZModelDocumentBuilder = class extends DefaultDocumentBuilder {
7132
8245
  }
7133
8246
  };
7134
8247
 
8248
+ // src/zmodel-documentation-provider.ts
8249
+ import { JSDocDocumentationProvider } from "langium";
8250
+ var ZModelDocumentationProvider = class extends JSDocDocumentationProvider {
8251
+ static {
8252
+ __name(this, "ZModelDocumentationProvider");
8253
+ }
8254
+ getDocumentation(node) {
8255
+ if ("comments" in node && Array.isArray(node.comments) && node.comments.length > 0) {
8256
+ return node.comments.map((c) => c.replace(/^[/]*\s*/, "")).join("\n");
8257
+ }
8258
+ return super.getDocumentation(node);
8259
+ }
8260
+ };
8261
+
8262
+ // src/zmodel-formatter.ts
8263
+ import { AbstractFormatter, Formatting } from "langium/lsp";
8264
+ var ZModelFormatter = class extends AbstractFormatter {
8265
+ static {
8266
+ __name(this, "ZModelFormatter");
8267
+ }
8268
+ formatOptions;
8269
+ configurationProvider;
8270
+ constructor(services) {
8271
+ super();
8272
+ this.configurationProvider = services.shared.workspace.ConfigurationProvider;
8273
+ }
8274
+ format(node) {
8275
+ const formatter = this.getNodeFormatter(node);
8276
+ if (isDataField(node)) {
8277
+ if (isDataModel(node.$container) || isTypeDef(node.$container)) {
8278
+ const dataModel = node.$container;
8279
+ const compareFn = /* @__PURE__ */ __name((a, b) => b - a, "compareFn");
8280
+ const maxNameLength = dataModel.fields.map((x) => x.name.length).sort(compareFn)[0] ?? 0;
8281
+ const maxTypeLength = dataModel.fields.map(this.getFieldTypeLength).sort(compareFn)[0] ?? 0;
8282
+ formatter.property("type").prepend(Formatting.spaces(maxNameLength - node.name.length + 1));
8283
+ if (node.attributes.length > 0) {
8284
+ formatter.node(node.attributes[0]).prepend(Formatting.spaces(maxTypeLength - this.getFieldTypeLength(node) + 1));
8285
+ formatter.nodes(...node.attributes.slice(1)).prepend(Formatting.oneSpace());
8286
+ }
8287
+ } else {
8288
+ formatter.property("type").prepend(Formatting.oneSpace());
8289
+ if (node.attributes.length > 0) {
8290
+ formatter.properties("attributes").prepend(Formatting.oneSpace());
8291
+ }
8292
+ }
8293
+ } else if (isDataFieldAttribute(node)) {
8294
+ formatter.keyword("(").surround(Formatting.noSpace());
8295
+ formatter.keyword(")").prepend(Formatting.noSpace());
8296
+ formatter.keyword(",").append(Formatting.oneSpace());
8297
+ if (node.args.length > 1) {
8298
+ formatter.nodes(...node.args.slice(1)).prepend(Formatting.oneSpace());
8299
+ }
8300
+ } else if (isAttributeArg(node)) {
8301
+ formatter.keyword(":").prepend(Formatting.noSpace());
8302
+ formatter.keyword(":").append(Formatting.oneSpace());
8303
+ } else if (isAbstractDeclaration(node)) {
8304
+ const bracesOpen = formatter.keyword("{");
8305
+ const bracesClose = formatter.keyword("}");
8306
+ formatter.interior(bracesOpen, bracesClose).prepend(Formatting.indent({
8307
+ allowMore: true
8308
+ }));
8309
+ bracesOpen.prepend(Formatting.oneSpace());
8310
+ bracesClose.prepend(Formatting.newLine());
8311
+ } else if (isModel(node)) {
8312
+ const model = node;
8313
+ const nodes = formatter.nodes(...model.declarations);
8314
+ nodes.prepend(Formatting.noIndent());
8315
+ }
8316
+ }
8317
+ formatDocument(document, params) {
8318
+ this.formatOptions = params.options;
8319
+ this.configurationProvider.getConfiguration(ZModelLanguageMetaData.languageId, "format").then((config) => {
8320
+ if (config) {
8321
+ }
8322
+ });
8323
+ return super.formatDocument(document, params);
8324
+ }
8325
+ getFormatOptions() {
8326
+ return this.formatOptions;
8327
+ }
8328
+ getIndent() {
8329
+ return 1;
8330
+ }
8331
+ getFieldTypeLength(field) {
8332
+ let length;
8333
+ if (field.type.type) {
8334
+ length = field.type.type.length;
8335
+ } else if (field.type.reference) {
8336
+ length = field.type.reference.$refText.length;
8337
+ } else if (isDataField(field) && field.type.unsupported) {
8338
+ const name = `Unsupported("${field.type.unsupported.value.value}")`;
8339
+ length = name.length;
8340
+ } else {
8341
+ length = 1;
8342
+ }
8343
+ if (field.type.optional) {
8344
+ length += 1;
8345
+ }
8346
+ if (field.type.array) {
8347
+ length += 2;
8348
+ }
8349
+ return length;
8350
+ }
8351
+ };
8352
+
7135
8353
  // src/zmodel-linker.ts
7136
8354
  import { AstUtils as AstUtils6, Cancellation, DefaultLinker, DocumentState, interruptAndCheck } from "langium";
7137
- import { match as match2 } from "ts-pattern";
8355
+ import { match as match4 } from "ts-pattern";
7138
8356
  var ZModelLinker = class extends DefaultLinker {
7139
8357
  static {
7140
8358
  __name(this, "ZModelLinker");
@@ -7323,7 +8541,7 @@ var ZModelLinker = class extends DefaultLinker {
7323
8541
  }
7324
8542
  }
7325
8543
  resolveLiteral(node) {
7326
- const type = match2(node).when(isStringLiteral, () => "String").when(isBooleanLiteral, () => "Boolean").when(isNumberLiteral, () => "Int").exhaustive();
8544
+ const type = match4(node).when(isStringLiteral, () => "String").when(isBooleanLiteral, () => "Boolean").when(isNumberLiteral, () => "Int").exhaustive();
7327
8545
  if (type) {
7328
8546
  this.resolveToBuiltinTypeOrDecl(node, type);
7329
8547
  }
@@ -7491,7 +8709,7 @@ var ZModelLinker = class extends DefaultLinker {
7491
8709
 
7492
8710
  // src/zmodel-scope.ts
7493
8711
  import { AstUtils as AstUtils7, DefaultScopeComputation, DefaultScopeProvider, EMPTY_SCOPE, StreamScope, UriUtils, interruptAndCheck as interruptAndCheck2 } from "langium";
7494
- import { match as match3 } from "ts-pattern";
8712
+ import { match as match5 } from "ts-pattern";
7495
8713
  var ZModelScopeComputation = class extends DefaultScopeComputation {
7496
8714
  static {
7497
8715
  __name(this, "ZModelScopeComputation");
@@ -7564,11 +8782,8 @@ var ZModelScopeProvider = class extends DefaultScopeProvider {
7564
8782
  const referenceType = this.reflection.getReferenceType(context);
7565
8783
  const globalScope = this.getGlobalScope(referenceType, context);
7566
8784
  const node = context.container;
7567
- const allowTypeDefScope = (
7568
- // isAuthOrAuthMemberAccess(node.operand) ||
7569
- !!AstUtils7.getContainerOfType(node, isTypeDef)
7570
- );
7571
- return match3(node.operand).when(isReferenceExpr, (operand) => {
8785
+ const allowTypeDefScope = isAuthOrAuthMemberAccess(node.operand) || !!AstUtils7.getContainerOfType(node, isTypeDef);
8786
+ return match5(node.operand).when(isReferenceExpr, (operand) => {
7572
8787
  const ref = operand.target.ref;
7573
8788
  if (isDataField(ref)) {
7574
8789
  return this.createScopeForContainer(ref.type.reference?.ref, globalScope, allowTypeDefScope);
@@ -7596,8 +8811,8 @@ var ZModelScopeProvider = class extends DefaultScopeProvider {
7596
8811
  const referenceType = this.reflection.getReferenceType(context);
7597
8812
  const globalScope = this.getGlobalScope(referenceType, context);
7598
8813
  const collection = collectionPredicate.left;
7599
- const allowTypeDefScope = false;
7600
- return match3(collection).when(isReferenceExpr, (expr) => {
8814
+ const allowTypeDefScope = isAuthOrAuthMemberAccess(collection);
8815
+ return match5(collection).when(isReferenceExpr, (expr) => {
7601
8816
  const ref = expr.target.ref;
7602
8817
  if (isDataField(ref)) {
7603
8818
  return this.createScopeForContainer(ref.type.reference?.ref, globalScope, allowTypeDefScope);
@@ -7659,11 +8874,95 @@ function getCollectionPredicateContext(node) {
7659
8874
  }
7660
8875
  __name(getCollectionPredicateContext, "getCollectionPredicateContext");
7661
8876
 
8877
+ // src/zmodel-semantic.ts
8878
+ import { AbstractSemanticTokenProvider } from "langium/lsp";
8879
+ import { SemanticTokenTypes } from "vscode-languageserver";
8880
+ var ZModelSemanticTokenProvider = class extends AbstractSemanticTokenProvider {
8881
+ static {
8882
+ __name(this, "ZModelSemanticTokenProvider");
8883
+ }
8884
+ highlightElement(node, acceptor) {
8885
+ if (isDataModel(node)) {
8886
+ acceptor({
8887
+ node,
8888
+ property: "name",
8889
+ type: SemanticTokenTypes.type
8890
+ });
8891
+ acceptor({
8892
+ node,
8893
+ property: "mixins",
8894
+ type: SemanticTokenTypes.type
8895
+ });
8896
+ acceptor({
8897
+ node,
8898
+ property: "baseModel",
8899
+ type: SemanticTokenTypes.type
8900
+ });
8901
+ } else if (isDataSource(node) || isGeneratorDecl(node) || isPlugin(node) || isEnum(node) || isTypeDef(node)) {
8902
+ acceptor({
8903
+ node,
8904
+ property: "name",
8905
+ type: SemanticTokenTypes.type
8906
+ });
8907
+ } else if (isDataField(node) || isConfigField(node) || isAttributeArg(node) || isPluginField(node) || isEnumField(node)) {
8908
+ acceptor({
8909
+ node,
8910
+ property: "name",
8911
+ type: SemanticTokenTypes.variable
8912
+ });
8913
+ } else if (isDataFieldType(node)) {
8914
+ if (node.type) {
8915
+ acceptor({
8916
+ node,
8917
+ property: "type",
8918
+ type: SemanticTokenTypes.type
8919
+ });
8920
+ } else {
8921
+ acceptor({
8922
+ node,
8923
+ property: "reference",
8924
+ type: SemanticTokenTypes.macro
8925
+ });
8926
+ }
8927
+ } else if (isDataModelAttribute(node) || isDataFieldAttribute(node) || isInternalAttribute(node)) {
8928
+ acceptor({
8929
+ node,
8930
+ property: "decl",
8931
+ type: SemanticTokenTypes.function
8932
+ });
8933
+ } else if (isInvocationExpr(node)) {
8934
+ acceptor({
8935
+ node,
8936
+ property: "function",
8937
+ type: SemanticTokenTypes.function
8938
+ });
8939
+ } else if (isFunctionDecl(node) || isAttribute(node)) {
8940
+ acceptor({
8941
+ node,
8942
+ property: "name",
8943
+ type: SemanticTokenTypes.function
8944
+ });
8945
+ } else if (isReferenceExpr(node)) {
8946
+ acceptor({
8947
+ node,
8948
+ property: "target",
8949
+ type: SemanticTokenTypes.variable
8950
+ });
8951
+ } else if (isMemberAccessExpr(node)) {
8952
+ acceptor({
8953
+ node,
8954
+ property: "member",
8955
+ type: SemanticTokenTypes.property
8956
+ });
8957
+ }
8958
+ }
8959
+ };
8960
+
7662
8961
  // src/zmodel-workspace-manager.ts
7663
- import { DefaultWorkspaceManager, URI as URI2, UriUtils as UriUtils2 } from "langium";
7664
- import fs2 from "fs";
8962
+ import { DefaultWorkspaceManager, URI as URI2 } from "langium";
8963
+ import fs3 from "fs";
7665
8964
  import path2 from "path";
7666
- import { fileURLToPath } from "url";
8965
+ import { fileURLToPath as fileURLToPath2 } from "url";
7667
8966
  var ZModelWorkspaceManager = class extends DefaultWorkspaceManager {
7668
8967
  static {
7669
8968
  __name(this, "ZModelWorkspaceManager");
@@ -7687,7 +8986,7 @@ var ZModelWorkspaceManager = class extends DefaultWorkspaceManager {
7687
8986
  });
7688
8987
  const languagePackageDir = path2.dirname(languagePackagePath);
7689
8988
  const candidateStdlibPath = path2.join(languagePackageDir, "res", STD_LIB_MODULE_NAME);
7690
- if (fs2.existsSync(candidateStdlibPath)) {
8989
+ if (fs3.existsSync(candidateStdlibPath)) {
7691
8990
  installedStdlibPath = candidateStdlibPath;
7692
8991
  console.log(`Found installed zenstack package stdlib at: ${installedStdlibPath}`);
7693
8992
  break;
@@ -7699,73 +8998,12 @@ var ZModelWorkspaceManager = class extends DefaultWorkspaceManager {
7699
8998
  if (installedStdlibPath) {
7700
8999
  stdLibPath = installedStdlibPath;
7701
9000
  } else {
7702
- const _dirname = typeof __dirname !== "undefined" ? __dirname : path2.dirname(fileURLToPath(import.meta.url));
9001
+ const _dirname = typeof __dirname !== "undefined" ? __dirname : path2.dirname(fileURLToPath2(import.meta.url));
7703
9002
  stdLibPath = path2.join(_dirname, "../res", STD_LIB_MODULE_NAME);
7704
9003
  console.log(`Using bundled stdlib in extension:`, stdLibPath);
7705
9004
  }
7706
9005
  const stdlib = await this.documentFactory.fromUri(URI2.file(stdLibPath));
7707
9006
  collector(stdlib);
7708
- const documents = this.langiumDocuments.all;
7709
- const pluginModels = /* @__PURE__ */ new Set();
7710
- documents.forEach((doc) => {
7711
- const parsed = doc.parseResult.value;
7712
- parsed.declarations.forEach((decl) => {
7713
- if (isPlugin(decl)) {
7714
- const providerField = decl.fields.find((f) => f.name === "provider");
7715
- if (providerField) {
7716
- const provider = getLiteral(providerField.value);
7717
- if (provider) {
7718
- pluginModels.add(provider);
7719
- }
7720
- }
7721
- }
7722
- });
7723
- });
7724
- if (pluginModels.size > 0) {
7725
- console.log(`Used plugin modules: ${Array.from(pluginModels)}`);
7726
- const pendingPluginModules = new Set(pluginModels);
7727
- await Promise.all(folders.map((wf) => [
7728
- wf,
7729
- this.getRootFolder(wf)
7730
- ]).map(async (entry) => this.loadPluginModels(...entry, pendingPluginModules, collector)));
7731
- }
7732
- }
7733
- async loadPluginModels(workspaceFolder, folderPath, pendingPluginModels, collector) {
7734
- const content = (await this.fileSystemProvider.readDirectory(folderPath)).sort((a, b) => {
7735
- if (a.isDirectory && b.isDirectory) {
7736
- const aName = UriUtils2.basename(a.uri);
7737
- if (aName === "node_modules") {
7738
- return -1;
7739
- } else {
7740
- return 1;
7741
- }
7742
- } else {
7743
- return 0;
7744
- }
7745
- });
7746
- for (const entry of content) {
7747
- if (entry.isDirectory) {
7748
- const name = UriUtils2.basename(entry.uri);
7749
- if (name === "node_modules") {
7750
- for (const plugin of Array.from(pendingPluginModels)) {
7751
- const path4 = UriUtils2.joinPath(entry.uri, plugin, PLUGIN_MODULE_NAME);
7752
- try {
7753
- await this.fileSystemProvider.readFile(path4);
7754
- const document = await this.langiumDocuments.getOrCreateDocument(path4);
7755
- collector(document);
7756
- console.log(`Adding plugin document from ${path4.path}`);
7757
- pendingPluginModels.delete(plugin);
7758
- if (pendingPluginModels.size === 0) {
7759
- return;
7760
- }
7761
- } catch {
7762
- }
7763
- }
7764
- } else {
7765
- await this.loadPluginModels(workspaceFolder, entry.uri, pendingPluginModels, collector);
7766
- }
7767
- }
7768
- }
7769
9007
  }
7770
9008
  };
7771
9009
 
@@ -7778,6 +9016,16 @@ var ZModelLanguageModule = {
7778
9016
  },
7779
9017
  validation: {
7780
9018
  ZModelValidator: /* @__PURE__ */ __name((services) => new ZModelValidator(services), "ZModelValidator")
9019
+ },
9020
+ lsp: {
9021
+ Formatter: /* @__PURE__ */ __name((services) => new ZModelFormatter(services), "Formatter"),
9022
+ DefinitionProvider: /* @__PURE__ */ __name((services) => new ZModelDefinitionProvider(services), "DefinitionProvider"),
9023
+ CompletionProvider: /* @__PURE__ */ __name((services) => new ZModelCompletionProvider(services), "CompletionProvider"),
9024
+ SemanticTokenProvider: /* @__PURE__ */ __name((services) => new ZModelSemanticTokenProvider(services), "SemanticTokenProvider")
9025
+ },
9026
+ documentation: {
9027
+ CommentProvider: /* @__PURE__ */ __name((services) => new ZModelCommentProvider(services), "CommentProvider"),
9028
+ DocumentationProvider: /* @__PURE__ */ __name((services) => new ZModelDocumentationProvider(services), "DocumentationProvider")
7781
9029
  }
7782
9030
  };
7783
9031
  var ZModelSharedModule = {
@@ -7786,7 +9034,7 @@ var ZModelSharedModule = {
7786
9034
  WorkspaceManager: /* @__PURE__ */ __name((services) => new ZModelWorkspaceManager(services), "WorkspaceManager")
7787
9035
  }
7788
9036
  };
7789
- function createZModelLanguageServices(context) {
9037
+ function createZModelLanguageServices(context, logToConsole = false) {
7790
9038
  const shared = inject(createDefaultSharedModule(context), ZModelGeneratedSharedModule, ZModelSharedModule);
7791
9039
  const ZModelLanguage = inject(createDefaultModule({
7792
9040
  shared
@@ -7796,30 +9044,47 @@ function createZModelLanguageServices(context) {
7796
9044
  if (!context.connection) {
7797
9045
  shared.workspace.ConfigurationProvider.initialized({});
7798
9046
  }
9047
+ shared.workspace.DocumentBuilder.onBuildPhase(DocumentState2.Parsed, async (documents) => {
9048
+ for (const doc of documents) {
9049
+ if (doc.parseResult.lexerErrors.length > 0 || doc.parseResult.parserErrors.length > 0) {
9050
+ continue;
9051
+ }
9052
+ if (doc.uri.scheme !== "file") {
9053
+ continue;
9054
+ }
9055
+ const schemaPath = fileURLToPath3(doc.uri.toString());
9056
+ const pluginSchemas = getPluginDocuments(doc.parseResult.value, schemaPath);
9057
+ for (const plugin of pluginSchemas) {
9058
+ const pluginDocUri = URI3.file(path3.resolve(plugin));
9059
+ let pluginDoc = shared.workspace.LangiumDocuments.getDocument(pluginDocUri);
9060
+ if (!pluginDoc) {
9061
+ pluginDoc = await shared.workspace.LangiumDocuments.getOrCreateDocument(pluginDocUri);
9062
+ if (pluginDoc) {
9063
+ shared.workspace.IndexManager.updateContent(pluginDoc);
9064
+ if (logToConsole) {
9065
+ console.log(`Loaded plugin model: ${plugin}`);
9066
+ }
9067
+ }
9068
+ }
9069
+ }
9070
+ }
9071
+ });
7799
9072
  return {
7800
9073
  shared,
7801
9074
  ZModelLanguage
7802
9075
  };
7803
9076
  }
7804
9077
  __name(createZModelLanguageServices, "createZModelLanguageServices");
7805
-
7806
- // src/index.ts
7807
- function createZModelServices() {
7808
- return createZModelLanguageServices(NodeFileSystem);
9078
+ function createZModelServices(logToConsole = false) {
9079
+ return createZModelLanguageServices(NodeFileSystem, logToConsole);
7809
9080
  }
7810
9081
  __name(createZModelServices, "createZModelServices");
7811
- var DocumentLoadError = class extends Error {
7812
- static {
7813
- __name(this, "DocumentLoadError");
7814
- }
7815
- constructor(message) {
7816
- super(message);
7817
- }
7818
- };
9082
+
9083
+ // src/document.ts
7819
9084
  async function loadDocument(fileName, additionalModelFiles = []) {
7820
- const { ZModelLanguage: services } = createZModelServices();
9085
+ const { ZModelLanguage: services } = createZModelServices(false);
7821
9086
  const extensions = services.LanguageMetaData.fileExtensions;
7822
- if (!extensions.includes(path3.extname(fileName))) {
9087
+ if (!extensions.includes(path4.extname(fileName))) {
7823
9088
  return {
7824
9089
  success: false,
7825
9090
  errors: [
@@ -7828,7 +9093,7 @@ async function loadDocument(fileName, additionalModelFiles = []) {
7828
9093
  warnings: []
7829
9094
  };
7830
9095
  }
7831
- if (!fs3.existsSync(fileName)) {
9096
+ if (!fs4.existsSync(fileName)) {
7832
9097
  return {
7833
9098
  success: false,
7834
9099
  errors: [
@@ -7837,19 +9102,19 @@ async function loadDocument(fileName, additionalModelFiles = []) {
7837
9102
  warnings: []
7838
9103
  };
7839
9104
  }
7840
- const _dirname = typeof __dirname !== "undefined" ? __dirname : path3.dirname(fileURLToPath2(import.meta.url));
7841
- const stdLib = await services.shared.workspace.LangiumDocuments.getOrCreateDocument(URI3.file(path3.resolve(path3.join(_dirname, "../res", STD_LIB_MODULE_NAME))));
7842
- const pluginDocs = await Promise.all(additionalModelFiles.map((file) => services.shared.workspace.LangiumDocuments.getOrCreateDocument(URI3.file(path3.resolve(file)))));
9105
+ const _dirname = typeof __dirname !== "undefined" ? __dirname : path4.dirname(fileURLToPath4(import.meta.url));
9106
+ const stdLib = await services.shared.workspace.LangiumDocuments.getOrCreateDocument(URI4.file(path4.resolve(path4.join(_dirname, "../res", STD_LIB_MODULE_NAME))));
7843
9107
  const langiumDocuments = services.shared.workspace.LangiumDocuments;
7844
- const document = await langiumDocuments.getOrCreateDocument(URI3.file(path3.resolve(fileName)));
9108
+ const document = await langiumDocuments.getOrCreateDocument(URI4.file(path4.resolve(fileName)));
7845
9109
  const importedURIs = await loadImports(document, langiumDocuments);
7846
9110
  const importedDocuments = [];
7847
9111
  for (const uri of importedURIs) {
7848
9112
  importedDocuments.push(await langiumDocuments.getOrCreateDocument(uri));
7849
9113
  }
9114
+ const additionalDocs = await Promise.all(additionalModelFiles.map((file) => services.shared.workspace.LangiumDocuments.getOrCreateDocument(URI4.file(path4.resolve(file)))));
7850
9115
  await services.shared.workspace.DocumentBuilder.build([
7851
9116
  stdLib,
7852
- ...pluginDocs,
9117
+ ...additionalDocs,
7853
9118
  document,
7854
9119
  ...importedDocuments
7855
9120
  ], {
@@ -7867,7 +9132,7 @@ async function loadDocument(fileName, additionalModelFiles = []) {
7867
9132
  const warnings = [];
7868
9133
  if (diagnostics.length > 0) {
7869
9134
  for (const { doc, diag } of diagnostics) {
7870
- const message = `${path3.relative(process.cwd(), doc.uri.fsPath)}:${diag.range.start.line + 1}:${diag.range.start.character + 1} - ${diag.message}`;
9135
+ const message = `${path4.relative(process.cwd(), doc.uri.fsPath)}:${diag.range.start.line + 1}:${diag.range.start.character + 1} - ${diag.message}`;
7871
9136
  if (diag.severity === 1) {
7872
9137
  errors.push(message);
7873
9138
  } else {
@@ -7916,7 +9181,7 @@ async function loadImports(document, documents, uris = /* @__PURE__ */ new Set()
7916
9181
  }
7917
9182
  }
7918
9183
  }
7919
- return Array.from(uris).filter((x) => uriString != x).map((e) => URI3.parse(e));
9184
+ return Array.from(uris).filter((x) => uriString != x).map((e) => URI4.parse(e));
7920
9185
  }
7921
9186
  __name(loadImports, "loadImports");
7922
9187
  function mergeImportsDeclarations(documents, model) {
@@ -7965,13 +9230,33 @@ function validationAfterImportMerge(model) {
7965
9230
  return errors;
7966
9231
  }
7967
9232
  __name(validationAfterImportMerge, "validationAfterImportMerge");
9233
+ async function formatDocument(content) {
9234
+ const services = createZModelServices().ZModelLanguage;
9235
+ const langiumDocuments = services.shared.workspace.LangiumDocuments;
9236
+ const document = langiumDocuments.createDocument(URI4.parse("memory://schema.zmodel"), content);
9237
+ const formatter = services.lsp.Formatter;
9238
+ const identifier = {
9239
+ uri: document.uri.toString()
9240
+ };
9241
+ const options = formatter.getFormatOptions() ?? {
9242
+ insertSpaces: true,
9243
+ tabSize: 4
9244
+ };
9245
+ const edits = await formatter.formatDocument(document, {
9246
+ options,
9247
+ textDocument: identifier
9248
+ });
9249
+ return TextDocument.applyEdits(document.textDocument, edits);
9250
+ }
9251
+ __name(formatDocument, "formatDocument");
7968
9252
  export {
7969
- DocumentLoadError,
9253
+ ZModelCodeGenerator,
7970
9254
  ZModelLanguageMetaData,
7971
9255
  ZModelLanguageModule,
7972
9256
  ZModelSharedModule,
7973
9257
  createZModelLanguageServices,
7974
9258
  createZModelServices,
9259
+ formatDocument,
7975
9260
  loadDocument
7976
9261
  };
7977
9262
  //# sourceMappingURL=index.js.map