@aws-amplify/data-schema 1.3.7 → 1.3.9

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.
@@ -17,10 +17,14 @@ function combine(schemas) {
17
17
  exports.combine = combine;
18
18
  function internalCombine(schemas) {
19
19
  validateDuplicateTypeNames(schemas);
20
- return {
20
+ const combined = {
21
21
  ...exports.combinedSchemaBrand,
22
22
  schemas: schemas,
23
23
  };
24
+ for (const schema of combined.schemas) {
25
+ schema.context = combined;
26
+ }
27
+ return combined;
24
28
  }
25
29
  function validateDuplicateTypeNames(schemas) {
26
30
  const allSchemaKeys = schemas.flatMap((s) => Object.keys(s.data.types));
@@ -1 +1 @@
1
- {"version":3,"file":"CombineSchema.js","sources":["../../src/CombineSchema.ts"],"sourcesContent":["\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.combine = exports.combinedSchemaBrand = void 0;\nconst util_1 = require(\"./util\");\nconst COMBINED_SCHEMA_LIMIT = 50;\nconst CombinedSchemaBrandName = 'CombinedSchema';\nexports.combinedSchemaBrand = (0, util_1.brand)(CombinedSchemaBrandName);\n/**\n * The interface for merging up to 50 schemas into a single API.\n * @param schemas The schemas to combine into a single API\n * @returns An API and data model definition to be deployed with Amplify (Gen 2) experience (`processSchema(...)`)\n * or with the Amplify Data CDK construct (`@aws-amplify/data-construct`)\n */\nfunction combine(schemas) {\n return internalCombine(schemas);\n}\nexports.combine = combine;\nfunction internalCombine(schemas) {\n validateDuplicateTypeNames(schemas);\n return {\n ...exports.combinedSchemaBrand,\n schemas: schemas,\n };\n}\nfunction validateDuplicateTypeNames(schemas) {\n const allSchemaKeys = schemas.flatMap((s) => Object.keys(s.data.types));\n const keySet = new Set();\n const duplicateKeySet = new Set();\n allSchemaKeys.forEach((key) => {\n if (keySet.has(key)) {\n duplicateKeySet.add(key);\n }\n else {\n keySet.add(key);\n }\n });\n if (duplicateKeySet.size > 0) {\n throw new Error(`The schemas you are attempting to combine have a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,GAAG,CAAC,CAAC;AACrC,SAAS;AACT,aAAa;AACb,YAAY,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAC5B,SAAS;AACT,KAAK,CAAC,CAAC;AACP,IAAI,IAAI,eAAe,CAAC,IAAI,GAAG,CAAC,EAAE;AAClC,QAAQ,MAAM,IAAI,KAAK,CAAC,CAAC,yFAAyF,EAAE,KAAK,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAC/J,KAAK;AACL;;"}
1
+ {"version":3,"file":"CombineSchema.js","sources":["../../src/CombineSchema.ts"],"sourcesContent":["\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.combine = exports.combinedSchemaBrand = void 0;\nconst util_1 = require(\"./util\");\nconst COMBINED_SCHEMA_LIMIT = 50;\nconst CombinedSchemaBrandName = 'CombinedSchema';\nexports.combinedSchemaBrand = (0, util_1.brand)(CombinedSchemaBrandName);\n/**\n * The interface for merging up to 50 schemas into a single API.\n * @param schemas The schemas to combine into a single API\n * @returns An API and data model definition to be deployed with Amplify (Gen 2) experience (`processSchema(...)`)\n * or with the Amplify Data CDK construct (`@aws-amplify/data-construct`)\n */\nfunction combine(schemas) {\n return internalCombine(schemas);\n}\nexports.combine = combine;\nfunction internalCombine(schemas) {\n validateDuplicateTypeNames(schemas);\n const combined = {\n ...exports.combinedSchemaBrand,\n schemas: schemas,\n };\n for (const schema of combined.schemas) {\n schema.context = combined;\n }\n return combined;\n}\nfunction validateDuplicateTypeNames(schemas) {\n const allSchemaKeys = schemas.flatMap((s) => Object.keys(s.data.types));\n const keySet = new Set();\n const duplicateKeySet = new Set();\n allSchemaKeys.forEach((key) => {\n if (keySet.has(key)) {\n duplicateKeySet.add(key);\n }\n else {\n keySet.add(key);\n }\n });\n if (duplicateKeySet.size > 0) {\n throw new Error(`The schemas you are attempting to combine have a name collision. Please remove or rename ${Array.from(duplicateKeySet).join(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,CAAC,OAAO,CAAC,CAAC,GAAG,KAAK;AACnC,QAAQ,IAAI,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;AAC7B,YAAY,eAAe,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACrC,SAAS;AACT,aAAa;AACb,YAAY,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAC5B,SAAS;AACT,KAAK,CAAC,CAAC;AACP,IAAI,IAAI,eAAe,CAAC,IAAI,GAAG,CAAC,EAAE;AAClC,QAAQ,MAAM,IAAI,KAAK,CAAC,CAAC,yFAAyF,EAAE,KAAK,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAC/J,KAAK;AACL;;"}
@@ -60,7 +60,10 @@ function _rdsSchema(types, config) {
60
60
  data,
61
61
  models,
62
62
  transform() {
63
- const internalSchema = { data };
63
+ const internalSchema = {
64
+ data,
65
+ context: this.context,
66
+ };
64
67
  return (0, SchemaProcessor_1.processSchema)({ schema: internalSchema });
65
68
  },
66
69
  authorization(callback) {
@@ -136,7 +139,10 @@ function _ddbSchema(types, config) {
136
139
  return {
137
140
  data,
138
141
  transform() {
139
- const internalSchema = { data };
142
+ const internalSchema = {
143
+ data,
144
+ context: this.context,
145
+ };
140
146
  return (0, SchemaProcessor_1.processSchema)({ schema: internalSchema });
141
147
  },
142
148
  authorization(callback) {
@@ -1 +1 @@
1
- {"version":3,"file":"ModelSchema.js","sources":["../../src/ModelSchema.ts"],"sourcesContent":["\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isCustomPathData = exports.configure = exports.schema = exports.isModelSchema = exports.ddbSchemaBrandName = exports.rdsSchemaBrand = exports.rdsSchemaBrandName = void 0;\nconst ModelType_1 = require(\"./ModelType\");\nconst SchemaProcessor_1 = require(\"./SchemaProcessor\");\nconst Authorization_1 = require(\"./Authorization\");\nconst util_1 = require(\"./util\");\nexports.rdsSchemaBrandName = 'RDSSchema';\nexports.rdsSchemaBrand = (0, util_1.brand)(exports.rdsSchemaBrandName);\nexports.ddbSchemaBrandName = 'DDBSchema';\nconst ddbSchemaBrand = (0, util_1.brand)(exports.ddbSchemaBrandName);\n/**\n * Filter the schema types down to only include the ModelTypes as SchemaModelType\n *\n * @param schemaContents The object containing all SchemaContent for this schema\n * @returns Only the schemaContents that are ModelTypes, coerced to the SchemaModelType surface\n */\nconst filterSchemaModelTypes = (schemaContents) => {\n const modelTypes = {};\n if (schemaContents) {\n Object.entries(schemaContents).forEach(([key, content]) => {\n if ((0, ModelType_1.isSchemaModelType)(content)) {\n modelTypes[key] = content;\n }\n });\n }\n return modelTypes;\n};\n/**\n * Model Schema type guard\n * @param schema - api-next ModelSchema or string\n * @returns true if the given value is a ModelSchema\n */\nconst isModelSchema = (schema) => {\n return typeof schema === 'object' && schema.data !== undefined;\n};\nexports.isModelSchema = isModelSchema;\n/**\n * Ensures that only supported entities are being added to the SQL schema through `addToSchema`\n * Models are not supported for brownfield SQL\n *\n * @param types - purposely widened to ModelSchemaContents, because we need to validate at runtime that a model is not being passed in here\n */\nfunction validateAddToSchema(types) {\n for (const [name, type] of Object.entries(types)) {\n if ((0, util_1.getBrand)(type) === 'modelType') {\n throw new Error(`Invalid value specified for ${name} in addToSchema(). Models cannot be manually added to a SQL schema.`);\n }\n }\n}\nfunction _rdsSchema(types, config) {\n const data = {\n types,\n authorization: [],\n configuration: config,\n };\n const models = filterSchemaModelTypes(data.types);\n return {\n data,\n models,\n transform() {\n const internalSchema = { data };\n return (0, SchemaProcessor_1.processSchema)({ schema: internalSchema });\n },\n authorization(callback) {\n const rules = callback(Authorization_1.allow);\n this.data.authorization = Array.isArray(rules) ? rules : [rules];\n const { authorization: _, ...rest } = this;\n return rest;\n },\n addToSchema(types) {\n validateAddToSchema(types);\n this.data.types = { ...this.data.types, ...types };\n const { addToSchema: _, ...rest } = this;\n return rest;\n },\n addQueries(types) {\n this.data.types = { ...this.data.types, ...types };\n const { addQueries: _, ...rest } = this;\n return rest;\n },\n addMutations(types) {\n this.data.types = { ...this.data.types, ...types };\n const { addMutations: _, ...rest } = this;\n return rest;\n },\n addSubscriptions(types) {\n this.data.types = { ...this.data.types, ...types };\n const { addSubscriptions: _, ...rest } = this;\n return rest;\n },\n setAuthorization(callback) {\n callback(models, this);\n const { setAuthorization: _, ...rest } = this;\n return rest;\n },\n setRelationships(callback) {\n const { setRelationships: _, ...rest } = this;\n // The relationships are added via `models.<Model>.relationships`\n // modifiers that's being called within the callback. They are modifying\n // by references on each model, so there is not anything else to be done\n // here.\n callback(models);\n return rest;\n },\n renameModels(callback) {\n const { renameModels: _, ...rest } = this;\n // returns an array of tuples [curName, newName]\n const changeLog = callback();\n changeLog.forEach(([curName, newName]) => {\n const currentType = data.types[curName];\n if (currentType === undefined) {\n throw new Error(`Invalid renameModels call. ${curName} is not defined in the schema`);\n }\n if (typeof newName !== 'string' || newName.length < 1) {\n throw new Error(`Invalid renameModels call. New name must be a non-empty string. Received: \"${newName}\"`);\n }\n models[newName] = currentType;\n data.types[newName] = currentType;\n models[newName].data.originalName = curName;\n delete models[curName];\n delete data.types[curName];\n });\n return rest;\n },\n ...exports.rdsSchemaBrand,\n };\n}\nfunction _ddbSchema(types, config) {\n const data = {\n types,\n authorization: [],\n configuration: config,\n };\n return {\n data,\n transform() {\n const internalSchema = { data };\n return (0, SchemaProcessor_1.processSchema)({ schema: internalSchema });\n },\n authorization(callback) {\n const rules = callback(Authorization_1.allow);\n this.data.authorization = Array.isArray(rules) ? rules : [rules];\n const { authorization: _, ...rest } = this;\n return rest;\n },\n models: filterSchemaModelTypes(data.types),\n ...ddbSchemaBrand,\n };\n}\nfunction bindConfigToSchema(config) {\n return (types) => {\n return (config.database.engine === 'dynamodb'\n ? _ddbSchema(types, config)\n : _rdsSchema(types, config));\n };\n}\n/**\n * The API and data model definition for Amplify Data. Pass in `{ <NAME>: a.model(...) }` to create a database table\n * and exposes CRUDL operations via an API.\n * @param types The API and data model definition\n * @returns An API and data model definition to be deployed with Amplify (Gen 2) experience (`processSchema(...)`)\n * or with the Amplify Data CDK construct (`@aws-amplify/data-construct`)\n */\nexports.schema = bindConfigToSchema({ database: { engine: 'dynamodb' } });\n/**\n * Configure wraps schema definition with non-default config to allow usecases other than\n * the default DynamoDB use-case.\n *\n * @param config The SchemaConfig augments the schema with content like the database type\n * @returns\n */\nfunction configure(config) {\n return {\n schema: bindConfigToSchema(config),\n };\n}\nexports.configure = configure;\nfunction isCustomPathData(obj) {\n return ('stack' in obj &&\n (typeof obj.stack === 'undefined' || typeof obj.stack === 'string') &&\n 'entry' in obj &&\n typeof obj.entry === 'string');\n}\nexports.isCustomPathData = isCustomPathData;\n"],"names":[],"mappings":";;AACA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AAC9D,OAAO,CAAC,gBAAgB,GAAG,OAAO,CAAC,SAAS,GAAG,OAAO,CAAC,MAAM,GAAG,OAAO,CAAC,aAAa,GAAG,OAAO,CAAC,kBAAkB,GAAG,OAAO,CAAC,cAAc,GAAG,OAAO,CAAC,kBAAkB,GAAG,KAAK,CAAC,CAAC;AAClL,MAAM,WAAW,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;AAC3C,MAAM,iBAAiB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;AACvD,MAAM,eAAe,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;AACnD,MAAM,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AACjC,OAAO,CAAC,kBAAkB,GAAG,WAAW,CAAC;AACzC,OAAO,CAAC,cAAc,GAAG,IAAI,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,kBAAkB,CAAC,CAAC;AACvE,OAAO,CAAC,kBAAkB,GAAG,WAAW,CAAC;AACzC,MAAM,cAAc,GAAG,IAAI,MAAM,CAAC,KAAK,EAAE,OAAO,CAA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AC;AAC1C,KAAK,CAAC;AACN,CAAC;AACD,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC;AAC9B,SAAS,gBAAgB,CAAC,GAAG,EAAE;AAC/B,IAAI,QAAQ,OAAO,IAAI,GAAG;AAC1B,SAAS,OAAO,GAAG,CAAC,KAAK,KAAK,WAAW,IAAI,OAAO,GAAG,CAAC,KAAK,KAAK,QAAQ,CAAC;AAC3E,QAAQ,OAAO,IAAI,GAAG;AACtB,QAAQ,OAAO,GAAG,CAAC,KAAK,KAAK,QAAQ,EAAE;AACvC,CAAC;AACD,OAAO,CAAC,gBAAgB,GAAG,gBAAgB;;"}
1
+ {"version":3,"file":"ModelSchema.js","sources":["../../src/ModelSchema.ts"],"sourcesContent":["\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isCustomPathData = exports.configure = exports.schema = exports.isModelSchema = exports.ddbSchemaBrandName = exports.rdsSchemaBrand = exports.rdsSchemaBrandName = void 0;\nconst ModelType_1 = require(\"./ModelType\");\nconst SchemaProcessor_1 = require(\"./SchemaProcessor\");\nconst Authorization_1 = require(\"./Authorization\");\nconst util_1 = require(\"./util\");\nexports.rdsSchemaBrandName = 'RDSSchema';\nexports.rdsSchemaBrand = (0, util_1.brand)(exports.rdsSchemaBrandName);\nexports.ddbSchemaBrandName = 'DDBSchema';\nconst ddbSchemaBrand = (0, util_1.brand)(exports.ddbSchemaBrandName);\n/**\n * Filter the schema types down to only include the ModelTypes as SchemaModelType\n *\n * @param schemaContents The object containing all SchemaContent for this schema\n * @returns Only the schemaContents that are ModelTypes, coerced to the SchemaModelType surface\n */\nconst filterSchemaModelTypes = (schemaContents) => {\n const modelTypes = {};\n if (schemaContents) {\n Object.entries(schemaContents).forEach(([key, content]) => {\n if ((0, ModelType_1.isSchemaModelType)(content)) {\n modelTypes[key] = content;\n }\n });\n }\n return modelTypes;\n};\n/**\n * Model Schema type guard\n * @param schema - api-next ModelSchema or string\n * @returns true if the given value is a ModelSchema\n */\nconst isModelSchema = (schema) => {\n return typeof schema === 'object' && schema.data !== undefined;\n};\nexports.isModelSchema = isModelSchema;\n/**\n * Ensures that only supported entities are being added to the SQL schema through `addToSchema`\n * Models are not supported for brownfield SQL\n *\n * @param types - purposely widened to ModelSchemaContents, because we need to validate at runtime that a model is not being passed in here\n */\nfunction validateAddToSchema(types) {\n for (const [name, type] of Object.entries(types)) {\n if ((0, util_1.getBrand)(type) === 'modelType') {\n throw new Error(`Invalid value specified for ${name} in addToSchema(). Models cannot be manually added to a SQL schema.`);\n }\n }\n}\nfunction _rdsSchema(types, config) {\n const data = {\n types,\n authorization: [],\n configuration: config,\n };\n const models = filterSchemaModelTypes(data.types);\n return {\n data,\n models,\n transform() {\n const internalSchema = {\n data,\n context: this.context,\n };\n return (0, SchemaProcessor_1.processSchema)({ schema: internalSchema });\n },\n authorization(callback) {\n const rules = callback(Authorization_1.allow);\n this.data.authorization = Array.isArray(rules) ? rules : [rules];\n const { authorization: _, ...rest } = this;\n return rest;\n },\n addToSchema(types) {\n validateAddToSchema(types);\n this.data.types = { ...this.data.types, ...types };\n const { addToSchema: _, ...rest } = this;\n return rest;\n },\n addQueries(types) {\n this.data.types = { ...this.data.types, ...types };\n const { addQueries: _, ...rest } = this;\n return rest;\n },\n addMutations(types) {\n this.data.types = { ...this.data.types, ...types };\n const { addMutations: _, ...rest } = this;\n return rest;\n },\n addSubscriptions(types) {\n this.data.types = { ...this.data.types, ...types };\n const { addSubscriptions: _, ...rest } = this;\n return rest;\n },\n setAuthorization(callback) {\n callback(models, this);\n const { setAuthorization: _, ...rest } = this;\n return rest;\n },\n setRelationships(callback) {\n const { setRelationships: _, ...rest } = this;\n // The relationships are added via `models.<Model>.relationships`\n // modifiers that's being called within the callback. They are modifying\n // by references on each model, so there is not anything else to be done\n // here.\n callback(models);\n return rest;\n },\n renameModels(callback) {\n const { renameModels: _, ...rest } = this;\n // returns an array of tuples [curName, newName]\n const changeLog = callback();\n changeLog.forEach(([curName, newName]) => {\n const currentType = data.types[curName];\n if (currentType === undefined) {\n throw new Error(`Invalid renameModels call. ${curName} is not defined in the schema`);\n }\n if (typeof newName !== 'string' || newName.length < 1) {\n throw new Error(`Invalid renameModels call. New name must be a non-empty string. Received: \"${newName}\"`);\n }\n models[newName] = currentType;\n data.types[newName] = currentType;\n models[newName].data.originalName = curName;\n delete models[curName];\n delete data.types[curName];\n });\n return rest;\n },\n ...exports.rdsSchemaBrand,\n };\n}\nfunction _ddbSchema(types, config) {\n const data = {\n types,\n authorization: [],\n configuration: config,\n };\n return {\n data,\n transform() {\n const internalSchema = {\n data,\n context: this.context,\n };\n return (0, SchemaProcessor_1.processSchema)({ schema: internalSchema });\n },\n authorization(callback) {\n const rules = callback(Authorization_1.allow);\n this.data.authorization = Array.isArray(rules) ? rules : [rules];\n const { authorization: _, ...rest } = this;\n return rest;\n },\n models: filterSchemaModelTypes(data.types),\n ...ddbSchemaBrand,\n };\n}\nfunction bindConfigToSchema(config) {\n return (types) => {\n return (config.database.engine === 'dynamodb'\n ? _ddbSchema(types, config)\n : _rdsSchema(types, config));\n };\n}\n/**\n * The API and data model definition for Amplify Data. Pass in `{ <NAME>: a.model(...) }` to create a database table\n * and exposes CRUDL operations via an API.\n * @param types The API and data model definition\n * @returns An API and data model definition to be deployed with Amplify (Gen 2) experience (`processSchema(...)`)\n * or with the Amplify Data CDK construct (`@aws-amplify/data-construct`)\n */\nexports.schema = bindConfigToSchema({ database: { engine: 'dynamodb' } });\n/**\n * Configure wraps schema definition with non-default config to allow usecases other than\n * the default DynamoDB use-case.\n *\n * @param config The SchemaConfig augments the schema with content like the database type\n * @returns\n */\nfunction configure(config) {\n return {\n schema: bindConfigToSchema(config),\n };\n}\nexports.configure = configure;\nfunction isCustomPathData(obj) {\n return ('stack' in obj &&\n (typeof obj.stack === 'undefined' || typeof obj.stack === 'string') &&\n 'entry' in obj &&\n typeof obj.entry === 'string');\n}\nexports.isCustomPathData = isCustomPathData;\n"],"names":[],"mappings":";;AACA,MAAM,CAAC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C,gBAAgB,GAAG,gBAAgB;;"}
@@ -4,6 +4,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.processSchema = void 0;
5
5
  const tslib_1 = require("tslib");
6
6
  const ModelField_1 = require("./ModelField");
7
+ const ModelRelationalField_1 = require("./ModelRelationalField");
7
8
  const Authorization_1 = require("./Authorization");
8
9
  const CustomOperation_1 = require("./CustomOperation");
9
10
  const util_1 = require("./util");
@@ -698,14 +699,36 @@ const extractFunctionSchemaAccess = (authRules) => {
698
699
  }
699
700
  return { schemaAuth, functionSchemaAccess };
700
701
  };
702
+ /**
703
+ * Searches a schema and all related schemas (through `.combine()`) for the given type by name.
704
+ *
705
+ * @param schema
706
+ * @param name
707
+ * @returns
708
+ */
709
+ const findCombinedSchemaType = (schema, name) => {
710
+ if (schema.context) {
711
+ for (const contextualSchema of schema.context.schemas) {
712
+ if (contextualSchema.data.types[name]) {
713
+ return contextualSchema.data.types[name];
714
+ }
715
+ }
716
+ }
717
+ else {
718
+ return schema.data.types[name];
719
+ }
720
+ return undefined;
721
+ };
701
722
  /**
702
723
  * Returns a closure for retrieving reference type and definition from schema
703
724
  */
704
725
  const getRefTypeForSchema = (schema) => {
705
- const getRefType = (source, target) => {
706
- const typeDef = schema.data.types[source];
726
+ const getRefType = (name, referrerName) => {
727
+ const typeDef = findCombinedSchemaType(schema, name);
707
728
  if (typeDef === undefined) {
708
- throw new Error(`Invalid ref. ${target} is referencing ${source} which is not defined in the schema`);
729
+ throw new Error(referrerName
730
+ ? `Invalid ref. ${referrerName} is referring to ${name} which is not defined in the schema`
731
+ : `Invalid ref. ${name} is not defined in the schema`);
709
732
  }
710
733
  if (isInternalModel(typeDef)) {
711
734
  return { type: 'Model', def: typeDef };
@@ -719,7 +742,9 @@ const getRefTypeForSchema = (schema) => {
719
742
  if (isEnumType(typeDef)) {
720
743
  return { type: 'Enum', def: typeDef };
721
744
  }
722
- throw new Error(`Invalid ref. ${target} is referencing ${source} which is neither a Model, Custom Operation, Custom Type, or Enum`);
745
+ throw new Error(referrerName
746
+ ? `Invalid ref. ${referrerName} is referring to ${name} which is neither a Model, Custom Operation, Custom Type, or Enum`
747
+ : `Invalid ref. ${name} is neither a Model, Custom Operation, Custom Type, or Enum`);
723
748
  };
724
749
  return getRefType;
725
750
  };
@@ -870,6 +895,14 @@ const schemaPreprocessor = (schema) => {
870
895
  if (authString == '') {
871
896
  throw new Error(`Model \`${typeName}\` is missing authorization rules. Add global rules to the schema or ensure every model has its own rules.`);
872
897
  }
898
+ const getInternalModel = (modelName, sourceName) => {
899
+ const model = getRefType(modelName, sourceName);
900
+ if (!isInternalModel(model.def)) {
901
+ throw new Error(`Expected to find model type with name ${modelName}`);
902
+ }
903
+ return model.def;
904
+ };
905
+ validateRelationships(typeName, fields, getInternalModel);
873
906
  const fieldLevelAuthRules = processFieldLevelAuthRules(fields, authFields);
874
907
  const { gqlFields, implicitTypes } = processFields(typeName, fields, authFields, fieldLevelAuthRules, identifier, partitionKey, transformedSecondaryIndexes);
875
908
  topLevelTypes.push(...implicitTypes);
@@ -1087,6 +1120,238 @@ function extractNestedCustomTypeNames(customTypeAuthRules, topLevelTypes, getRef
1087
1120
  const nestedCustomTypeNames = traverseCustomTypeFields(customTypeAuthRules.typeName, customTypeDef);
1088
1121
  return nestedCustomTypeNames;
1089
1122
  }
1123
+ /**
1124
+ * Validates that defined relationships conform to the following rules.
1125
+ * - relationships are bidirectional
1126
+ * - hasOne has a belongsTo counterpart
1127
+ * - hasMany has a belongsTo counterpart
1128
+ * - belongsTo has either a hasOne or hasMany counterpart
1129
+ * - both sides of a relationship have identical `references` defined.
1130
+ * - the `references` match the primary key of the parent model
1131
+ * - references[0] is the primaryKey's partitionKey on the parent model
1132
+ * - references[1...n] are the primaryKey's sortKey(s) on the parent model
1133
+ * - types match (id / string / number)
1134
+ * - the `references` are fields defined on the child model
1135
+ * - field names match the named `references` arguments
1136
+ * - child model references fields types match those of the parent model's primaryKey
1137
+ * @param typeName source model's type name.
1138
+ * @param record map of field name to {@link ModelField}
1139
+ * @param getInternalModel given a model name, return an {@link InternalModel}
1140
+ */
1141
+ function validateRelationships(typeName, record, getInternalModel) {
1142
+ for (const [name, field] of Object.entries(record)) {
1143
+ // If the field's type is not a model, there's no relationship
1144
+ // to evaluate and we can skip this iteration.
1145
+ if (!isModelField(field)) {
1146
+ continue;
1147
+ }
1148
+ // Create a structure representing the relationship for validation.
1149
+ const relationship = getModelRelationship(typeName, { name: name, def: field.data }, getInternalModel);
1150
+ // Validate that the references defined in the relationship follow the
1151
+ // relational definition rules.
1152
+ validateRelationalReferences(relationship);
1153
+ }
1154
+ }
1155
+ /**
1156
+ * Helper function that describes the relationship of a given connection field for use in logging or error messages.
1157
+ *
1158
+ * `Parent.child: Child @hasMany(references: ['parentId'])`
1159
+ * -- or --
1160
+ * `Child.parent: Parent @belongsTo(references: ['parentId'])`
1161
+ * @param sourceField The {@link ConnectionField} to describe.
1162
+ * @param sourceModelName The name of the model within which the sourceField is defined.
1163
+ * @returns a 'string' describing the relationship
1164
+ */
1165
+ function describeConnectFieldRelationship(sourceField, sourceModelName) {
1166
+ const associatedTypeDescription = sourceField.def.array
1167
+ ? `[${sourceField.def.relatedModel}]`
1168
+ : sourceField.def.relatedModel;
1169
+ const referencesDescription = sourceField.def.references
1170
+ .reduce((description, reference) => description + `'${reference}', `, 'references: [')
1171
+ .slice(0, -2) + ']';
1172
+ return `${sourceModelName}.${sourceField.name}: ${associatedTypeDescription} @${sourceField.def.type}(${referencesDescription})`;
1173
+ }
1174
+ /**
1175
+ * Validates that the types of child model's reference fields match the types of the parent model's identifier fields.
1176
+ * @param relationship The {@link ModelRelationship} to validate.
1177
+ */
1178
+ function validateRelationalReferences(relationship) {
1179
+ const { parent, parentConnectionField, child, childConnectionField, references, } = relationship;
1180
+ const parentIdentifiers = getIndentifierTypes(parent);
1181
+ const childReferenceTypes = [];
1182
+ // Iterate through the model schema defined 'references' to find each matching field on the Related model.
1183
+ // If a field by that name is not found, throw a validate error.
1184
+ // Accumulate the ModelFieldType for each reference field to validate matching types below.
1185
+ for (const reference of references) {
1186
+ const relatedReferenceType = child.data.fields[reference]?.data
1187
+ .fieldType;
1188
+ // reference field on related type with name passed to references not found. Time to throw a validation error.
1189
+ if (!relatedReferenceType) {
1190
+ const errorMessage = `reference field '${reference}' must be defined on ${parentConnectionField.def.relatedModel}. ` +
1191
+ describeConnectFieldRelationship(parentConnectionField, childConnectionField.def.relatedModel) +
1192
+ ' <-> ' +
1193
+ describeConnectFieldRelationship(childConnectionField, parentConnectionField.def.relatedModel);
1194
+ throw new Error(errorMessage);
1195
+ }
1196
+ childReferenceTypes.push(relatedReferenceType);
1197
+ }
1198
+ if (parentIdentifiers.length !== childReferenceTypes.length) {
1199
+ throw new Error(`The identifiers defined on ${childConnectionField.def.relatedModel} must match the reference fields defined on ${parentConnectionField.def.relatedModel}.\n` +
1200
+ `${parentIdentifiers.length} identifiers defined on ${childConnectionField.def.relatedModel}.\n` +
1201
+ `${childReferenceTypes.length} reference fields found on ${parentConnectionField.def.relatedModel}`);
1202
+ }
1203
+ const matchingModelFieldType = (a, b) => {
1204
+ // `String` and `Id` are considered equal types for when comparing
1205
+ // the child model's references fields with their counterparts within
1206
+ // the parent model's identifier (parent key) fields.
1207
+ const matching = [ModelField_1.ModelFieldType.Id, ModelField_1.ModelFieldType.String];
1208
+ return a === b || (matching.includes(a) && matching.includes(b));
1209
+ };
1210
+ // Zip pairs of child model's reference field with corresponding parent model's identifier field.
1211
+ // Confirm that the types match. If they don't, throw a validation error.
1212
+ parentIdentifiers
1213
+ .map((identifier, index) => [identifier, childReferenceTypes[index]])
1214
+ .forEach(([parent, child]) => {
1215
+ if (!matchingModelFieldType(parent, child)) {
1216
+ throw new Error('Validate Error: types do not match');
1217
+ }
1218
+ });
1219
+ }
1220
+ /**
1221
+ * Relationship definitions require bi-directionality.
1222
+ * Use this to generate a `ModelRelationshipTypes[]` containing acceptable counterparts on the
1223
+ * associated model.
1224
+ *
1225
+ * Given {@link ModelRelationshipTypes.hasOne} or {@link ModelRelationshipTypes.hasOne} returns [{@link ModelRelationshipTypes.belongsTo}]
1226
+ * Given {@link ModelRelationshipTypes.belongsTo} returns [{@link ModelRelationshipTypes.hasOne}, {@link ModelRelationshipTypes.belongsTo}]
1227
+ *
1228
+ * @param relationshipType {@link ModelRelationshipTypes} defined on source model's connection field.
1229
+ * @returns possible counterpart {@link ModelRelationshipTypes} as `ModelRelationshipTypes[]`
1230
+ */
1231
+ function associatedRelationshipTypes(relationshipType) {
1232
+ switch (relationshipType) {
1233
+ case ModelRelationalField_1.ModelRelationshipTypes.hasOne:
1234
+ case ModelRelationalField_1.ModelRelationshipTypes.hasMany:
1235
+ return [ModelRelationalField_1.ModelRelationshipTypes.belongsTo];
1236
+ case ModelRelationalField_1.ModelRelationshipTypes.belongsTo:
1237
+ return [ModelRelationalField_1.ModelRelationshipTypes.hasOne, ModelRelationalField_1.ModelRelationshipTypes.hasMany];
1238
+ default:
1239
+ return []; // TODO: Remove this case on types are updated.
1240
+ }
1241
+ }
1242
+ /**
1243
+ * Retrieves the types of the identifiers defined on a model.
1244
+ *
1245
+ * Note: if a field by the name `id` isn't found in the {@link InternalModel},
1246
+ * this assumes an implicitly generated identifier is used with the type.
1247
+ *
1248
+ * This function does not validate that a corresponding field exists for each of the
1249
+ * identifiers because this validation happens at compile time.
1250
+ * @param model {@link InternalModel} from which to retrieve identifier types.
1251
+ * @returns Array of {@link ModelFieldType} of the model's identifiers found.
1252
+ */
1253
+ function getIndentifierTypes(model) {
1254
+ return model.data.identifier.flatMap((fieldName) => {
1255
+ const field = model.data.fields[fieldName];
1256
+ if (field) {
1257
+ return [field.data.fieldType];
1258
+ }
1259
+ else if (fieldName === 'id') {
1260
+ // implicity generated ID
1261
+ return [ModelField_1.ModelFieldType.Id];
1262
+ }
1263
+ return [];
1264
+ });
1265
+ }
1266
+ /**
1267
+ * Given a relationship definition within a source model (`sourceModelName`, `sourceConnectionField`) and
1268
+ * the associated model (`associatedModel`), this finds the connection field for the relationship defined on the
1269
+ * associated model. Invalid states, such a 0 or >1 matching connection fields result in an error.
1270
+ * @param sourceModelName
1271
+ * @param sourceConnectionField
1272
+ * @param associatedModel
1273
+ * @returns
1274
+ */
1275
+ function getAssociatedConnectionField(sourceModelName, sourceConnectionField, associatedModel) {
1276
+ const associatedRelationshipOptions = associatedRelationshipTypes(sourceConnectionField.def.type);
1277
+ // Iterate through the associated model's fields to find the associated connection field for the relationship defined on the source model.
1278
+ const associatedConnectionFieldCandidates = Object.entries(associatedModel.data.fields).filter(([_key, connectionField]) => {
1279
+ // If the field isn't a model, it's not part of the relationship definition -- ignore the field.
1280
+ if (!isModelField(connectionField)) {
1281
+ return false;
1282
+ }
1283
+ // In order to find that associated connection field, we need to do some validation that we'll depend on further downstream.
1284
+ // 1. Field type matches the source model's type.
1285
+ // 2. A valid counterpart relational modifier is defined on the field. See `associatedRelationshipTypes` for more information.
1286
+ // 3. The reference arguments provided to the field match (element count + string comparison) references passed to the source connection field.
1287
+ return (connectionField.data.relatedModel === sourceModelName &&
1288
+ associatedRelationshipOptions.includes(connectionField.data.type) &&
1289
+ connectionField.data.references.length ===
1290
+ sourceConnectionField.def.references.length &&
1291
+ connectionField.data.references.every((value, index) => value === sourceConnectionField.def.references[index]));
1292
+ });
1293
+ // We should have found exactly one connection field candidate. If that's not the case, we need to throw a validation error.
1294
+ if (associatedConnectionFieldCandidates.length != 1) {
1295
+ // const associatedModelDescription = sourceConnectionField.def.array
1296
+ // ? `[${sourceConnectionField.def.relatedModel}]`
1297
+ // : sourceConnectionField.def.relatedModel
1298
+ const sourceConnectionFieldDescription = describeConnectFieldRelationship(sourceConnectionField, sourceModelName); // `${sourceModelName}.${sourceConnectionField.name}: ${associatedModelDescription} @${sourceConnectionField.def.type}(references: [${sourceConnectionField.def.references}])`
1299
+ const errorMessage = associatedConnectionFieldCandidates.length === 0
1300
+ ? `Unable to find associated relationship definition in ${sourceConnectionField.def.relatedModel}`
1301
+ : `Found multiple relationship associations with ${associatedConnectionFieldCandidates.map((field) => `${sourceConnectionField.def.relatedModel}.${field[0]}`).join(', ')}`;
1302
+ throw new Error(`${errorMessage} for ${sourceConnectionFieldDescription}`);
1303
+ }
1304
+ const associatedConnectionField = associatedConnectionFieldCandidates[0];
1305
+ if (!isModelField(associatedConnectionField[1])) {
1306
+ // This shouldn't happen because we've validated that it's a model field above.
1307
+ // However it's necessary to narrow the type.
1308
+ // const associatedModelDescription = sourceConnectionField.def.array
1309
+ // ? `[${sourceConnectionField.def.relatedModel}]`
1310
+ // : sourceConnectionField.def.relatedModel
1311
+ const sourceConnectionFieldDescription = describeConnectFieldRelationship(sourceConnectionField, sourceModelName);
1312
+ const errorMessage = `Cannot find counterpart to relationship defintion for ${sourceConnectionFieldDescription}`;
1313
+ throw new Error(errorMessage);
1314
+ }
1315
+ return {
1316
+ name: associatedConnectionField[0],
1317
+ def: associatedConnectionField[1].data,
1318
+ };
1319
+ }
1320
+ /**
1321
+ * Given either side of a relationship (source), this retrieves the other side (related)
1322
+ * and packages the information neatly into a {@link ModelRelationship} for validation purposes.
1323
+ *
1324
+ * @param sourceModelName
1325
+ * @param sourceConnectionField
1326
+ * @param getInternalModel
1327
+ * @returns a {@link ModelRelationship}
1328
+ */
1329
+ function getModelRelationship(sourceModelName, sourceModelConnectionField, getInternalModel) {
1330
+ const sourceModel = getInternalModel(sourceModelName, sourceModelName);
1331
+ const associatedModel = getInternalModel(sourceModelConnectionField.def.relatedModel, sourceModelName);
1332
+ const relatedModelConnectionField = getAssociatedConnectionField(sourceModelName, sourceModelConnectionField, associatedModel);
1333
+ switch (sourceModelConnectionField.def.type) {
1334
+ case ModelRelationalField_1.ModelRelationshipTypes.hasOne:
1335
+ case ModelRelationalField_1.ModelRelationshipTypes.hasMany:
1336
+ return {
1337
+ parent: sourceModel,
1338
+ parentConnectionField: sourceModelConnectionField,
1339
+ child: associatedModel,
1340
+ childConnectionField: relatedModelConnectionField,
1341
+ references: sourceModelConnectionField.def.references,
1342
+ };
1343
+ case ModelRelationalField_1.ModelRelationshipTypes.belongsTo:
1344
+ return {
1345
+ parent: associatedModel,
1346
+ parentConnectionField: relatedModelConnectionField,
1347
+ child: sourceModel,
1348
+ childConnectionField: sourceModelConnectionField,
1349
+ references: sourceModelConnectionField.def.references,
1350
+ };
1351
+ default:
1352
+ throw new Error(`"${sourceModelConnectionField.def.type}" is not a valid relationship type.`);
1353
+ }
1354
+ }
1090
1355
  /**
1091
1356
  * Returns API definition from ModelSchema or string schema
1092
1357
  * @param arg - { schema }