@zenstackhq/sdk 3.0.0-beta.8 → 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
@@ -90,7 +90,7 @@ __name(resolved, "resolved");
90
90
  function getAuthDecl(model) {
91
91
  let found = model.declarations.find((d) => (isDataModel(d) || isTypeDef(d)) && d.attributes.some((attr) => attr.decl.$refText === "@@auth"));
92
92
  if (!found) {
93
- found = model.declarations.find((d) => isDataModel(d) && d.name === "User");
93
+ found = model.declarations.find((d) => (isDataModel(d) || isTypeDef(d)) && d.name === "User");
94
94
  }
95
95
  return found;
96
96
  }
@@ -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, isNullExpr, isReferenceExpr, isStringLiteral, isTypeDef as isTypeDef2, NumberLiteral, StringLiteral } from "@zenstackhq/language/ast";
107
- import { getAllAttributes, getAllFields as getAllFields2, isAuthInvocation, 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, isGeneratorDecl, 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");
@@ -534,10 +538,13 @@ var PrismaSchemaGenerator = class {
534
538
  break;
535
539
  }
536
540
  }
541
+ if (!this.zmodel.declarations.some(isGeneratorDecl)) {
542
+ this.generateDefaultGenerator(prisma);
543
+ }
537
544
  return this.PRELUDE + prisma.toString();
538
545
  }
539
546
  generateDataSource(prisma, dataSource) {
540
- const fields = dataSource.fields.map((f) => ({
547
+ const fields = dataSource.fields.filter((f) => !NON_PRISMA_DATASOURCE_FIELDS.includes(f.name)).map((f) => ({
541
548
  name: f.name,
542
549
  text: this.configExprToText(f.value)
543
550
  }));
@@ -574,6 +581,21 @@ var PrismaSchemaGenerator = class {
574
581
  text: this.configExprToText(f.value)
575
582
  })));
576
583
  }
584
+ generateDefaultGenerator(prisma) {
585
+ const gen = prisma.addGenerator("client", [
586
+ {
587
+ name: "provider",
588
+ text: '"prisma-client-js"'
589
+ }
590
+ ]);
591
+ const dataSource = this.zmodel.declarations.find(isDataSource);
592
+ if (dataSource?.fields.some((f) => f.name === "extensions")) {
593
+ gen.fields.push({
594
+ name: "previewFeatures",
595
+ text: '["postgresqlExtensions"]'
596
+ });
597
+ }
598
+ }
577
599
  generateModel(prisma, decl) {
578
600
  const model = decl.isView ? prisma.addView(decl.name) : prisma.addModel(decl.name);
579
601
  const allFields = getAllFields2(decl, true);
@@ -585,14 +607,30 @@ var PrismaSchemaGenerator = class {
585
607
  this.generateModelField(model, field, decl);
586
608
  }
587
609
  }
588
- const allAttributes = getAllAttributes(decl);
589
- for (const attr of allAttributes.filter((attr2) => this.isPrismaAttribute(attr2))) {
610
+ const allAttributes = getAllAttributes(decl).filter((attr) => this.isPrismaAttribute(attr));
611
+ for (const attr of allAttributes) {
590
612
  this.generateContainerAttribute(model, attr);
591
613
  }
614
+ if (this.datasourceHasSchemasSetting(decl.$container) && !allAttributes.some((attr) => attr.decl.ref?.name === "@@schema")) {
615
+ model.addAttribute("@@schema", [
616
+ new AttributeArg(void 0, new AttributeArgValue("String", this.getDefaultPostgresSchemaName(decl.$container)))
617
+ ]);
618
+ }
592
619
  decl.comments.forEach((c) => model.addComment(c));
593
620
  this.generateDelegateRelationForBase(model, decl);
594
621
  this.generateDelegateRelationForConcrete(model, decl);
595
622
  }
