@zenstackhq/sdk 3.0.0-beta.2 → 3.0.0-beta.21

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
@@ -20,7 +20,7 @@ __export(model_utils_exports, {
20
20
  isUniqueField: () => isUniqueField,
21
21
  resolved: () => resolved
22
22
  });
23
- import { isDataModel, isLiteralExpr, isModel } from "@zenstackhq/language/ast";
23
+ import { isDataModel, isLiteralExpr, isModel, isTypeDef } from "@zenstackhq/language/ast";
24
24
  import { getAllFields, getModelIdFields, getModelUniqueFields } from "@zenstackhq/language/utils";
25
25
  function isIdField(field, contextModel) {
26
26
  if (hasAttribute(field, "@id")) {
@@ -88,7 +88,7 @@ function resolved(ref) {
88
88
  }
89
89
  __name(resolved, "resolved");
90
90
  function getAuthDecl(model) {
91
- let found = model.declarations.find((d) => isDataModel(d) && d.attributes.some((attr) => attr.decl.$refText === "@@auth"));
91
+ let found = model.declarations.find((d) => (isDataModel(d) || isTypeDef(d)) && d.attributes.some((attr) => attr.decl.$refText === "@@auth"));
92
92
  if (!found) {
93
93
  found = model.declarations.find((d) => isDataModel(d) && d.name === "User");
94
94
  }
@@ -103,8 +103,9 @@ var DELEGATE_AUX_RELATION_PREFIX = "delegate_aux";
103
103
 
104
104
  // src/prisma/prisma-schema-generator.ts
105
105
  import { lowerCaseFirst } from "@zenstackhq/common-helpers";
106
- import { BooleanLiteral, DataModel, DataSource as DataSource2, Enum as Enum2, GeneratorDecl, isArrayExpr, isDataModel as isDataModel2, isInvocationExpr, isLiteralExpr as isLiteralExpr2, isModel as isModel2, isNullExpr, isReferenceExpr, isStringLiteral, isTypeDef, NumberLiteral, StringLiteral } from "@zenstackhq/language/ast";
107
- import { getAllAttributes, getAllFields as getAllFields2, isDelegateModel as isDelegateModel2 } from "@zenstackhq/language/utils";
106
+ import { ZModelCodeGenerator } from "@zenstackhq/language";
107
+ import { BooleanLiteral, DataModel, DataSource as DataSource2, Enum as Enum2, GeneratorDecl, isArrayExpr, isDataModel as isDataModel2, isDataSource, isInvocationExpr, isLiteralExpr as isLiteralExpr2, isNullExpr, isReferenceExpr, isStringLiteral, isTypeDef as isTypeDef2, NumberLiteral, StringLiteral } from "@zenstackhq/language/ast";
108
+ import { getAllAttributes, getAllFields as getAllFields2, getStringLiteral, isAuthInvocation, isDelegateModel as isDelegateModel2 } from "@zenstackhq/language/utils";
108
109
  import { AstUtils } from "langium";
109
110
  import { match } from "ts-pattern";
110
111
 
@@ -500,6 +501,9 @@ var EnumField = class extends DeclarationBase {
500
501
 
501
502
  // src/prisma/prisma-schema-generator.ts
502
503
  var IDENTIFIER_NAME_MAX_LENGTH = 50 - DELEGATE_AUX_RELATION_PREFIX.length;
504
+ var NON_PRISMA_DATASOURCE_FIELDS = [
505
+ "defaultSchema"
506
+ ];
503
507
  var PrismaSchemaGenerator = class {
504
508
  static {
505
509
  __name(this, "PrismaSchemaGenerator");
@@ -537,7 +541,7 @@ var PrismaSchemaGenerator = class {
537
541
  return this.PRELUDE + prisma.toString();
538
542
  }
539
543
  generateDataSource(prisma, dataSource) {
540
- const fields = dataSource.fields.map((f) => ({
544
+ const fields = dataSource.fields.filter((f) => !NON_PRISMA_DATASOURCE_FIELDS.includes(f.name)).map((f) => ({
541
545
  name: f.name,
542
546
  text: this.configExprToText(f.value)
543
547
  }));
@@ -585,14 +589,37 @@ var PrismaSchemaGenerator = class {
585
589
  this.generateModelField(model, field, decl);
586
590
  }
587
591
  }
588
- const allAttributes = getAllAttributes(decl);
589
- for (const attr of allAttributes.filter((attr2) => this.isPrismaAttribute(attr2))) {
592
+ const allAttributes = getAllAttributes(decl).filter((attr) => this.isPrismaAttribute(attr) && !this.isInheritedMapAttribute(attr, decl));
593
+ for (const attr of allAttributes) {
590
594
  this.generateContainerAttribute(model, attr);
591
595
  }
596
+ if (this.datasourceHasSchemasSetting(decl.$container) && !allAttributes.some((attr) => attr.decl.ref?.name === "@@schema")) {
597
+ model.addAttribute("@@schema", [
598
+ new AttributeArg(void 0, new AttributeArgValue("String", this.getDefaultPostgresSchemaName(decl.$container)))
599
+ ]);
600
+ }
592
601
  decl.comments.forEach((c) => model.addComment(c));
593
602
  this.generateDelegateRelationForBase(model, decl);
594
603
  this.generateDelegateRelationForConcrete(model, decl);
595
604
  }
605
+ getDatasourceField(zmodel, fieldName) {
606
+ const dataSource = zmodel.declarations.find(isDataSource);
607
+ return dataSource?.fields.find((f) => f.name === fieldName);
608
+ }
609
+ datasourceHasSchemasSetting(zmodel) {
610
+ return !!this.getDatasourceField(zmodel, "schemas");
611
+ }
612
+ getDefaultPostgresSchemaName(zmodel) {
613
+ const defaultSchemaField = this.getDatasourceField(zmodel, "defaultSchema");
614
+ return getStringLiteral(defaultSchemaField?.value) ?? "public";
615
+ }
616
+ isInheritedMapAttribute(attr, contextModel) {
617
+ if (attr.$container === contextModel) {
618
+ return false;
619
+ }
620
+ const attrName = attr.decl.ref?.name ?? attr.decl.$refText;
621
+ return attrName === "@@map";
622
+ }
596
623
  isPrismaAttribute(attr) {
597
624
  if (!attr.decl.ref) {
598
625
  return false;
@@ -601,7 +628,7 @@ var PrismaSchemaGenerator = class {
601
628
  }
602
629
  getUnsupportedFieldType(fieldType) {
603
630
  if (fieldType.unsupported) {
604
- const value = this.getStringLiteral(fieldType.unsupported.value);
631
+ const value = getStringLiteral(fieldType.unsupported.value);
605
632
  if (value) {
606
633
  return `Unsupported("${value}")`;
607
634
  } else {
@@ -611,15 +638,12 @@ var PrismaSchemaGenerator = class {
611
638
  return void 0;
612
639
  }
613
640
  }
614
- getStringLiteral(node) {
615
- return isStringLiteral(node) ? node.value : void 0;
616
- }
617
641
  generateModelField(model, field, contextModel, addToFront = false) {
618
642
  let fieldType;
619
643
  if (field.type.type) {
620
644
  fieldType = field.type.type;
621
645
  } else if (field.type.reference?.ref) {
622
- if (isTypeDef(field.type.reference.ref)) {
646
+ if (isTypeDef2(field.type.reference.ref)) {
623
647
  fieldType = "Json";
624
648
  } else {
625
649
  fieldType = field.type.reference.ref.name;
@@ -635,10 +659,10 @@ var PrismaSchemaGenerator = class {
635
659
  }
636
660
  const isArray = (
637
661
  // typed-JSON fields should be translated to scalar Json type
638
- isTypeDef(field.type.reference?.ref) ? false : field.type.array
662
+ isTypeDef2(field.type.reference?.ref) ? false : field.type.array
639
663
  );
640
664
  const type = new ModelFieldType(fieldType, isArray, field.type.optional);
641
- const attributes = field.attributes.filter((attr) => this.isPrismaAttribute(attr)).filter((attr) => !this.isDefaultWithPluginInvocation(attr)).filter((attr) => (
665
+ const attributes = field.attributes.filter((attr) => this.isPrismaAttribute(attr)).filter((attr) => !this.isDefaultWithAuthInvocation(attr)).filter((attr) => (
642
666
  // when building physical schema, exclude `@default` for id fields inherited from delegate base
643
667
  !(model_utils_exports.isIdField(field, contextModel) && this.isInheritedFromDelegate(field, contextModel) && attr.decl.$refText === "@default")
644
668
  )).map((attr) => this.makeFieldAttribute(attr));
@@ -648,7 +672,7 @@ var PrismaSchemaGenerator = class {
648
672
  const result = model.addField(field.name, type, attributes, docs, addToFront);
649
673
  return result;
650
674
  }
651
- isDefaultWithPluginInvocation(attr) {
675
+ isDefaultWithAuthInvocation(attr) {
652
676
  if (attr.decl.ref?.name !== "@default") {
653
677
  return false;
654
678
  }
@@ -656,11 +680,7 @@ var PrismaSchemaGenerator = class {
656
680
  if (!expr) {
657
681
  return false;
658
682
  }
659
- return AstUtils.streamAst(expr).some((node) => isInvocationExpr(node) && this.isFromPlugin(node.function.ref));
660
- }
661
- isFromPlugin(node) {
662
- const model = AstUtils.getContainerOfType(node, isModel2);
663
- return !!model && !!model.$document && model.$document.uri.path.endsWith("plugin.zmodel");
683
+ return AstUtils.streamAst(expr).some(isAuthInvocation);
664
684
  }
665
685
  isInheritedFromDelegate(field, contextModel) {
666
686
  return field.$container !== contextModel && model_utils_exports.isDelegateModel(field.$container);
@@ -778,8 +798,8 @@ var PrismaSchemaGenerator = class {
778
798
 
779
799
  // src/ts-schema-generator.ts
780
800
  import { invariant } from "@zenstackhq/common-helpers";
781
- import { isArrayExpr as isArrayExpr2, isBinaryExpr, isDataField, isDataModel as isDataModel3, isDataSource, isEnum, isEnumField, isInvocationExpr as isInvocationExpr2, isLiteralExpr as isLiteralExpr3, isMemberAccessExpr, isNullExpr as isNullExpr2, isProcedure, isReferenceExpr as isReferenceExpr2, isThisExpr, isTypeDef as isTypeDef2, isUnaryExpr } from "@zenstackhq/language/ast";
782
- import { getAllAttributes as getAllAttributes2, getAllFields as getAllFields3, isDataFieldReference } from "@zenstackhq/language/utils";
801
+ import { isArrayExpr as isArrayExpr2, isBinaryExpr, isDataField, isDataModel as isDataModel3, isDataSource as isDataSource2, isEnum, isEnumField, isInvocationExpr as isInvocationExpr2, isLiteralExpr as isLiteralExpr3, isMemberAccessExpr, isNullExpr as isNullExpr2, isProcedure, isReferenceExpr as isReferenceExpr2, isThisExpr, isTypeDef as isTypeDef3, isUnaryExpr } from "@zenstackhq/language/ast";
802
+ import { getAllAttributes as getAllAttributes2, getAllFields as getAllFields3, getAttributeArg, isDataFieldReference } from "@zenstackhq/language/utils";
783
803
  import fs from "fs";
784
804
  import path from "path";
785
805
  import { match as match2 } from "ts-pattern";
@@ -788,38 +808,58 @@ var TsSchemaGenerator = class {
788
808
  static {
789
809
  __name(this, "TsSchemaGenerator");
790
810
  }
791
- async generate(model, outputDir) {
792
- fs.mkdirSync(outputDir, {
811
+ usedExpressionUtils = false;
812
+ async generate(model, options) {
813
+ fs.mkdirSync(options.outDir, {
793
814
  recursive: true
794
815
  });
795
- this.generateSchema(model, outputDir);
796
- this.generateModelsAndTypeDefs(model, outputDir);
797
- this.generateInputTypes(model, outputDir);
798
- }
799
- generateSchema(model, outputDir) {
800
- const statements = [];
801
- this.generateSchemaStatements(model, statements);
802
- this.generateBannerComments(statements);
803
- const schemaOutputFile = path.join(outputDir, "schema.ts");
804
- const sourceFile = ts.createSourceFile(schemaOutputFile, "", ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS);
805
- const printer = ts.createPrinter();
806
- const result = printer.printList(ts.ListFormat.MultiLine, ts.factory.createNodeArray(statements), sourceFile);
807
- fs.writeFileSync(schemaOutputFile, result);
816
+ this.usedExpressionUtils = false;
817
+ this.generateSchema(model, options);
818
+ this.generateModelsAndTypeDefs(model, options);
819
+ this.generateInputTypes(model, options);
820
+ }
821
+ generateSchema(model, options) {
822
+ const targets = [];
823
+ if (!options.liteOnly) {
824
+ targets.push({
825
+ lite: false,
826
+ file: "schema.ts"
827
+ });
828
+ }
829
+ if (options.lite || options.liteOnly) {
830
+ targets.push({
831
+ lite: true,
832
+ file: "schema-lite.ts"
833
+ });
834
+ }
835
+ for (const { lite, file } of targets) {
836
+ const statements = [];
837
+ this.generateSchemaStatements(model, statements, lite);
838
+ this.generateBannerComments(statements);
839
+ const schemaOutputFile = path.join(options.outDir, file);
840
+ const sourceFile = ts.createSourceFile(schemaOutputFile, "", ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS);
841
+ const printer = ts.createPrinter();
842
+ const result = printer.printList(ts.ListFormat.MultiLine, ts.factory.createNodeArray(statements), sourceFile);
843
+ fs.writeFileSync(schemaOutputFile, result);
844
+ }
808
845
  }
809
- generateSchemaStatements(model, statements) {
846
+ generateSchemaStatements(model, statements, lite) {
810
847
  const hasComputedFields = model.declarations.some((d) => isDataModel3(d) && d.fields.some((f) => hasAttribute(f, "@computed")));
848
+ const schemaObject = this.createSchemaObject(model, lite);
811
849
  const runtimeImportDecl = ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(false, void 0, ts.factory.createNamedImports([
812
850
  ts.factory.createImportSpecifier(true, void 0, ts.factory.createIdentifier("SchemaDef")),
813
851
  ...hasComputedFields ? [
814
852
  ts.factory.createImportSpecifier(true, void 0, ts.factory.createIdentifier("OperandExpression"))
815
853
  ] : [],
816
- ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier("ExpressionUtils"))
817
- ])), ts.factory.createStringLiteral("@zenstackhq/runtime/schema"));
854
+ ...this.usedExpressionUtils ? [
855
+ ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier("ExpressionUtils"))
856
+ ] : []
857
+ ])), ts.factory.createStringLiteral("@zenstackhq/orm/schema"));
818
858
  statements.push(runtimeImportDecl);
819
859
  const declaration = ts.factory.createVariableStatement([
820
860
  ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)
821
861
  ], ts.factory.createVariableDeclarationList([
822
- ts.factory.createVariableDeclaration("schema", void 0, void 0, ts.factory.createSatisfiesExpression(ts.factory.createAsExpression(this.createSchemaObject(model), ts.factory.createTypeReferenceNode("const")), ts.factory.createTypeReferenceNode("SchemaDef")))
862
+ ts.factory.createVariableDeclaration("schema", void 0, void 0, ts.factory.createSatisfiesExpression(ts.factory.createAsExpression(schemaObject, ts.factory.createTypeReferenceNode("const")), ts.factory.createTypeReferenceNode("SchemaDef")))
823
863
  ], ts.NodeFlags.Const));
824
864
  statements.push(declaration);
825
865
  const typeDeclaration = ts.factory.createTypeAliasDeclaration([
@@ -827,15 +867,19 @@ var TsSchemaGenerator = class {
827
867
  ], "SchemaType", void 0, ts.factory.createTypeReferenceNode("typeof schema"));
828
868
  statements.push(typeDeclaration);
829
869
  }
830
- createSchemaObject(model) {
870
+ createExpressionUtilsCall(method, args) {
871
+ this.usedExpressionUtils = true;
872
+ return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("ExpressionUtils"), method), void 0, args || []);
873
+ }
874
+ createSchemaObject(model, lite) {
831
875
  const properties = [
832
876
  // provider
833
877
  ts.factory.createPropertyAssignment("provider", this.createProviderObject(model)),
834
878
  // models
835
- ts.factory.createPropertyAssignment("models", this.createModelsObject(model)),
879
+ ts.factory.createPropertyAssignment("models", this.createModelsObject(model, lite)),
836
880
  // typeDefs
837
- ...model.declarations.some(isTypeDef2) ? [
838
- ts.factory.createPropertyAssignment("typeDefs", this.createTypeDefsObject(model))
881
+ ...model.declarations.some(isTypeDef3) ? [
882
+ ts.factory.createPropertyAssignment("typeDefs", this.createTypeDefsObject(model, lite))
839
883
  ] : []
840
884
  ];
841
885
  const enums = model.declarations.filter(isEnum);
@@ -855,19 +899,23 @@ var TsSchemaGenerator = class {
855
899
  }
856
900
  createProviderObject(model) {
857
901
  const dsProvider = this.getDataSourceProvider(model);
902
+ const defaultSchema = this.getDataSourceDefaultSchema(model);
858
903
  return ts.factory.createObjectLiteralExpression([
859
- ts.factory.createPropertyAssignment("type", ts.factory.createStringLiteral(dsProvider.type))
904
+ ts.factory.createPropertyAssignment("type", ts.factory.createStringLiteral(dsProvider)),
905
+ ...defaultSchema ? [
906
+ ts.factory.createPropertyAssignment("defaultSchema", ts.factory.createStringLiteral(defaultSchema))
907
+ ] : []
860
908
  ], true);
861
909
  }
862
- createModelsObject(model) {
863
- return ts.factory.createObjectLiteralExpression(model.declarations.filter((d) => isDataModel3(d) && !hasAttribute(d, "@@ignore")).map((dm) => ts.factory.createPropertyAssignment(dm.name, this.createDataModelObject(dm))), true);
910
+ createModelsObject(model, lite) {
911
+ return ts.factory.createObjectLiteralExpression(model.declarations.filter((d) => isDataModel3(d) && !hasAttribute(d, "@@ignore")).map((dm) => ts.factory.createPropertyAssignment(dm.name, this.createDataModelObject(dm, lite))), true);
864
912
  }
865
- createTypeDefsObject(model) {
866
- return ts.factory.createObjectLiteralExpression(model.declarations.filter((d) => isTypeDef2(d)).map((td) => ts.factory.createPropertyAssignment(td.name, this.createTypeDefObject(td))), true);
913
+ createTypeDefsObject(model, lite) {
914
+ return ts.factory.createObjectLiteralExpression(model.declarations.filter((d) => isTypeDef3(d)).map((td) => ts.factory.createPropertyAssignment(td.name, this.createTypeDefObject(td, lite))), true);
867
915
  }
868
- createDataModelObject(dm) {
916
+ createDataModelObject(dm, lite) {
869
917
  const allFields = getAllFields3(dm);
870
- const allAttributes = getAllAttributes2(dm).filter((attr) => {
918
+ const allAttributes = lite ? [] : getAllAttributes2(dm).filter((attr) => {
871
919
  if (attr.decl.$refText === "@@delegate" && attr.$container !== dm) {
872
920
  return false;
873
921
  }
@@ -882,7 +930,7 @@ var TsSchemaGenerator = class {
882
930
  ts.factory.createPropertyAssignment("baseModel", ts.factory.createStringLiteral(dm.baseModel.$refText))
883
931
  ] : [],
884
932
  // fields
885
- ts.factory.createPropertyAssignment("fields", ts.factory.createObjectLiteralExpression(allFields.map((field) => ts.factory.createPropertyAssignment(field.name, this.createDataFieldObject(field, dm))), true)),
933
+ ts.factory.createPropertyAssignment("fields", ts.factory.createObjectLiteralExpression(allFields.map((field) => ts.factory.createPropertyAssignment(field.name, this.createDataFieldObject(field, dm, lite))), true)),
886
934
  // attributes
887
935
  ...allAttributes.length > 0 ? [
888
936
  ts.factory.createPropertyAssignment("attributes", ts.factory.createArrayLiteralExpression(allAttributes.map((attr) => this.createAttributeObject(attr)), true))
@@ -898,6 +946,9 @@ var TsSchemaGenerator = class {
898
946
  // subModels
899
947
  ...subModels.length > 0 ? [
900
948
  ts.factory.createPropertyAssignment("subModels", ts.factory.createArrayLiteralExpression(subModels.map((subModel) => ts.factory.createStringLiteral(subModel))))
949
+ ] : [],
950
+ ...dm.isView ? [
951
+ ts.factory.createPropertyAssignment("isView", ts.factory.createTrue())
901
952
  ] : []
902
953
  ];
903
954
  const computedFields = dm.fields.filter((f) => hasAttribute(f, "@computed"));
@@ -909,14 +960,14 @@ var TsSchemaGenerator = class {
909
960
  getSubModels(dm) {
910
961
  return dm.$container.declarations.filter(isDataModel3).filter((d) => d.baseModel?.ref === dm).map((d) => d.name);
911
962
  }
912
- createTypeDefObject(td) {
963
+ createTypeDefObject(td, lite) {
913
964
  const allFields = getAllFields3(td);
914
965
  const allAttributes = getAllAttributes2(td);
915
966
  const fields = [
916
967
  // name
917
968
  ts.factory.createPropertyAssignment("name", ts.factory.createStringLiteral(td.name)),
918
969
  // fields
919
- ts.factory.createPropertyAssignment("fields", ts.factory.createObjectLiteralExpression(allFields.map((field) => ts.factory.createPropertyAssignment(field.name, this.createDataFieldObject(field, void 0))), true)),
970
+ ts.factory.createPropertyAssignment("fields", ts.factory.createObjectLiteralExpression(allFields.map((field) => ts.factory.createPropertyAssignment(field.name, this.createDataFieldObject(field, void 0, lite))), true)),
920
971
  // attributes
921
972
  ...allAttributes.length > 0 ? [
922
973
  ts.factory.createPropertyAssignment("attributes", ts.factory.createArrayLiteralExpression(allAttributes.map((attr) => this.createAttributeObject(attr)), true))
@@ -926,9 +977,9 @@ var TsSchemaGenerator = class {
926
977
  }
927
978
  createComputedFieldsObject(fields) {
928
979
  return ts.factory.createObjectLiteralExpression(fields.map((field) => ts.factory.createMethodDeclaration(void 0, void 0, field.name, void 0, void 0, [
929
- // parameter: `context: { currentModel: string }`
980
+ // parameter: `context: { modelAlias: string }`
930
981
  ts.factory.createParameterDeclaration(void 0, void 0, "_context", void 0, ts.factory.createTypeLiteralNode([
931
- ts.factory.createPropertySignature(void 0, "currentModel", void 0, ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword))
982
+ ts.factory.createPropertySignature(void 0, "modelAlias", void 0, ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword))
932
983
  ]), void 0)
933
984
  ], ts.factory.createTypeReferenceNode("OperandExpression", [
934
985
  ts.factory.createTypeReferenceNode(this.mapFieldTypeToTSType(field.type))
@@ -948,7 +999,7 @@ var TsSchemaGenerator = class {
948
999
  }
949
1000
  return result;
950
1001
  }
951
- createDataFieldObject(field, contextModel) {
1002
+ createDataFieldObject(field, contextModel, lite) {
952
1003
  const objectFields = [
953
1004
  // name
954
1005
  ts.factory.createPropertyAssignment("name", ts.factory.createStringLiteral(field.name)),
@@ -977,22 +1028,24 @@ var TsSchemaGenerator = class {
977
1028
  if (this.isDiscriminatorField(field)) {
978
1029
  objectFields.push(ts.factory.createPropertyAssignment("isDiscriminator", ts.factory.createTrue()));
979
1030
  }
980
- if (field.attributes.length > 0) {
1031
+ if (!lite && field.attributes.length > 0) {
981
1032
  objectFields.push(ts.factory.createPropertyAssignment("attributes", ts.factory.createArrayLiteralExpression(field.attributes.map((attr) => this.createAttributeObject(attr)))));
982
1033
  }
983
1034
  const defaultValue = this.getFieldMappedDefault(field);
984
1035
  if (defaultValue !== void 0) {
985
1036
  if (typeof defaultValue === "object" && !Array.isArray(defaultValue)) {
986
1037
  if ("call" in defaultValue) {
987
- objectFields.push(ts.factory.createPropertyAssignment("default", ts.factory.createCallExpression(ts.factory.createIdentifier("ExpressionUtils.call"), void 0, [
1038
+ objectFields.push(ts.factory.createPropertyAssignment("default", this.createExpressionUtilsCall("call", [
988
1039
  ts.factory.createStringLiteral(defaultValue.call),
989
1040
  ...defaultValue.args.length > 0 ? [
990
- ts.factory.createArrayLiteralExpression(defaultValue.args.map((arg) => this.createLiteralNode(arg)))
1041
+ ts.factory.createArrayLiteralExpression(defaultValue.args.map((arg) => this.createExpressionUtilsCall("literal", [
1042
+ this.createLiteralNode(arg)
1043
+ ])))
991
1044
  ] : []
992
1045
  ])));
993
1046
  } else if ("authMember" in defaultValue) {
994
- objectFields.push(ts.factory.createPropertyAssignment("default", ts.factory.createCallExpression(ts.factory.createIdentifier("ExpressionUtils.member"), void 0, [
995
- ts.factory.createCallExpression(ts.factory.createIdentifier("ExpressionUtils.call"), void 0, [
1047
+ objectFields.push(ts.factory.createPropertyAssignment("default", this.createExpressionUtilsCall("member", [
1048
+ this.createExpressionUtilsCall("call", [
996
1049
  ts.factory.createStringLiteral("auth")
997
1050
  ]),
998
1051
  ts.factory.createArrayLiteralExpression(defaultValue.authMember.map((m) => ts.factory.createStringLiteral(m)))
@@ -1025,14 +1078,21 @@ var TsSchemaGenerator = class {
1025
1078
  return getAttribute(origin, "@@delegate")?.args.some((arg) => arg.$resolvedParam.name === "discriminator" && isDataFieldReference(arg.value) && arg.value.target.ref === field);
1026
1079
  }
1027
1080
  getDataSourceProvider(model) {
1028
- const dataSource = model.declarations.find(isDataSource);
1081
+ const dataSource = model.declarations.find(isDataSource2);
1029
1082
  invariant(dataSource, "No data source found in the model");
1030
1083
  const providerExpr = dataSource.fields.find((f) => f.name === "provider")?.value;
1031
- invariant(isLiteralExpr3(providerExpr), "Provider must be a literal");
1032
- const type = providerExpr.value;
1033
- return {
1034
- type
1035
- };
1084
+ invariant(isLiteralExpr3(providerExpr) && typeof providerExpr.value === "string", "Provider must be a string literal");
1085
+ return providerExpr.value;
1086
+ }
1087
+ getDataSourceDefaultSchema(model) {
1088
+ const dataSource = model.declarations.find(isDataSource2);
1089
+ invariant(dataSource, "No data source found in the model");
1090
+ const defaultSchemaExpr = dataSource.fields.find((f) => f.name === "defaultSchema")?.value;
1091
+ if (!defaultSchemaExpr) {
1092
+ return void 0;
1093
+ }
1094
+ invariant(isLiteralExpr3(defaultSchemaExpr) && typeof defaultSchemaExpr.value === "string", "Default schema must be a string literal");
1095
+ return defaultSchemaExpr.value;
1036
1096
  }
1037
1097
  getFieldMappedDefault(field) {
1038
1098
  const defaultAttr = getAttribute(field, "@default");
@@ -1102,12 +1162,16 @@ var TsSchemaGenerator = class {
1102
1162
  relationFields.push(ts.factory.createPropertyAssignment("name", ts.factory.createStringLiteral(relationName)));
1103
1163
  }
1104
1164
  const relation = getAttribute(field, "@relation");
1165
+ const fkFields = [];
1105
1166
  if (relation) {
1106
1167
  for (const arg of relation.args) {
1107
1168
  const param = arg.$resolvedParam.name;
1108
1169
  if (param === "fields" || param === "references") {
1109
1170
  const fieldNames = this.getReferenceNames(arg.value);
1110
1171
  if (fieldNames) {
1172
+ if (param === "fields") {
1173
+ fkFields.push(...fieldNames);
1174
+ }
1111
1175
  relationFields.push(ts.factory.createPropertyAssignment(param, ts.factory.createArrayLiteralExpression(fieldNames.map((el) => ts.factory.createStringLiteral(el)))));
1112
1176
  }
1113
1177
  }
@@ -1117,6 +1181,15 @@ var TsSchemaGenerator = class {
1117
1181
  }
1118
1182
  }
1119
1183
  }
1184
+ if (fkFields.length > 0) {
1185
+ const allHaveDefault = fkFields.every((fieldName) => {
1186
+ const fieldDef = field.$container.fields.find((f) => f.name === fieldName);
1187
+ return fieldDef && hasAttribute(fieldDef, "@default");
1188
+ });
1189
+ if (allHaveDefault) {
1190
+ relationFields.push(ts.factory.createPropertyAssignment("hasDefault", ts.factory.createTrue()));
1191
+ }
1192
+ }
1120
1193
  return ts.factory.createObjectLiteralExpression(relationFields);
1121
1194
  }
1122
1195
  getReferenceNames(expr) {
@@ -1185,7 +1258,11 @@ var TsSchemaGenerator = class {
1185
1258
  const seenKeys = /* @__PURE__ */ new Set();
1186
1259
  for (const attr of allAttributes) {
1187
1260
  if (attr.decl.$refText === "@@id" || attr.decl.$refText === "@@unique") {
1188
- const fieldNames = this.getReferenceNames(attr.args[0].value);
1261
+ const fieldsArg = getAttributeArg(attr, "fields");
1262
+ if (!fieldsArg) {
1263
+ continue;
1264
+ }
1265
+ const fieldNames = this.getReferenceNames(fieldsArg);
1189
1266
  if (!fieldNames) {
1190
1267
  continue;
1191
1268
  }
@@ -1224,7 +1301,21 @@ var TsSchemaGenerator = class {
1224
1301
  return field.type.type ? ts.factory.createStringLiteral(field.type.type) : field.type.reference ? ts.factory.createStringLiteral(field.type.reference.$refText) : ts.factory.createStringLiteral("Unsupported");
1225
1302
  }
1226
1303
  createEnumObject(e) {
1227
- return ts.factory.createObjectLiteralExpression(e.fields.map((field) => ts.factory.createPropertyAssignment(field.name, ts.factory.createStringLiteral(field.name))), true);
1304
+ return ts.factory.createObjectLiteralExpression([
1305
+ ts.factory.createPropertyAssignment("values", ts.factory.createObjectLiteralExpression(e.fields.map((f) => ts.factory.createPropertyAssignment(f.name, ts.factory.createStringLiteral(f.name))), true)),
1306
+ // only generate `fields` if there are attributes on the fields
1307
+ ...e.fields.some((f) => f.attributes.length > 0) ? [
1308
+ ts.factory.createPropertyAssignment("fields", ts.factory.createObjectLiteralExpression(e.fields.map((field) => ts.factory.createPropertyAssignment(field.name, ts.factory.createObjectLiteralExpression([
1309
+ ts.factory.createPropertyAssignment("name", ts.factory.createStringLiteral(field.name)),
1310
+ ...field.attributes.length > 0 ? [
1311
+ ts.factory.createPropertyAssignment("attributes", ts.factory.createArrayLiteralExpression(field.attributes?.map((attr) => this.createAttributeObject(attr)) ?? [], true))
1312
+ ] : []
1313
+ ], true))), true))
1314
+ ] : [],
1315
+ ...e.attributes.length > 0 ? [
1316
+ ts.factory.createPropertyAssignment("attributes", ts.factory.createArrayLiteralExpression(e.attributes.map((attr) => this.createAttributeObject(attr)), true))
1317
+ ] : []
1318
+ ], true);
1228
1319
  }
1229
1320
  getLiteral(expr) {
1230
1321
  if (!isLiteralExpr3(expr)) {
@@ -1306,7 +1397,7 @@ var TsSchemaGenerator = class {
1306
1397
  });
1307
1398
  }
1308
1399
  createThisExpression() {
1309
- return ts.factory.createCallExpression(ts.factory.createIdentifier("ExpressionUtils._this"), void 0, []);
1400
+ return this.createExpressionUtilsCall("_this");
1310
1401
  }
1311
1402
  createMemberExpression(expr) {
1312
1403
  const members = [];
@@ -1320,32 +1411,32 @@ var TsSchemaGenerator = class {
1320
1411
  this.createExpression(receiver),
1321
1412
  ts.factory.createArrayLiteralExpression(members.map((m) => ts.factory.createStringLiteral(m)))
1322
1413
  ];
1323
- return ts.factory.createCallExpression(ts.factory.createIdentifier("ExpressionUtils.member"), void 0, args);
1414
+ return this.createExpressionUtilsCall("member", args);
1324
1415
  }
1325
1416
  createNullExpression() {
1326
- return ts.factory.createCallExpression(ts.factory.createIdentifier("ExpressionUtils._null"), void 0, []);
1417
+ return this.createExpressionUtilsCall("_null");
1327
1418
  }
1328
1419
  createBinaryExpression(expr) {
1329
- return ts.factory.createCallExpression(ts.factory.createIdentifier("ExpressionUtils.binary"), void 0, [
1420
+ return this.createExpressionUtilsCall("binary", [
1330
1421
  this.createExpression(expr.left),
1331
1422
  this.createLiteralNode(expr.operator),
1332
1423
  this.createExpression(expr.right)
1333
1424
  ]);
1334
1425
  }
1335
1426
  createUnaryExpression(expr) {
1336
- return ts.factory.createCallExpression(ts.factory.createIdentifier("ExpressionUtils.unary"), void 0, [
1427
+ return this.createExpressionUtilsCall("unary", [
1337
1428
  this.createLiteralNode(expr.operator),
1338
1429
  this.createExpression(expr.operand)
1339
1430
  ]);
1340
1431
  }
1341
1432
  createArrayExpression(expr) {
1342
- return ts.factory.createCallExpression(ts.factory.createIdentifier("ExpressionUtils.array"), void 0, [
1433
+ return this.createExpressionUtilsCall("array", [
1343
1434
  ts.factory.createArrayLiteralExpression(expr.items.map((item) => this.createExpression(item)))
1344
1435
  ]);
1345
1436
  }
1346
1437
  createRefExpression(expr) {
1347
1438
  if (isDataField(expr.target.ref)) {
1348
- return ts.factory.createCallExpression(ts.factory.createIdentifier("ExpressionUtils.field"), void 0, [
1439
+ return this.createExpressionUtilsCall("field", [
1349
1440
  this.createLiteralNode(expr.target.$refText)
1350
1441
  ]);
1351
1442
  } else if (isEnumField(expr.target.ref)) {
@@ -1355,7 +1446,7 @@ var TsSchemaGenerator = class {
1355
1446
  }
1356
1447
  }
1357
1448
  createCallExpression(expr) {
1358
- return ts.factory.createCallExpression(ts.factory.createIdentifier("ExpressionUtils.call"), void 0, [
1449
+ return this.createExpressionUtilsCall("call", [
1359
1450
  ts.factory.createStringLiteral(expr.function.$refText),
1360
1451
  ...expr.args.length > 0 ? [
1361
1452
  ts.factory.createArrayLiteralExpression(expr.args.map((arg) => this.createExpression(arg.value)))
@@ -1363,25 +1454,25 @@ var TsSchemaGenerator = class {
1363
1454
  ]);
1364
1455
  }
1365
1456
  createLiteralExpression(type, value) {
1366
- return match2(type).with("BooleanLiteral", () => ts.factory.createCallExpression(ts.factory.createIdentifier("ExpressionUtils.literal"), void 0, [
1457
+ return match2(type).with("BooleanLiteral", () => this.createExpressionUtilsCall("literal", [
1367
1458
  this.createLiteralNode(value)
1368
- ])).with("NumberLiteral", () => ts.factory.createCallExpression(ts.factory.createIdentifier("ExpressionUtils.literal"), void 0, [
1459
+ ])).with("NumberLiteral", () => this.createExpressionUtilsCall("literal", [
1369
1460
  ts.factory.createIdentifier(value)
1370
- ])).with("StringLiteral", () => ts.factory.createCallExpression(ts.factory.createIdentifier("ExpressionUtils.literal"), void 0, [
1461
+ ])).with("StringLiteral", () => this.createExpressionUtilsCall("literal", [
1371
1462
  this.createLiteralNode(value)
1372
1463
  ])).otherwise(() => {
1373
1464
  throw new Error(`Unsupported literal type: ${type}`);
1374
1465
  });
1375
1466
  }
1376
- generateModelsAndTypeDefs(model, outputDir) {
1467
+ generateModelsAndTypeDefs(model, options) {
1377
1468
  const statements = [];
1378
- statements.push(this.generateSchemaImport(model, true, true));
1469
+ statements.push(this.generateSchemaImport(model, true, true, !!(options.lite || options.liteOnly)));
1379
1470
  statements.push(ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(false, void 0, ts.factory.createNamedImports([
1380
1471
  ts.factory.createImportSpecifier(true, void 0, ts.factory.createIdentifier(`ModelResult as $ModelResult`)),
1381
- ...model.declarations.some(isTypeDef2) ? [
1472
+ ...model.declarations.some(isTypeDef3) ? [
1382
1473
  ts.factory.createImportSpecifier(true, void 0, ts.factory.createIdentifier(`TypeDefResult as $TypeDefResult`))
1383
1474
  ] : []
1384
- ])), ts.factory.createStringLiteral("@zenstackhq/runtime")));
1475
+ ])), ts.factory.createStringLiteral("@zenstackhq/orm")));
1385
1476
  const dataModels = model.declarations.filter(isDataModel3);
1386
1477
  for (const dm of dataModels) {
1387
1478
  let modelType = ts.factory.createTypeAliasDeclaration([
@@ -1395,7 +1486,7 @@ var TsSchemaGenerator = class {
1395
1486
  }
1396
1487
  statements.push(modelType);
1397
1488
  }
1398
- const typeDefs = model.declarations.filter(isTypeDef2);
1489
+ const typeDefs = model.declarations.filter(isTypeDef3);
1399
1490
  for (const td of typeDefs) {
1400
1491
  let typeDef = ts.factory.createTypeAliasDeclaration([
1401
1492
  ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)
@@ -1413,7 +1504,7 @@ var TsSchemaGenerator = class {
1413
1504
  let enumDecl = ts.factory.createVariableStatement([
1414
1505
  ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)
1415
1506
  ], ts.factory.createVariableDeclarationList([
1416
- ts.factory.createVariableDeclaration(e.name, void 0, void 0, ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("$schema"), ts.factory.createIdentifier("enums")), ts.factory.createIdentifier(e.name)))
1507
+ ts.factory.createVariableDeclaration(e.name, void 0, void 0, ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("$schema"), ts.factory.createIdentifier("enums")), ts.factory.createIdentifier(e.name)), ts.factory.createIdentifier("values")))
1417
1508
  ], ts.NodeFlags.Const));
1418
1509
  if (e.comments.length > 0) {
1419
1510
  enumDecl = this.generateDocs(enumDecl, e);
@@ -1428,13 +1519,13 @@ var TsSchemaGenerator = class {
1428
1519
  statements.push(typeAlias);
1429
1520
  }
1430
1521
  this.generateBannerComments(statements);
1431
- const outputFile = path.join(outputDir, "models.ts");
1522
+ const outputFile = path.join(options.outDir, "models.ts");
1432
1523
  const sourceFile = ts.createSourceFile(outputFile, "", ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS);
1433
1524
  const printer = ts.createPrinter();
1434
1525
  const result = printer.printList(ts.ListFormat.MultiLine, ts.factory.createNodeArray(statements), sourceFile);
1435
1526
  fs.writeFileSync(outputFile, result);
1436
1527
  }
1437
- generateSchemaImport(model, schemaObject, schemaType) {
1528
+ generateSchemaImport(model, schemaObject, schemaType, useLite) {
1438
1529
  const importSpecifiers = [];
1439
1530
  if (schemaObject) {
1440
1531
  if (model.declarations.some(isEnum)) {
@@ -1444,17 +1535,17 @@ var TsSchemaGenerator = class {
1444
1535
  if (schemaType) {
1445
1536
  importSpecifiers.push(ts.factory.createImportSpecifier(true, ts.factory.createIdentifier("SchemaType"), ts.factory.createIdentifier("$Schema")));
1446
1537
  }
1447
- return ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(false, void 0, ts.factory.createNamedImports(importSpecifiers)), ts.factory.createStringLiteral("./schema"));
1538
+ return ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(false, void 0, ts.factory.createNamedImports(importSpecifiers)), ts.factory.createStringLiteral(useLite ? "./schema-lite" : "./schema"));
1448
1539
  }
1449
1540
  generateDocs(tsDecl, decl) {
1450
1541
  return ts.addSyntheticLeadingComment(tsDecl, ts.SyntaxKind.MultiLineCommentTrivia, `*
1451
1542
  * ${decl.comments.map((c) => c.replace(/^\s*\/*\s*/, "")).join("\n * ")}
1452
1543
  `, true);
1453
1544
  }
1454
- generateInputTypes(model, outputDir) {
1545
+ generateInputTypes(model, options) {
1455
1546
  const dataModels = model.declarations.filter(isDataModel3);
1456
1547
  const statements = [];
1457
- statements.push(this.generateSchemaImport(model, false, true));
1548
+ statements.push(this.generateSchemaImport(model, false, true, !!(options.lite || options.liteOnly)));
1458
1549
  const inputTypes = [
1459
1550
  "FindManyArgs",
1460
1551
  "FindUniqueArgs",
@@ -1481,11 +1572,11 @@ var TsSchemaGenerator = class {
1481
1572
  IncludeInput: "Include",
1482
1573
  OmitInput: "Omit"
1483
1574
  };
1484
- statements.push(ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(true, void 0, ts.factory.createNamedImports(inputTypes.map((inputType) => ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier(`${inputType} as $${inputType}`))))), ts.factory.createStringLiteral("@zenstackhq/runtime")));
1575
+ statements.push(ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(true, void 0, ts.factory.createNamedImports(inputTypes.map((inputType) => ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier(`${inputType} as $${inputType}`))))), ts.factory.createStringLiteral("@zenstackhq/orm")));
1485
1576
  statements.push(ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(true, void 0, ts.factory.createNamedImports([
1486
1577
  ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier("SimplifiedModelResult as $SimplifiedModelResult")),
1487
1578
  ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier("SelectIncludeOmit as $SelectIncludeOmit"))
1488
- ])), ts.factory.createStringLiteral("@zenstackhq/runtime")));
1579
+ ])), ts.factory.createStringLiteral("@zenstackhq/orm")));
1489
1580
  for (const dm of dataModels) {
1490
1581
  for (const inputType of inputTypes) {
1491
1582
  const exportName = inputTypeNameFixes[inputType] ? `${dm.name}${inputTypeNameFixes[inputType]}` : `${dm.name}${inputType}`;
@@ -1511,517 +1602,16 @@ var TsSchemaGenerator = class {
1511
1602
  ])));
1512
1603
  }
1513
1604
  this.generateBannerComments(statements);
1514
- const outputFile = path.join(outputDir, "input.ts");
1605
+ const outputFile = path.join(options.outDir, "input.ts");
1515
1606
  const sourceFile = ts.createSourceFile(outputFile, "", ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS);
1516
1607
  const printer = ts.createPrinter();
1517
1608
  const result = printer.printList(ts.ListFormat.MultiLine, ts.factory.createNodeArray(statements), sourceFile);
1518
1609
  fs.writeFileSync(outputFile, result);
1519
1610
  }
1520
1611
  };
1521
-
1522
- // src/zmodel-code-generator.ts
1523
- import { ArrayExpr, Attribute, AttributeArg as AttributeArg2, AttributeParam, AttributeParamType, BinaryExpr, BinaryExprOperatorPriority, BooleanLiteral as BooleanLiteral2, ConfigArrayExpr, ConfigField, ConfigInvocationExpr, DataField, DataFieldAttribute, DataModel as DataModel2, DataModelAttribute, DataSource as DataSource3, Enum as Enum3, EnumField as EnumField2, FunctionDecl, FunctionParam, FunctionParamType, GeneratorDecl as GeneratorDecl2, InvocationExpr, LiteralExpr, MemberAccessExpr, Model as Model2, NullExpr, NumberLiteral as NumberLiteral2, ObjectExpr, Plugin, PluginField, ReferenceArg, ReferenceExpr, StringLiteral as StringLiteral2, ThisExpr, TypeDef, UnaryExpr } from "@zenstackhq/language/ast";
1524
- function _ts_decorate(decorators, target, key, desc) {
1525
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1526
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1527
- 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;
1528
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1529
- }
1530
- __name(_ts_decorate, "_ts_decorate");
1531
- function _ts_metadata(k, v) {
1532
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1533
- }
1534
- __name(_ts_metadata, "_ts_metadata");
1535
- var generationHandlers = /* @__PURE__ */ new Map();
1536
- function gen(name) {
1537
- return function(_target, _propertyKey, descriptor) {
1538
- if (!generationHandlers.get(name)) {
1539
- generationHandlers.set(name, descriptor);
1540
- }
1541
- return descriptor;
1542
- };
1543
- }
1544
- __name(gen, "gen");
1545
- var ZModelCodeGenerator = class {
1546
- static {
1547
- __name(this, "ZModelCodeGenerator");
1548
- }
1549
- options;
1550
- constructor(options) {
1551
- this.options = {
1552
- binaryExprNumberOfSpaces: options?.binaryExprNumberOfSpaces ?? 1,
1553
- unaryExprNumberOfSpaces: options?.unaryExprNumberOfSpaces ?? 0,
1554
- indent: options?.indent ?? 4,
1555
- quote: options?.quote ?? "single"
1556
- };
1557
- }
1558
- /**
1559
- * Generates ZModel source code from AST.
1560
- */
1561
- generate(ast) {
1562
- const handler = generationHandlers.get(ast.$type);
1563
- if (!handler) {
1564
- throw new Error(`No generation handler found for ${ast.$type}`);
1565
- }
1566
- return handler.value.call(this, ast);
1567
- }
1568
- _generateModel(ast) {
1569
- return ast.declarations.map((d) => this.generate(d)).join("\n\n");
1570
- }
1571
- _generateDataSource(ast) {
1572
- return `datasource ${ast.name} {
1573
- ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}
1574
- }`;
1575
- }
1576
- _generateEnum(ast) {
1577
- return `enum ${ast.name} {
1578
- ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}
1579
- }`;
1580
- }
1581
- _generateEnumField(ast) {
1582
- return `${ast.name}${ast.attributes.length > 0 ? " " + ast.attributes.map((x) => this.generate(x)).join(" ") : ""}`;
1583
- }
1584
- _generateGenerator(ast) {
1585
- return `generator ${ast.name} {
1586
- ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}
1587
- }`;
1588
- }
1589
- _generateConfigField(ast) {
1590
- return `${ast.name} = ${this.generate(ast.value)}`;
1591
- }
1592
- _generateConfigArrayExpr(ast) {
1593
- return `[${ast.items.map((x) => this.generate(x)).join(", ")}]`;
1594
- }
1595
- _generateConfigInvocationExpr(ast) {
1596
- if (ast.args.length === 0) {
1597
- return ast.name;
1598
- } else {
1599
- return `${ast.name}(${ast.args.map((x) => (x.name ? x.name + ": " : "") + this.generate(x.value)).join(", ")})`;
1600
- }
1601
- }
1602
- _generatePlugin(ast) {
1603
- return `plugin ${ast.name} {
1604
- ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}
1605
- }`;
1606
- }
1607
- _generatePluginField(ast) {
1608
- return `${ast.name} = ${this.generate(ast.value)}`;
1609
- }
1610
- _generateDataModel(ast) {
1611
- return `${ast.isView ? "view" : "model"} ${ast.name}${ast.mixins.length > 0 ? " mixes " + ast.mixins.map((x) => x.ref?.name).join(", ") : ""} {
1612
- ${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") : ""}
1613
- }`;
1614
- }
1615
- _generateDataField(ast) {
1616
- return `${ast.name} ${this.fieldType(ast.type)}${ast.attributes.length > 0 ? " " + ast.attributes.map((x) => this.generate(x)).join(" ") : ""}`;
1617
- }
1618
- fieldType(type) {
1619
- const baseType = type.type ? type.type : type.$type == "DataFieldType" && type.unsupported ? "Unsupported(" + this.generate(type.unsupported.value) + ")" : type.reference?.$refText;
1620
- return `${baseType}${type.array ? "[]" : ""}${type.optional ? "?" : ""}`;
1621
- }
1622
- _generateDataModelAttribute(ast) {
1623
- return this.attribute(ast);
1624
- }
1625
- _generateDataFieldAttribute(ast) {
1626
- return this.attribute(ast);
1627
- }
1628
- attribute(ast) {
1629
- const args = ast.args.length ? `(${ast.args.map((x) => this.generate(x)).join(", ")})` : "";
1630
- return `${resolved(ast.decl).name}${args}`;
1631
- }
1632
- _generateAttributeArg(ast) {
1633
- if (ast.name) {
1634
- return `${ast.name}: ${this.generate(ast.value)}`;
1635
- } else {
1636
- return this.generate(ast.value);
1637
- }
1638
- }
1639
- _generateObjectExpr(ast) {
1640
- return `{ ${ast.fields.map((field) => this.objectField(field)).join(", ")} }`;
1641
- }
1642
- objectField(field) {
1643
- return `${field.name}: ${this.generate(field.value)}`;
1644
- }
1645
- _generateArrayExpr(ast) {
1646
- return `[${ast.items.map((item) => this.generate(item)).join(", ")}]`;
1647
- }
1648
- _generateLiteralExpr(ast) {
1649
- return this.options.quote === "single" ? `'${ast.value}'` : `"${ast.value}"`;
1650
- }
1651
- _generateNumberLiteral(ast) {
1652
- return ast.value.toString();
1653
- }
1654
- _generateBooleanLiteral(ast) {
1655
- return ast.value.toString();
1656
- }
1657
- _generateUnaryExpr(ast) {
1658
- return `${ast.operator}${this.unaryExprSpace}${this.generate(ast.operand)}`;
1659
- }
1660
- _generateBinaryExpr(ast) {
1661
- const operator = ast.operator;
1662
- const isCollectionPredicate = this.isCollectionPredicateOperator(operator);
1663
- const rightExpr = this.generate(ast.right);
1664
- const { left: isLeftParenthesis, right: isRightParenthesis } = this.isParenthesesNeededForBinaryExpr(ast);
1665
- return `${isLeftParenthesis ? "(" : ""}${this.generate(ast.left)}${isLeftParenthesis ? ")" : ""}${isCollectionPredicate ? "" : this.binaryExprSpace}${operator}${isCollectionPredicate ? "" : this.binaryExprSpace}${isRightParenthesis ? "(" : ""}${isCollectionPredicate ? `[${rightExpr}]` : rightExpr}${isRightParenthesis ? ")" : ""}`;
1666
- }
1667
- _generateReferenceExpr(ast) {
1668
- const args = ast.args.length ? `(${ast.args.map((x) => this.generate(x)).join(", ")})` : "";
1669
- return `${ast.target.ref?.name}${args}`;
1670
- }
1671
- _generateReferenceArg(ast) {
1672
- return `${ast.name}:${this.generate(ast.value)}`;
1673
- }
1674
- _generateMemberExpr(ast) {
1675
- return `${this.generate(ast.operand)}.${ast.member.ref?.name}`;
1676
- }
1677
- _generateInvocationExpr(ast) {
1678
- return `${ast.function.ref?.name}(${ast.args.map((x) => this.argument(x)).join(", ")})`;
1679
- }
1680
- _generateNullExpr() {
1681
- return "null";
1682
- }
1683
- _generateThisExpr() {
1684
- return "this";
1685
- }
1686
- _generateAttribute(ast) {
1687
- return `attribute ${ast.name}(${ast.params.map((x) => this.generate(x)).join(", ")})`;
1688
- }
1689
- _generateAttributeParam(ast) {
1690
- return `${ast.default ? "_ " : ""}${ast.name}: ${this.generate(ast.type)}`;
1691
- }
1692
- _generateAttributeParamType(ast) {
1693
- return `${ast.type ?? ast.reference?.$refText}${ast.array ? "[]" : ""}${ast.optional ? "?" : ""}`;
1694
- }
1695
- _generateFunctionDecl(ast) {
1696
- return `function ${ast.name}(${ast.params.map((x) => this.generate(x)).join(", ")}) ${ast.returnType ? ": " + this.generate(ast.returnType) : ""} {}`;
1697
- }
1698
- _generateFunctionParam(ast) {
1699
- return `${ast.name}: ${this.generate(ast.type)}`;
1700
- }
1701
- _generateFunctionParamType(ast) {
1702
- return `${ast.type ?? ast.reference?.$refText}${ast.array ? "[]" : ""}`;
1703
- }
1704
- _generateTypeDef(ast) {
1705
- return `type ${ast.name} {
1706
- ${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") : ""}
1707
- }`;
1708
- }
1709
- argument(ast) {
1710
- return this.generate(ast.value);
1711
- }
1712
- get binaryExprSpace() {
1713
- return " ".repeat(this.options.binaryExprNumberOfSpaces);
1714
- }
1715
- get unaryExprSpace() {
1716
- return " ".repeat(this.options.unaryExprNumberOfSpaces);
1717
- }
1718
- get indent() {
1719
- return " ".repeat(this.options.indent);
1720
- }
1721
- isParenthesesNeededForBinaryExpr(ast) {
1722
- const result = {
1723
- left: false,
1724
- right: false
1725
- };
1726
- const operator = ast.operator;
1727
- const isCollectionPredicate = this.isCollectionPredicateOperator(operator);
1728
- const currentPriority = BinaryExprOperatorPriority[operator];
1729
- if (ast.left.$type === BinaryExpr && BinaryExprOperatorPriority[ast.left["operator"]] < currentPriority) {
1730
- result.left = true;
1731
- }
1732
- if (!isCollectionPredicate && ast.right.$type === BinaryExpr && BinaryExprOperatorPriority[ast.right["operator"]] <= currentPriority) {
1733
- result.right = true;
1734
- }
1735
- return result;
1736
- }
1737
- isCollectionPredicateOperator(op) {
1738
- return [
1739
- "?",
1740
- "!",
1741
- "^"
1742
- ].includes(op);
1743
- }
1744
- };
1745
- _ts_decorate([
1746
- gen(Model2),
1747
- _ts_metadata("design:type", Function),
1748
- _ts_metadata("design:paramtypes", [
1749
- typeof Model2 === "undefined" ? Object : Model2
1750
- ]),
1751
- _ts_metadata("design:returntype", void 0)
1752
- ], ZModelCodeGenerator.prototype, "_generateModel", null);
1753
- _ts_decorate([
1754
- gen(DataSource3),
1755
- _ts_metadata("design:type", Function),
1756
- _ts_metadata("design:paramtypes", [
1757
- typeof DataSource3 === "undefined" ? Object : DataSource3
1758
- ]),
1759
- _ts_metadata("design:returntype", void 0)
1760
- ], ZModelCodeGenerator.prototype, "_generateDataSource", null);
1761
- _ts_decorate([
1762
- gen(Enum3),
1763
- _ts_metadata("design:type", Function),
1764
- _ts_metadata("design:paramtypes", [
1765
- typeof Enum3 === "undefined" ? Object : Enum3
1766
- ]),
1767
- _ts_metadata("design:returntype", void 0)
1768
- ], ZModelCodeGenerator.prototype, "_generateEnum", null);
1769
- _ts_decorate([
1770
- gen(EnumField2),
1771
- _ts_metadata("design:type", Function),
1772
- _ts_metadata("design:paramtypes", [
1773
- typeof EnumField2 === "undefined" ? Object : EnumField2
1774
- ]),
1775
- _ts_metadata("design:returntype", void 0)
1776
- ], ZModelCodeGenerator.prototype, "_generateEnumField", null);
1777
- _ts_decorate([
1778
- gen(GeneratorDecl2),
1779
- _ts_metadata("design:type", Function),
1780
- _ts_metadata("design:paramtypes", [
1781
- typeof GeneratorDecl2 === "undefined" ? Object : GeneratorDecl2
1782
- ]),
1783
- _ts_metadata("design:returntype", void 0)
1784
- ], ZModelCodeGenerator.prototype, "_generateGenerator", null);
1785
- _ts_decorate([
1786
- gen(ConfigField),
1787
- _ts_metadata("design:type", Function),
1788
- _ts_metadata("design:paramtypes", [
1789
- typeof ConfigField === "undefined" ? Object : ConfigField
1790
- ]),
1791
- _ts_metadata("design:returntype", void 0)
1792
- ], ZModelCodeGenerator.prototype, "_generateConfigField", null);
1793
- _ts_decorate([
1794
- gen(ConfigArrayExpr),
1795
- _ts_metadata("design:type", Function),
1796
- _ts_metadata("design:paramtypes", [
1797
- typeof ConfigArrayExpr === "undefined" ? Object : ConfigArrayExpr
1798
- ]),
1799
- _ts_metadata("design:returntype", void 0)
1800
- ], ZModelCodeGenerator.prototype, "_generateConfigArrayExpr", null);
1801
- _ts_decorate([
1802
- gen(ConfigInvocationExpr),
1803
- _ts_metadata("design:type", Function),
1804
- _ts_metadata("design:paramtypes", [
1805
- typeof ConfigInvocationExpr === "undefined" ? Object : ConfigInvocationExpr
1806
- ]),
1807
- _ts_metadata("design:returntype", void 0)
1808
- ], ZModelCodeGenerator.prototype, "_generateConfigInvocationExpr", null);
1809
- _ts_decorate([
1810
- gen(Plugin),
1811
- _ts_metadata("design:type", Function),
1812
- _ts_metadata("design:paramtypes", [
1813
- typeof Plugin === "undefined" ? Object : Plugin
1814
- ]),
1815
- _ts_metadata("design:returntype", void 0)
1816
- ], ZModelCodeGenerator.prototype, "_generatePlugin", null);
1817
- _ts_decorate([
1818
- gen(PluginField),
1819
- _ts_metadata("design:type", Function),
1820
- _ts_metadata("design:paramtypes", [
1821
- typeof PluginField === "undefined" ? Object : PluginField
1822
- ]),
1823
- _ts_metadata("design:returntype", void 0)
1824
- ], ZModelCodeGenerator.prototype, "_generatePluginField", null);
1825
- _ts_decorate([
1826
- gen(DataModel2),
1827
- _ts_metadata("design:type", Function),
1828
- _ts_metadata("design:paramtypes", [
1829
- typeof DataModel2 === "undefined" ? Object : DataModel2
1830
- ]),
1831
- _ts_metadata("design:returntype", void 0)
1832
- ], ZModelCodeGenerator.prototype, "_generateDataModel", null);
1833
- _ts_decorate([
1834
- gen(DataField),
1835
- _ts_metadata("design:type", Function),
1836
- _ts_metadata("design:paramtypes", [
1837
- typeof DataField === "undefined" ? Object : DataField
1838
- ]),
1839
- _ts_metadata("design:returntype", void 0)
1840
- ], ZModelCodeGenerator.prototype, "_generateDataField", null);
1841
- _ts_decorate([
1842
- gen(DataModelAttribute),
1843
- _ts_metadata("design:type", Function),
1844
- _ts_metadata("design:paramtypes", [
1845
- typeof DataModelAttribute === "undefined" ? Object : DataModelAttribute
1846
- ]),
1847
- _ts_metadata("design:returntype", void 0)
1848
- ], ZModelCodeGenerator.prototype, "_generateDataModelAttribute", null);
1849
- _ts_decorate([
1850
- gen(DataFieldAttribute),
1851
- _ts_metadata("design:type", Function),
1852
- _ts_metadata("design:paramtypes", [
1853
- typeof DataFieldAttribute === "undefined" ? Object : DataFieldAttribute
1854
- ]),
1855
- _ts_metadata("design:returntype", void 0)
1856
- ], ZModelCodeGenerator.prototype, "_generateDataFieldAttribute", null);
1857
- _ts_decorate([
1858
- gen(AttributeArg2),
1859
- _ts_metadata("design:type", Function),
1860
- _ts_metadata("design:paramtypes", [
1861
- typeof AttributeArg2 === "undefined" ? Object : AttributeArg2
1862
- ]),
1863
- _ts_metadata("design:returntype", void 0)
1864
- ], ZModelCodeGenerator.prototype, "_generateAttributeArg", null);
1865
- _ts_decorate([
1866
- gen(ObjectExpr),
1867
- _ts_metadata("design:type", Function),
1868
- _ts_metadata("design:paramtypes", [
1869
- typeof ObjectExpr === "undefined" ? Object : ObjectExpr
1870
- ]),
1871
- _ts_metadata("design:returntype", void 0)
1872
- ], ZModelCodeGenerator.prototype, "_generateObjectExpr", null);
1873
- _ts_decorate([
1874
- gen(ArrayExpr),
1875
- _ts_metadata("design:type", Function),
1876
- _ts_metadata("design:paramtypes", [
1877
- typeof ArrayExpr === "undefined" ? Object : ArrayExpr
1878
- ]),
1879
- _ts_metadata("design:returntype", void 0)
1880
- ], ZModelCodeGenerator.prototype, "_generateArrayExpr", null);
1881
- _ts_decorate([
1882
- gen(StringLiteral2),
1883
- _ts_metadata("design:type", Function),
1884
- _ts_metadata("design:paramtypes", [
1885
- typeof LiteralExpr === "undefined" ? Object : LiteralExpr
1886
- ]),
1887
- _ts_metadata("design:returntype", void 0)
1888
- ], ZModelCodeGenerator.prototype, "_generateLiteralExpr", null);
1889
- _ts_decorate([
1890
- gen(NumberLiteral2),
1891
- _ts_metadata("design:type", Function),
1892
- _ts_metadata("design:paramtypes", [
1893
- typeof NumberLiteral2 === "undefined" ? Object : NumberLiteral2
1894
- ]),
1895
- _ts_metadata("design:returntype", void 0)
1896
- ], ZModelCodeGenerator.prototype, "_generateNumberLiteral", null);
1897
- _ts_decorate([
1898
- gen(BooleanLiteral2),
1899
- _ts_metadata("design:type", Function),
1900
- _ts_metadata("design:paramtypes", [
1901
- typeof BooleanLiteral2 === "undefined" ? Object : BooleanLiteral2
1902
- ]),
1903
- _ts_metadata("design:returntype", void 0)
1904
- ], ZModelCodeGenerator.prototype, "_generateBooleanLiteral", null);
1905
- _ts_decorate([
1906
- gen(UnaryExpr),
1907
- _ts_metadata("design:type", Function),
1908
- _ts_metadata("design:paramtypes", [
1909
- typeof UnaryExpr === "undefined" ? Object : UnaryExpr
1910
- ]),
1911
- _ts_metadata("design:returntype", void 0)
1912
- ], ZModelCodeGenerator.prototype, "_generateUnaryExpr", null);
1913
- _ts_decorate([
1914
- gen(BinaryExpr),
1915
- _ts_metadata("design:type", Function),
1916
- _ts_metadata("design:paramtypes", [
1917
- typeof BinaryExpr === "undefined" ? Object : BinaryExpr
1918
- ]),
1919
- _ts_metadata("design:returntype", void 0)
1920
- ], ZModelCodeGenerator.prototype, "_generateBinaryExpr", null);
1921
- _ts_decorate([
1922
- gen(ReferenceExpr),
1923
- _ts_metadata("design:type", Function),
1924
- _ts_metadata("design:paramtypes", [
1925
- typeof ReferenceExpr === "undefined" ? Object : ReferenceExpr
1926
- ]),
1927
- _ts_metadata("design:returntype", void 0)
1928
- ], ZModelCodeGenerator.prototype, "_generateReferenceExpr", null);
1929
- _ts_decorate([
1930
- gen(ReferenceArg),
1931
- _ts_metadata("design:type", Function),
1932
- _ts_metadata("design:paramtypes", [
1933
- typeof ReferenceArg === "undefined" ? Object : ReferenceArg
1934
- ]),
1935
- _ts_metadata("design:returntype", void 0)
1936
- ], ZModelCodeGenerator.prototype, "_generateReferenceArg", null);
1937
- _ts_decorate([
1938
- gen(MemberAccessExpr),
1939
- _ts_metadata("design:type", Function),
1940
- _ts_metadata("design:paramtypes", [
1941
- typeof MemberAccessExpr === "undefined" ? Object : MemberAccessExpr
1942
- ]),
1943
- _ts_metadata("design:returntype", void 0)
1944
- ], ZModelCodeGenerator.prototype, "_generateMemberExpr", null);
1945
- _ts_decorate([
1946
- gen(InvocationExpr),
1947
- _ts_metadata("design:type", Function),
1948
- _ts_metadata("design:paramtypes", [
1949
- typeof InvocationExpr === "undefined" ? Object : InvocationExpr
1950
- ]),
1951
- _ts_metadata("design:returntype", void 0)
1952
- ], ZModelCodeGenerator.prototype, "_generateInvocationExpr", null);
1953
- _ts_decorate([
1954
- gen(NullExpr),
1955
- _ts_metadata("design:type", Function),
1956
- _ts_metadata("design:paramtypes", []),
1957
- _ts_metadata("design:returntype", void 0)
1958
- ], ZModelCodeGenerator.prototype, "_generateNullExpr", null);
1959
- _ts_decorate([
1960
- gen(ThisExpr),
1961
- _ts_metadata("design:type", Function),
1962
- _ts_metadata("design:paramtypes", []),
1963
- _ts_metadata("design:returntype", void 0)
1964
- ], ZModelCodeGenerator.prototype, "_generateThisExpr", null);
1965
- _ts_decorate([
1966
- gen(Attribute),
1967
- _ts_metadata("design:type", Function),
1968
- _ts_metadata("design:paramtypes", [
1969
- typeof Attribute === "undefined" ? Object : Attribute
1970
- ]),
1971
- _ts_metadata("design:returntype", void 0)
1972
- ], ZModelCodeGenerator.prototype, "_generateAttribute", null);
1973
- _ts_decorate([
1974
- gen(AttributeParam),
1975
- _ts_metadata("design:type", Function),
1976
- _ts_metadata("design:paramtypes", [
1977
- typeof AttributeParam === "undefined" ? Object : AttributeParam
1978
- ]),
1979
- _ts_metadata("design:returntype", void 0)
1980
- ], ZModelCodeGenerator.prototype, "_generateAttributeParam", null);
1981
- _ts_decorate([
1982
- gen(AttributeParamType),
1983
- _ts_metadata("design:type", Function),
1984
- _ts_metadata("design:paramtypes", [
1985
- typeof AttributeParamType === "undefined" ? Object : AttributeParamType
1986
- ]),
1987
- _ts_metadata("design:returntype", void 0)
1988
- ], ZModelCodeGenerator.prototype, "_generateAttributeParamType", null);
1989
- _ts_decorate([
1990
- gen(FunctionDecl),
1991
- _ts_metadata("design:type", Function),
1992
- _ts_metadata("design:paramtypes", [
1993
- typeof FunctionDecl === "undefined" ? Object : FunctionDecl
1994
- ]),
1995
- _ts_metadata("design:returntype", void 0)
1996
- ], ZModelCodeGenerator.prototype, "_generateFunctionDecl", null);
1997
- _ts_decorate([
1998
- gen(FunctionParam),
1999
- _ts_metadata("design:type", Function),
2000
- _ts_metadata("design:paramtypes", [
2001
- typeof FunctionParam === "undefined" ? Object : FunctionParam
2002
- ]),
2003
- _ts_metadata("design:returntype", void 0)
2004
- ], ZModelCodeGenerator.prototype, "_generateFunctionParam", null);
2005
- _ts_decorate([
2006
- gen(FunctionParamType),
2007
- _ts_metadata("design:type", Function),
2008
- _ts_metadata("design:paramtypes", [
2009
- typeof FunctionParamType === "undefined" ? Object : FunctionParamType
2010
- ]),
2011
- _ts_metadata("design:returntype", void 0)
2012
- ], ZModelCodeGenerator.prototype, "_generateFunctionParamType", null);
2013
- _ts_decorate([
2014
- gen(TypeDef),
2015
- _ts_metadata("design:type", Function),
2016
- _ts_metadata("design:paramtypes", [
2017
- typeof TypeDef === "undefined" ? Object : TypeDef
2018
- ]),
2019
- _ts_metadata("design:returntype", void 0)
2020
- ], ZModelCodeGenerator.prototype, "_generateTypeDef", null);
2021
1612
  export {
2022
1613
  model_utils_exports as ModelUtils,
2023
1614
  PrismaSchemaGenerator,
2024
- TsSchemaGenerator,
2025
- ZModelCodeGenerator
1615
+ TsSchemaGenerator
2026
1616
  };
2027
1617
  //# sourceMappingURL=index.js.map