@strapi/core 5.0.0-rc.6 → 5.0.0-rc.8
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/loaders/plugins/get-enabled-plugins.d.ts.map +1 -1
- package/dist/loaders/plugins/get-enabled-plugins.js +26 -1
- package/dist/loaders/plugins/get-enabled-plugins.js.map +1 -1
- package/dist/loaders/plugins/get-enabled-plugins.mjs +4 -1
- package/dist/loaders/plugins/get-enabled-plugins.mjs.map +1 -1
- package/dist/services/entity-validator/blocks-validator.d.ts +1 -2
- package/dist/services/entity-validator/blocks-validator.d.ts.map +1 -1
- package/dist/services/entity-validator/blocks-validator.js +4 -3
- package/dist/services/entity-validator/blocks-validator.js.map +1 -1
- package/dist/services/entity-validator/blocks-validator.mjs +3 -3
- package/dist/services/entity-validator/blocks-validator.mjs.map +1 -1
- package/dist/services/entity-validator/index.d.ts +2 -1
- package/dist/services/entity-validator/index.d.ts.map +1 -1
- package/dist/services/entity-validator/index.js +10 -15
- package/dist/services/entity-validator/index.js.map +1 -1
- package/dist/services/entity-validator/index.mjs +14 -19
- package/dist/services/entity-validator/index.mjs.map +1 -1
- package/dist/services/entity-validator/validators.d.ts +32 -23
- package/dist/services/entity-validator/validators.d.ts.map +1 -1
- package/dist/services/entity-validator/validators.js +122 -53
- package/dist/services/entity-validator/validators.js.map +1 -1
- package/dist/services/entity-validator/validators.mjs +121 -53
- package/dist/services/entity-validator/validators.mjs.map +1 -1
- package/package.json +13 -13
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../../../src/services/entity-validator/index.ts"],"sourcesContent":["/**\n * Entity validator\n * Module that will validate input data for entity creation or edition\n */\n\nimport { uniqBy, castArray, isNil, isArray, mergeWith } from 'lodash';\nimport { has, prop, isObject, isEmpty } from 'lodash/fp';\nimport strapiUtils from '@strapi/utils';\nimport { Modules, UID, Struct, Schema } from '@strapi/types';\nimport validators from './validators';\n\ntype CreateOrUpdate = 'creation' | 'update';\n\nconst { yup, validateYupSchema } = strapiUtils;\nconst { isMediaAttribute, isScalarAttribute, getWritableAttributes } = strapiUtils.contentTypes;\nconst { ValidationError } = strapiUtils.errors;\n\ntype ID = { id: string | number };\n\ntype RelationSource = string | number | ID;\n\nexport type ComponentContext = {\n parentContent: {\n // The model of the parent content type that contains the current component.\n model: Struct.Schema;\n // The numeric id of the parent entity that contains the component.\n id?: number;\n // The options passed to the entity validator. From which we can extract\n // entity dimensions such as locale and publication state.\n options?: ValidatorContext;\n };\n // The path to the component within the parent content type schema.\n pathToComponent: string[];\n // If working with a repeatable component this contains the\n // full data of the repeatable component in the current entity.\n repeatableData: Modules.EntityValidator.Entity[];\n};\n\ninterface WithComponentContext {\n componentContext?: ComponentContext;\n}\n\ninterface ValidatorMeta<TAttribute = Schema.Attribute.AnyAttribute> extends WithComponentContext {\n attr: TAttribute;\n updatedAttribute: { name: string; value: any };\n}\n\ninterface ValidatorContext {\n isDraft?: boolean;\n locale?: string | null;\n}\n\ninterface AttributeValidatorMetas extends WithComponentContext {\n attr: Schema.Attribute.AnyAttribute;\n updatedAttribute: { name: string; value: unknown };\n model: Struct.Schema;\n entity?: Modules.EntityValidator.Entity;\n}\n\ninterface ModelValidatorMetas extends WithComponentContext {\n model: Struct.Schema;\n data: Record<string, unknown>;\n entity?: Modules.EntityValidator.Entity;\n}\n\nconst isInteger = (value: unknown): value is number => Number.isInteger(value);\n\nconst addMinMax = <\n T extends {\n min(value: number): T;\n max(value: number): T;\n },\n>(\n validator: T,\n {\n attr,\n updatedAttribute,\n }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.MinMaxOption<string | number>>\n): T => {\n let nextValidator: T = validator;\n\n if (\n isInteger(attr.min) &&\n (('required' in attr && attr.required) ||\n (Array.isArray(updatedAttribute.value) && updatedAttribute.value.length > 0))\n ) {\n nextValidator = nextValidator.min(attr.min);\n }\n if (isInteger(attr.max)) {\n nextValidator = nextValidator.max(attr.max);\n }\n return nextValidator;\n};\n\nconst addRequiredValidation = (createOrUpdate: CreateOrUpdate) => {\n return <T extends strapiUtils.yup.AnySchema>(\n validator: T,\n {\n attr: { required },\n }: ValidatorMeta<Partial<Schema.Attribute.AnyAttribute & Schema.Attribute.RequiredOption>>\n ): T => {\n let nextValidator = validator;\n\n if (required) {\n if (createOrUpdate === 'creation') {\n nextValidator = nextValidator.notNil();\n } else if (createOrUpdate === 'update') {\n nextValidator = nextValidator.notNull();\n }\n } else {\n nextValidator = nextValidator.nullable();\n }\n return nextValidator;\n };\n};\n\nconst addDefault = (createOrUpdate: CreateOrUpdate) => {\n return (\n validator: strapiUtils.yup.BaseSchema,\n { attr }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.DefaultOption<unknown>>\n ) => {\n let nextValidator = validator;\n\n if (createOrUpdate === 'creation') {\n if (\n ((attr.type === 'component' && attr.repeatable) || attr.type === 'dynamiczone') &&\n !attr.required\n ) {\n nextValidator = nextValidator.default([]);\n } else {\n nextValidator = nextValidator.default(attr.default);\n }\n } else {\n nextValidator = nextValidator.default(undefined);\n }\n\n return nextValidator;\n };\n};\n\nconst preventCast = (validator: strapiUtils.yup.AnySchema) =>\n validator.transform((val, originalVal) => originalVal);\n\nconst createComponentValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n {\n attr,\n updatedAttribute,\n componentContext,\n }: ValidatorMeta<Schema.Attribute.Component<UID.Component, boolean>>,\n { isDraft }: ValidatorContext\n ) => {\n const model = strapi.getModel(attr.component);\n if (!model) {\n throw new Error('Validation failed: Model not found');\n }\n\n if (attr?.repeatable) {\n // FIXME: yup v1\n\n let validator = yup\n .array()\n .of(\n yup.lazy((item) =>\n createModelValidator(createOrUpdate)(\n { componentContext, model, data: item },\n { isDraft }\n ).notNull()\n ) as any\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n validator = addMinMax(validator, { attr, updatedAttribute });\n\n return validator;\n }\n\n let validator = createModelValidator(createOrUpdate)(\n {\n model,\n data: updatedAttribute.value,\n componentContext,\n },\n { isDraft }\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !isDraft && attr.required },\n updatedAttribute,\n });\n\n return validator;\n };\n\nconst createDzValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ attr, updatedAttribute, componentContext }: ValidatorMeta, { isDraft }: ValidatorContext) => {\n let validator;\n\n validator = yup.array().of(\n yup.lazy((item) => {\n const model = strapi.getModel(prop('__component', item));\n const schema = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(strapi.components)),\n })\n .notNull();\n\n return model\n ? schema.concat(\n createModelValidator(createOrUpdate)(\n { model, data: item, componentContext },\n { isDraft }\n )\n )\n : schema;\n }) as any // FIXME: yup v1\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n validator = addMinMax(validator, { attr, updatedAttribute });\n\n return validator;\n };\n\nconst createRelationValidator = ({\n updatedAttribute,\n}: ValidatorMeta<Schema.Attribute.Relation>) => {\n let validator;\n\n if (Array.isArray(updatedAttribute.value)) {\n validator = yup.array().of(yup.mixed());\n } else {\n validator = yup.mixed();\n }\n\n return validator;\n};\n\nconst createScalarAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMeta, options: ValidatorContext) => {\n let validator;\n\n if (has(metas.attr.type, validators)) {\n validator = (validators as any)[metas.attr.type](metas, options);\n } else {\n // No validators specified - fall back to mixed\n validator = yup.mixed();\n }\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !options.isDraft && metas.attr.required },\n updatedAttribute: metas.updatedAttribute,\n });\n\n return validator;\n };\n\nconst createAttributeValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (metas: AttributeValidatorMetas, options: ValidatorContext) => {\n let validator = yup.mixed();\n\n if (isMediaAttribute(metas.attr)) {\n validator = yup.mixed();\n } else if (isScalarAttribute(metas.attr)) {\n validator = createScalarAttributeValidator(createOrUpdate)(metas, options);\n } else {\n if (metas.attr.type === 'component') {\n // Build the path to the component within the parent content type schema.\n const pathToComponent = [\n ...(metas?.componentContext?.pathToComponent ?? []),\n metas.updatedAttribute.name,\n ];\n\n // If working with a repeatable component, determine the repeatable data\n // based on the component's path.\n\n // In order to validate the repeatable within this entity we need\n // access to the full repeatable data. In case we are validating a\n // nested component within a repeatable.\n // Hence why we set this up when the path to the component is only one level deep.\n const repeatableData = (\n metas.attr.repeatable && pathToComponent.length === 1\n ? metas.updatedAttribute.value\n : metas.componentContext?.repeatableData\n ) as Modules.EntityValidator.Entity[];\n\n const newComponentContext = {\n ...(metas?.componentContext ?? {}),\n pathToComponent,\n repeatableData,\n };\n\n validator = createComponentValidator(createOrUpdate)(\n {\n componentContext: newComponentContext as ComponentContext,\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n } else if (metas.attr.type === 'dynamiczone') {\n // TODO: fix! query layer fails when building a where for dynamic\n // zones\n const pathToComponent = [\n ...(metas?.componentContext?.pathToComponent ?? []),\n metas.updatedAttribute.name,\n ];\n\n const newComponentContext = {\n ...(metas?.componentContext ?? {}),\n pathToComponent,\n };\n\n validator = createDzValidator(createOrUpdate)(\n { ...metas, componentContext: newComponentContext as ComponentContext },\n options\n );\n } else if (metas.attr.type === 'relation') {\n validator = createRelationValidator({\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n });\n }\n\n validator = preventCast(validator);\n }\n\n validator = addDefault(createOrUpdate)(validator, metas);\n\n return validator;\n };\n\nconst createModelValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ componentContext, model, data, entity }: ModelValidatorMetas, options: ValidatorContext) => {\n const writableAttributes = model ? getWritableAttributes(model as any) : [];\n\n const schema = writableAttributes.reduce(\n (validators, attributeName) => {\n const metas = {\n attr: model.attributes[attributeName],\n updatedAttribute: { name: attributeName, value: prop(attributeName, data) },\n model,\n entity,\n componentContext,\n };\n\n const validator = createAttributeValidator(createOrUpdate)(metas, options);\n\n validators[attributeName] = validator;\n\n return validators;\n },\n {} as Record<string, strapiUtils.yup.BaseSchema>\n );\n\n return yup.object().shape(schema);\n };\n\nconst createValidateEntity = (createOrUpdate: CreateOrUpdate) => {\n return async <\n TUID extends UID.ContentType,\n TData extends Modules.EntityService.Params.Data.Input<TUID>,\n >(\n model: Schema.ContentType<TUID>,\n data: TData | Partial<TData> | undefined,\n options?: ValidatorContext,\n entity?: Modules.EntityValidator.Entity\n ): Promise<TData> => {\n if (!isObject(data)) {\n const { displayName } = model.info;\n\n throw new ValidationError(\n `Invalid payload submitted for the ${createOrUpdate} of an entity of type ${displayName}. Expected an object, but got ${typeof data}`\n );\n }\n\n const validator = createModelValidator(createOrUpdate)(\n {\n model,\n data,\n entity,\n componentContext: {\n // Set up the initial component context.\n // Keeping track of parent content type context in which a component will be used.\n // This is necessary to validate component field constraints such as uniqueness.\n parentContent: {\n id: entity?.id,\n model,\n options,\n },\n pathToComponent: [],\n repeatableData: [],\n },\n },\n {\n isDraft: options?.isDraft ?? false,\n locale: options?.locale ?? null,\n }\n )\n .test(\n 'relations-test',\n 'check that all relations exist',\n async function relationsValidation(data) {\n try {\n await checkRelationsExist(buildRelationsStore({ uid: model.uid, data }));\n } catch (e) {\n return this.createError({\n path: this.path,\n message: (e instanceof ValidationError && e.message) || 'Invalid relations',\n });\n }\n return true;\n }\n )\n .required();\n\n return validateYupSchema(validator, {\n strict: false,\n abortEarly: false,\n })(data);\n };\n};\n\n/**\n * Builds an object containing all the media and relations being associated with an entity\n */\nconst buildRelationsStore = <TUID extends UID.Schema>({\n uid,\n data,\n}: {\n uid: TUID;\n data: Record<string, unknown> | null;\n}): Record<string, ID[]> => {\n if (!uid) {\n throw new ValidationError(`Cannot build relations store: \"uid\" is undefined`);\n }\n\n if (isEmpty(data)) {\n return {};\n }\n\n const currentModel = strapi.getModel(uid);\n\n return Object.keys(currentModel.attributes).reduce(\n (result, attributeName: string) => {\n const attribute = currentModel.attributes[attributeName];\n const value = data[attributeName];\n\n if (isNil(value)) {\n return result;\n }\n\n switch (attribute.type) {\n case 'relation':\n case 'media': {\n if (\n attribute.type === 'relation' &&\n (attribute.relation === 'morphToMany' || attribute.relation === 'morphToOne')\n ) {\n // TODO: handle polymorphic relations\n break;\n }\n\n const target =\n // eslint-disable-next-line no-nested-ternary\n attribute.type === 'media' ? 'plugin::upload.file' : attribute.target;\n // As there are multiple formats supported for associating relations\n // with an entity, the value here can be an: array, object or number.\n let source: RelationSource[];\n if (Array.isArray(value)) {\n source = value;\n } else if (isObject(value)) {\n if ('connect' in value && !isNil(value.connect)) {\n source = value.connect as RelationSource[];\n } else if ('set' in value && !isNil(value.set)) {\n source = value.set as RelationSource[];\n } else {\n source = [];\n }\n } else {\n source = castArray(value as RelationSource);\n }\n const idArray = source.map((v) => ({\n id: typeof v === 'object' ? v.id : v,\n }));\n\n // Update the relationStore to keep track of all associations being made\n // with relations and media.\n result[target] = result[target] || [];\n result[target].push(...idArray);\n break;\n }\n case 'component': {\n return castArray(value).reduce((relationsStore, componentValue) => {\n if (!attribute.component) {\n throw new ValidationError(\n `Cannot build relations store from component, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: attribute.component,\n data: componentValue as Record<string, unknown>,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n case 'dynamiczone': {\n return castArray(value).reduce((relationsStore, dzValue) => {\n const value = dzValue as Record<string, unknown>;\n if (!value.__component) {\n throw new ValidationError(\n `Cannot build relations store from dynamiczone, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: value.__component as UID.Component,\n data: value,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n default:\n break;\n }\n\n return result;\n },\n {} as Record<string, ID[]>\n );\n};\n\n/**\n * Iterate through the relations store and validates that every relation or media\n * mentioned exists\n */\nconst checkRelationsExist = async (relationsStore: Record<string, ID[]> = {}) => {\n const promises: Promise<void>[] = [];\n\n for (const [key, value] of Object.entries(relationsStore)) {\n const evaluate = async () => {\n const uniqueValues = uniqBy(value, `id`);\n const count = await strapi.db.query(key as UID.Schema).count({\n where: {\n id: {\n $in: uniqueValues.map((v) => v.id),\n },\n },\n });\n\n if (count !== uniqueValues.length) {\n throw new ValidationError(\n `${\n uniqueValues.length - count\n } relation(s) of type ${key} associated with this entity do not exist`\n );\n }\n };\n promises.push(evaluate());\n }\n\n return Promise.all(promises);\n};\n\nconst entityValidator: Modules.EntityValidator.EntityValidator = {\n validateEntityCreation: createValidateEntity('creation'),\n validateEntityUpdate: createValidateEntity('update'),\n};\n\nexport default entityValidator;\n"],"names":["validator","validators","data","value"],"mappings":";;;;AAaA,MAAM,EAAE,KAAK,kBAAsB,IAAA;AACnC,MAAM,EAAE,kBAAkB,mBAAmB,sBAAA,IAA0B,YAAY;AACnF,MAAM,EAAE,gBAAgB,IAAI,YAAY;AAkDxC,MAAM,YAAY,CAAC,UAAoC,OAAO,UAAU,KAAK;AAE7E,MAAM,YAAY,CAMhB,WACA;AAAA,EACE;AAAA,EACA;AACF,MACM;AACN,MAAI,gBAAmB;AAEvB,MACE,UAAU,KAAK,GAAG,MAChB,cAAc,QAAQ,KAAK,YAC1B,MAAM,QAAQ,iBAAiB,KAAK,KAAK,iBAAiB,MAAM,SAAS,IAC5E;AACgB,oBAAA,cAAc,IAAI,KAAK,GAAG;AAAA,EAC5C;AACI,MAAA,UAAU,KAAK,GAAG,GAAG;AACP,oBAAA,cAAc,IAAI,KAAK,GAAG;AAAA,EAC5C;AACO,SAAA;AACT;AAEA,MAAM,wBAAwB,CAAC,mBAAmC;AAChE,SAAO,CACL,WACA;AAAA,IACE,MAAM,EAAE,SAAS;AAAA,EAAA,MAEb;AACN,QAAI,gBAAgB;AAEpB,QAAI,UAAU;AACZ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+
{"version":3,"file":"index.mjs","sources":["../../../src/services/entity-validator/index.ts"],"sourcesContent":["/**\n * Entity validator\n * Module that will validate input data for entity creation or edition\n */\n\nimport { uniqBy, castArray, isNil, isArray, mergeWith } from 'lodash';\nimport { has, prop, isObject, isEmpty } from 'lodash/fp';\nimport strapiUtils from '@strapi/utils';\nimport { Modules, UID, Struct, Schema } from '@strapi/types';\nimport { Validators, ValidatorMetas } from './validators';\n\ntype CreateOrUpdate = 'creation' | 'update';\n\nconst { yup, validateYupSchema } = strapiUtils;\nconst { isMediaAttribute, isScalarAttribute, getWritableAttributes } = strapiUtils.contentTypes;\nconst { ValidationError } = strapiUtils.errors;\n\ntype ID = { id: string | number };\n\ntype RelationSource = string | number | ID;\n\nexport type ComponentContext = {\n parentContent: {\n // The model of the parent content type that contains the current component.\n model: Struct.Schema;\n // The numeric id of the parent entity that contains the component.\n id?: number;\n // The options passed to the entity validator. From which we can extract\n // entity dimensions such as locale and publication state.\n options?: ValidatorContext;\n };\n // The path to the component within the parent content type schema.\n pathToComponent: string[];\n // If working with a repeatable component this contains the\n // full data of the repeatable component in the current entity.\n repeatableData: Modules.EntityValidator.Entity[];\n fullDynamicZoneContent?: Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n};\n\ninterface WithComponentContext {\n componentContext?: ComponentContext;\n}\n\ninterface ValidatorMeta<TAttribute = Schema.Attribute.AnyAttribute> extends WithComponentContext {\n attr: TAttribute;\n updatedAttribute: { name: string; value: any };\n}\n\ninterface ValidatorContext {\n isDraft?: boolean;\n locale?: string | null;\n}\n\ninterface ModelValidatorMetas extends WithComponentContext {\n model: Struct.Schema;\n data: Record<string, unknown>;\n entity?: Modules.EntityValidator.Entity;\n}\n\nconst isInteger = (value: unknown): value is number => Number.isInteger(value);\n\nconst addMinMax = <\n T extends {\n min(value: number): T;\n max(value: number): T;\n },\n>(\n validator: T,\n {\n attr,\n updatedAttribute,\n }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.MinMaxOption<string | number>>\n): T => {\n let nextValidator: T = validator;\n\n if (\n isInteger(attr.min) &&\n (('required' in attr && attr.required) ||\n (Array.isArray(updatedAttribute.value) && updatedAttribute.value.length > 0))\n ) {\n nextValidator = nextValidator.min(attr.min);\n }\n if (isInteger(attr.max)) {\n nextValidator = nextValidator.max(attr.max);\n }\n return nextValidator;\n};\n\nconst addRequiredValidation = (createOrUpdate: CreateOrUpdate) => {\n return <T extends strapiUtils.yup.AnySchema>(\n validator: T,\n {\n attr: { required },\n }: ValidatorMeta<Partial<Schema.Attribute.AnyAttribute & Schema.Attribute.RequiredOption>>\n ): T => {\n let nextValidator = validator;\n\n if (required) {\n if (createOrUpdate === 'creation') {\n nextValidator = nextValidator.notNil();\n } else if (createOrUpdate === 'update') {\n nextValidator = nextValidator.notNull();\n }\n } else {\n nextValidator = nextValidator.nullable();\n }\n return nextValidator;\n };\n};\n\nconst addDefault = (createOrUpdate: CreateOrUpdate) => {\n return (\n validator: strapiUtils.yup.BaseSchema,\n { attr }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.DefaultOption<unknown>>\n ) => {\n let nextValidator = validator;\n\n if (createOrUpdate === 'creation') {\n if (\n ((attr.type === 'component' && attr.repeatable) || attr.type === 'dynamiczone') &&\n !attr.required\n ) {\n nextValidator = nextValidator.default([]);\n } else {\n nextValidator = nextValidator.default(attr.default);\n }\n } else {\n nextValidator = nextValidator.default(undefined);\n }\n\n return nextValidator;\n };\n};\n\nconst preventCast = (validator: strapiUtils.yup.AnySchema) =>\n validator.transform((val, originalVal) => originalVal);\n\nconst createComponentValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n {\n attr,\n updatedAttribute,\n componentContext,\n }: ValidatorMeta<Schema.Attribute.Component<UID.Component, boolean>>,\n { isDraft }: ValidatorContext\n ) => {\n const model = strapi.getModel(attr.component);\n if (!model) {\n throw new Error('Validation failed: Model not found');\n }\n\n if (attr?.repeatable) {\n // FIXME: yup v1\n\n let validator = yup\n .array()\n .of(\n yup.lazy((item) =>\n createModelValidator(createOrUpdate)(\n { componentContext, model, data: item },\n { isDraft }\n ).notNull()\n ) as any\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n validator = addMinMax(validator, { attr, updatedAttribute });\n\n return validator;\n }\n\n let validator = createModelValidator(createOrUpdate)(\n {\n model,\n data: updatedAttribute.value,\n componentContext,\n },\n { isDraft }\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !isDraft && attr.required },\n updatedAttribute,\n });\n\n return validator;\n };\n\nconst createDzValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ attr, updatedAttribute, componentContext }: ValidatorMeta, { isDraft }: ValidatorContext) => {\n let validator;\n\n validator = yup.array().of(\n yup.lazy((item) => {\n const model = strapi.getModel(prop('__component', item));\n const schema = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(strapi.components)),\n })\n .notNull();\n\n return model\n ? schema.concat(\n createModelValidator(createOrUpdate)(\n { model, data: item, componentContext },\n { isDraft }\n )\n )\n : schema;\n }) as any // FIXME: yup v1\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n validator = addMinMax(validator, { attr, updatedAttribute });\n\n return validator;\n };\n\nconst createRelationValidator = ({\n updatedAttribute,\n}: ValidatorMeta<Schema.Attribute.Relation>) => {\n let validator;\n\n if (Array.isArray(updatedAttribute.value)) {\n validator = yup.array().of(yup.mixed());\n } else {\n validator = yup.mixed();\n }\n\n return validator;\n};\n\nconst createScalarAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMeta, options: ValidatorContext) => {\n let validator;\n\n if (has(metas.attr.type, Validators)) {\n validator = (Validators as any)[metas.attr.type](metas, options);\n } else {\n // No validators specified - fall back to mixed\n validator = yup.mixed();\n }\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !options.isDraft && metas.attr.required },\n updatedAttribute: metas.updatedAttribute,\n });\n\n return validator;\n };\n\nconst createAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMetas, options: ValidatorContext) => {\n let validator = yup.mixed();\n\n if (isMediaAttribute(metas.attr)) {\n validator = yup.mixed();\n } else if (isScalarAttribute(metas.attr)) {\n validator = createScalarAttributeValidator(createOrUpdate)(metas, options);\n } else {\n if (metas.attr.type === 'component' && metas.componentContext) {\n // Build the path to the component within the parent content type schema.\n const pathToComponent = [\n ...(metas?.componentContext?.pathToComponent ?? []),\n metas.updatedAttribute.name,\n ];\n\n // If working with a repeatable component, determine the repeatable data\n // based on the component's path.\n\n // In order to validate the repeatable within this entity we need\n // access to the full repeatable data. In case we are validating a\n // nested component within a repeatable.\n // Hence why we set this up when the path to the component is only one level deep.\n const repeatableData = (\n metas.attr.repeatable && pathToComponent.length === 1\n ? metas.updatedAttribute.value\n : metas.componentContext?.repeatableData\n ) as Modules.EntityValidator.Entity[];\n\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n pathToComponent,\n repeatableData,\n };\n\n validator = createComponentValidator(createOrUpdate)(\n {\n componentContext: newComponentContext,\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n } else if (metas.attr.type === 'dynamiczone' && metas.componentContext) {\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n fullDynamicZoneContent: metas.updatedAttribute.value,\n pathToComponent: [...metas.componentContext.pathToComponent, metas.updatedAttribute.name],\n };\n\n Object.assign(metas, { componentContext: newComponentContext });\n\n validator = createDzValidator(createOrUpdate)(metas, options);\n } else if (metas.attr.type === 'relation') {\n validator = createRelationValidator({\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n });\n }\n\n validator = preventCast(validator);\n }\n\n validator = addDefault(createOrUpdate)(validator, metas);\n\n return validator;\n };\n\nconst createModelValidator =\n (createOrUpdate: CreateOrUpdate) =>\n ({ componentContext, model, data, entity }: ModelValidatorMetas, options: ValidatorContext) => {\n const writableAttributes = model ? getWritableAttributes(model as any) : [];\n\n const schema = writableAttributes.reduce(\n (validators, attributeName) => {\n const metas = {\n attr: model.attributes[attributeName],\n updatedAttribute: { name: attributeName, value: prop(attributeName, data) },\n model,\n entity,\n componentContext,\n };\n\n const validator = createAttributeValidator(createOrUpdate)(metas, options);\n\n validators[attributeName] = validator;\n\n return validators;\n },\n {} as Record<string, strapiUtils.yup.BaseSchema>\n );\n\n return yup.object().shape(schema);\n };\n\nconst createValidateEntity = (createOrUpdate: CreateOrUpdate) => {\n return async <\n TUID extends UID.ContentType,\n TData extends Modules.EntityService.Params.Data.Input<TUID>,\n >(\n model: Schema.ContentType<TUID>,\n data: TData | Partial<TData> | undefined,\n options?: ValidatorContext,\n entity?: Modules.EntityValidator.Entity\n ): Promise<TData> => {\n if (!isObject(data)) {\n const { displayName } = model.info;\n\n throw new ValidationError(\n `Invalid payload submitted for the ${createOrUpdate} of an entity of type ${displayName}. Expected an object, but got ${typeof data}`\n );\n }\n\n const validator = createModelValidator(createOrUpdate)(\n {\n model,\n data,\n entity,\n componentContext: {\n // Set up the initial component context.\n // Keeping track of parent content type context in which a component will be used.\n // This is necessary to validate component field constraints such as uniqueness.\n parentContent: {\n id: entity?.id,\n model,\n options,\n },\n pathToComponent: [],\n repeatableData: [],\n },\n },\n {\n isDraft: options?.isDraft ?? false,\n locale: options?.locale ?? null,\n }\n )\n .test(\n 'relations-test',\n 'check that all relations exist',\n async function relationsValidation(data) {\n try {\n await checkRelationsExist(buildRelationsStore({ uid: model.uid, data }));\n } catch (e) {\n return this.createError({\n path: this.path,\n message: (e instanceof ValidationError && e.message) || 'Invalid relations',\n });\n }\n return true;\n }\n )\n .required();\n\n return validateYupSchema(validator, {\n strict: false,\n abortEarly: false,\n })(data);\n };\n};\n\n/**\n * Builds an object containing all the media and relations being associated with an entity\n */\nconst buildRelationsStore = <TUID extends UID.Schema>({\n uid,\n data,\n}: {\n uid: TUID;\n data: Record<string, unknown> | null;\n}): Record<string, ID[]> => {\n if (!uid) {\n throw new ValidationError(`Cannot build relations store: \"uid\" is undefined`);\n }\n\n if (isEmpty(data)) {\n return {};\n }\n\n const currentModel = strapi.getModel(uid);\n\n return Object.keys(currentModel.attributes).reduce(\n (result, attributeName: string) => {\n const attribute = currentModel.attributes[attributeName];\n const value = data[attributeName];\n\n if (isNil(value)) {\n return result;\n }\n\n switch (attribute.type) {\n case 'relation':\n case 'media': {\n if (\n attribute.type === 'relation' &&\n (attribute.relation === 'morphToMany' || attribute.relation === 'morphToOne')\n ) {\n // TODO: handle polymorphic relations\n break;\n }\n\n const target =\n // eslint-disable-next-line no-nested-ternary\n attribute.type === 'media' ? 'plugin::upload.file' : attribute.target;\n // As there are multiple formats supported for associating relations\n // with an entity, the value here can be an: array, object or number.\n let source: RelationSource[];\n if (Array.isArray(value)) {\n source = value;\n } else if (isObject(value)) {\n if ('connect' in value && !isNil(value.connect)) {\n source = value.connect as RelationSource[];\n } else if ('set' in value && !isNil(value.set)) {\n source = value.set as RelationSource[];\n } else {\n source = [];\n }\n } else {\n source = castArray(value as RelationSource);\n }\n const idArray = source.map((v) => ({\n id: typeof v === 'object' ? v.id : v,\n }));\n\n // Update the relationStore to keep track of all associations being made\n // with relations and media.\n result[target] = result[target] || [];\n result[target].push(...idArray);\n break;\n }\n case 'component': {\n return castArray(value).reduce((relationsStore, componentValue) => {\n if (!attribute.component) {\n throw new ValidationError(\n `Cannot build relations store from component, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: attribute.component,\n data: componentValue as Record<string, unknown>,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n case 'dynamiczone': {\n return castArray(value).reduce((relationsStore, dzValue) => {\n const value = dzValue as Record<string, unknown>;\n if (!value.__component) {\n throw new ValidationError(\n `Cannot build relations store from dynamiczone, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: value.__component as UID.Component,\n data: value,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n default:\n break;\n }\n\n return result;\n },\n {} as Record<string, ID[]>\n );\n};\n\n/**\n * Iterate through the relations store and validates that every relation or media\n * mentioned exists\n */\nconst checkRelationsExist = async (relationsStore: Record<string, ID[]> = {}) => {\n const promises: Promise<void>[] = [];\n\n for (const [key, value] of Object.entries(relationsStore)) {\n const evaluate = async () => {\n const uniqueValues = uniqBy(value, `id`);\n const count = await strapi.db.query(key as UID.Schema).count({\n where: {\n id: {\n $in: uniqueValues.map((v) => v.id),\n },\n },\n });\n\n if (count !== uniqueValues.length) {\n throw new ValidationError(\n `${\n uniqueValues.length - count\n } relation(s) of type ${key} associated with this entity do not exist`\n );\n }\n };\n promises.push(evaluate());\n }\n\n return Promise.all(promises);\n};\n\nconst entityValidator: Modules.EntityValidator.EntityValidator = {\n validateEntityCreation: createValidateEntity('creation'),\n validateEntityUpdate: createValidateEntity('update'),\n};\n\nexport default entityValidator;\n"],"names":["validator","data","value"],"mappings":";;;;AAaA,MAAM,EAAE,KAAK,kBAAsB,IAAA;AACnC,MAAM,EAAE,kBAAkB,mBAAmB,sBAAA,IAA0B,YAAY;AACnF,MAAM,EAAE,gBAAgB,IAAI,YAAY;AA4CxC,MAAM,YAAY,CAAC,UAAoC,OAAO,UAAU,KAAK;AAE7E,MAAM,YAAY,CAMhB,WACA;AAAA,EACE;AAAA,EACA;AACF,MACM;AACN,MAAI,gBAAmB;AAEvB,MACE,UAAU,KAAK,GAAG,MAChB,cAAc,QAAQ,KAAK,YAC1B,MAAM,QAAQ,iBAAiB,KAAK,KAAK,iBAAiB,MAAM,SAAS,IAC5E;AACgB,oBAAA,cAAc,IAAI,KAAK,GAAG;AAAA,EAC5C;AACI,MAAA,UAAU,KAAK,GAAG,GAAG;AACP,oBAAA,cAAc,IAAI,KAAK,GAA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U;AAAA,EAC1B;AAEO,SAAA,QAAQ,IAAI,QAAQ;AAC7B;AAEA,MAAM,kBAA2D;AAAA,EAC/D,wBAAwB,qBAAqB,UAAU;AAAA,EACvD,sBAAsB,qBAAqB,QAAQ;AACrD;"}
|
@@ -1,41 +1,50 @@
|
|
1
1
|
import { yup } from '@strapi/utils';
|
2
2
|
import type { Schema, Struct, Modules } from '@strapi/types';
|
3
3
|
import type { ComponentContext } from '.';
|
4
|
-
interface ValidatorMetas<TAttribute extends Schema.Attribute.AnyAttribute> {
|
4
|
+
export interface ValidatorMetas<TAttribute extends Schema.Attribute.AnyAttribute = Schema.Attribute.AnyAttribute, TValue extends Schema.Attribute.Value<TAttribute> = Schema.Attribute.Value<TAttribute>> {
|
5
5
|
attr: TAttribute;
|
6
|
-
model: Struct.
|
6
|
+
model: Struct.Schema;
|
7
7
|
updatedAttribute: {
|
8
8
|
name: string;
|
9
|
-
value:
|
9
|
+
value: TValue;
|
10
10
|
};
|
11
|
-
|
12
|
-
|
11
|
+
componentContext?: ComponentContext;
|
12
|
+
entity?: Modules.EntityValidator.Entity;
|
13
13
|
}
|
14
14
|
interface ValidatorOptions {
|
15
15
|
isDraft: boolean;
|
16
16
|
locale?: string;
|
17
17
|
}
|
18
|
-
declare const
|
19
|
-
|
20
|
-
|
21
|
-
|
22
|
-
|
23
|
-
|
18
|
+
export declare const emailValidator: (metas: ValidatorMetas<Schema.Attribute.Email>, options: ValidatorOptions) => import("yup").StringSchema<string | undefined, Record<string, any>, string | undefined>;
|
19
|
+
export declare const uidValidator: (metas: ValidatorMetas<Schema.Attribute.UID>, options: ValidatorOptions) => import("yup").StringSchema<string | undefined, Record<string, any>, string | undefined>;
|
20
|
+
export declare const enumerationValidator: ({ attr }: {
|
21
|
+
attr: Schema.Attribute.Enumeration;
|
22
|
+
}) => import("yup").StringSchema<string | undefined, Record<string, any>, string | undefined>;
|
23
|
+
export declare const integerValidator: (metas: ValidatorMetas<Schema.Attribute.Integer | Schema.Attribute.BigInteger>, options: ValidatorOptions) => yup.NumberSchema<number | undefined, Record<string, any>, number | undefined>;
|
24
|
+
export declare const floatValidator: (metas: ValidatorMetas<Schema.Attribute.Decimal | Schema.Attribute.Float>, options: ValidatorOptions) => yup.NumberSchema<number | undefined, Record<string, any>, number | undefined>;
|
25
|
+
export declare const bigintegerValidator: (metas: ValidatorMetas<Schema.Attribute.BigInteger>, options: ValidatorOptions) => import("yup/lib/mixed").MixedSchema<any, Record<string, any>, any>;
|
26
|
+
export declare const datesValidator: (metas: ValidatorMetas<Schema.Attribute.Date | Schema.Attribute.DateTime | Schema.Attribute.Time | Schema.Attribute.Timestamp>, options: ValidatorOptions) => import("yup/lib/mixed").MixedSchema<any, Record<string, any>, any>;
|
27
|
+
export declare const Validators: {
|
28
|
+
string: (metas: ValidatorMetas<Schema.Attribute.String | Schema.Attribute.Text | Schema.Attribute.RichText | Schema.Attribute.Password | Schema.Attribute.Email | Schema.Attribute.UID>, options: ValidatorOptions) => import("yup").StringSchema<string | undefined, Record<string, any>, string | undefined>;
|
29
|
+
text: (metas: ValidatorMetas<Schema.Attribute.String | Schema.Attribute.Text | Schema.Attribute.RichText | Schema.Attribute.Password | Schema.Attribute.Email | Schema.Attribute.UID>, options: ValidatorOptions) => import("yup").StringSchema<string | undefined, Record<string, any>, string | undefined>;
|
30
|
+
richtext: (metas: ValidatorMetas<Schema.Attribute.String | Schema.Attribute.Text | Schema.Attribute.RichText | Schema.Attribute.Password | Schema.Attribute.Email | Schema.Attribute.UID>, options: ValidatorOptions) => import("yup").StringSchema<string | undefined, Record<string, any>, string | undefined>;
|
31
|
+
password: (metas: ValidatorMetas<Schema.Attribute.String | Schema.Attribute.Text | Schema.Attribute.RichText | Schema.Attribute.Password | Schema.Attribute.Email | Schema.Attribute.UID>, options: ValidatorOptions) => import("yup").StringSchema<string | undefined, Record<string, any>, string | undefined>;
|
32
|
+
email: (metas: ValidatorMetas<Schema.Attribute.Email>, options: ValidatorOptions) => import("yup").StringSchema<string | undefined, Record<string, any>, string | undefined>;
|
24
33
|
enumeration: ({ attr }: {
|
25
|
-
attr: Schema.Attribute.
|
34
|
+
attr: Schema.Attribute.Enumeration;
|
26
35
|
}) => import("yup").StringSchema<string | undefined, Record<string, any>, string | undefined>;
|
27
36
|
boolean: () => yup.BooleanSchema<boolean | undefined, Record<string, any>, boolean | undefined>;
|
28
|
-
uid: (metas: ValidatorMetas<Schema.Attribute.
|
37
|
+
uid: (metas: ValidatorMetas<Schema.Attribute.UID>, options: ValidatorOptions) => import("yup").StringSchema<string | undefined, Record<string, any>, string | undefined>;
|
29
38
|
json: () => import("yup/lib/mixed").MixedSchema<any, Record<string, any>, any>;
|
30
|
-
integer: (metas: ValidatorMetas<
|
31
|
-
biginteger: (metas: ValidatorMetas<Schema.Attribute.
|
32
|
-
float: (metas: ValidatorMetas<
|
33
|
-
decimal: (metas: ValidatorMetas<
|
34
|
-
date: (metas: ValidatorMetas<
|
35
|
-
time: (metas: ValidatorMetas<
|
36
|
-
datetime: (metas: ValidatorMetas<
|
37
|
-
timestamp: (metas: ValidatorMetas<
|
38
|
-
blocks: (
|
39
|
+
integer: (metas: ValidatorMetas<Schema.Attribute.Integer | Schema.Attribute.BigInteger>, options: ValidatorOptions) => yup.NumberSchema<number | undefined, Record<string, any>, number | undefined>;
|
40
|
+
biginteger: (metas: ValidatorMetas<Schema.Attribute.BigInteger>, options: ValidatorOptions) => import("yup/lib/mixed").MixedSchema<any, Record<string, any>, any>;
|
41
|
+
float: (metas: ValidatorMetas<Schema.Attribute.Decimal | Schema.Attribute.Float>, options: ValidatorOptions) => yup.NumberSchema<number | undefined, Record<string, any>, number | undefined>;
|
42
|
+
decimal: (metas: ValidatorMetas<Schema.Attribute.Decimal | Schema.Attribute.Float>, options: ValidatorOptions) => yup.NumberSchema<number | undefined, Record<string, any>, number | undefined>;
|
43
|
+
date: (metas: ValidatorMetas<Schema.Attribute.Date | Schema.Attribute.DateTime | Schema.Attribute.Time | Schema.Attribute.Timestamp>, options: ValidatorOptions) => import("yup/lib/mixed").MixedSchema<any, Record<string, any>, any>;
|
44
|
+
time: (metas: ValidatorMetas<Schema.Attribute.Date | Schema.Attribute.DateTime | Schema.Attribute.Time | Schema.Attribute.Timestamp>, options: ValidatorOptions) => import("yup/lib/mixed").MixedSchema<any, Record<string, any>, any>;
|
45
|
+
datetime: (metas: ValidatorMetas<Schema.Attribute.Date | Schema.Attribute.DateTime | Schema.Attribute.Time | Schema.Attribute.Timestamp>, options: ValidatorOptions) => import("yup/lib/mixed").MixedSchema<any, Record<string, any>, any>;
|
46
|
+
timestamp: (metas: ValidatorMetas<Schema.Attribute.Date | Schema.Attribute.DateTime | Schema.Attribute.Time | Schema.Attribute.Timestamp>, options: ValidatorOptions) => import("yup/lib/mixed").MixedSchema<any, Record<string, any>, any>;
|
47
|
+
blocks: () => yup.ArraySchema<any, import("yup/lib/types").AnyObject, any[] | undefined, any[] | undefined>;
|
39
48
|
};
|
40
|
-
export
|
49
|
+
export {};
|
41
50
|
//# sourceMappingURL=validators.d.ts.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"validators.d.ts","sourceRoot":"","sources":["../../../src/services/entity-validator/validators.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,MAAM,eAAe,CAAC;AACpC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAG7D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,GAAG,CAAC;AAE1C,
|
1
|
+
{"version":3,"file":"validators.d.ts","sourceRoot":"","sources":["../../../src/services/entity-validator/validators.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,MAAM,eAAe,CAAC;AACpC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAG7D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,GAAG,CAAC;AAE1C,MAAM,WAAW,cAAc,CA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BlB,eAAe,OAAO,SAAS,WAAW,CAAC,WACzC,gBAAgB;mBAblB,eAAe,OAAO,SAAS,CAAC,OAAO,GAAG,OAAO,SAAS,CAAC,KAAK,CAAC,WAC/D,gBAAgB;qBADlB,eAAe,OAAO,SAAS,CAAC,OAAO,GAAG,OAAO,SAAS,CAAC,KAAK,CAAC,WAC/D,gBAAgB;kBAmBlB,eACH,OAAO,SAAS,KAAK,GACrB,OAAO,SAAS,CAAC,QAAQ,GACzB,OAAO,SAAS,CAAC,IAAI,GACrB,OAAO,SAAS,CAAC,SAAS,CAC7B,WACQ,gBAAgB;kBANlB,eACH,OAAO,SAAS,KAAK,GACrB,OAAO,SAAS,CAAC,QAAQ,GACzB,OAAO,SAAS,CAAC,IAAI,GACrB,OAAO,SAAS,CAAC,SAAS,CAC7B,WACQ,gBAAgB;sBANlB,eACH,OAAO,SAAS,KAAK,GACrB,OAAO,SAAS,CAAC,QAAQ,GACzB,OAAO,SAAS,CAAC,IAAI,GACrB,OAAO,SAAS,CAAC,SAAS,CAC7B,WACQ,gBAAgB;uBANlB,eACH,OAAO,SAAS,KAAK,GACrB,OAAO,SAAS,CAAC,QAAQ,GACzB,OAAO,SAAS,CAAC,IAAI,GACrB,OAAO,SAAS,CAAC,SAAS,CAC7B,WACQ,gBAAgB;;CAyB1B,CAAC"}
|
@@ -1,4 +1,5 @@
|
|
1
1
|
"use strict";
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
2
3
|
const _ = require("lodash");
|
3
4
|
const strapiUtils = require("@strapi/utils");
|
4
5
|
const blocksValidator = require("./blocks-validator.js");
|
@@ -41,6 +42,94 @@ const addUniqueValidator = (validator, {
|
|
41
42
|
if (attr.type !== "uid" && !attr.unique) {
|
42
43
|
return validator;
|
43
44
|
}
|
45
|
+
const validateUniqueFieldWithinComponent = async (value) => {
|
46
|
+
if (!componentContext) {
|
47
|
+
return false;
|
48
|
+
}
|
49
|
+
const hasRepeatableData = componentContext.repeatableData.length > 0;
|
50
|
+
if (hasRepeatableData) {
|
51
|
+
const { name: updatedName, value: updatedValue } = updatedAttribute;
|
52
|
+
const pathToCheck = [...componentContext.pathToComponent.slice(1), updatedName].join(".");
|
53
|
+
const values = componentContext.repeatableData.map((item) => {
|
54
|
+
return pathToCheck.split(".").reduce((acc, key) => acc[key], item);
|
55
|
+
});
|
56
|
+
const isUpdatedAttributeRepeatedInThisEntity = values.filter((value2) => value2 === updatedValue).length > 1;
|
57
|
+
if (isUpdatedAttributeRepeatedInThisEntity) {
|
58
|
+
return false;
|
59
|
+
}
|
60
|
+
}
|
61
|
+
const {
|
62
|
+
model: parentModel,
|
63
|
+
options: parentOptions,
|
64
|
+
id: excludeId
|
65
|
+
} = componentContext.parentContent;
|
66
|
+
const whereConditions = {};
|
67
|
+
const isParentDraft = parentOptions && parentOptions.isDraft;
|
68
|
+
whereConditions.publishedAt = isParentDraft ? null : { $notNull: true };
|
69
|
+
if (parentOptions?.locale) {
|
70
|
+
whereConditions.locale = parentOptions.locale;
|
71
|
+
}
|
72
|
+
if (excludeId && !Number.isNaN(excludeId)) {
|
73
|
+
whereConditions.id = { $ne: excludeId };
|
74
|
+
}
|
75
|
+
const queryUid = parentModel.uid;
|
76
|
+
const queryWhere = {
|
77
|
+
...componentContext.pathToComponent.reduceRight((acc, key) => ({ [key]: acc }), {
|
78
|
+
[updatedAttribute.name]: value
|
79
|
+
}),
|
80
|
+
...whereConditions
|
81
|
+
};
|
82
|
+
return !await strapi.db.query(queryUid).findOne({ where: queryWhere });
|
83
|
+
};
|
84
|
+
const validateUniqueFieldWithinDynamicZoneComponent = async (startOfPath) => {
|
85
|
+
if (!componentContext) {
|
86
|
+
return false;
|
87
|
+
}
|
88
|
+
const targetComponentUID = model.uid;
|
89
|
+
const countOfValueInThisEntity = (componentContext?.fullDynamicZoneContent ?? []).reduce(
|
90
|
+
(acc, component) => {
|
91
|
+
if (component.__component !== targetComponentUID) {
|
92
|
+
return acc;
|
93
|
+
}
|
94
|
+
const updatedValue = component[updatedAttribute.name];
|
95
|
+
return updatedValue === updatedAttribute.value ? acc + 1 : acc;
|
96
|
+
},
|
97
|
+
0
|
98
|
+
);
|
99
|
+
if (countOfValueInThisEntity > 1) {
|
100
|
+
return false;
|
101
|
+
}
|
102
|
+
const query = {
|
103
|
+
select: ["id"],
|
104
|
+
where: {},
|
105
|
+
populate: {
|
106
|
+
[startOfPath]: {
|
107
|
+
on: {
|
108
|
+
[targetComponentUID]: {
|
109
|
+
select: ["id"],
|
110
|
+
where: { [updatedAttribute.name]: updatedAttribute.value }
|
111
|
+
}
|
112
|
+
}
|
113
|
+
}
|
114
|
+
}
|
115
|
+
};
|
116
|
+
const { options: options2, id } = componentContext.parentContent;
|
117
|
+
if (options2?.isDraft !== void 0) {
|
118
|
+
query.where.published_at = options2.isDraft ? { $eq: null } : { $ne: null };
|
119
|
+
}
|
120
|
+
if (id) {
|
121
|
+
query.where.id = { $ne: id };
|
122
|
+
}
|
123
|
+
if (options2?.locale) {
|
124
|
+
query.where.locale = options2.locale;
|
125
|
+
}
|
126
|
+
const parentModelQueryResult = await strapi.db.query(componentContext.parentContent.model.uid).findMany(query);
|
127
|
+
const filteredResults = parentModelQueryResult.filter((result) => Array.isArray(result[startOfPath]) && result[startOfPath].length).flatMap((result) => result[startOfPath]).filter((dynamicZoneComponent) => dynamicZoneComponent.__component === targetComponentUID);
|
128
|
+
if (filteredResults.length >= 1) {
|
129
|
+
return false;
|
130
|
+
}
|
131
|
+
return true;
|
132
|
+
};
|
44
133
|
return validator.test("unique", "This attribute must be unique", async (value) => {
|
45
134
|
const isPublish = options.isDraft === false;
|
46
135
|
if (___default.default.isNil(value)) {
|
@@ -49,58 +138,27 @@ const addUniqueValidator = (validator, {
|
|
49
138
|
if (!isPublish && value === entity?.[updatedAttribute.name]) {
|
50
139
|
return true;
|
51
140
|
}
|
52
|
-
|
53
|
-
let queryWhere = {};
|
54
|
-
const hasPathToComponent = componentContext?.pathToComponent?.length > 0;
|
141
|
+
const hasPathToComponent = componentContext && componentContext.pathToComponent.length > 0;
|
55
142
|
if (hasPathToComponent) {
|
56
|
-
const
|
57
|
-
|
58
|
-
|
59
|
-
|
60
|
-
const values = componentContext.repeatableData.map((item) => {
|
61
|
-
return pathToCheck.split(".").reduce((acc, key) => acc[key], item);
|
62
|
-
});
|
63
|
-
const isUpdatedAttributeRepeatedInThisEntity = values.filter((value2) => value2 === updatedValue).length > 1;
|
64
|
-
if (isUpdatedAttributeRepeatedInThisEntity) {
|
65
|
-
return false;
|
66
|
-
}
|
67
|
-
}
|
68
|
-
const {
|
69
|
-
model: parentModel,
|
70
|
-
options: parentOptions,
|
71
|
-
id: excludeId
|
72
|
-
} = componentContext.parentContent;
|
73
|
-
queryUid = parentModel.uid;
|
74
|
-
const whereConditions = {};
|
75
|
-
const isParentDraft = parentOptions && parentOptions.isDraft;
|
76
|
-
whereConditions.publishedAt = isParentDraft ? null : { $notNull: true };
|
77
|
-
if (parentOptions?.locale) {
|
78
|
-
whereConditions.locale = parentOptions.locale;
|
79
|
-
}
|
80
|
-
if (excludeId && !Number.isNaN(excludeId)) {
|
81
|
-
whereConditions.id = { $ne: excludeId };
|
143
|
+
const startOfPath = componentContext.pathToComponent[0];
|
144
|
+
const testingDZ = componentContext.parentContent.model.attributes[startOfPath].type === "dynamiczone";
|
145
|
+
if (testingDZ) {
|
146
|
+
return validateUniqueFieldWithinDynamicZoneComponent(startOfPath);
|
82
147
|
}
|
83
|
-
|
84
|
-
...componentContext.pathToComponent.reduceRight((acc, key) => ({ [key]: acc }), {
|
85
|
-
[updatedAttribute.name]: value
|
86
|
-
}),
|
87
|
-
...whereConditions
|
88
|
-
};
|
89
|
-
} else {
|
90
|
-
queryUid = model.uid;
|
91
|
-
const scalarAttributeWhere = {
|
92
|
-
[updatedAttribute.name]: value
|
93
|
-
};
|
94
|
-
scalarAttributeWhere.publishedAt = options.isDraft ? null : { $notNull: true };
|
95
|
-
if (options?.locale) {
|
96
|
-
scalarAttributeWhere.locale = options.locale;
|
97
|
-
}
|
98
|
-
if (entity?.id) {
|
99
|
-
scalarAttributeWhere.id = { $ne: entity.id };
|
100
|
-
}
|
101
|
-
queryWhere = scalarAttributeWhere;
|
148
|
+
return validateUniqueFieldWithinComponent(value);
|
102
149
|
}
|
103
|
-
|
150
|
+
const scalarAttributeWhere = {
|
151
|
+
[updatedAttribute.name]: value
|
152
|
+
};
|
153
|
+
scalarAttributeWhere.publishedAt = options.isDraft ? null : { $notNull: true };
|
154
|
+
if (options?.locale) {
|
155
|
+
scalarAttributeWhere.locale = options.locale;
|
156
|
+
}
|
157
|
+
if (entity?.id) {
|
158
|
+
scalarAttributeWhere.id = { $ne: entity.id };
|
159
|
+
}
|
160
|
+
const queryUid = model.uid;
|
161
|
+
return !await strapi.db.query(queryUid).findOne({ where: scalarAttributeWhere });
|
104
162
|
});
|
105
163
|
};
|
106
164
|
const stringValidator = (metas, options) => {
|
@@ -113,7 +171,11 @@ const stringValidator = (metas, options) => {
|
|
113
171
|
};
|
114
172
|
const emailValidator = (metas, options) => {
|
115
173
|
const schema = stringValidator(metas, options);
|
116
|
-
return schema.email().min(
|
174
|
+
return schema.email().min(
|
175
|
+
1,
|
176
|
+
// eslint-disable-next-line no-template-curly-in-string
|
177
|
+
"${path} cannot be empty"
|
178
|
+
);
|
117
179
|
};
|
118
180
|
const uidValidator = (metas, options) => {
|
119
181
|
const schema = stringValidator(metas, options);
|
@@ -144,7 +206,7 @@ const datesValidator = (metas, options) => {
|
|
144
206
|
const schema = strapiUtils.yup.mixed();
|
145
207
|
return addUniqueValidator(schema, metas, options);
|
146
208
|
};
|
147
|
-
const
|
209
|
+
const Validators = {
|
148
210
|
string: stringValidator,
|
149
211
|
text: stringValidator,
|
150
212
|
richtext: stringValidator,
|
@@ -162,7 +224,14 @@ const validators = {
|
|
162
224
|
time: datesValidator,
|
163
225
|
datetime: datesValidator,
|
164
226
|
timestamp: datesValidator,
|
165
|
-
blocks: blocksValidator
|
227
|
+
blocks: blocksValidator.blocksValidator
|
166
228
|
};
|
167
|
-
|
229
|
+
exports.Validators = Validators;
|
230
|
+
exports.bigintegerValidator = bigintegerValidator;
|
231
|
+
exports.datesValidator = datesValidator;
|
232
|
+
exports.emailValidator = emailValidator;
|
233
|
+
exports.enumerationValidator = enumerationValidator;
|
234
|
+
exports.floatValidator = floatValidator;
|
235
|
+
exports.integerValidator = integerValidator;
|
236
|
+
exports.uidValidator = uidValidator;
|
168
237
|
//# sourceMappingURL=validators.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"validators.js","sources":["../../../src/services/entity-validator/validators.ts"],"sourcesContent":["import _ from 'lodash';\nimport { yup } from '@strapi/utils';\nimport type { Schema, Struct, Modules } from '@strapi/types';\nimport blocksValidator from './blocks-validator';\n\nimport type { ComponentContext } from '.';\n\ninterface ValidatorMetas<TAttribute extends Schema.Attribute.AnyAttribute> {\n attr: TAttribute;\n model: Struct.ContentTypeSchema;\n updatedAttribute: { name: string; value: unknown };\n entity: Modules.EntityValidator.Entity;\n componentContext: ComponentContext;\n}\n\ninterface ValidatorOptions {\n isDraft: boolean;\n locale?: string;\n}\n\n/* Validator utils */\n\n/**\n * Adds minLength validator\n */\nconst addMinLengthValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n },\n { isDraft }: ValidatorOptions\n) => {\n return attr.minLength && _.isInteger(attr.minLength) && !isDraft\n ? validator.min(attr.minLength)\n : validator;\n};\n\n/**\n * Adds maxLength validator\n * @returns {StringSchema}\n */\nconst addMaxLengthValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n }\n) => {\n return attr.maxLength && _.isInteger(attr.maxLength) ? validator.max(attr.maxLength) : validator;\n};\n\n/**\n * Adds min integer validator\n * @returns {NumberSchema}\n */\nconst addMinIntegerValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n }\n) => (_.isNumber(attr.min) ? validator.min(_.toInteger(attr.min)) : validator);\n\n/**\n * Adds max integer validator\n */\nconst addMaxIntegerValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n }\n) => (_.isNumber(attr.max) ? validator.max(_.toInteger(attr.max)) : validator);\n\n/**\n * Adds min float/decimal validator\n */\nconst addMinFloatValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n }\n) => (_.isNumber(attr.min) ? validator.min(attr.min) : validator);\n\n/**\n * Adds max float/decimal validator\n */\nconst addMaxFloatValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n }\n) => (_.isNumber(attr.max) ? validator.max(attr.max) : validator);\n\n/**\n * Adds regex validator\n */\nconst addStringRegexValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n }\n) => {\n return 'regex' in attr && !_.isUndefined(attr.regex)\n ? validator.matches(new RegExp(attr.regex), { excludeEmptyString: !attr.required })\n : validator;\n};\n\n/**\n * Adds unique validator\n */\nconst addUniqueValidator = <T extends yup.AnySchema>(\n validator: T,\n {\n attr,\n model,\n updatedAttribute,\n entity,\n componentContext,\n }: ValidatorMetas<Schema.Attribute.AnyAttribute & Schema.Attribute.UniqueOption>,\n options: ValidatorOptions\n): T => {\n if (attr.type !== 'uid' && !attr.unique) {\n return validator;\n }\n\n return validator.test('unique', 'This attribute must be unique', async (value) => {\n const isPublish = options.isDraft === false;\n\n /**\n * If the attribute value is `null` we want to skip the unique validation.\n * Otherwise it'll only accept a single `null` entry in the database.\n */\n if (_.isNil(value)) {\n return true;\n }\n\n /**\n * If we are updating a draft and the value is unchanged we skip the unique verification. This will\n * prevent the validator to be triggered in case the user activated the\n * unique constraint after already creating multiple entries with\n * the same attribute value for that field.\n */\n if (!isPublish && value === entity?.[updatedAttribute.name]) {\n return true;\n }\n\n let queryUid: string;\n let queryWhere: Record<string, any> = {};\n\n const hasPathToComponent = componentContext?.pathToComponent?.length > 0;\n if (hasPathToComponent) {\n const hasRepeatableData = componentContext.repeatableData.length > 0;\n if (hasRepeatableData) {\n // If we are validating a unique field within a repeatable component,\n // we first need to ensure that the repeatable in the current entity is\n // valid against itself.\n\n const { name: updatedName, value: updatedValue } = updatedAttribute;\n // Construct the full path to the unique field within the component.\n const pathToCheck = [...componentContext.pathToComponent.slice(1), updatedName].join('.');\n\n // Extract the values from the repeatable data using the constructed path\n const values = componentContext.repeatableData.map((item) => {\n return pathToCheck.split('.').reduce((acc, key) => acc[key], item as any);\n });\n\n // Check if the value is repeated in the current entity\n const isUpdatedAttributeRepeatedInThisEntity =\n values.filter((value) => value === updatedValue).length > 1;\n\n if (isUpdatedAttributeRepeatedInThisEntity) {\n return false;\n }\n }\n\n /**\n * When `componentContext` is present it means we are dealing with a unique\n * field within a component.\n *\n * The unique validation must consider the specific context of the\n * component, which will always be contained within a parent content type\n * and may also be nested within another component.\n *\n * We construct a query that takes into account the parent's model UID,\n * dimensions (such as draft and publish state/locale) and excludes the current\n * content type entity by its ID if provided.\n */\n const {\n model: parentModel,\n options: parentOptions,\n id: excludeId,\n } = componentContext.parentContent;\n queryUid = parentModel.uid;\n\n const whereConditions: Record<string, any> = {};\n const isParentDraft = parentOptions && parentOptions.isDraft;\n\n whereConditions.publishedAt = isParentDraft ? null : { $notNull: true };\n\n if (parentOptions?.locale) {\n whereConditions.locale = parentOptions.locale;\n }\n\n if (excludeId && !Number.isNaN(excludeId)) {\n whereConditions.id = { $ne: excludeId };\n }\n\n queryWhere = {\n ...componentContext.pathToComponent.reduceRight((acc, key) => ({ [key]: acc }), {\n [updatedAttribute.name]: value,\n }),\n\n ...whereConditions,\n };\n } else {\n /**\n * Here we are validating a scalar unique field from the content type's schema.\n * We construct a query to check if the value is unique\n * considering dimensions (e.g. locale, publication state) and excluding the current entity by its ID if available.\n */\n queryUid = model.uid;\n const scalarAttributeWhere: Record<string, any> = {\n [updatedAttribute.name]: value,\n };\n\n scalarAttributeWhere.publishedAt = options.isDraft ? null : { $notNull: true };\n\n if (options?.locale) {\n scalarAttributeWhere.locale = options.locale;\n }\n\n if (entity?.id) {\n scalarAttributeWhere.id = { $ne: entity.id };\n }\n\n queryWhere = scalarAttributeWhere;\n }\n\n // The validation should pass if there is no other record found from the query\n // TODO query not working for dynamic zones (type === relation)\n return !(await strapi.db.query(queryUid).findOne({ where: queryWhere }));\n });\n};\n\n/* Type validators */\n\nconst stringValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID\n >,\n options: ValidatorOptions\n) => {\n let schema = yup.string().transform((val, originalVal) => originalVal);\n\n schema = addMinLengthValidator(schema, metas, options);\n schema = addMaxLengthValidator(schema, metas);\n schema = addStringRegexValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst emailValidator = (\n metas: ValidatorMetas<Schema.Attribute.Email>,\n options: ValidatorOptions\n) => {\n const schema = stringValidator(metas, options);\n return schema.email().min(1, '${path} cannot be empty');\n};\n\nconst uidValidator = (metas: ValidatorMetas<Schema.Attribute.UID>, options: ValidatorOptions) => {\n const schema = stringValidator(metas, options);\n\n return schema.matches(/^[A-Za-z0-9-_.~]*$/);\n};\n\nconst enumerationValidator = ({ attr }: { attr: Schema.Attribute.Enumeration }) => {\n return yup\n .string()\n .oneOf((Array.isArray(attr.enum) ? attr.enum : [attr.enum]).concat(null as any));\n};\n\nconst integerValidator = (\n metas: ValidatorMetas<Schema.Attribute.Integer | Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n let schema = yup.number().integer();\n\n schema = addMinIntegerValidator(schema, metas);\n schema = addMaxIntegerValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst floatValidator = (\n metas: ValidatorMetas<Schema.Attribute.Decimal | Schema.Attribute.Float>,\n options: ValidatorOptions\n) => {\n let schema = yup.number();\n schema = addMinFloatValidator(schema, metas);\n schema = addMaxFloatValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst bigintegerValidator = (\n metas: ValidatorMetas<Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nconst datesValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.Date\n | Schema.Attribute.DateTime\n | Schema.Attribute.Time\n | Schema.Attribute.Timestamp\n >,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nexport default {\n string: stringValidator,\n text: stringValidator,\n richtext: stringValidator,\n password: stringValidator,\n email: emailValidator,\n enumeration: enumerationValidator,\n boolean: () => yup.boolean(),\n uid: uidValidator,\n json: () => yup.mixed(),\n integer: integerValidator,\n biginteger: bigintegerValidator,\n float: floatValidator,\n decimal: floatValidator,\n date: datesValidator,\n time: datesValidator,\n datetime: datesValidator,\n timestamp: datesValidator,\n blocks: blocksValidator,\n};\n"],"names":["_","value","yup"],"mappings":";;;;;;AAyBA,MAAM,wBAAwB,CAC5B,WACA;AAAA,EACE;AACF,GASA,EAAE,cACC;AACH,SAAO,KAAK,aAAaA,WAAE,QAAA,UAAU,KAAK,SAAS,KAAK,CAAC,UACrD,UAAU,IAAI,KAAK,SAAS,IAC5B;AACN;AAMA,MAAM,wBAA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QAAQ,KAAK;AACpC,WAAA,mBAAmB,QAAQ,OAAO,OAAO;AAE3C,SAAA;AACT;AAEA,MAAM,iBAAiB,CACrB,OACA,YACG;AACC,MAAA,SAASA,gBAAI;AACR,WAAA,qBAAqB,QAAQ,KAAK;AAClC,WAAA,qBAAqB,QAAQ,KAAK;AAClC,WAAA,mBAAmB,QAAQ,OAAO,OAAO;AAE3C,SAAA;AACT;AAEA,MAAM,sBAAsB,CAC1B,OACA,YACG;AACG,QAAA,SAASA,gBAAI;AACZ,SAAA,mBAAmB,QAAQ,OAAO,OAAO;AAClD;AAEA,MAAM,iBAAiB,CACrB,OAMA,YACG;AACG,QAAA,SAASA,gBAAI;AACZ,SAAA,mBAAmB,QAAQ,OAAO,OAAO;AAClD;AAEA,MAAe,aAAA;AAAA,EACb,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,UAAU;AAAA,EACV,UAAU;AAAA,EACV,OAAO;AAAA,EACP,aAAa;AAAA,EACb,SAAS,MAAMA,YAAA,IAAI,QAAQ;AAAA,EAC3B,KAAK;AAAA,EACL,MAAM,MAAMA,YAAA,IAAI,MAAM;AAAA,EACtB,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AAAA,EACN,UAAU;AAAA,EACV,WAAW;AAAA,EACX,QAAQ;AACV;;"}
|
1
|
+
{"version":3,"file":"validators.js","sources":["../../../src/services/entity-validator/validators.ts"],"sourcesContent":["import _ from 'lodash';\nimport { yup } from '@strapi/utils';\nimport type { Schema, Struct, Modules } from '@strapi/types';\nimport { blocksValidator } from './blocks-validator';\n\nimport type { ComponentContext } from '.';\n\nexport interface ValidatorMetas<\n TAttribute extends Schema.Attribute.AnyAttribute = Schema.Attribute.AnyAttribute,\n TValue extends Schema.Attribute.Value<TAttribute> = Schema.Attribute.Value<TAttribute>,\n> {\n attr: TAttribute;\n model: Struct.Schema;\n updatedAttribute: {\n name: string;\n value: TValue;\n };\n componentContext?: ComponentContext;\n entity?: Modules.EntityValidator.Entity;\n}\n\ninterface ValidatorOptions {\n isDraft: boolean;\n locale?: string;\n}\n\n/* Validator utils */\n\n/**\n * Adds minLength validator\n */\nconst addMinLengthValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n },\n { isDraft }: ValidatorOptions\n) => {\n return attr.minLength && _.isInteger(attr.minLength) && !isDraft\n ? validator.min(attr.minLength)\n : validator;\n};\n\n/**\n * Adds maxLength validator\n * @returns {StringSchema}\n */\nconst addMaxLengthValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n }\n) => {\n return attr.maxLength && _.isInteger(attr.maxLength) ? validator.max(attr.maxLength) : validator;\n};\n\n/**\n * Adds min integer validator\n * @returns {NumberSchema}\n */\nconst addMinIntegerValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n }\n) => (_.isNumber(attr.min) ? validator.min(_.toInteger(attr.min)) : validator);\n\n/**\n * Adds max integer validator\n */\nconst addMaxIntegerValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n }\n) => (_.isNumber(attr.max) ? validator.max(_.toInteger(attr.max)) : validator);\n\n/**\n * Adds min float/decimal validator\n */\nconst addMinFloatValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n }\n) => (_.isNumber(attr.min) ? validator.min(attr.min) : validator);\n\n/**\n * Adds max float/decimal validator\n */\nconst addMaxFloatValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n }\n) => (_.isNumber(attr.max) ? validator.max(attr.max) : validator);\n\n/**\n * Adds regex validator\n */\nconst addStringRegexValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n }\n) => {\n return 'regex' in attr && !_.isUndefined(attr.regex)\n ? validator.matches(new RegExp(attr.regex), { excludeEmptyString: !attr.required })\n : validator;\n};\n\nconst addUniqueValidator = <T extends yup.AnySchema>(\n validator: T,\n {\n attr,\n model,\n updatedAttribute,\n entity,\n componentContext,\n }: ValidatorMetas<Schema.Attribute.AnyAttribute & Schema.Attribute.UniqueOption>,\n options: ValidatorOptions\n): T => {\n if (attr.type !== 'uid' && !attr.unique) {\n return validator;\n }\n\n const validateUniqueFieldWithinComponent = async (value: any): Promise<boolean> => {\n if (!componentContext) {\n return false;\n }\n\n // If we are validating a unique field within a repeatable component,\n // we first need to ensure that the repeatable in the current entity is\n // valid against itself.\n const hasRepeatableData = componentContext.repeatableData.length > 0;\n if (hasRepeatableData) {\n const { name: updatedName, value: updatedValue } = updatedAttribute;\n // Construct the full path to the unique field within the component.\n const pathToCheck = [...componentContext.pathToComponent.slice(1), updatedName].join('.');\n\n // Extract the values from the repeatable data using the constructed path\n const values = componentContext.repeatableData.map((item) => {\n return pathToCheck.split('.').reduce((acc, key) => acc[key], item as any);\n });\n\n // Check if the value is repeated in the current entity\n const isUpdatedAttributeRepeatedInThisEntity =\n values.filter((value) => value === updatedValue).length > 1;\n\n if (isUpdatedAttributeRepeatedInThisEntity) {\n return false;\n }\n }\n\n /**\n * When `componentContext` is present it means we are dealing with a unique\n * field within a component.\n *\n * The unique validation must consider the specific context of the\n * component, which will always be contained within a parent content type\n * and may also be nested within another component.\n *\n * We construct a query that takes into account the parent's model UID,\n * dimensions (such as draft and publish state/locale) and excludes the current\n * content type entity by its ID if provided.\n */\n const {\n model: parentModel,\n options: parentOptions,\n id: excludeId,\n } = componentContext.parentContent;\n\n const whereConditions: Record<string, any> = {};\n const isParentDraft = parentOptions && parentOptions.isDraft;\n\n whereConditions.publishedAt = isParentDraft ? null : { $notNull: true };\n\n if (parentOptions?.locale) {\n whereConditions.locale = parentOptions.locale;\n }\n\n if (excludeId && !Number.isNaN(excludeId)) {\n whereConditions.id = { $ne: excludeId };\n }\n\n const queryUid = parentModel.uid;\n const queryWhere = {\n ...componentContext.pathToComponent.reduceRight((acc, key) => ({ [key]: acc }), {\n [updatedAttribute.name]: value,\n }),\n\n ...whereConditions,\n };\n\n // The validation should pass if there is no other record found from the query\n return !(await strapi.db.query(queryUid).findOne({ where: queryWhere }));\n };\n\n const validateUniqueFieldWithinDynamicZoneComponent = async (\n startOfPath: string\n ): Promise<boolean> => {\n if (!componentContext) {\n return false;\n }\n\n const targetComponentUID = model.uid;\n // Ensure that the value is unique within the dynamic zone in this entity.\n const countOfValueInThisEntity = (componentContext?.fullDynamicZoneContent ?? []).reduce(\n (acc, component) => {\n if (component.__component !== targetComponentUID) {\n return acc;\n }\n\n const updatedValue = component[updatedAttribute.name];\n return updatedValue === updatedAttribute.value ? acc + 1 : acc;\n },\n 0\n );\n\n if (countOfValueInThisEntity > 1) {\n // If the value is repeated in the current entity, the validation fails.\n return false;\n }\n\n // Build a query for the parent content type to find all entities in the\n // same locale and publication state\n type QueryType = {\n select: string[];\n where: {\n published_at?: { $eq: null } | { $ne: null };\n id?: { $ne: number };\n locale?: string;\n };\n populate: {\n [key: string]: {\n on: {\n [key: string]: {\n select: string[];\n where: { [key: string]: string | number | boolean };\n };\n };\n };\n };\n };\n\n // Populate the dynamic zone for any components that share the same value\n // as the updated attribute.\n const query: QueryType = {\n select: ['id'],\n where: {},\n populate: {\n [startOfPath]: {\n on: {\n [targetComponentUID]: {\n select: ['id'],\n where: { [updatedAttribute.name]: updatedAttribute.value },\n },\n },\n },\n },\n };\n\n const { options, id } = componentContext.parentContent;\n\n if (options?.isDraft !== undefined) {\n query.where.published_at = options.isDraft ? { $eq: null } : { $ne: null };\n }\n\n if (id) {\n query.where.id = { $ne: id };\n }\n\n if (options?.locale) {\n query.where.locale = options.locale;\n }\n\n const parentModelQueryResult = await strapi.db\n .query(componentContext.parentContent.model.uid)\n .findMany(query);\n\n // Filter the results to only include results that have components in the\n // dynamic zone that match the target component type.\n const filteredResults = parentModelQueryResult\n .filter((result) => Array.isArray(result[startOfPath]) && result[startOfPath].length)\n .flatMap((result) => result[startOfPath])\n .filter((dynamicZoneComponent) => dynamicZoneComponent.__component === targetComponentUID);\n\n if (filteredResults.length >= 1) {\n return false;\n }\n\n return true;\n };\n\n return validator.test('unique', 'This attribute must be unique', async (value) => {\n const isPublish = options.isDraft === false;\n\n /**\n * If the attribute value is `null` we want to skip the unique validation.\n * Otherwise it'll only accept a single `null` entry in the database.\n */\n if (_.isNil(value)) {\n return true;\n }\n\n /**\n * If we are updating a draft and the value is unchanged we skip the unique verification. This will\n * prevent the validator to be triggered in case the user activated the\n * unique constraint after already creating multiple entries with\n * the same attribute value for that field.\n */\n if (!isPublish && value === entity?.[updatedAttribute.name]) {\n return true;\n }\n\n const hasPathToComponent = componentContext && componentContext.pathToComponent.length > 0;\n if (hasPathToComponent) {\n // Detect if we are validating within a dynamiczone by checking if the first\n // path is a dynamiczone attribute in the parent content type.\n const startOfPath = componentContext.pathToComponent[0];\n const testingDZ =\n componentContext.parentContent.model.attributes[startOfPath].type === 'dynamiczone';\n\n if (testingDZ) {\n return validateUniqueFieldWithinDynamicZoneComponent(startOfPath);\n }\n\n return validateUniqueFieldWithinComponent(value);\n }\n\n /**\n * Here we are validating a scalar unique field from the content type's schema.\n * We construct a query to check if the value is unique\n * considering dimensions (e.g. locale, publication state) and excluding the current entity by its ID if available.\n */\n const scalarAttributeWhere: Record<string, any> = {\n [updatedAttribute.name]: value,\n };\n\n scalarAttributeWhere.publishedAt = options.isDraft ? null : { $notNull: true };\n\n if (options?.locale) {\n scalarAttributeWhere.locale = options.locale;\n }\n\n if (entity?.id) {\n scalarAttributeWhere.id = { $ne: entity.id };\n }\n\n // The validation should pass if there is no other record found from the query\n const queryUid = model.uid;\n return !(await strapi.db.query(queryUid).findOne({ where: scalarAttributeWhere }));\n });\n};\n\n/* Type validators */\n\nconst stringValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID\n >,\n options: ValidatorOptions\n) => {\n let schema = yup.string().transform((val, originalVal) => originalVal);\n\n schema = addMinLengthValidator(schema, metas, options);\n schema = addMaxLengthValidator(schema, metas);\n schema = addStringRegexValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nexport const emailValidator = (\n metas: ValidatorMetas<Schema.Attribute.Email>,\n options: ValidatorOptions\n) => {\n const schema = stringValidator(metas, options);\n return schema.email().min(\n 1,\n // eslint-disable-next-line no-template-curly-in-string\n '${path} cannot be empty'\n );\n};\n\nexport const uidValidator = (\n metas: ValidatorMetas<Schema.Attribute.UID>,\n options: ValidatorOptions\n) => {\n const schema = stringValidator(metas, options);\n\n return schema.matches(/^[A-Za-z0-9-_.~]*$/);\n};\n\nexport const enumerationValidator = ({ attr }: { attr: Schema.Attribute.Enumeration }) => {\n return yup\n .string()\n .oneOf((Array.isArray(attr.enum) ? attr.enum : [attr.enum]).concat(null as any));\n};\n\nexport const integerValidator = (\n metas: ValidatorMetas<Schema.Attribute.Integer | Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n let schema = yup.number().integer();\n\n schema = addMinIntegerValidator(schema, metas);\n schema = addMaxIntegerValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nexport const floatValidator = (\n metas: ValidatorMetas<Schema.Attribute.Decimal | Schema.Attribute.Float>,\n options: ValidatorOptions\n) => {\n let schema = yup.number();\n schema = addMinFloatValidator(schema, metas);\n schema = addMaxFloatValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nexport const bigintegerValidator = (\n metas: ValidatorMetas<Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nexport const datesValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.Date\n | Schema.Attribute.DateTime\n | Schema.Attribute.Time\n | Schema.Attribute.Timestamp\n >,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nexport const Validators = {\n string: stringValidator,\n text: stringValidator,\n richtext: stringValidator,\n password: stringValidator,\n email: emailValidator,\n enumeration: enumerationValidator,\n boolean: () => yup.boolean(),\n uid: uidValidator,\n json: () => yup.mixed(),\n integer: integerValidator,\n biginteger: bigintegerValidator,\n float: floatValidator,\n decimal: floatValidator,\n date: datesValidator,\n time: datesValidator,\n datetime: datesValidator,\n timestamp: datesValidator,\n blocks: blocksValidator,\n};\n"],"names":["_","value","options","yup","blocksValidator"],"mappings":";;;;;;;AA+BA,MAAM,wBAAwB,CAC5B,WACA;AAAA,EACE;AACF,GASA,EAAE,cACC;AACH,SAAO,KAAK,aAAaA,WAAE,QAAA,UAAU,KAAK,SAAS,KAAK,CAAC,UACrD,UAAU,IAAI,KAAK,SAAS,IAC5B;AACN;AAMA,MAAM,wBAAwB,CAC5B,WACA;AAAA,EACE;AACF,MASG;AACI,SAAA,KAAK,aAAaA,mBAAE,UAAU,KAAK,SAAS,IAAI,UAAU,IAAI,KAAK,SAAS,IAAI;AACzF;AAMA,MAAM,yBAAyB,CAC7B,WACA;AAAA,EACE;AACF,MAGIA,WAAE,QAAA,SAAS,KAAK,GAAG,IAAI,UAAU,IAAIA,WAAAA,QAAE,UAAU,KAAK,GAAG,CAAC,IAAI;AAKpE,MAAM,yBAAyB,CAC7B,WACA;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