623
+ getDatasourceField(zmodel, fieldName) {
624
+ const dataSource = zmodel.declarations.find(isDataSource);
625
+ return dataSource?.fields.find((f) => f.name === fieldName);
626
+ }
627
+ datasourceHasSchemasSetting(zmodel) {
628
+ return !!this.getDatasourceField(zmodel, "schemas");
629
+ }
630
+ getDefaultPostgresSchemaName(zmodel) {
631
+ const defaultSchemaField = this.getDatasourceField(zmodel, "defaultSchema");
632
+ return getStringLiteral(defaultSchemaField?.value) ?? "public";
633
+ }
596
634
  isPrismaAttribute(attr) {
597
635
  if (!attr.decl.ref) {
598
636
  return false;
@@ -601,7 +639,7 @@ var PrismaSchemaGenerator = class {
601
639
  }
602
640
  getUnsupportedFieldType(fieldType) {
603
641
  if (fieldType.unsupported) {
604
- const value = this.getStringLiteral(fieldType.unsupported.value);
642
+ const value = getStringLiteral(fieldType.unsupported.value);
605
643
  if (value) {
606
644
  return `Unsupported("${value}")`;
607
645
  } else {
@@ -611,9 +649,6 @@ var PrismaSchemaGenerator = class {
611
649
  return void 0;
612
650
  }
613
651
  }
614
- getStringLiteral(node) {
615
- return isStringLiteral(node) ? node.value : void 0;
616
- }
617
652
  generateModelField(model, field, contextModel, addToFront = false) {
618
653
  let fieldType;
619
654
  if (field.type.type) {
@@ -704,9 +739,15 @@ var PrismaSchemaGenerator = class {
704
739
  for (const field of decl.fields) {
705
740
  this.generateEnumField(_enum, field);
706
741
  }
707
- for (const attr of decl.attributes.filter((attr2) => this.isPrismaAttribute(attr2))) {
742
+ const allAttributes = decl.attributes.filter((attr) => this.isPrismaAttribute(attr));
743
+ for (const attr of allAttributes) {
708
744
  this.generateContainerAttribute(_enum, attr);
709
745
  }
746
+ if (this.datasourceHasSchemasSetting(decl.$container) && !allAttributes.some((attr) => attr.decl.ref?.name === "@@schema")) {
747
+ _enum.addAttribute("@@schema", [
748
+ new AttributeArg(void 0, new AttributeArgValue("String", this.getDefaultPostgresSchemaName(decl.$container)))
749
+ ]);
750
+ }
710
751
  decl.comments.forEach((c) => _enum.addComment(c));
711
752
  }
712
753
  generateEnumField(_enum, field) {
@@ -774,8 +815,8 @@ var PrismaSchemaGenerator = class {
774
815
 
775
816
  // src/ts-schema-generator.ts
776
817
  import { invariant } from "@zenstackhq/common-helpers";
777
- 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 isTypeDef3, isUnaryExpr } from "@zenstackhq/language/ast";
778
- import { getAllAttributes as getAllAttributes2, getAllFields as getAllFields3, isDataFieldReference } from "@zenstackhq/language/utils";
818
+ 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";
819
+ import { getAllAttributes as getAllAttributes2, getAllFields as getAllFields3, getAttributeArg, isDataFieldReference } from "@zenstackhq/language/utils";
779
820
  import fs from "fs";
780
821
  import path from "path";
781
822
  import { match as match2 } from "ts-pattern";
@@ -785,29 +826,44 @@ var TsSchemaGenerator = class {
785
826
  __name(this, "TsSchemaGenerator");
786
827
  }
787
828
  usedExpressionUtils = false;
788
- async generate(model, outputDir) {
789
- fs.mkdirSync(outputDir, {
829
+ async generate(model, options) {
830
+ fs.mkdirSync(options.outDir, {
790
831
  recursive: true
791
832
  });
792
833
  this.usedExpressionUtils = false;
793
- this.generateSchema(model, outputDir);
794
- this.generateModelsAndTypeDefs(model, outputDir);
795
- this.generateInputTypes(model, outputDir);
796
- }
797
- generateSchema(model, outputDir) {
798
- const statements = [];
799
- this.generateSchemaStatements(model, statements);
800
- this.generateBannerComments(statements);
801
- const schemaOutputFile = path.join(outputDir, "schema.ts");
802
- const sourceFile = ts.createSourceFile(schemaOutputFile, "", ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS);
803
- const printer = ts.createPrinter();
804
- const result = printer.printList(ts.ListFormat.MultiLine, ts.factory.createNodeArray(statements), sourceFile);
805
- fs.writeFileSync(schemaOutputFile, result);
834
+ this.generateSchema(model, options);
835
+ this.generateModelsAndTypeDefs(model, options);
836
+ this.generateInputTypes(model, options);
837
+ }
838
+ generateSchema(model, options) {
839
+ const targets = [];
840
+ if (!options.liteOnly) {
841
+ targets.push({
842
+ lite: false,
843
+ file: "schema.ts"
844
+ });
845
+ }
846
+ if (options.lite || options.liteOnly) {
847
+ targets.push({
848
+ lite: true,
849
+ file: "schema-lite.ts"
850
+ });
851
+ }
852
+ for (const { lite, file } of targets) {
853
+ const statements = [];
854
+ this.generateSchemaStatements(model, statements, lite);
855
+ this.generateBannerComments(statements);
856
+ const schemaOutputFile = path.join(options.outDir, file);
857
+ const sourceFile = ts.createSourceFile(schemaOutputFile, "", ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS);
858
+ const printer = ts.createPrinter();
859
+ const result = printer.printList(ts.ListFormat.MultiLine, ts.factory.createNodeArray(statements), sourceFile);
860
+ fs.writeFileSync(schemaOutputFile, result);
861
+ }
806
862
  }
807
- generateSchemaStatements(model, statements) {
863
+ generateSchemaStatements(model, statements, lite) {
808
864
  const hasComputedFields = model.declarations.some((d) => isDataModel3(d) && d.fields.some((f) => hasAttribute(f, "@computed")));
809
- const schemaObject = this.createSchemaObject(model);
810
- const runtimeImportDecl = ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(false, void 0, ts.factory.createNamedImports([
865
+ const schemaClass = this.createSchemaClass(model, lite);
866
+ const runtimeImportDecl = ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(void 0, void 0, ts.factory.createNamedImports([
811
867
  ts.factory.createImportSpecifier(true, void 0, ts.factory.createIdentifier("SchemaDef")),
812
868
  ...hasComputedFields ? [
813
869
  ts.factory.createImportSpecifier(true, void 0, ts.factory.createIdentifier("OperandExpression"))
@@ -815,64 +871,81 @@ var TsSchemaGenerator = class {
815
871
  ...this.usedExpressionUtils ? [
816
872
  ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier("ExpressionUtils"))
817
873
  ] : []
818
- ])), ts.factory.createStringLiteral("@zenstackhq/runtime/schema"));
874
+ ])), ts.factory.createStringLiteral("@zenstackhq/orm/schema"));
819
875
  statements.push(runtimeImportDecl);
820
- const declaration = ts.factory.createVariableStatement([
876
+ statements.push(schemaClass);
877
+ const schemaDecl = ts.factory.createVariableStatement([
821
878
  ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)
822
879
  ], ts.factory.createVariableDeclarationList([
823
- ts.factory.createVariableDeclaration("schema", void 0, void 0, ts.factory.createSatisfiesExpression(ts.factory.createAsExpression(schemaObject, ts.factory.createTypeReferenceNode("const")), ts.factory.createTypeReferenceNode("SchemaDef")))
880
+ ts.factory.createVariableDeclaration("schema", void 0, void 0, ts.factory.createNewExpression(ts.factory.createIdentifier("SchemaType"), void 0, []))
824
881
  ], ts.NodeFlags.Const));
825
- statements.push(declaration);
826
- const typeDeclaration = ts.factory.createTypeAliasDeclaration([
827
- ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)
828
- ], "SchemaType", void 0, ts.factory.createTypeReferenceNode("typeof schema"));
829
- statements.push(typeDeclaration);
882
+ statements.push(schemaDecl);
830
883
  }
831
884
  createExpressionUtilsCall(method, args) {
832
885
  this.usedExpressionUtils = true;
833
886
  return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("ExpressionUtils"), method), void 0, args || []);
834
887
  }
835
- createSchemaObject(model) {
836
- const properties = [
888
+ createSchemaClass(model, lite) {
889
+ const members = [
837
890
  // provider
838
- ts.factory.createPropertyAssignment("provider", this.createProviderObject(model)),
891
+ ts.factory.createPropertyDeclaration(void 0, "provider", void 0, void 0, this.createAsConst(this.createProviderObject(model))),
839
892
  // models
840
- ts.factory.createPropertyAssignment("models", this.createModelsObject(model)),
893
+ ts.factory.createPropertyDeclaration(void 0, "models", void 0, void 0, this.createAsConst(this.createModelsObject(model, lite))),
841
894
  // typeDefs
842
895
  ...model.declarations.some(isTypeDef3) ? [
843
- ts.factory.createPropertyAssignment("typeDefs", this.createTypeDefsObject(model))
896
+ ts.factory.createPropertyDeclaration(void 0, "typeDefs", void 0, void 0, this.createAsConst(this.createTypeDefsObject(model, lite)))
844
897
  ] : []
845
898
  ];
846
899
  const enums = model.declarations.filter(isEnum);
847
900
  if (enums.length > 0) {
848
- properties.push(ts.factory.createPropertyAssignment("enums", ts.factory.createObjectLiteralExpression(enums.map((e) => ts.factory.createPropertyAssignment(e.name, this.createEnumObject(e))), true)));
901
+ members.push(ts.factory.createPropertyDeclaration(void 0, "enums", void 0, void 0, this.createAsConst(ts.factory.createObjectLiteralExpression(enums.map((e) => ts.factory.createPropertyAssignment(e.name, this.createEnumObject(e))), true))));
849
902
  }
850
903
  const authType = getAuthDecl(model);
851
904
  if (authType) {
852
- properties.push(ts.factory.createPropertyAssignment("authType", this.createLiteralNode(authType.name)));
905
+ members.push(ts.factory.createPropertyDeclaration(void 0, "authType", void 0, void 0, this.createAsConst(this.createLiteralNode(authType.name))));
853
906
  }
854
907
  const procedures = model.declarations.filter(isProcedure);
855
908
  if (procedures.length > 0) {
856
- properties.push(ts.factory.createPropertyAssignment("procedures", this.createProceduresObject(procedures)));
909
+ members.push(ts.factory.createPropertyDeclaration(void 0, "procedures", void 0, void 0, this.createAsConst(this.createProceduresObject(procedures))));
857
910
  }
858
- properties.push(ts.factory.createPropertyAssignment("plugins", ts.factory.createObjectLiteralExpression([], true)));
859
- return ts.factory.createObjectLiteralExpression(properties, true);
911
+ members.push(ts.factory.createPropertyDeclaration(void 0, "plugins", void 0, void 0, ts.factory.createObjectLiteralExpression([], true)));
912
+ const schemaClass = ts.factory.createClassDeclaration([
913
+ ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)
914
+ ], "SchemaType", void 0, [
915
+ ts.factory.createHeritageClause(ts.SyntaxKind.ImplementsKeyword, [
916
+ ts.factory.createExpressionWithTypeArguments(ts.factory.createIdentifier("SchemaDef"), void 0)
917
+ ])
918
+ ], members);
919
+ return schemaClass;
920
+ }
921
+ createAsConst(expr) {
922
+ return ts.factory.createAsExpression(expr, ts.factory.createTypeReferenceNode("const"));
860
923
  }
861
924
  createProviderObject(model) {
862
925
  const dsProvider = this.getDataSourceProvider(model);
926
+ const defaultSchema = this.getDataSourceDefaultSchema(model);
863
927
  return ts.factory.createObjectLiteralExpression([
864
- ts.factory.createPropertyAssignment("type", ts.factory.createStringLiteral(dsProvider.type))
928
+ ts.factory.createPropertyAssignment("type", ts.factory.createStringLiteral(dsProvider)),
929
+ ...defaultSchema ? [
930
+ ts.factory.createPropertyAssignment("defaultSchema", ts.factory.createStringLiteral(defaultSchema))
931
+ ] : []
865
932
  ], true);
866
933
  }
867
- createModelsObject(model) {
868
- return ts.factory.createObjectLiteralExpression(model.declarations.filter((d) => isDataModel3(d) && !hasAttribute(d, "@@ignore")).map((dm) => ts.factory.createPropertyAssignment(dm.name, this.createDataModelObject(dm))), true);
934
+ createModelsObject(model, lite) {
935
+ return ts.factory.createObjectLiteralExpression(this.getAllDataModels(model).map((dm) => ts.factory.createPropertyAssignment(dm.name, this.createDataModelObject(dm, lite))), true);
936
+ }
937
+ getAllDataModels(model) {
938
+ return model.declarations.filter((d) => isDataModel3(d) && !hasAttribute(d, "@@ignore"));
869
939
  }
870
- createTypeDefsObject(model) {
871
- return ts.factory.createObjectLiteralExpression(model.declarations.filter((d) => isTypeDef3(d)).map((td) => ts.factory.createPropertyAssignment(td.name, this.createTypeDefObject(td))), true);
940
+ getAllTypeDefs(model) {
941
+ return model.declarations.filter((d) => isTypeDef3(d) && !hasAttribute(d, "@@ignore"));
872
942
  }
873
- createDataModelObject(dm) {
943
+ createTypeDefsObject(model, lite) {
944
+ return ts.factory.createObjectLiteralExpression(this.getAllTypeDefs(model).map((td) => ts.factory.createPropertyAssignment(td.name, this.createTypeDefObject(td, lite))), true);
945
+ }
946
+ createDataModelObject(dm, lite) {
874
947
  const allFields = getAllFields3(dm);
875
- const allAttributes = getAllAttributes2(dm).filter((attr) => {
948
+ const allAttributes = lite ? [] : getAllAttributes2(dm).filter((attr) => {
876
949
  if (attr.decl.$refText === "@@delegate" && attr.$container !== dm) {
877
950
  return false;
878
951
  }
@@ -887,7 +960,7 @@ var TsSchemaGenerator = class {
887
960
  ts.factory.createPropertyAssignment("baseModel", ts.factory.createStringLiteral(dm.baseModel.$refText))
888
961
  ] : [],
889
962
  // fields
890
- ts.factory.createPropertyAssignment("fields", ts.factory.createObjectLiteralExpression(allFields.map((field) => ts.factory.createPropertyAssignment(field.name, this.createDataFieldObject(field, dm))), true)),
963
+ ts.factory.createPropertyAssignment("fields", ts.factory.createObjectLiteralExpression(allFields.map((field) => ts.factory.createPropertyAssignment(field.name, this.createDataFieldObject(field, dm, lite))), true)),
891
964
  // attributes
892
965
  ...allAttributes.length > 0 ? [
893
966
  ts.factory.createPropertyAssignment("attributes", ts.factory.createArrayLiteralExpression(allAttributes.map((attr) => this.createAttributeObject(attr)), true))
@@ -917,14 +990,14 @@ var TsSchemaGenerator = class {
917
990
  getSubModels(dm) {
918
991
  return dm.$container.declarations.filter(isDataModel3).filter((d) => d.baseModel?.ref === dm).map((d) => d.name);
919
992
  }
920
- createTypeDefObject(td) {
993
+ createTypeDefObject(td, lite) {
921
994
  const allFields = getAllFields3(td);
922
995
  const allAttributes = getAllAttributes2(td);
923
996
  const fields = [
924
997
  // name
925
998
  ts.factory.createPropertyAssignment("name", ts.factory.createStringLiteral(td.name)),
926
999
  // fields
927
- ts.factory.createPropertyAssignment("fields", ts.factory.createObjectLiteralExpression(allFields.map((field) => ts.factory.createPropertyAssignment(field.name, this.createDataFieldObject(field, void 0))), true)),
1000
+ ts.factory.createPropertyAssignment("fields", ts.factory.createObjectLiteralExpression(allFields.map((field) => ts.factory.createPropertyAssignment(field.name, this.createDataFieldObject(field, void 0, lite))), true)),
928
1001
  // attributes
929
1002
  ...allAttributes.length > 0 ? [
930
1003
  ts.factory.createPropertyAssignment("attributes", ts.factory.createArrayLiteralExpression(allAttributes.map((attr) => this.createAttributeObject(attr)), true))
@@ -956,7 +1029,7 @@ var TsSchemaGenerator = class {
956
1029
  }
957
1030
  return result;
958
1031
  }
959
- createDataFieldObject(field, contextModel) {
1032
+ createDataFieldObject(field, contextModel, lite) {
960
1033
  const objectFields = [
961
1034
  // name
962
1035
  ts.factory.createPropertyAssignment("name", ts.factory.createStringLiteral(field.name)),
@@ -978,6 +1051,9 @@ var TsSchemaGenerator = class {
978
1051
  if (hasAttribute(field, "@updatedAt")) {
979
1052
  objectFields.push(ts.factory.createPropertyAssignment("updatedAt", ts.factory.createTrue()));
980
1053
  }
1054
+ if (hasAttribute(field, "@omit")) {
1055
+ objectFields.push(ts.factory.createPropertyAssignment("omit", ts.factory.createTrue()));
1056
+ }
981
1057
  if (contextModel && // id fields are duplicated in inherited models
982
1058
  !isIdField(field, contextModel) && field.$container !== contextModel && isDelegateModel(field.$container)) {
983
1059
  objectFields.push(ts.factory.createPropertyAssignment("originModel", ts.factory.createStringLiteral(field.$container.name)));
@@ -985,7 +1061,7 @@ var TsSchemaGenerator = class {
985
1061
  if (this.isDiscriminatorField(field)) {
986
1062
  objectFields.push(ts.factory.createPropertyAssignment("isDiscriminator", ts.factory.createTrue()));
987
1063
  }
988
- if (field.attributes.length > 0) {
1064
+ if (!lite && field.attributes.length > 0) {
989
1065
  objectFields.push(ts.factory.createPropertyAssignment("attributes", ts.factory.createArrayLiteralExpression(field.attributes.map((attr) => this.createAttributeObject(attr)))));
990
1066
  }
991
1067
  const defaultValue = this.getFieldMappedDefault(field);
@@ -995,7 +1071,9 @@ var TsSchemaGenerator = class {
995
1071
  objectFields.push(ts.factory.createPropertyAssignment("default", this.createExpressionUtilsCall("call", [
996
1072
  ts.factory.createStringLiteral(defaultValue.call),
997
1073
  ...defaultValue.args.length > 0 ? [
998
- ts.factory.createArrayLiteralExpression(defaultValue.args.map((arg) => this.createLiteralNode(arg)))
1074
+ ts.factory.createArrayLiteralExpression(defaultValue.args.map((arg) => this.createExpressionUtilsCall("literal", [
1075
+ this.createLiteralNode(arg)
1076
+ ])))
999
1077
  ] : []
1000
1078
  ])));
1001
1079
  } else if ("authMember" in defaultValue) {
@@ -1033,14 +1111,21 @@ var TsSchemaGenerator = class {
1033
1111
  return getAttribute(origin, "@@delegate")?.args.some((arg) => arg.$resolvedParam.name === "discriminator" && isDataFieldReference(arg.value) && arg.value.target.ref === field);
1034
1112
  }
1035
1113
  getDataSourceProvider(model) {
1036
- const dataSource = model.declarations.find(isDataSource);
1114
+ const dataSource = model.declarations.find(isDataSource2);
1037
1115
  invariant(dataSource, "No data source found in the model");
1038
1116
  const providerExpr = dataSource.fields.find((f) => f.name === "provider")?.value;
1039
- invariant(isLiteralExpr3(providerExpr), "Provider must be a literal");
1040
- const type = providerExpr.value;
1041
- return {
1042
- type
1043
- };
1117
+ invariant(isLiteralExpr3(providerExpr) && typeof providerExpr.value === "string", "Provider must be a string literal");
1118
+ return providerExpr.value;
1119
+ }
1120
+ getDataSourceDefaultSchema(model) {
1121
+ const dataSource = model.declarations.find(isDataSource2);
1122
+ invariant(dataSource, "No data source found in the model");
1123
+ const defaultSchemaExpr = dataSource.fields.find((f) => f.name === "defaultSchema")?.value;
1124
+ if (!defaultSchemaExpr) {
1125
+ return void 0;
1126
+ }
1127
+ invariant(isLiteralExpr3(defaultSchemaExpr) && typeof defaultSchemaExpr.value === "string", "Default schema must be a string literal");
1128
+ return defaultSchemaExpr.value;
1044
1129
  }
1045
1130
  getFieldMappedDefault(field) {
1046
1131
  const defaultAttr = getAttribute(field, "@default");
@@ -1110,12 +1195,16 @@ var TsSchemaGenerator = class {
1110
1195
  relationFields.push(ts.factory.createPropertyAssignment("name", ts.factory.createStringLiteral(relationName)));
1111
1196
  }
1112
1197
  const relation = getAttribute(field, "@relation");
1198
+ const fkFields = [];
1113
1199
  if (relation) {
1114
1200
  for (const arg of relation.args) {
1115
1201
  const param = arg.$resolvedParam.name;
1116
1202
  if (param === "fields" || param === "references") {
1117
1203
  const fieldNames = this.getReferenceNames(arg.value);
1118
1204
  if (fieldNames) {
1205
+ if (param === "fields") {
1206
+ fkFields.push(...fieldNames);
1207
+ }
1119
1208
  relationFields.push(ts.factory.createPropertyAssignment(param, ts.factory.createArrayLiteralExpression(fieldNames.map((el) => ts.factory.createStringLiteral(el)))));
1120
1209
  }
1121
1210
  }
@@ -1125,6 +1214,15 @@ var TsSchemaGenerator = class {
1125
1214
  }
1126
1215
  }
1127
1216
  }
1217
+ if (fkFields.length > 0) {
1218
+ const allHaveDefault = fkFields.every((fieldName) => {
1219
+ const fieldDef = field.$container.fields.find((f) => f.name === fieldName);
1220
+ return fieldDef && hasAttribute(fieldDef, "@default");
1221
+ });
1222
+ if (allHaveDefault) {
1223
+ relationFields.push(ts.factory.createPropertyAssignment("hasDefault", ts.factory.createTrue()));
1224
+ }
1225
+ }
1128
1226
  return ts.factory.createObjectLiteralExpression(relationFields);
1129
1227
  }
1130
1228
  getReferenceNames(expr) {
@@ -1193,7 +1291,11 @@ var TsSchemaGenerator = class {
1193
1291
  const seenKeys = /* @__PURE__ */ new Set();
1194
1292
  for (const attr of allAttributes) {
1195
1293
  if (attr.decl.$refText === "@@id" || attr.decl.$refText === "@@unique") {
1196
- const fieldNames = this.getReferenceNames(attr.args[0].value);
1294
+ const fieldsArg = getAttributeArg(attr, "fields");
1295
+ if (!fieldsArg) {
1296
+ continue;
1297
+ }
1298
+ const fieldNames = this.getReferenceNames(fieldsArg);
1197
1299
  if (!fieldNames) {
1198
1300
  continue;
1199
1301
  }
@@ -1232,7 +1334,21 @@ var TsSchemaGenerator = class {
1232
1334
  return field.type.type ? ts.factory.createStringLiteral(field.type.type) : field.type.reference ? ts.factory.createStringLiteral(field.type.reference.$refText) : ts.factory.createStringLiteral("Unsupported");
1233
1335
  }
1234
1336
  createEnumObject(e) {
1235
- return ts.factory.createObjectLiteralExpression(e.fields.map((field) => ts.factory.createPropertyAssignment(field.name, ts.factory.createStringLiteral(field.name))), true);
1337
+ return ts.factory.createObjectLiteralExpression([
1338
+ ts.factory.createPropertyAssignment("values", ts.factory.createObjectLiteralExpression(e.fields.map((f) => ts.factory.createPropertyAssignment(f.name, ts.factory.createStringLiteral(f.name))), true)),
1339
+ // only generate `fields` if there are attributes on the fields
1340
+ ...e.fields.some((f) => f.attributes.length > 0) ? [
1341
+ ts.factory.createPropertyAssignment("fields", ts.factory.createObjectLiteralExpression(e.fields.map((field) => ts.factory.createPropertyAssignment(field.name, ts.factory.createObjectLiteralExpression([
1342
+ ts.factory.createPropertyAssignment("name", ts.factory.createStringLiteral(field.name)),
1343
+ ...field.attributes.length > 0 ? [
1344
+ ts.factory.createPropertyAssignment("attributes", ts.factory.createArrayLiteralExpression(field.attributes?.map((attr) => this.createAttributeObject(attr)) ?? [], true))
1345
+ ] : []
1346
+ ], true))), true))
1347
+ ] : [],
1348
+ ...e.attributes.length > 0 ? [
1349
+ ts.factory.createPropertyAssignment("attributes", ts.factory.createArrayLiteralExpression(e.attributes.map((attr) => this.createAttributeObject(attr)), true))
1350
+ ] : []
1351
+ ], true);
1236
1352
  }
1237
1353
  getLiteral(expr) {
1238
1354
  if (!isLiteralExpr3(expr)) {
@@ -1249,7 +1365,10 @@ var TsSchemaGenerator = class {
1249
1365
  }
1250
1366
  }
1251
1367
  createLiteralNode(arg) {
1252
- return arg === null ? ts.factory.createNull() : typeof arg === "string" ? ts.factory.createStringLiteral(arg) : typeof arg === "number" ? ts.factory.createNumericLiteral(arg) : arg === true ? ts.factory.createTrue() : arg === false ? ts.factory.createFalse() : void 0;
1368
+ return arg === null ? ts.factory.createNull() : typeof arg === "string" ? ts.factory.createStringLiteral(arg) : typeof arg === "number" ? this.createNumberLiteral(arg) : arg === true ? ts.factory.createTrue() : arg === false ? ts.factory.createFalse() : void 0;
1369
+ }
1370
+ createNumberLiteral(arg) {
1371
+ return arg < 0 ? ts.factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, ts.factory.createNumericLiteral(-arg)) : ts.factory.createNumericLiteral(arg);
1253
1372
  }
1254
1373
  createProceduresObject(procedures) {
1255
1374
  return ts.factory.createObjectLiteralExpression(procedures.map((proc) => ts.factory.createPropertyAssignment(proc.name, this.createProcedureObject(proc))), true);
@@ -1381,16 +1500,16 @@ var TsSchemaGenerator = class {
1381
1500
  throw new Error(`Unsupported literal type: ${type}`);
1382
1501
  });
1383
1502
  }
1384
- generateModelsAndTypeDefs(model, outputDir) {
1503
+ generateModelsAndTypeDefs(model, options) {
1385
1504
  const statements = [];
1386
- statements.push(this.generateSchemaImport(model, true, true));
1505
+ statements.push(this.generateSchemaImport(model, true, true, !!(options.lite || options.liteOnly), options.importWithFileExtension));
1387
1506
  statements.push(ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(false, void 0, ts.factory.createNamedImports([
1388
1507
  ts.factory.createImportSpecifier(true, void 0, ts.factory.createIdentifier(`ModelResult as $ModelResult`)),
1389
1508
  ...model.declarations.some(isTypeDef3) ? [
1390
1509
  ts.factory.createImportSpecifier(true, void 0, ts.factory.createIdentifier(`TypeDefResult as $TypeDefResult`))
1391
1510
  ] : []
1392
- ])), ts.factory.createStringLiteral("@zenstackhq/runtime")));
1393
- const dataModels = model.declarations.filter(isDataModel3);
1511
+ ])), ts.factory.createStringLiteral("@zenstackhq/orm")));
1512
+ const dataModels = this.getAllDataModels(model);
1394
1513
  for (const dm of dataModels) {
1395
1514
  let modelType = ts.factory.createTypeAliasDeclaration([
1396
1515
  ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)
@@ -1403,7 +1522,7 @@ var TsSchemaGenerator = class {
1403
1522
  }
1404
1523
  statements.push(modelType);
1405
1524
  }
1406
- const typeDefs = model.declarations.filter(isTypeDef3);
1525
+ const typeDefs = this.getAllTypeDefs(model);
1407
1526
  for (const td of typeDefs) {
1408
1527
  let typeDef = ts.factory.createTypeAliasDeclaration([
1409
1528
  ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)
@@ -1421,7 +1540,7 @@ var TsSchemaGenerator = class {
1421
1540
  let enumDecl = ts.factory.createVariableStatement([
1422
1541
  ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)
1423
1542
  ], ts.factory.createVariableDeclarationList([
1424
- 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)))
1543
+ 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")))
1425
1544
  ], ts.NodeFlags.Const));
1426
1545
  if (e.comments.length > 0) {
1427
1546
  enumDecl = this.generateDocs(enumDecl, e);
@@ -1436,13 +1555,13 @@ var TsSchemaGenerator = class {
1436
1555
  statements.push(typeAlias);
1437
1556
  }
1438
1557
  this.generateBannerComments(statements);
1439
- const outputFile = path.join(outputDir, "models.ts");
1558
+ const outputFile = path.join(options.outDir, "models.ts");
1440
1559
  const sourceFile = ts.createSourceFile(outputFile, "", ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS);
1441
1560
  const printer = ts.createPrinter();
1442
1561
  const result = printer.printList(ts.ListFormat.MultiLine, ts.factory.createNodeArray(statements), sourceFile);
1443
1562
  fs.writeFileSync(outputFile, result);
1444
1563
  }
1445
- generateSchemaImport(model, schemaObject, schemaType) {
1564
+ generateSchemaImport(model, schemaObject, schemaType, useLite, importWithFileExtension) {
1446
1565
  const importSpecifiers = [];
1447
1566
  if (schemaObject) {
1448
1567
  if (model.declarations.some(isEnum)) {
@@ -1452,17 +1571,21 @@ var TsSchemaGenerator = class {
1452
1571
  if (schemaType) {
1453
1572
  importSpecifiers.push(ts.factory.createImportSpecifier(true, ts.factory.createIdentifier("SchemaType"), ts.factory.createIdentifier("$Schema")));
1454
1573
  }
1455
- return ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(false, void 0, ts.factory.createNamedImports(importSpecifiers)), ts.factory.createStringLiteral("./schema"));
1574
+ let importFrom = useLite ? "./schema-lite" : "./schema";
1575
+ if (importWithFileExtension) {
1576
+ importFrom += importWithFileExtension.startsWith(".") ? importWithFileExtension : `.${importWithFileExtension}`;
1577
+ }
1578
+ return ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(false, void 0, ts.factory.createNamedImports(importSpecifiers)), ts.factory.createStringLiteral(importFrom));
1456
1579
  }
1457
1580
  generateDocs(tsDecl, decl) {
1458
1581
  return ts.addSyntheticLeadingComment(tsDecl, ts.SyntaxKind.MultiLineCommentTrivia, `*
1459
1582
  * ${decl.comments.map((c) => c.replace(/^\s*\/*\s*/, "")).join("\n * ")}
1460
1583
  `, true);
1461
1584
  }
1462
- generateInputTypes(model, outputDir) {
1463
- const dataModels = model.declarations.filter(isDataModel3);
1585
+ generateInputTypes(model, options) {
1586
+ const dataModels = this.getAllDataModels(model);
1464
1587
  const statements = [];
1465
- statements.push(this.generateSchemaImport(model, false, true));
1588
+ statements.push(this.generateSchemaImport(model, false, true, !!(options.lite || options.liteOnly), options.importWithFileExtension));
1466
1589
  const inputTypes = [
1467
1590
  "FindManyArgs",
1468
1591
  "FindUniqueArgs",
@@ -1489,11 +1612,14 @@ var TsSchemaGenerator = class {
1489
1612
  IncludeInput: "Include",
1490
1613
  OmitInput: "Omit"
1491
1614
  };
1492
- 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")));
1493
1615
  statements.push(ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(true, void 0, ts.factory.createNamedImports([
1494
- ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier("SimplifiedModelResult as $SimplifiedModelResult")),
1616
+ ...inputTypes.map((inputType) => ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier(`${inputType} as $${inputType}`))),
1617
+ ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier("QueryOptions as $QueryOptions"))
1618
+ ])), ts.factory.createStringLiteral("@zenstackhq/orm")));
1619
+ statements.push(ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(true, void 0, ts.factory.createNamedImports([
1620
+ ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier("SimplifiedPlainResult as $Result")),
1495
1621
  ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier("SelectIncludeOmit as $SelectIncludeOmit"))
1496
- ])), ts.factory.createStringLiteral("@zenstackhq/runtime")));
1622
+ ])), ts.factory.createStringLiteral("@zenstackhq/orm")));
1497
1623
  for (const dm of dataModels) {
1498
1624
  for (const inputType of inputTypes) {
1499
1625
  const exportName = inputTypeNameFixes[inputType] ? `${dm.name}${inputTypeNameFixes[inputType]}` : `${dm.name}${inputType}`;
@@ -1511,525 +1637,30 @@ var TsSchemaGenerator = class {
1511
1637
  ts.factory.createTypeReferenceNode("$Schema"),
1512
1638
  ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(dm.name)),
1513
1639
  ts.factory.createLiteralTypeNode(ts.factory.createTrue())
1640
+ ])),
1641
+ ts.factory.createTypeParameterDeclaration(void 0, "Options", ts.factory.createTypeReferenceNode("$QueryOptions", [
1642
+ ts.factory.createTypeReferenceNode("$Schema")
1643
+ ]), ts.factory.createTypeReferenceNode("$QueryOptions", [
1644
+ ts.factory.createTypeReferenceNode("$Schema")
1514
1645
  ]))
1515
- ], ts.factory.createTypeReferenceNode("$SimplifiedModelResult", [
1646
+ ], ts.factory.createTypeReferenceNode("$Result", [
1516
1647
  ts.factory.createTypeReferenceNode("$Schema"),
1517
1648
  ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(dm.name)),
1518
- ts.factory.createTypeReferenceNode("Args")
1649
+ ts.factory.createTypeReferenceNode("Args"),
1650
+ ts.factory.createTypeReferenceNode("Options")
1519
1651
  ])));
1520
1652
  }
1521
1653
  this.generateBannerComments(statements);
1522
- const outputFile = path.join(outputDir, "input.ts");
1654
+ const outputFile = path.join(options.outDir, "input.ts");
1523
1655
  const sourceFile = ts.createSourceFile(outputFile, "", ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS);
1524
1656
  const printer = ts.createPrinter();
1525
1657
  const result = printer.printList(ts.ListFormat.MultiLine, ts.factory.createNodeArray(statements), sourceFile);
1526
1658
  fs.writeFileSync(outputFile, result);
1527
1659
  }
1528
1660
  };
1529
-
1530
- // src/zmodel-code-generator.ts
1531
- 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";
1532
- function _ts_decorate(decorators, target, key, desc) {
1533
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1534
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1535
- 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;
1536
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1537
- }
1538
- __name(_ts_decorate, "_ts_decorate");
1539
- function _ts_metadata(k, v) {
1540
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1541
- }
1542
- __name(_ts_metadata, "_ts_metadata");
1543
- var generationHandlers = /* @__PURE__ */ new Map();
1544
- function gen(name) {
1545
- return function(_target, _propertyKey, descriptor) {
1546
- if (!generationHandlers.get(name)) {
1547
- generationHandlers.set(name, descriptor);
1548
- }
1549
- return descriptor;
1550
- };
1551
- }
1552
- __name(gen, "gen");
1553
- var ZModelCodeGenerator = class {
1554
- static {
1555
- __name(this, "ZModelCodeGenerator");
1556
- }
1557
- options;
1558
- constructor(options) {
1559
- this.options = {
1560
- binaryExprNumberOfSpaces: options?.binaryExprNumberOfSpaces ?? 1,
1561
- unaryExprNumberOfSpaces: options?.unaryExprNumberOfSpaces ?? 0,
1562
- indent: options?.indent ?? 4,
1563
- quote: options?.quote ?? "single"
1564
- };
1565
- }
1566
- /**
1567
- * Generates ZModel source code from AST.
1568
- */
1569
- generate(ast) {
1570
- const handler = generationHandlers.get(ast.$type);
1571
- if (!handler) {
1572
- throw new Error(`No generation handler found for ${ast.$type}`);
1573
- }
1574
- return handler.value.call(this, ast);
1575
- }
1576
- _generateModel(ast) {
1577
- return ast.declarations.map((d) => this.generate(d)).join("\n\n");
1578
- }
1579
- _generateDataSource(ast) {
1580
- return `datasource ${ast.name} {
1581
- ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}
1582
- }`;
1583
- }
1584
- _generateEnum(ast) {
1585
- return `enum ${ast.name} {
1586
- ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}
1587
- }`;
1588
- }
1589
- _generateEnumField(ast) {
1590
- return `${ast.name}${ast.attributes.length > 0 ? " " + ast.attributes.map((x) => this.generate(x)).join(" ") : ""}`;
1591
- }
1592
- _generateGenerator(ast) {
1593
- return `generator ${ast.name} {
1594
- ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}
1595
- }`;
1596
- }
1597
- _generateConfigField(ast) {
1598
- return `${ast.name} = ${this.generate(ast.value)}`;
1599
- }
1600
- _generateConfigArrayExpr(ast) {
1601
- return `[${ast.items.map((x) => this.generate(x)).join(", ")}]`;
1602
- }
1603
- _generateConfigInvocationExpr(ast) {
1604
- if (ast.args.length === 0) {
1605
- return ast.name;
1606
- } else {
1607
- return `${ast.name}(${ast.args.map((x) => (x.name ? x.name + ": " : "") + this.generate(x.value)).join(", ")})`;
1608
- }
1609
- }
1610
- _generatePlugin(ast) {
1611
- return `plugin ${ast.name} {
1612
- ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}
1613
- }`;
1614
- }
1615
- _generatePluginField(ast) {
1616
- return `${ast.name} = ${this.generate(ast.value)}`;
1617
- }
1618
- _generateDataModel(ast) {
1619
- return `${ast.isView ? "view" : "model"} ${ast.name}${ast.mixins.length > 0 ? " mixes " + ast.mixins.map((x) => x.ref?.name).join(", ") : ""} {
1620
- ${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") : ""}
1621
- }`;
1622
- }
1623
- _generateDataField(ast) {
1624
- return `${ast.name} ${this.fieldType(ast.type)}${ast.attributes.length > 0 ? " " + ast.attributes.map((x) => this.generate(x)).join(" ") : ""}`;
1625
- }
1626
- fieldType(type) {
1627
- const baseType = type.type ? type.type : type.$type == "DataFieldType" && type.unsupported ? "Unsupported(" + this.generate(type.unsupported.value) + ")" : type.reference?.$refText;
1628
- return `${baseType}${type.array ? "[]" : ""}${type.optional ? "?" : ""}`;
1629
- }
1630
- _generateDataModelAttribute(ast) {
1631
- return this.attribute(ast);
1632
- }
1633
- _generateDataFieldAttribute(ast) {
1634
- return this.attribute(ast);
1635
- }
1636
- attribute(ast) {
1637
- const args = ast.args.length ? `(${ast.args.map((x) => this.generate(x)).join(", ")})` : "";
1638
- return `${resolved(ast.decl).name}${args}`;
1639
- }
1640
- _generateAttributeArg(ast) {
1641
- if (ast.name) {
1642
- return `${ast.name}: ${this.generate(ast.value)}`;
1643
- } else {
1644
- return this.generate(ast.value);
1645
- }
1646
- }
1647
- _generateObjectExpr(ast) {
1648
- return `{ ${ast.fields.map((field) => this.objectField(field)).join(", ")} }`;
1649
- }
1650
- objectField(field) {
1651
- return `${field.name}: ${this.generate(field.value)}`;
1652
- }
1653
- _generateArrayExpr(ast) {
1654
- return `[${ast.items.map((item) => this.generate(item)).join(", ")}]`;
1655
- }
1656
- _generateLiteralExpr(ast) {
1657
- return this.options.quote === "single" ? `'${ast.value}'` : `"${ast.value}"`;
1658
- }
1659
- _generateNumberLiteral(ast) {
1660
- return ast.value.toString();
1661
- }
1662
- _generateBooleanLiteral(ast) {
1663
- return ast.value.toString();
1664
- }
1665
- _generateUnaryExpr(ast) {
1666
- return `${ast.operator}${this.unaryExprSpace}${this.generate(ast.operand)}`;
1667
- }
1668
- _generateBinaryExpr(ast) {
1669
- const operator = ast.operator;
1670
- const isCollectionPredicate = this.isCollectionPredicateOperator(operator);
1671
- const rightExpr = this.generate(ast.right);
1672
- const { left: isLeftParenthesis, right: isRightParenthesis } = this.isParenthesesNeededForBinaryExpr(ast);
1673
- return `${isLeftParenthesis ? "(" : ""}${this.generate(ast.left)}${isLeftParenthesis ? ")" : ""}${isCollectionPredicate ? "" : this.binaryExprSpace}${operator}${isCollectionPredicate ? "" : this.binaryExprSpace}${isRightParenthesis ? "(" : ""}${isCollectionPredicate ? `[${rightExpr}]` : rightExpr}${isRightParenthesis ? ")" : ""}`;
1674
- }
1675
- _generateReferenceExpr(ast) {
1676
- const args = ast.args.length ? `(${ast.args.map((x) => this.generate(x)).join(", ")})` : "";
1677
- return `${ast.target.ref?.name}${args}`;
1678
- }
1679
- _generateReferenceArg(ast) {
1680
- return `${ast.name}:${this.generate(ast.value)}`;
1681
- }
1682
- _generateMemberExpr(ast) {
1683
- return `${this.generate(ast.operand)}.${ast.member.ref?.name}`;
1684
- }
1685
- _generateInvocationExpr(ast) {
1686
- return `${ast.function.ref?.name}(${ast.args.map((x) => this.argument(x)).join(", ")})`;
1687
- }
1688
- _generateNullExpr() {
1689
- return "null";
1690
- }
1691
- _generateThisExpr() {
1692
- return "this";
1693
- }
1694
- _generateAttribute(ast) {
1695
- return `attribute ${ast.name}(${ast.params.map((x) => this.generate(x)).join(", ")})`;
1696
- }
1697
- _generateAttributeParam(ast) {
1698
- return `${ast.default ? "_ " : ""}${ast.name}: ${this.generate(ast.type)}`;
1699
- }
1700
- _generateAttributeParamType(ast) {
1701
- return `${ast.type ?? ast.reference?.$refText}${ast.array ? "[]" : ""}${ast.optional ? "?" : ""}`;
1702
- }
1703
- _generateFunctionDecl(ast) {
1704
- return `function ${ast.name}(${ast.params.map((x) => this.generate(x)).join(", ")}) ${ast.returnType ? ": " + this.generate(ast.returnType) : ""} {}`;
1705
- }
1706
- _generateFunctionParam(ast) {
1707
- return `${ast.name}: ${this.generate(ast.type)}`;
1708
- }
1709
- _generateFunctionParamType(ast) {
1710
- return `${ast.type ?? ast.reference?.$refText}${ast.array ? "[]" : ""}`;
1711
- }
1712
- _generateTypeDef(ast) {
1713
- return `type ${ast.name} {
1714
- ${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") : ""}
1715
- }`;
1716
- }
1717
- argument(ast) {
1718
- return this.generate(ast.value);
1719
- }
1720
- get binaryExprSpace() {
1721
- return " ".repeat(this.options.binaryExprNumberOfSpaces);
1722
- }
1723
- get unaryExprSpace() {
1724
- return " ".repeat(this.options.unaryExprNumberOfSpaces);
1725
- }
1726
- get indent() {
1727
- return " ".repeat(this.options.indent);
1728
- }
1729
- isParenthesesNeededForBinaryExpr(ast) {
1730
- const result = {
1731
- left: false,
1732
- right: false
1733
- };
1734
- const operator = ast.operator;
1735
- const isCollectionPredicate = this.isCollectionPredicateOperator(operator);
1736
- const currentPriority = BinaryExprOperatorPriority[operator];
1737
- if (ast.left.$type === BinaryExpr && BinaryExprOperatorPriority[ast.left["operator"]] < currentPriority) {
1738
- result.left = true;
1739
- }
1740
- if (!isCollectionPredicate && ast.right.$type === BinaryExpr && BinaryExprOperatorPriority[ast.right["operator"]] <= currentPriority) {
1741
- result.right = true;
1742
- }
1743
- return result;
1744
- }
1745
- isCollectionPredicateOperator(op) {
1746
- return [
1747
- "?",
1748
- "!",
1749
- "^"
1750
- ].includes(op);
1751
- }
1752
- };
1753
- _ts_decorate([
1754
- gen(Model2),
1755
- _ts_metadata("design:type", Function),
1756
- _ts_metadata("design:paramtypes", [
1757
- typeof Model2 === "undefined" ? Object : Model2
1758
- ]),
1759
- _ts_metadata("design:returntype", void 0)
1760
- ], ZModelCodeGenerator.prototype, "_generateModel", null);
1761
- _ts_decorate([
1762
- gen(DataSource3),
1763
- _ts_metadata("design:type", Function),
1764
- _ts_metadata("design:paramtypes", [
1765
- typeof DataSource3 === "undefined" ? Object : DataSource3
1766
- ]),
1767
- _ts_metadata("design:returntype", void 0)
1768
- ], ZModelCodeGenerator.prototype, "_generateDataSource", null);
1769
- _ts_decorate([
1770
- gen(Enum3),
1771
- _ts_metadata("design:type", Function),
1772
- _ts_metadata("design:paramtypes", [
1773
- typeof Enum3 === "undefined" ? Object : Enum3
1774
- ]),
1775
- _ts_metadata("design:returntype", void 0)
1776
- ], ZModelCodeGenerator.prototype, "_generateEnum", null);
1777
- _ts_decorate([
1778
- gen(EnumField2),
1779
- _ts_metadata("design:type", Function),
1780
- _ts_metadata("design:paramtypes", [
1781
- typeof EnumField2 === "undefined" ? Object : EnumField2
1782
- ]),
1783
- _ts_metadata("design:returntype", void 0)
1784
- ], ZModelCodeGenerator.prototype, "_generateEnumField", null);
1785
- _ts_decorate([
1786
- gen(GeneratorDecl2),
1787
- _ts_metadata("design:type", Function),
1788
- _ts_metadata("design:paramtypes", [
1789
- typeof GeneratorDecl2 === "undefined" ? Object : GeneratorDecl2
1790
- ]),
1791
- _ts_metadata("design:returntype", void 0)
1792
- ], ZModelCodeGenerator.prototype, "_generateGenerator", null);
1793
- _ts_decorate([
1794
- gen(ConfigField),
1795
- _ts_metadata("design:type", Function),
1796
- _ts_metadata("design:paramtypes", [
1797
- typeof ConfigField === "undefined" ? Object : ConfigField
1798
- ]),
1799
- _ts_metadata("design:returntype", void 0)
1800
- ], ZModelCodeGenerator.prototype, "_generateConfigField", null);
1801
- _ts_decorate([
1802
- gen(ConfigArrayExpr),
1803
- _ts_metadata("design:type", Function),
1804
- _ts_metadata("design:paramtypes", [
1805
- typeof ConfigArrayExpr === "undefined" ? Object : ConfigArrayExpr
1806
- ]),
1807
- _ts_metadata("design:returntype", void 0)
1808
- ], ZModelCodeGenerator.prototype, "_generateConfigArrayExpr", null);
1809
- _ts_decorate([
1810
- gen(ConfigInvocationExpr),
1811
- _ts_metadata("design:type", Function),
1812
- _ts_metadata("design:paramtypes", [
1813
- typeof ConfigInvocationExpr === "undefined" ? Object : ConfigInvocationExpr
1814
- ]),
1815
- _ts_metadata("design:returntype", void 0)
1816
- ], ZModelCodeGenerator.prototype, "_generateConfigInvocationExpr", null);
1817
- _ts_decorate([
1818
- gen(Plugin),
1819
- _ts_metadata("design:type", Function),
1820
- _ts_metadata("design:paramtypes", [
1821
- typeof Plugin === "undefined" ? Object : Plugin
1822
- ]),
1823
- _ts_metadata("design:returntype", void 0)
1824
- ], ZModelCodeGenerator.prototype, "_generatePlugin", null);
1825
- _ts_decorate([
1826
- gen(PluginField),
1827
- _ts_metadata("design:type", Function),
1828
- _ts_metadata("design:paramtypes", [
1829
- typeof PluginField === "undefined" ? Object : PluginField
1830
- ]),
1831
- _ts_metadata("design:returntype", void 0)
1832
- ], ZModelCodeGenerator.prototype, "_generatePluginField", null);
1833
- _ts_decorate([
1834
- gen(DataModel2),
1835
- _ts_metadata("design:type", Function),
1836
- _ts_metadata("design:paramtypes", [
1837
- typeof DataModel2 === "undefined" ? Object : DataModel2
1838
- ]),
1839
- _ts_metadata("design:returntype", void 0)
1840
- ], ZModelCodeGenerator.prototype, "_generateDataModel", null);
1841
- _ts_decorate([
1842
- gen(DataField),
1843
- _ts_metadata("design:type", Function),
1844
- _ts_metadata("design:paramtypes", [
1845
- typeof DataField === "undefined" ? Object : DataField
1846
- ]),
1847
- _ts_metadata("design:returntype", void 0)
1848
- ], ZModelCodeGenerator.prototype, "_generateDataField", null);
1849
- _ts_decorate([
1850
- gen(DataModelAttribute),
1851
- _ts_metadata("design:type", Function),
1852
- _ts_metadata("design:paramtypes", [
1853
- typeof DataModelAttribute === "undefined" ? Object : DataModelAttribute
1854
- ]),
1855
- _ts_metadata("design:returntype", void 0)
1856
- ], ZModelCodeGenerator.prototype, "_generateDataModelAttribute", null);
1857
- _ts_decorate([
1858
- gen(DataFieldAttribute),
1859
- _ts_metadata("design:type", Function),
1860
- _ts_metadata("design:paramtypes", [
1861
- typeof DataFieldAttribute === "undefined" ? Object : DataFieldAttribute
1862
- ]),
1863
- _ts_metadata("design:returntype", void 0)
1864
- ], ZModelCodeGenerator.prototype, "_generateDataFieldAttribute", null);
1865
- _ts_decorate([
1866
- gen(AttributeArg2),
1867
- _ts_metadata("design:type", Function),
1868
- _ts_metadata("design:paramtypes", [
1869
- typeof AttributeArg2 === "undefined" ? Object : AttributeArg2
1870
- ]),
1871
- _ts_metadata("design:returntype", void 0)
1872
- ], ZModelCodeGenerator.prototype, "_generateAttributeArg", null);
1873
- _ts_decorate([
1874
- gen(ObjectExpr),
1875
- _ts_metadata("design:type", Function),
1876
- _ts_metadata("design:paramtypes", [
1877
- typeof ObjectExpr === "undefined" ? Object : ObjectExpr
1878
- ]),
1879
- _ts_metadata("design:returntype", void 0)
1880
- ], ZModelCodeGenerator.prototype, "_generateObjectExpr", null);
1881
- _ts_decorate([
1882
- gen(ArrayExpr),
1883
- _ts_metadata("design:type", Function),
1884
- _ts_metadata("design:paramtypes", [
1885
- typeof ArrayExpr === "undefined" ? Object : ArrayExpr
1886
- ]),
1887
- _ts_metadata("design:returntype", void 0)
1888
- ], ZModelCodeGenerator.prototype, "_generateArrayExpr", null);
1889
- _ts_decorate([
1890
- gen(StringLiteral2),
1891
- _ts_metadata("design:type", Function),
1892
- _ts_metadata("design:paramtypes", [
1893
- typeof LiteralExpr === "undefined" ? Object : LiteralExpr
1894
- ]),
1895
- _ts_metadata("design:returntype", void 0)
1896
- ], ZModelCodeGenerator.prototype, "_generateLiteralExpr", null);
1897
- _ts_decorate([
1898
- gen(NumberLiteral2),
1899
- _ts_metadata("design:type", Function),
1900
- _ts_metadata("design:paramtypes", [
1901
- typeof NumberLiteral2 === "undefined" ? Object : NumberLiteral2
1902
- ]),
1903
- _ts_metadata("design:returntype", void 0)
1904
- ], ZModelCodeGenerator.prototype, "_generateNumberLiteral", null);
1905
- _ts_decorate([
1906
- gen(BooleanLiteral2),
1907
- _ts_metadata("design:type", Function),
1908
- _ts_metadata("design:paramtypes", [
1909
- typeof BooleanLiteral2 === "undefined" ? Object : BooleanLiteral2
1910
- ]),
1911
- _ts_metadata("design:returntype", void 0)
1912
- ], ZModelCodeGenerator.prototype, "_generateBooleanLiteral", null);
1913
- _ts_decorate([
1914
- gen(UnaryExpr),
1915
- _ts_metadata("design:type", Function),
1916
- _ts_metadata("design:paramtypes", [
1917
- typeof UnaryExpr === "undefined" ? Object : UnaryExpr
1918
- ]),
1919
- _ts_metadata("design:returntype", void 0)
1920
- ], ZModelCodeGenerator.prototype, "_generateUnaryExpr", null);
1921
- _ts_decorate([
1922
- gen(BinaryExpr),
1923
- _ts_metadata("design:type", Function),
1924
- _ts_metadata("design:paramtypes", [
1925
- typeof BinaryExpr === "undefined" ? Object : BinaryExpr
1926
- ]),
1927
- _ts_metadata("design:returntype", void 0)
1928
- ], ZModelCodeGenerator.prototype, "_generateBinaryExpr", null);
1929
- _ts_decorate([
1930
- gen(ReferenceExpr),
1931
- _ts_metadata("design:type", Function),
1932
- _ts_metadata("design:paramtypes", [
1933
- typeof ReferenceExpr === "undefined" ? Object : ReferenceExpr
1934
- ]),
1935
- _ts_metadata("design:returntype", void 0)
1936
- ], ZModelCodeGenerator.prototype, "_generateReferenceExpr", null);
1937
- _ts_decorate([
1938
- gen(ReferenceArg),
1939
- _ts_metadata("design:type", Function),
1940
- _ts_metadata("design:paramtypes", [
1941
- typeof ReferenceArg === "undefined" ? Object : ReferenceArg
1942
- ]),
1943
- _ts_metadata("design:returntype", void 0)
1944
- ], ZModelCodeGenerator.prototype, "_generateReferenceArg", null);
1945
- _ts_decorate([
1946
- gen(MemberAccessExpr),
1947
- _ts_metadata("design:type", Function),
1948
- _ts_metadata("design:paramtypes", [
1949
- typeof MemberAccessExpr === "undefined" ? Object : MemberAccessExpr
1950
- ]),
1951
- _ts_metadata("design:returntype", void 0)
1952
- ], ZModelCodeGenerator.prototype, "_generateMemberExpr", null);
1953
- _ts_decorate([
1954
- gen(InvocationExpr),
1955
- _ts_metadata("design:type", Function),
1956
- _ts_metadata("design:paramtypes", [
1957
- typeof InvocationExpr === "undefined" ? Object : InvocationExpr
1958
- ]),
1959
- _ts_metadata("design:returntype", void 0)
1960
- ], ZModelCodeGenerator.prototype, "_generateInvocationExpr", null);
1961
- _ts_decorate([
1962
- gen(NullExpr),
1963
- _ts_metadata("design:type", Function),
1964
- _ts_metadata("design:paramtypes", []),
1965
- _ts_metadata("design:returntype", void 0)
1966
- ], ZModelCodeGenerator.prototype, "_generateNullExpr", null);
1967
- _ts_decorate([
1968
- gen(ThisExpr),
1969
- _ts_metadata("design:type", Function),
1970
- _ts_metadata("design:paramtypes", []),
1971
- _ts_metadata("design:returntype", void 0)
1972
- ], ZModelCodeGenerator.prototype, "_generateThisExpr", null);
1973
- _ts_decorate([
1974
- gen(Attribute),
1975
- _ts_metadata("design:type", Function),
1976
- _ts_metadata("design:paramtypes", [
1977
- typeof Attribute === "undefined" ? Object : Attribute
1978
- ]),
1979
- _ts_metadata("design:returntype", void 0)
1980
- ], ZModelCodeGenerator.prototype, "_generateAttribute", null);
1981
- _ts_decorate([
1982
- gen(AttributeParam),
1983
- _ts_metadata("design:type", Function),
1984
- _ts_metadata("design:paramtypes", [
1985
- typeof AttributeParam === "undefined" ? Object : AttributeParam
1986
- ]),
1987
- _ts_metadata("design:returntype", void 0)
1988
- ], ZModelCodeGenerator.prototype, "_generateAttributeParam", null);
1989
- _ts_decorate([
1990
- gen(AttributeParamType),
1991
- _ts_metadata("design:type", Function),
1992
- _ts_metadata("design:paramtypes", [
1993
- typeof AttributeParamType === "undefined" ? Object : AttributeParamType
1994
- ]),
1995
- _ts_metadata("design:returntype", void 0)
1996
- ], ZModelCodeGenerator.prototype, "_generateAttributeParamType", null);
1997
- _ts_decorate([
1998
- gen(FunctionDecl),
1999
- _ts_metadata("design:type", Function),
2000
- _ts_metadata("design:paramtypes", [
2001
- typeof FunctionDecl === "undefined" ? Object : FunctionDecl
2002
- ]),
2003
- _ts_metadata("design:returntype", void 0)
2004
- ], ZModelCodeGenerator.prototype, "_generateFunctionDecl", null);
2005
- _ts_decorate([
2006
- gen(FunctionParam),
2007
- _ts_metadata("design:type", Function),
2008
- _ts_metadata("design:paramtypes", [
2009
- typeof FunctionParam === "undefined" ? Object : FunctionParam
2010
- ]),
2011
- _ts_metadata("design:returntype", void 0)
2012
- ], ZModelCodeGenerator.prototype, "_generateFunctionParam", null);
2013
- _ts_decorate([
2014
- gen(FunctionParamType),
2015
- _ts_metadata("design:type", Function),
2016
- _ts_metadata("design:paramtypes", [
2017
- typeof FunctionParamType === "undefined" ? Object : FunctionParamType
2018
- ]),
2019
- _ts_metadata("design:returntype", void 0)
2020
- ], ZModelCodeGenerator.prototype, "_generateFunctionParamType", null);
2021
- _ts_decorate([
2022
- gen(TypeDef),
2023
- _ts_metadata("design:type", Function),
2024
- _ts_metadata("design:paramtypes", [
2025
- typeof TypeDef === "undefined" ? Object : TypeDef
2026
- ]),
2027
- _ts_metadata("design:returntype", void 0)
2028
- ], ZModelCodeGenerator.prototype, "_generateTypeDef", null);
2029
1661
  export {
2030
1662
  model_utils_exports as ModelUtils,
2031
1663
  PrismaSchemaGenerator,
2032
- TsSchemaGenerator,
2033
- ZModelCodeGenerator
1664
+ TsSchemaGenerator
2034
1665
  };
2035
1666
  //# sourceMappingURL=index.js.map