@strapi/content-manager 5.36.0 → 5.36.1

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.
@@ -247,13 +247,12 @@ const addMaxLengthValidation = (attribute)=>(schema)=>{
247
247
  return schema;
248
248
  };
249
249
  const addMinValidation = (attribute, options)=>(schema)=>{
250
- // do not validate min for draft
251
250
  if (options.status === 'draft') {
252
251
  return schema;
253
252
  }
254
253
  if ('min' in attribute && 'min' in schema) {
255
254
  const min = toInteger(attribute.min);
256
- if (min) {
255
+ if (min !== undefined) {
257
256
  return schema.min(min, {
258
257
  ...strapiAdmin.translatedErrors.min,
259
258
  values: {
@@ -267,7 +266,7 @@ const addMinValidation = (attribute, options)=>(schema)=>{
267
266
  const addMaxValidation = (attribute)=>(schema)=>{
268
267
  if ('max' in attribute) {
269
268
  const max = toInteger(attribute.max);
270
- if ('max' in schema && max) {
269
+ if ('max' in schema && max !== undefined) {
271
270
  return schema.max(max, {
272
271
  ...strapiAdmin.translatedErrors.max,
273
272
  values: {
@@ -1 +1 @@
1
- {"version":3,"file":"validation.js","sources":["../../../admin/src/utils/validation.ts"],"sourcesContent":["import { translatedErrors } from '@strapi/admin/strapi-admin';\nimport pipe from 'lodash/fp/pipe';\nimport * as yup from 'yup';\n\nimport { DOCUMENT_META_FIELDS } from '../constants/attributes';\n\nimport type { ComponentsDictionary, Schema } from '../hooks/useDocument';\nimport type { Schema as SchemaUtils } from '@strapi/types';\nimport type { ObjectShape } from 'yup/lib/object';\n\ntype AnySchema =\n | yup.StringSchema\n | yup.NumberSchema\n | yup.BooleanSchema\n | yup.DateSchema\n | yup.ArraySchema<any>\n | yup.ObjectSchema<any>;\n\n/* -------------------------------------------------------------------------------------------------\n * createYupSchema\n * -----------------------------------------------------------------------------------------------*/\n\ninterface ValidationOptions {\n status: 'draft' | 'published' | null;\n removedAttributes?: string[];\n}\n\nconst arrayValidator = (attribute: Schema['attributes'][string], options: ValidationOptions) => ({\n message: translatedErrors.required,\n test(value: unknown) {\n if (options.status === 'draft') {\n return true;\n }\n\n if (!attribute.required) {\n return true;\n }\n\n if (!value) {\n return false;\n }\n\n if (Array.isArray(value) && value.length === 0) {\n return false;\n }\n\n return true;\n },\n});\nconst escapeRegex = (str: string) => str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n/**\n * TODO: should we create a Map to store these based on the hash of the schema?\n */\nconst createYupSchema = (\n attributes: Schema['attributes'] = {},\n components: ComponentsDictionary = {},\n options: ValidationOptions = { status: null }\n): yup.ObjectSchema<any> => {\n const createModelSchema = (\n attributes: Schema['attributes'],\n removedAttributes: string[] = []\n ): yup.ObjectSchema<any> =>\n yup\n .object()\n .shape(\n Object.entries(attributes).reduce<ObjectShape>((acc, [name, attribute]) => {\n const getNestedPathsForAttribute = (removed: string[], attrName: string): string[] => {\n const prefix = `${attrName}.`;\n // Match both numeric indices [0] and __temp_key__ values [some_key]\n const bracketRegex = new RegExp(`^${escapeRegex(attrName)}\\\\[[^\\\\]]+\\\\]\\\\.`);\n\n return removed\n .filter((p) => p.startsWith(prefix) || bracketRegex.test(p))\n .map((p) =>\n p.startsWith(prefix) ? p.slice(prefix.length) : p.replace(bracketRegex, '')\n );\n };\n\n if (DOCUMENT_META_FIELDS.includes(name)) {\n return acc;\n }\n\n if (removedAttributes?.includes(name)) {\n // If the attribute is not visible, we don't want to validate it\n return acc;\n }\n\n const nestedRemoved = getNestedPathsForAttribute(removedAttributes, name);\n\n /**\n * These validations won't apply to every attribute\n * and that's okay, in that case we just return the\n * schema as it was passed.\n */\n const validations = [\n addNullableValidation,\n addRequiredValidation,\n addMinLengthValidation,\n addMaxLengthValidation,\n addMinValidation,\n addMaxValidation,\n addRegexValidation,\n ].map((fn) => fn(attribute, options));\n\n const transformSchema = pipe(...validations);\n\n switch (attribute.type) {\n case 'component': {\n const { attributes } = components[attribute.component];\n\n if (attribute.repeatable) {\n return {\n ...acc,\n [name]: transformSchema(\n yup.array().of(createModelSchema(attributes, nestedRemoved).nullable(false))\n ).test(arrayValidator(attribute, options)),\n };\n } else {\n return {\n ...acc,\n [name]: transformSchema(createModelSchema(attributes, nestedRemoved).nullable()),\n };\n }\n }\n case 'dynamiczone':\n return {\n ...acc,\n [name]: transformSchema(\n yup.array().of(\n yup.lazy(\n (\n data: SchemaUtils.Attribute.Value<SchemaUtils.Attribute.DynamicZone>[number]\n ) => {\n const attributes = components?.[data?.__component]?.attributes;\n\n const validation = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(components)),\n })\n .nullable(false);\n if (!attributes) {\n return validation;\n }\n\n return validation.concat(createModelSchema(attributes, nestedRemoved));\n }\n ) as unknown as yup.ObjectSchema<any>\n )\n ).test(arrayValidator(attribute, options)),\n };\n case 'relation':\n return {\n ...acc,\n [name]: transformSchema(\n yup.lazy((value) => {\n if (!value) {\n return yup.mixed().nullable(true);\n } else if (Array.isArray(value)) {\n // If a relation value is an array, we expect\n // an array of objects with {id} properties, representing the related entities.\n return yup.array().of(\n yup.object().shape({\n id: yup.number().required(),\n })\n );\n } else if (typeof value === 'object') {\n // A realtion value can also be an object. Some API\n // repsonses return the number of entities in the relation\n // as { count: x }\n return yup.object();\n } else {\n return yup\n .mixed()\n .test(\n 'type-error',\n 'Relation values must be either null, an array of objects with {id} or an object.',\n () => false\n );\n }\n })\n ),\n };\n default:\n return {\n ...acc,\n [name]: transformSchema(createAttributeSchema(attribute)),\n };\n }\n }, {})\n )\n /**\n * TODO: investigate why an undefined object fails a check of `nullable`.\n */\n .default(null);\n\n return createModelSchema(attributes, options.removedAttributes);\n};\n\nconst createAttributeSchema = (\n attribute: Exclude<\n SchemaUtils.Attribute.AnyAttribute,\n { type: 'dynamiczone' } | { type: 'component' } | { type: 'relation' }\n >\n) => {\n switch (attribute.type) {\n case 'biginteger':\n return yup.string().matches(/^-?\\d*$/);\n case 'boolean':\n return yup.boolean().nullable();\n case 'blocks':\n return yup.mixed().test('isBlocks', translatedErrors.json, (value) => {\n if (!value || Array.isArray(value)) {\n return true;\n } else {\n return false;\n }\n });\n case 'decimal':\n case 'float':\n case 'integer':\n return yup.number();\n case 'email':\n return yup.string().email(translatedErrors.email);\n case 'enumeration':\n return yup.string().oneOf([...attribute.enum, null]);\n case 'json':\n return yup.mixed().test('isJSON', translatedErrors.json, (value) => {\n /**\n * We don't want to validate the JSON field if it's empty.\n */\n if (!value || (typeof value === 'string' && value.length === 0)) {\n return true;\n }\n\n // If the value was created via content API and wasn't changed, then it's still an object\n if (typeof value === 'object') {\n try {\n JSON.stringify(value);\n return true;\n } catch (err) {\n return false;\n }\n }\n\n try {\n JSON.parse(value);\n\n return true;\n } catch (err) {\n return false;\n }\n });\n case 'password':\n return yup.string().nullable();\n case 'richtext':\n case 'string':\n case 'text':\n return yup.string();\n case 'uid':\n return yup\n .string()\n .matches(attribute.regex ? new RegExp(attribute.regex) : /^[A-Za-z0-9-_.~]*$/);\n default:\n /**\n * This allows any value.\n */\n return yup.mixed();\n }\n};\n\n// Helper function to return schema.nullable() if it exists, otherwise return schema\nconst nullableSchema = <TSchema extends AnySchema>(schema: TSchema) => {\n return schema?.nullable\n ? schema.nullable()\n : // In some cases '.nullable' will not be available on the schema.\n // e.g. when the schema has been built using yup.lazy (e.g. for relations).\n // In these cases we should just return the schema as it is.\n schema;\n};\n\n/* -------------------------------------------------------------------------------------------------\n * Validators\n * -----------------------------------------------------------------------------------------------*/\n/**\n * Our validator functions can be preped with the\n * attribute and then have the schema piped through them.\n */\ntype ValidationFn = (\n attribute: Schema['attributes'][string],\n options: ValidationOptions\n) => <TSchema extends AnySchema>(schema: TSchema) => TSchema;\n\nconst addNullableValidation: ValidationFn = () => (schema) => {\n return nullableSchema(schema);\n};\n\nconst addRequiredValidation: ValidationFn = (attribute, options) => (schema) => {\n if (options.status === 'draft' || !attribute.required || attribute.type === 'password') {\n return schema;\n }\n\n if (attribute.required && 'required' in schema) {\n return schema.required(translatedErrors.required);\n }\n\n return schema;\n};\n\nconst addMinLengthValidation: ValidationFn =\n (attribute, options) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n // Skip minLength validation for draft\n if (options.status === 'draft') {\n return schema;\n }\n\n if (\n 'minLength' in attribute &&\n attribute.minLength &&\n Number.isInteger(attribute.minLength) &&\n 'min' in schema\n ) {\n return schema.min(attribute.minLength, {\n ...translatedErrors.minLength,\n values: {\n min: attribute.minLength,\n },\n }) as TSchema;\n }\n\n return schema;\n };\n\nconst addMaxLengthValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if (\n 'maxLength' in attribute &&\n attribute.maxLength &&\n Number.isInteger(attribute.maxLength) &&\n 'max' in schema\n ) {\n return schema.max(attribute.maxLength, {\n ...translatedErrors.maxLength,\n values: {\n max: attribute.maxLength,\n },\n }) as TSchema;\n }\n\n return schema;\n };\n\nconst addMinValidation: ValidationFn =\n (attribute, options) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n // do not validate min for draft\n if (options.status === 'draft') {\n return schema;\n }\n\n if ('min' in attribute && 'min' in schema) {\n const min = toInteger(attribute.min);\n\n if (min) {\n return schema.min(min, {\n ...translatedErrors.min,\n values: {\n min,\n },\n }) as TSchema;\n }\n }\n\n return schema;\n };\n\nconst addMaxValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if ('max' in attribute) {\n const max = toInteger(attribute.max);\n\n if ('max' in schema && max) {\n return schema.max(max, {\n ...translatedErrors.max,\n values: {\n max,\n },\n }) as TSchema;\n }\n }\n\n return schema;\n };\n\nconst toInteger = (val?: string | number): number | undefined => {\n if (typeof val === 'number' || val === undefined) {\n return val;\n } else {\n const num = Number(val);\n return isNaN(num) ? undefined : num;\n }\n};\n\nconst addRegexValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if ('regex' in attribute && attribute.regex && 'matches' in schema) {\n return schema.matches(new RegExp(attribute.regex), {\n message: {\n id: translatedErrors.regex.id,\n defaultMessage: 'The value does not match the defined pattern.',\n },\n\n excludeEmptyString: !attribute.required,\n }) as TSchema;\n }\n\n return schema;\n };\n\nexport { createYupSchema };\n"],"names":["arrayValidator","attribute","options","message","translatedErrors","required","test","value","status","Array","isArray","length","escapeRegex","str","replace","createYupSchema","attributes","components","createModelSchema","removedAttributes","yup","object","shape","Object","entries","reduce","acc","name","getNestedPathsForAttribute","removed","attrName","prefix","bracketRegex","RegExp","filter","p","startsWith","map","slice","DOCUMENT_META_FIELDS","includes","nestedRemoved","validations","addNullableValidation","addRequiredValidation","addMinLengthValidation","addMaxLengthValidation","addMinValidation","addMaxValidation","addRegexValidation","fn","transformSchema","pipe","type","component","repeatable","array","of","nullable","lazy","data","__component","validation","string","oneOf","keys","concat","mixed","id","number","createAttributeSchema","default","matches","boolean","json","email","enum","JSON","stringify","err","parse","regex","nullableSchema","schema","minLength","Number","isInteger","min","values","maxLength","max","toInteger","val","undefined","num","isNaN","defaultMessage","excludeEmptyString"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAMA,cAAiB,GAAA,CAACC,SAAyCC,EAAAA,OAAAA,IAAgC;AAC/FC,QAAAA,OAAAA,EAASC,6BAAiBC,QAAQ;AAClCC,QAAAA,IAAAA,CAAAA,CAAKC,KAAc,EAAA;YACjB,IAAIL,OAAAA,CAAQM,MAAM,KAAK,OAAS,EAAA;gBAC9B,OAAO,IAAA;AACT;YAEA,IAAI,CAACP,SAAUI,CAAAA,QAAQ,EAAE;gBACvB,OAAO,IAAA;AACT;AAEA,YAAA,IAAI,CAACE,KAAO,EAAA;gBACV,OAAO,KAAA;AACT;AAEA,YAAA,IAAIE,MAAMC,OAAO,CAACH,UAAUA,KAAMI,CAAAA,MAAM,KAAK,CAAG,EAAA;gBAC9C,OAAO,KAAA;AACT;YAEA,OAAO,IAAA;AACT;KACF,CAAA;AACA,MAAMC,cAAc,CAACC,GAAAA,GAAgBA,GAAIC,CAAAA,OAAO,CAAC,qBA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AUO,GAAK,EAAA;gBAC1B,OAAOP,MAAAA,CAAOO,GAAG,CAACA,GAAK,EAAA;AACrB,oBAAA,GAAGtF,6BAAiBsF,GAAG;oBACvBF,MAAQ,EAAA;AACNE,wBAAAA;AACF;AACF,iBAAA,CAAA;AACF;AACF;QAEA,OAAOP,MAAAA;AACT,KAAA;AAEF,MAAMQ,YAAY,CAACC,GAAAA,GAAAA;AACjB,IAAA,IAAI,OAAOA,GAAAA,KAAQ,QAAYA,IAAAA,GAAAA,KAAQC,SAAW,EAAA;QAChD,OAAOD,GAAAA;KACF,MAAA;AACL,QAAA,MAAME,MAAMT,MAAOO,CAAAA,GAAAA,CAAAA;QACnB,OAAOG,KAAAA,CAAMD,OAAOD,SAAYC,GAAAA,GAAAA;AAClC;AACF,CAAA;AAEA,MAAM7C,kBAAAA,GACJ,CAAChD,SAAAA,GACD,CAA4BkF,MAAAA,GAAAA;AAC1B,QAAA,IAAI,WAAWlF,SAAaA,IAAAA,SAAAA,CAAUgF,KAAK,IAAI,aAAaE,MAAQ,EAAA;AAClE,YAAA,OAAOA,OAAOX,OAAO,CAAC,IAAIvC,MAAOhC,CAAAA,SAAAA,CAAUgF,KAAK,CAAG,EAAA;gBACjD9E,OAAS,EAAA;oBACPiE,EAAIhE,EAAAA,4BAAAA,CAAiB6E,KAAK,CAACb,EAAE;oBAC7B4B,cAAgB,EAAA;AAClB,iBAAA;gBAEAC,kBAAoB,EAAA,CAAChG,UAAUI;AACjC,aAAA,CAAA;AACF;QAEA,OAAO8E,MAAAA;AACT,KAAA;;;;"}
1
+ {"version":3,"file":"validation.js","sources":["../../../admin/src/utils/validation.ts"],"sourcesContent":["import { translatedErrors } from '@strapi/admin/strapi-admin';\nimport pipe from 'lodash/fp/pipe';\nimport * as yup from 'yup';\n\nimport { DOCUMENT_META_FIELDS } from '../constants/attributes';\n\nimport type { ComponentsDictionary, Schema } from '../hooks/useDocument';\nimport type { Schema as SchemaUtils } from '@strapi/types';\nimport type { ObjectShape } from 'yup/lib/object';\n\ntype AnySchema =\n | yup.StringSchema\n | yup.NumberSchema\n | yup.BooleanSchema\n | yup.DateSchema\n | yup.ArraySchema<any>\n | yup.ObjectSchema<any>;\n\n/* -------------------------------------------------------------------------------------------------\n * createYupSchema\n * -----------------------------------------------------------------------------------------------*/\n\ninterface ValidationOptions {\n status: 'draft' | 'published' | null;\n removedAttributes?: string[];\n}\n\nconst arrayValidator = (attribute: Schema['attributes'][string], options: ValidationOptions) => ({\n message: translatedErrors.required,\n test(value: unknown) {\n if (options.status === 'draft') {\n return true;\n }\n\n if (!attribute.required) {\n return true;\n }\n\n if (!value) {\n return false;\n }\n\n if (Array.isArray(value) && value.length === 0) {\n return false;\n }\n\n return true;\n },\n});\nconst escapeRegex = (str: string) => str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n/**\n * TODO: should we create a Map to store these based on the hash of the schema?\n */\nconst createYupSchema = (\n attributes: Schema['attributes'] = {},\n components: ComponentsDictionary = {},\n options: ValidationOptions = { status: null }\n): yup.ObjectSchema<any> => {\n const createModelSchema = (\n attributes: Schema['attributes'],\n removedAttributes: string[] = []\n ): yup.ObjectSchema<any> =>\n yup\n .object()\n .shape(\n Object.entries(attributes).reduce<ObjectShape>((acc, [name, attribute]) => {\n const getNestedPathsForAttribute = (removed: string[], attrName: string): string[] => {\n const prefix = `${attrName}.`;\n // Match both numeric indices [0] and __temp_key__ values [some_key]\n const bracketRegex = new RegExp(`^${escapeRegex(attrName)}\\\\[[^\\\\]]+\\\\]\\\\.`);\n\n return removed\n .filter((p) => p.startsWith(prefix) || bracketRegex.test(p))\n .map((p) =>\n p.startsWith(prefix) ? p.slice(prefix.length) : p.replace(bracketRegex, '')\n );\n };\n\n if (DOCUMENT_META_FIELDS.includes(name)) {\n return acc;\n }\n\n if (removedAttributes?.includes(name)) {\n // If the attribute is not visible, we don't want to validate it\n return acc;\n }\n\n const nestedRemoved = getNestedPathsForAttribute(removedAttributes, name);\n\n /**\n * These validations won't apply to every attribute\n * and that's okay, in that case we just return the\n * schema as it was passed.\n */\n const validations = [\n addNullableValidation,\n addRequiredValidation,\n addMinLengthValidation,\n addMaxLengthValidation,\n addMinValidation,\n addMaxValidation,\n addRegexValidation,\n ].map((fn) => fn(attribute, options));\n\n const transformSchema = pipe(...validations);\n\n switch (attribute.type) {\n case 'component': {\n const { attributes } = components[attribute.component];\n\n if (attribute.repeatable) {\n return {\n ...acc,\n [name]: transformSchema(\n yup.array().of(createModelSchema(attributes, nestedRemoved).nullable(false))\n ).test(arrayValidator(attribute, options)),\n };\n } else {\n return {\n ...acc,\n [name]: transformSchema(createModelSchema(attributes, nestedRemoved).nullable()),\n };\n }\n }\n case 'dynamiczone':\n return {\n ...acc,\n [name]: transformSchema(\n yup.array().of(\n yup.lazy(\n (\n data: SchemaUtils.Attribute.Value<SchemaUtils.Attribute.DynamicZone>[number]\n ) => {\n const attributes = components?.[data?.__component]?.attributes;\n\n const validation = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(components)),\n })\n .nullable(false);\n if (!attributes) {\n return validation;\n }\n\n return validation.concat(createModelSchema(attributes, nestedRemoved));\n }\n ) as unknown as yup.ObjectSchema<any>\n )\n ).test(arrayValidator(attribute, options)),\n };\n case 'relation':\n return {\n ...acc,\n [name]: transformSchema(\n yup.lazy((value) => {\n if (!value) {\n return yup.mixed().nullable(true);\n } else if (Array.isArray(value)) {\n // If a relation value is an array, we expect\n // an array of objects with {id} properties, representing the related entities.\n return yup.array().of(\n yup.object().shape({\n id: yup.number().required(),\n })\n );\n } else if (typeof value === 'object') {\n // A realtion value can also be an object. Some API\n // repsonses return the number of entities in the relation\n // as { count: x }\n return yup.object();\n } else {\n return yup\n .mixed()\n .test(\n 'type-error',\n 'Relation values must be either null, an array of objects with {id} or an object.',\n () => false\n );\n }\n })\n ),\n };\n default:\n return {\n ...acc,\n [name]: transformSchema(createAttributeSchema(attribute)),\n };\n }\n }, {})\n )\n /**\n * TODO: investigate why an undefined object fails a check of `nullable`.\n */\n .default(null);\n\n return createModelSchema(attributes, options.removedAttributes);\n};\n\nconst createAttributeSchema = (\n attribute: Exclude<\n SchemaUtils.Attribute.AnyAttribute,\n { type: 'dynamiczone' } | { type: 'component' } | { type: 'relation' }\n >\n) => {\n switch (attribute.type) {\n case 'biginteger':\n return yup.string().matches(/^-?\\d*$/);\n case 'boolean':\n return yup.boolean().nullable();\n case 'blocks':\n return yup.mixed().test('isBlocks', translatedErrors.json, (value) => {\n if (!value || Array.isArray(value)) {\n return true;\n } else {\n return false;\n }\n });\n case 'decimal':\n case 'float':\n case 'integer':\n return yup.number();\n case 'email':\n return yup.string().email(translatedErrors.email);\n case 'enumeration':\n return yup.string().oneOf([...attribute.enum, null]);\n case 'json':\n return yup.mixed().test('isJSON', translatedErrors.json, (value) => {\n /**\n * We don't want to validate the JSON field if it's empty.\n */\n if (!value || (typeof value === 'string' && value.length === 0)) {\n return true;\n }\n\n // If the value was created via content API and wasn't changed, then it's still an object\n if (typeof value === 'object') {\n try {\n JSON.stringify(value);\n return true;\n } catch (err) {\n return false;\n }\n }\n\n try {\n JSON.parse(value);\n\n return true;\n } catch (err) {\n return false;\n }\n });\n case 'password':\n return yup.string().nullable();\n case 'richtext':\n case 'string':\n case 'text':\n return yup.string();\n case 'uid':\n return yup\n .string()\n .matches(attribute.regex ? new RegExp(attribute.regex) : /^[A-Za-z0-9-_.~]*$/);\n default:\n /**\n * This allows any value.\n */\n return yup.mixed();\n }\n};\n\n// Helper function to return schema.nullable() if it exists, otherwise return schema\nconst nullableSchema = <TSchema extends AnySchema>(schema: TSchema) => {\n return schema?.nullable\n ? schema.nullable()\n : // In some cases '.nullable' will not be available on the schema.\n // e.g. when the schema has been built using yup.lazy (e.g. for relations).\n // In these cases we should just return the schema as it is.\n schema;\n};\n\n/* -------------------------------------------------------------------------------------------------\n * Validators\n * -----------------------------------------------------------------------------------------------*/\n/**\n * Our validator functions can be preped with the\n * attribute and then have the schema piped through them.\n */\ntype ValidationFn = (\n attribute: Schema['attributes'][string],\n options: ValidationOptions\n) => <TSchema extends AnySchema>(schema: TSchema) => TSchema;\n\nconst addNullableValidation: ValidationFn = () => (schema) => {\n return nullableSchema(schema);\n};\n\nconst addRequiredValidation: ValidationFn = (attribute, options) => (schema) => {\n if (options.status === 'draft' || !attribute.required || attribute.type === 'password') {\n return schema;\n }\n\n if (attribute.required && 'required' in schema) {\n return schema.required(translatedErrors.required);\n }\n\n return schema;\n};\n\nconst addMinLengthValidation: ValidationFn =\n (attribute, options) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n // Skip minLength validation for draft\n if (options.status === 'draft') {\n return schema;\n }\n\n if (\n 'minLength' in attribute &&\n attribute.minLength &&\n Number.isInteger(attribute.minLength) &&\n 'min' in schema\n ) {\n return schema.min(attribute.minLength, {\n ...translatedErrors.minLength,\n values: {\n min: attribute.minLength,\n },\n }) as TSchema;\n }\n\n return schema;\n };\n\nconst addMaxLengthValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if (\n 'maxLength' in attribute &&\n attribute.maxLength &&\n Number.isInteger(attribute.maxLength) &&\n 'max' in schema\n ) {\n return schema.max(attribute.maxLength, {\n ...translatedErrors.maxLength,\n values: {\n max: attribute.maxLength,\n },\n }) as TSchema;\n }\n\n return schema;\n };\n\nconst addMinValidation: ValidationFn =\n (attribute, options) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if (options.status === 'draft') {\n return schema;\n }\n\n if ('min' in attribute && 'min' in schema) {\n const min = toInteger(attribute.min);\n\n if (min !== undefined) {\n return schema.min(min, {\n ...translatedErrors.min,\n values: {\n min,\n },\n }) as TSchema;\n }\n }\n\n return schema;\n };\n\nconst addMaxValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if ('max' in attribute) {\n const max = toInteger(attribute.max);\n\n if ('max' in schema && max !== undefined) {\n return schema.max(max, {\n ...translatedErrors.max,\n values: {\n max,\n },\n }) as TSchema;\n }\n }\n\n return schema;\n };\n\nconst toInteger = (val?: string | number): number | undefined => {\n if (typeof val === 'number' || val === undefined) {\n return val;\n } else {\n const num = Number(val);\n return isNaN(num) ? undefined : num;\n }\n};\n\nconst addRegexValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if ('regex' in attribute && attribute.regex && 'matches' in schema) {\n return schema.matches(new RegExp(attribute.regex), {\n message: {\n id: translatedErrors.regex.id,\n defaultMessage: 'The value does not match the defined pattern.',\n },\n\n excludeEmptyString: !attribute.required,\n }) as TSchema;\n }\n\n return schema;\n };\n\nexport { createYupSchema };\n"],"names":["arrayValidator","attribute","options","message","translatedErrors","required","test","value","status","Array","isArray","length","escapeRegex","str","replace","createYupSchema","attributes","components","createModelSchema","removedAttributes","yup","object","shape","Object","entries","reduce","acc","name","getNestedPathsForAttribute","removed","attrName","prefix","bracketRegex","RegExp","filter","p","startsWith","map","slice","DOCUMENT_META_FIELDS","includes","nestedRemoved","validations","addNullableValidation","addRequiredValidation","addMinLengthValidation","addMaxLengthValidation","addMinValidation","addMaxValidation","addRegexValidation","fn","transformSchema","pipe","type","component","repeatable","array","of","nullable","lazy","data","__component","validation","string","oneOf","keys","concat","mixed","id","number","createAttributeSchema","default","matches","boolean","json","email","enum","JSON","stringify","err","parse","regex","nullableSchema","schema","minLength","Number","isInteger","min","values","maxLength","max","toInteger","undefined","val","num","isNaN","defaultMessage","excludeEmptyString"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAMA,cAAiB,GAAA,CAACC,SAAyCC,EAAAA,OAAAA,IAAgC;AAC/FC,QAAAA,OAAAA,EAASC,6BAAiBC,QAAQ;AAClCC,QAAAA,IAAAA,CAAAA,CAAKC,KAAc,EAAA;YACjB,IAAIL,OAAAA,CAAQM,MAAM,KAAK,OAAS,EAAA;gBAC9B,OAAO,IAAA;AACT;YAEA,IAAI,CAACP,SAAUI,CAAAA,QAAQ,EAA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ACjC,aAAA,CAAA;AACF;QAEA,OAAO8E,MAAAA;AACT,KAAA;;;;"}
@@ -226,13 +226,12 @@ const addMaxLengthValidation = (attribute)=>(schema)=>{
226
226
  return schema;
227
227
  };
228
228
  const addMinValidation = (attribute, options)=>(schema)=>{
229
- // do not validate min for draft
230
229
  if (options.status === 'draft') {
231
230
  return schema;
232
231
  }
233
232
  if ('min' in attribute && 'min' in schema) {
234
233
  const min = toInteger(attribute.min);
235
- if (min) {
234
+ if (min !== undefined) {
236
235
  return schema.min(min, {
237
236
  ...translatedErrors.min,
238
237
  values: {
@@ -246,7 +245,7 @@ const addMinValidation = (attribute, options)=>(schema)=>{
246
245
  const addMaxValidation = (attribute)=>(schema)=>{
247
246
  if ('max' in attribute) {
248
247
  const max = toInteger(attribute.max);
249
- if ('max' in schema && max) {
248
+ if ('max' in schema && max !== undefined) {
250
249
  return schema.max(max, {
251
250
  ...translatedErrors.max,
252
251
  values: {
@@ -1 +1 @@
1
- {"version":3,"file":"validation.mjs","sources":["../../../admin/src/utils/validation.ts"],"sourcesContent":["import { translatedErrors } from '@strapi/admin/strapi-admin';\nimport pipe from 'lodash/fp/pipe';\nimport * as yup from 'yup';\n\nimport { DOCUMENT_META_FIELDS } from '../constants/attributes';\n\nimport type { ComponentsDictionary, Schema } from '../hooks/useDocument';\nimport type { Schema as SchemaUtils } from '@strapi/types';\nimport type { ObjectShape } from 'yup/lib/object';\n\ntype AnySchema =\n | yup.StringSchema\n | yup.NumberSchema\n | yup.BooleanSchema\n | yup.DateSchema\n | yup.ArraySchema<any>\n | yup.ObjectSchema<any>;\n\n/* -------------------------------------------------------------------------------------------------\n * createYupSchema\n * -----------------------------------------------------------------------------------------------*/\n\ninterface ValidationOptions {\n status: 'draft' | 'published' | null;\n removedAttributes?: string[];\n}\n\nconst arrayValidator = (attribute: Schema['attributes'][string], options: ValidationOptions) => ({\n message: translatedErrors.required,\n test(value: unknown) {\n if (options.status === 'draft') {\n return true;\n }\n\n if (!attribute.required) {\n return true;\n }\n\n if (!value) {\n return false;\n }\n\n if (Array.isArray(value) && value.length === 0) {\n return false;\n }\n\n return true;\n },\n});\nconst escapeRegex = (str: string) => str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n/**\n * TODO: should we create a Map to store these based on the hash of the schema?\n */\nconst createYupSchema = (\n attributes: Schema['attributes'] = {},\n components: ComponentsDictionary = {},\n options: ValidationOptions = { status: null }\n): yup.ObjectSchema<any> => {\n const createModelSchema = (\n attributes: Schema['attributes'],\n removedAttributes: string[] = []\n ): yup.ObjectSchema<any> =>\n yup\n .object()\n .shape(\n Object.entries(attributes).reduce<ObjectShape>((acc, [name, attribute]) => {\n const getNestedPathsForAttribute = (removed: string[], attrName: string): string[] => {\n const prefix = `${attrName}.`;\n // Match both numeric indices [0] and __temp_key__ values [some_key]\n const bracketRegex = new RegExp(`^${escapeRegex(attrName)}\\\\[[^\\\\]]+\\\\]\\\\.`);\n\n return removed\n .filter((p) => p.startsWith(prefix) || bracketRegex.test(p))\n .map((p) =>\n p.startsWith(prefix) ? p.slice(prefix.length) : p.replace(bracketRegex, '')\n );\n };\n\n if (DOCUMENT_META_FIELDS.includes(name)) {\n return acc;\n }\n\n if (removedAttributes?.includes(name)) {\n // If the attribute is not visible, we don't want to validate it\n return acc;\n }\n\n const nestedRemoved = getNestedPathsForAttribute(removedAttributes, name);\n\n /**\n * These validations won't apply to every attribute\n * and that's okay, in that case we just return the\n * schema as it was passed.\n */\n const validations = [\n addNullableValidation,\n addRequiredValidation,\n addMinLengthValidation,\n addMaxLengthValidation,\n addMinValidation,\n addMaxValidation,\n addRegexValidation,\n ].map((fn) => fn(attribute, options));\n\n const transformSchema = pipe(...validations);\n\n switch (attribute.type) {\n case 'component': {\n const { attributes } = components[attribute.component];\n\n if (attribute.repeatable) {\n return {\n ...acc,\n [name]: transformSchema(\n yup.array().of(createModelSchema(attributes, nestedRemoved).nullable(false))\n ).test(arrayValidator(attribute, options)),\n };\n } else {\n return {\n ...acc,\n [name]: transformSchema(createModelSchema(attributes, nestedRemoved).nullable()),\n };\n }\n }\n case 'dynamiczone':\n return {\n ...acc,\n [name]: transformSchema(\n yup.array().of(\n yup.lazy(\n (\n data: SchemaUtils.Attribute.Value<SchemaUtils.Attribute.DynamicZone>[number]\n ) => {\n const attributes = components?.[data?.__component]?.attributes;\n\n const validation = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(components)),\n })\n .nullable(false);\n if (!attributes) {\n return validation;\n }\n\n return validation.concat(createModelSchema(attributes, nestedRemoved));\n }\n ) as unknown as yup.ObjectSchema<any>\n )\n ).test(arrayValidator(attribute, options)),\n };\n case 'relation':\n return {\n ...acc,\n [name]: transformSchema(\n yup.lazy((value) => {\n if (!value) {\n return yup.mixed().nullable(true);\n } else if (Array.isArray(value)) {\n // If a relation value is an array, we expect\n // an array of objects with {id} properties, representing the related entities.\n return yup.array().of(\n yup.object().shape({\n id: yup.number().required(),\n })\n );\n } else if (typeof value === 'object') {\n // A realtion value can also be an object. Some API\n // repsonses return the number of entities in the relation\n // as { count: x }\n return yup.object();\n } else {\n return yup\n .mixed()\n .test(\n 'type-error',\n 'Relation values must be either null, an array of objects with {id} or an object.',\n () => false\n );\n }\n })\n ),\n };\n default:\n return {\n ...acc,\n [name]: transformSchema(createAttributeSchema(attribute)),\n };\n }\n }, {})\n )\n /**\n * TODO: investigate why an undefined object fails a check of `nullable`.\n */\n .default(null);\n\n return createModelSchema(attributes, options.removedAttributes);\n};\n\nconst createAttributeSchema = (\n attribute: Exclude<\n SchemaUtils.Attribute.AnyAttribute,\n { type: 'dynamiczone' } | { type: 'component' } | { type: 'relation' }\n >\n) => {\n switch (attribute.type) {\n case 'biginteger':\n return yup.string().matches(/^-?\\d*$/);\n case 'boolean':\n return yup.boolean().nullable();\n case 'blocks':\n return yup.mixed().test('isBlocks', translatedErrors.json, (value) => {\n if (!value || Array.isArray(value)) {\n return true;\n } else {\n return false;\n }\n });\n case 'decimal':\n case 'float':\n case 'integer':\n return yup.number();\n case 'email':\n return yup.string().email(translatedErrors.email);\n case 'enumeration':\n return yup.string().oneOf([...attribute.enum, null]);\n case 'json':\n return yup.mixed().test('isJSON', translatedErrors.json, (value) => {\n /**\n * We don't want to validate the JSON field if it's empty.\n */\n if (!value || (typeof value === 'string' && value.length === 0)) {\n return true;\n }\n\n // If the value was created via content API and wasn't changed, then it's still an object\n if (typeof value === 'object') {\n try {\n JSON.stringify(value);\n return true;\n } catch (err) {\n return false;\n }\n }\n\n try {\n JSON.parse(value);\n\n return true;\n } catch (err) {\n return false;\n }\n });\n case 'password':\n return yup.string().nullable();\n case 'richtext':\n case 'string':\n case 'text':\n return yup.string();\n case 'uid':\n return yup\n .string()\n .matches(attribute.regex ? new RegExp(attribute.regex) : /^[A-Za-z0-9-_.~]*$/);\n default:\n /**\n * This allows any value.\n */\n return yup.mixed();\n }\n};\n\n// Helper function to return schema.nullable() if it exists, otherwise return schema\nconst nullableSchema = <TSchema extends AnySchema>(schema: TSchema) => {\n return schema?.nullable\n ? schema.nullable()\n : // In some cases '.nullable' will not be available on the schema.\n // e.g. when the schema has been built using yup.lazy (e.g. for relations).\n // In these cases we should just return the schema as it is.\n schema;\n};\n\n/* -------------------------------------------------------------------------------------------------\n * Validators\n * -----------------------------------------------------------------------------------------------*/\n/**\n * Our validator functions can be preped with the\n * attribute and then have the schema piped through them.\n */\ntype ValidationFn = (\n attribute: Schema['attributes'][string],\n options: ValidationOptions\n) => <TSchema extends AnySchema>(schema: TSchema) => TSchema;\n\nconst addNullableValidation: ValidationFn = () => (schema) => {\n return nullableSchema(schema);\n};\n\nconst addRequiredValidation: ValidationFn = (attribute, options) => (schema) => {\n if (options.status === 'draft' || !attribute.required || attribute.type === 'password') {\n return schema;\n }\n\n if (attribute.required && 'required' in schema) {\n return schema.required(translatedErrors.required);\n }\n\n return schema;\n};\n\nconst addMinLengthValidation: ValidationFn =\n (attribute, options) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n // Skip minLength validation for draft\n if (options.status === 'draft') {\n return schema;\n }\n\n if (\n 'minLength' in attribute &&\n attribute.minLength &&\n Number.isInteger(attribute.minLength) &&\n 'min' in schema\n ) {\n return schema.min(attribute.minLength, {\n ...translatedErrors.minLength,\n values: {\n min: attribute.minLength,\n },\n }) as TSchema;\n }\n\n return schema;\n };\n\nconst addMaxLengthValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if (\n 'maxLength' in attribute &&\n attribute.maxLength &&\n Number.isInteger(attribute.maxLength) &&\n 'max' in schema\n ) {\n return schema.max(attribute.maxLength, {\n ...translatedErrors.maxLength,\n values: {\n max: attribute.maxLength,\n },\n }) as TSchema;\n }\n\n return schema;\n };\n\nconst addMinValidation: ValidationFn =\n (attribute, options) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n // do not validate min for draft\n if (options.status === 'draft') {\n return schema;\n }\n\n if ('min' in attribute && 'min' in schema) {\n const min = toInteger(attribute.min);\n\n if (min) {\n return schema.min(min, {\n ...translatedErrors.min,\n values: {\n min,\n },\n }) as TSchema;\n }\n }\n\n return schema;\n };\n\nconst addMaxValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if ('max' in attribute) {\n const max = toInteger(attribute.max);\n\n if ('max' in schema && max) {\n return schema.max(max, {\n ...translatedErrors.max,\n values: {\n max,\n },\n }) as TSchema;\n }\n }\n\n return schema;\n };\n\nconst toInteger = (val?: string | number): number | undefined => {\n if (typeof val === 'number' || val === undefined) {\n return val;\n } else {\n const num = Number(val);\n return isNaN(num) ? undefined : num;\n }\n};\n\nconst addRegexValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if ('regex' in attribute && attribute.regex && 'matches' in schema) {\n return schema.matches(new RegExp(attribute.regex), {\n message: {\n id: translatedErrors.regex.id,\n defaultMessage: 'The value does not match the defined pattern.',\n },\n\n excludeEmptyString: !attribute.required,\n }) as TSchema;\n }\n\n return schema;\n };\n\nexport { createYupSchema };\n"],"names":["arrayValidator","attribute","options","message","translatedErrors","required","test","value","status","Array","isArray","length","escapeRegex","str","replace","createYupSchema","attributes","components","createModelSchema","removedAttributes","yup","object","shape","Object","entries","reduce","acc","name","getNestedPathsForAttribute","removed","attrName","prefix","bracketRegex","RegExp","filter","p","startsWith","map","slice","DOCUMENT_META_FIELDS","includes","nestedRemoved","validations","addNullableValidation","addRequiredValidation","addMinLengthValidation","addMaxLengthValidation","addMinValidation","addMaxValidation","addRegexValidation","fn","transformSchema","pipe","type","component","repeatable","array","of","nullable","lazy","data","__component","validation","string","oneOf","keys","concat","mixed","id","number","createAttributeSchema","default","matches","boolean","json","email","enum","JSON","stringify","err","parse","regex","nullableSchema","schema","minLength","Number","isInteger","min","values","maxLength","max","toInteger","val","undefined","num","isNaN","defaultMessage","excludeEmptyString"],"mappings":";;;;;AA2BA,MAAMA,cAAiB,GAAA,CAACC,SAAyCC,EAAAA,OAAAA,IAAgC;AAC/FC,QAAAA,OAAAA,EAASC,iBAAiBC,QAAQ;AAClCC,QAAAA,IAAAA,CAAAA,CAAKC,KAAc,EAAA;YACjB,IAAIL,OAAAA,CAAQM,MAAM,KAAK,OAAS,EAAA;gBAC9B,OAAO,IAAA;AACT;YAEA,IAAI,CAACP,SAAUI,CAAAA,QAAQ,EAAE;gBACvB,OAAO,IAAA;AACT;AAEA,YAAA,IAAI,CAACE,KAAO,EAAA;gBACV,OAAO,KAAA;AACT;AAEA,YAAA,IAAIE,MAAMC,OAAO,CAACH,UAAUA,KAAMI,CAAAA,MAAM,KAAK,CAAG,EAAA;gBAC9C,OAAO,KAAA;AACT;YAEA,OAAO,IAAA;AACT;KACF,CAAA;AACA,MAAMC,cAAc,CAACC,GAAAA,GAAgBA,GAAIC,CAAAA,OAAO,CAAC,qBAAuB,EAAA,MAAA,CAAA;AACxE;;IAGA,MAAMC,eAAkB,GAAA,CACtBC,UAAmC,GAAA,EAAE,EACrCC,UA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iBAAiBsF,GAAG;oBACvBF,MAAQ,EAAA;AACNE,wBAAAA;AACF;AACF,iBAAA,CAAA;AACF;AACF;QAEA,OAAOP,MAAAA;AACT,KAAA;AAEF,MAAMQ,YAAY,CAACC,GAAAA,GAAAA;AACjB,IAAA,IAAI,OAAOA,GAAAA,KAAQ,QAAYA,IAAAA,GAAAA,KAAQC,SAAW,EAAA;QAChD,OAAOD,GAAAA;KACF,MAAA;AACL,QAAA,MAAME,MAAMT,MAAOO,CAAAA,GAAAA,CAAAA;QACnB,OAAOG,KAAAA,CAAMD,OAAOD,SAAYC,GAAAA,GAAAA;AAClC;AACF,CAAA;AAEA,MAAM7C,kBAAAA,GACJ,CAAChD,SAAAA,GACD,CAA4BkF,MAAAA,GAAAA;AAC1B,QAAA,IAAI,WAAWlF,SAAaA,IAAAA,SAAAA,CAAUgF,KAAK,IAAI,aAAaE,MAAQ,EAAA;AAClE,YAAA,OAAOA,OAAOX,OAAO,CAAC,IAAIvC,MAAOhC,CAAAA,SAAAA,CAAUgF,KAAK,CAAG,EAAA;gBACjD9E,OAAS,EAAA;oBACPiE,EAAIhE,EAAAA,gBAAAA,CAAiB6E,KAAK,CAACb,EAAE;oBAC7B4B,cAAgB,EAAA;AAClB,iBAAA;gBAEAC,kBAAoB,EAAA,CAAChG,UAAUI;AACjC,aAAA,CAAA;AACF;QAEA,OAAO8E,MAAAA;AACT,KAAA;;;;"}
1
+ {"version":3,"file":"validation.mjs","sources":["../../../admin/src/utils/validation.ts"],"sourcesContent":["import { translatedErrors } from '@strapi/admin/strapi-admin';\nimport pipe from 'lodash/fp/pipe';\nimport * as yup from 'yup';\n\nimport { DOCUMENT_META_FIELDS } from '../constants/attributes';\n\nimport type { ComponentsDictionary, Schema } from '../hooks/useDocument';\nimport type { Schema as SchemaUtils } from '@strapi/types';\nimport type { ObjectShape } from 'yup/lib/object';\n\ntype AnySchema =\n | yup.StringSchema\n | yup.NumberSchema\n | yup.BooleanSchema\n | yup.DateSchema\n | yup.ArraySchema<any>\n | yup.ObjectSchema<any>;\n\n/* -------------------------------------------------------------------------------------------------\n * createYupSchema\n * -----------------------------------------------------------------------------------------------*/\n\ninterface ValidationOptions {\n status: 'draft' | 'published' | null;\n removedAttributes?: string[];\n}\n\nconst arrayValidator = (attribute: Schema['attributes'][string], options: ValidationOptions) => ({\n message: translatedErrors.required,\n test(value: unknown) {\n if (options.status === 'draft') {\n return true;\n }\n\n if (!attribute.required) {\n return true;\n }\n\n if (!value) {\n return false;\n }\n\n if (Array.isArray(value) && value.length === 0) {\n return false;\n }\n\n return true;\n },\n});\nconst escapeRegex = (str: string) => str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n/**\n * TODO: should we create a Map to store these based on the hash of the schema?\n */\nconst createYupSchema = (\n attributes: Schema['attributes'] = {},\n components: ComponentsDictionary = {},\n options: ValidationOptions = { status: null }\n): yup.ObjectSchema<any> => {\n const createModelSchema = (\n attributes: Schema['attributes'],\n removedAttributes: string[] = []\n ): yup.ObjectSchema<any> =>\n yup\n .object()\n .shape(\n Object.entries(attributes).reduce<ObjectShape>((acc, [name, attribute]) => {\n const getNestedPathsForAttribute = (removed: string[], attrName: string): string[] => {\n const prefix = `${attrName}.`;\n // Match both numeric indices [0] and __temp_key__ values [some_key]\n const bracketRegex = new RegExp(`^${escapeRegex(attrName)}\\\\[[^\\\\]]+\\\\]\\\\.`);\n\n return removed\n .filter((p) => p.startsWith(prefix) || bracketRegex.test(p))\n .map((p) =>\n p.startsWith(prefix) ? p.slice(prefix.length) : p.replace(bracketRegex, '')\n );\n };\n\n if (DOCUMENT_META_FIELDS.includes(name)) {\n return acc;\n }\n\n if (removedAttributes?.includes(name)) {\n // If the attribute is not visible, we don't want to validate it\n return acc;\n }\n\n const nestedRemoved = getNestedPathsForAttribute(removedAttributes, name);\n\n /**\n * These validations won't apply to every attribute\n * and that's okay, in that case we just return the\n * schema as it was passed.\n */\n const validations = [\n addNullableValidation,\n addRequiredValidation,\n addMinLengthValidation,\n addMaxLengthValidation,\n addMinValidation,\n addMaxValidation,\n addRegexValidation,\n ].map((fn) => fn(attribute, options));\n\n const transformSchema = pipe(...validations);\n\n switch (attribute.type) {\n case 'component': {\n const { attributes } = components[attribute.component];\n\n if (attribute.repeatable) {\n return {\n ...acc,\n [name]: transformSchema(\n yup.array().of(createModelSchema(attributes, nestedRemoved).nullable(false))\n ).test(arrayValidator(attribute, options)),\n };\n } else {\n return {\n ...acc,\n [name]: transformSchema(createModelSchema(attributes, nestedRemoved).nullable()),\n };\n }\n }\n case 'dynamiczone':\n return {\n ...acc,\n [name]: transformSchema(\n yup.array().of(\n yup.lazy(\n (\n data: SchemaUtils.Attribute.Value<SchemaUtils.Attribute.DynamicZone>[number]\n ) => {\n const attributes = components?.[data?.__component]?.attributes;\n\n const validation = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(components)),\n })\n .nullable(false);\n if (!attributes) {\n return validation;\n }\n\n return validation.concat(createModelSchema(attributes, nestedRemoved));\n }\n ) as unknown as yup.ObjectSchema<any>\n )\n ).test(arrayValidator(attribute, options)),\n };\n case 'relation':\n return {\n ...acc,\n [name]: transformSchema(\n yup.lazy((value) => {\n if (!value) {\n return yup.mixed().nullable(true);\n } else if (Array.isArray(value)) {\n // If a relation value is an array, we expect\n // an array of objects with {id} properties, representing the related entities.\n return yup.array().of(\n yup.object().shape({\n id: yup.number().required(),\n })\n );\n } else if (typeof value === 'object') {\n // A realtion value can also be an object. Some API\n // repsonses return the number of entities in the relation\n // as { count: x }\n return yup.object();\n } else {\n return yup\n .mixed()\n .test(\n 'type-error',\n 'Relation values must be either null, an array of objects with {id} or an object.',\n () => false\n );\n }\n })\n ),\n };\n default:\n return {\n ...acc,\n [name]: transformSchema(createAttributeSchema(attribute)),\n };\n }\n }, {})\n )\n /**\n * TODO: investigate why an undefined object fails a check of `nullable`.\n */\n .default(null);\n\n return createModelSchema(attributes, options.removedAttributes);\n};\n\nconst createAttributeSchema = (\n attribute: Exclude<\n SchemaUtils.Attribute.AnyAttribute,\n { type: 'dynamiczone' } | { type: 'component' } | { type: 'relation' }\n >\n) => {\n switch (attribute.type) {\n case 'biginteger':\n return yup.string().matches(/^-?\\d*$/);\n case 'boolean':\n return yup.boolean().nullable();\n case 'blocks':\n return yup.mixed().test('isBlocks', translatedErrors.json, (value) => {\n if (!value || Array.isArray(value)) {\n return true;\n } else {\n return false;\n }\n });\n case 'decimal':\n case 'float':\n case 'integer':\n return yup.number();\n case 'email':\n return yup.string().email(translatedErrors.email);\n case 'enumeration':\n return yup.string().oneOf([...attribute.enum, null]);\n case 'json':\n return yup.mixed().test('isJSON', translatedErrors.json, (value) => {\n /**\n * We don't want to validate the JSON field if it's empty.\n */\n if (!value || (typeof value === 'string' && value.length === 0)) {\n return true;\n }\n\n // If the value was created via content API and wasn't changed, then it's still an object\n if (typeof value === 'object') {\n try {\n JSON.stringify(value);\n return true;\n } catch (err) {\n return false;\n }\n }\n\n try {\n JSON.parse(value);\n\n return true;\n } catch (err) {\n return false;\n }\n });\n case 'password':\n return yup.string().nullable();\n case 'richtext':\n case 'string':\n case 'text':\n return yup.string();\n case 'uid':\n return yup\n .string()\n .matches(attribute.regex ? new RegExp(attribute.regex) : /^[A-Za-z0-9-_.~]*$/);\n default:\n /**\n * This allows any value.\n */\n return yup.mixed();\n }\n};\n\n// Helper function to return schema.nullable() if it exists, otherwise return schema\nconst nullableSchema = <TSchema extends AnySchema>(schema: TSchema) => {\n return schema?.nullable\n ? schema.nullable()\n : // In some cases '.nullable' will not be available on the schema.\n // e.g. when the schema has been built using yup.lazy (e.g. for relations).\n // In these cases we should just return the schema as it is.\n schema;\n};\n\n/* -------------------------------------------------------------------------------------------------\n * Validators\n * -----------------------------------------------------------------------------------------------*/\n/**\n * Our validator functions can be preped with the\n * attribute and then have the schema piped through them.\n */\ntype ValidationFn = (\n attribute: Schema['attributes'][string],\n options: ValidationOptions\n) => <TSchema extends AnySchema>(schema: TSchema) => TSchema;\n\nconst addNullableValidation: ValidationFn = () => (schema) => {\n return nullableSchema(schema);\n};\n\nconst addRequiredValidation: ValidationFn = (attribute, options) => (schema) => {\n if (options.status === 'draft' || !attribute.required || attribute.type === 'password') {\n return schema;\n }\n\n if (attribute.required && 'required' in schema) {\n return schema.required(translatedErrors.required);\n }\n\n return schema;\n};\n\nconst addMinLengthValidation: ValidationFn =\n (attribute, options) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n // Skip minLength validation for draft\n if (options.status === 'draft') {\n return schema;\n }\n\n if (\n 'minLength' in attribute &&\n attribute.minLength &&\n Number.isInteger(attribute.minLength) &&\n 'min' in schema\n ) {\n return schema.min(attribute.minLength, {\n ...translatedErrors.minLength,\n values: {\n min: attribute.minLength,\n },\n }) as TSchema;\n }\n\n return schema;\n };\n\nconst addMaxLengthValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if (\n 'maxLength' in attribute &&\n attribute.maxLength &&\n Number.isInteger(attribute.maxLength) &&\n 'max' in schema\n ) {\n return schema.max(attribute.maxLength, {\n ...translatedErrors.maxLength,\n values: {\n max: attribute.maxLength,\n },\n }) as TSchema;\n }\n\n return schema;\n };\n\nconst addMinValidation: ValidationFn =\n (attribute, options) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if (options.status === 'draft') {\n return schema;\n }\n\n if ('min' in attribute && 'min' in schema) {\n const min = toInteger(attribute.min);\n\n if (min !== undefined) {\n return schema.min(min, {\n ...translatedErrors.min,\n values: {\n min,\n },\n }) as TSchema;\n }\n }\n\n return schema;\n };\n\nconst addMaxValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if ('max' in attribute) {\n const max = toInteger(attribute.max);\n\n if ('max' in schema && max !== undefined) {\n return schema.max(max, {\n ...translatedErrors.max,\n values: {\n max,\n },\n }) as TSchema;\n }\n }\n\n return schema;\n };\n\nconst toInteger = (val?: string | number): number | undefined => {\n if (typeof val === 'number' || val === undefined) {\n return val;\n } else {\n const num = Number(val);\n return isNaN(num) ? undefined : num;\n }\n};\n\nconst addRegexValidation: ValidationFn =\n (attribute) =>\n <TSchema extends AnySchema>(schema: TSchema): TSchema => {\n if ('regex' in attribute && attribute.regex && 'matches' in schema) {\n return schema.matches(new RegExp(attribute.regex), {\n message: {\n id: translatedErrors.regex.id,\n defaultMessage: 'The value does not match the defined pattern.',\n },\n\n excludeEmptyString: !attribute.required,\n }) as TSchema;\n }\n\n return schema;\n };\n\nexport { createYupSchema };\n"],"names":["arrayValidator","attribute","options","message","translatedErrors","required","test","value","status","Array","isArray","length","escapeRegex","str","replace","createYupSchema","attributes","components","createModelSchema","removedAttributes","yup","object","shape","Object","entries","reduce","acc","name","getNestedPathsForAttribute","removed","attrName","prefix","bracketRegex","RegExp","filter","p","startsWith","map","slice","DOCUMENT_META_FIELDS","includes","nestedRemoved","validations","addNullableValidation","addRequiredValidation","addMinLengthValidation","addMaxLengthValidation","addMinValidation","addMaxValidation","addRegexValidation","fn","transformSchema","pipe","type","component","repeatable","array","of","nullable","lazy","data","__component","validation","string","oneOf","keys","concat","mixed","id","number","createAttributeSchema","default","matches","boolean","json","email","enum","JSON","stringify","err","parse","regex","nullableSchema","schema","minLength","Number","isInteger","min","values","maxLength","max","toInteger","undefined","val","num","isNaN","defaultMessage","excludeEmptyString"],"mappings":";;;;;AA2BA,MAAMA,cAAiB,GAAA,CAACC,SAAyCC,EAAAA,OAAAA,IAAgC;AAC/FC,QAAAA,OAAAA,EAASC,iBAAiBC,QAAQ;AAClCC,QAAAA,IAAAA,CAAAA,CAAKC,KAAc,EAAA;YACjB,IAAIL,OAAAA,CAAQM,MAAM,KAAK,OAAS,EAAA;gBAC9B,OAAO,IAAA;AACT;YAEA,IAAI,CAACP,SAAUI,CAAAA,QAAQ,EAAE;gBACvB,OAAO,IAAA;AACT;AAEA,YAAA,IAAI,CAACE,KAAO,EAAA;gBACV,OAAO,KAAA;AACT;AAEA,YAAA,IAAIE,MAAMC,OAA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128
  strapi1.cron.add({
129
129
  deleteHistoryDaily: {
130
130
  async task () {
131
+ const BATCH_SIZE = 1000;
131
132
  const retentionDaysInMilliseconds = serviceUtils.getRetentionDays() * 24 * 60 * 60 * 1000;
132
133
  const expirationDate = new Date(Date.now() - retentionDaysInMilliseconds);
133
- strapi1.db.query(constants.HISTORY_VERSION_UID).deleteMany({
134
- where: {
135
- created_at: {
136
- $lt: expirationDate
137
- }
138
- }
139
- }).catch((error)=>{
140
- if (error instanceof Error) {
141
- strapi1.log.error('Error deleting expired history versions', error.message);
134
+ // Delete in batches of 1000 to avoid a single query that
135
+ // exhausts the DB connection pool and blocks other operations.
136
+ let deleted;
137
+ do {
138
+ // Fetch up to BATCH_SIZE expired IDs
139
+ const expiredVersions = await strapi1.db.query(constants.HISTORY_VERSION_UID).findMany({
140
+ select: [
141
+ 'id'
142
+ ],
143
+ where: {
144
+ created_at: {
145
+ $lt: expirationDate
146
+ }
147
+ },
148
+ limit: BATCH_SIZE
149
+ });
150
+ const ids = expiredVersions.map((v)=>v.id);
151
+ deleted = ids.length;
152
+ // Delete this batch by ID
153
+ if (deleted > 0) {
154
+ await strapi1.db.query(constants.HISTORY_VERSION_UID).deleteMany({
155
+ where: {
156
+ id: {
157
+ $in: ids
158
+ }
159
+ }
160
+ });
142
161
  }
143
- });
162
+ // If we got a full batch, there are likely more rows to delete — loop again.
163
+ // If we got fewer, we've handled everything and can stop.
164
+ }while (deleted >= BATCH_SIZE)
144
165
  },
145
166
  options: '0 0 * * *'
146
167
  }
@@ -1 +1 @@
1
- {"version":3,"file":"lifecycles.js","sources":["../../../../server/src/history/services/lifecycles.ts"],"sourcesContent":["import type { Core, Modules, UID } from '@strapi/types';\nimport { contentTypes } from '@strapi/utils';\n\nimport { omit, castArray } from 'lodash/fp';\n\nimport { getService } from '../utils';\nimport { FIELDS_TO_IGNORE, HISTORY_VERSION_UID } from '../constants';\n\nimport type { CreateHistoryVersion } from '../../../../shared/contracts/history-versions';\nimport { createServiceUtils } from './utils';\n\n/**\n * Filters out actions that should not create a history version.\n */\nconst shouldCreateHistoryVersion = (\n context: Modules.Documents.Middleware.Context\n): context is Modules.Documents.Middleware.Context & {\n action: 'create' | 'update' | 'clone' | 'publish' | 'unpublish' | 'discardDraft';\n contentType: UID.CollectionType;\n} => {\n // Ignore requests that are not related to the content manager\n if (!strapi.requestContext.get()?.request.url.startsWith('/content-manager')) {\n return false;\n }\n\n // NOTE: cannot do type narrowing with array includes\n if (\n context.action !== 'create' &&\n context.action !== 'update' &&\n context.action !== 'clone' &&\n context.action !== 'publish' &&\n context.action !== 'unpublish' &&\n context.action !== 'discardDraft'\n ) {\n return false;\n }\n\n /**\n * When a document is published, the draft version of the document is also updated.\n * It creates confusion for users because they see two history versions each publish action.\n * To avoid this, we silence the update action during a publish request,\n * so that they only see the published version of the document in the history.\n */\n if (\n context.action === 'update' &&\n strapi.requestContext.get()?.request.url.endsWith('/actions/publish')\n ) {\n return false;\n }\n\n // Ignore content types not created by the user\n if (!context.contentType.uid.startsWith('api::')) {\n return false;\n }\n\n return true;\n};\n\n/**\n * Returns the content type schema (and its components schemas).\n * Used to determine if changes were made in the content type builder since a history version was created.\n * And therefore which fields can be restored and which cannot.\n */\nconst getSchemas = (uid: UID.CollectionType) => {\n const attributesSchema = strapi.getModel(uid).attributes;\n\n // TODO: Handle nested components\n const componentsSchemas = Object.keys(attributesSchema).reduce(\n (currentComponentSchemas, key) => {\n const fieldSchema = attributesSchema[key];\n\n if (fieldSchema.type === 'component') {\n const componentSchema = strapi.getModel(fieldSchema.component).attributes;\n return {\n ...currentComponentSchemas,\n [fieldSchema.component]: componentSchema,\n };\n }\n\n // Ignore anything that's not a component\n return currentComponentSchemas;\n },\n {} as CreateHistoryVersion['componentsSchemas']\n );\n\n return {\n schema: omit(FIELDS_TO_IGNORE, attributesSchema) as CreateHistoryVersion['schema'],\n componentsSchemas,\n };\n};\n\nconst createLifecyclesService = ({ strapi }: { strapi: Core.Strapi }) => {\n const state: {\n isInitialized: boolean;\n } = {\n isInitialized: false,\n };\n\n const serviceUtils = createServiceUtils({ strapi });\n const { persistTablesWithPrefix } = strapi.service('admin::persist-tables');\n\n return {\n async bootstrap() {\n // Prevent initializing the service twice\n if (state.isInitialized) {\n return;\n }\n\n // Avoid data loss in case users temporarily don't have a license\n await persistTablesWithPrefix('strapi_history_versions');\n\n strapi.documents.use(async (context, next) => {\n const result = (await next()) as any;\n\n if (!shouldCreateHistoryVersion(context)) {\n return result;\n }\n\n // On create/clone actions, the documentId is not available before creating the action is executed\n const documentId =\n context.action === 'create' || context.action === 'clone'\n ? result.documentId\n : context.params.documentId;\n\n // Apply default locale if not available in the request\n const defaultLocale = await serviceUtils.getDefaultLocale();\n const locales = castArray(context.params?.locale || defaultLocale);\n if (!locales.length) {\n return result;\n }\n\n // All schemas related to the content type\n const uid = context.contentType.uid;\n const schemas = getSchemas(uid);\n const model = strapi.getModel(uid);\n\n const isLocalizedContentType = serviceUtils.isLocalizedContentType(model);\n\n // Find all affected entries\n const localeEntries = await strapi.db.query(uid).findMany({\n where: {\n documentId,\n ...(isLocalizedContentType ? { locale: { $in: locales } } : {}),\n ...(contentTypes.hasDraftAndPublish(strapi.contentTypes[uid])\n ? { publishedAt: null }\n : {}),\n },\n populate: serviceUtils.getDeepPopulate(uid, true /* use database syntax */),\n });\n\n await strapi.db.transaction(async ({ onCommit }) => {\n // .createVersion() is executed asynchronously,\n // onCommit prevents creating a history version\n // when the transaction has already been committed\n onCommit(async () => {\n for (const entry of localeEntries) {\n const status = await serviceUtils.getVersionStatus(uid, entry);\n\n await getService(strapi, 'history').createVersion({\n contentType: uid,\n data: omit(FIELDS_TO_IGNORE, entry) as Modules.Documents.AnyDocument,\n relatedDocumentId: documentId,\n locale: entry.locale,\n status,\n ...schemas,\n });\n }\n });\n });\n\n return result;\n });\n\n // Schedule a job to delete expired history versions every day at midnight\n strapi.cron.add({\n deleteHistoryDaily: {\n async task() {\n const retentionDaysInMilliseconds =\n serviceUtils.getRetentionDays() * 24 * 60 * 60 * 1000;\n const expirationDate = new Date(Date.now() - retentionDaysInMilliseconds);\n\n strapi.db\n .query(HISTORY_VERSION_UID)\n .deleteMany({\n where: {\n created_at: {\n $lt: expirationDate,\n },\n },\n })\n .catch((error) => {\n if (error instanceof Error) {\n strapi.log.error('Error deleting expired history versions', error.message);\n }\n });\n },\n options: '0 0 * * *',\n },\n });\n\n state.isInitialized = true;\n },\n\n async destroy() {\n strapi.cron.remove('deleteHistoryDaily');\n },\n };\n};\n\nexport { createLifecyclesService };\n"],"names":["shouldCreateHistoryVersion","context","strapi","requestContext","get","request","url","startsWith","action","endsWith","contentType","uid","getSchemas","attributesSchema","getModel","attributes","componentsSchemas","Object","keys","reduce","currentComponentSchemas","key","fieldSchema","type","componentSchema","component","schema","omit","FIELDS_TO_IGNORE","createLifecyclesService","state","isInitialized","serviceUtils","createServiceUtils","persistTablesWithPrefix","service","bootstrap","documents","use","next","result","documentId","params","defaultLocale","getDefaultLocale","locales","castArray","locale","length","schemas","model","isLocalizedContentType","localeEntries","db","query","findMany","where","$in","contentTypes","hasDraftAndPublish","publishedAt","populate","getDeepPopulate","transaction","onCommit","entry","status","getVersionStatus","getService","createVersion","data","relatedDocumentId","cron","add","deleteHistoryDaily","task","retentionDaysInMilliseconds","getRetentionDays","expirationDate","Date","now","HISTORY_VERSION_UID","deleteMany","created_at","$lt","catch","error","Error","log","message","options","destroy","remove"],"mappings":";;;;;;;;AAWA;;IAGA,MAAMA,6BAA6B,CACjCC,OAAAA,GAAAA;;IAMA,IAAI,CAACC,OAAOC,cAAc,CAACC,GAAG,EAAIC,EAAAA,OAAAA,CAAQC,GAAIC,CAAAA,UAAAA,CAAW,kBAAqB,CAAA,EAAA;QAC5E,OAAO,KAAA;AACT;;IAGA,IACEN,OAAAA,CAAQO,MAAM,KAAK,QAAA,IACnBP,QAAQO,MAAM,KAAK,QACnBP,IAAAA,OAAAA,CAAQO,MAAM,KAAK,WACnBP,OAAQO,CAAAA,MAAM,KAAK,S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AGAtC,OAAOsE,CAAAA,IAAI,CAACC,GAAG,CAAC;gBACdC,kBAAoB,EAAA;oBAClB,MAAMC,IAAAA,CAAAA,GAAAA;AACJ,wBAAA,MAAMC,8BACJ5C,YAAa6C,CAAAA,gBAAgB,EAAK,GAAA,EAAA,GAAK,KAAK,EAAK,GAAA,IAAA;AACnD,wBAAA,MAAMC,cAAiB,GAAA,IAAIC,IAAKA,CAAAA,IAAAA,CAAKC,GAAG,EAAKJ,GAAAA,2BAAAA,CAAAA;AAE7C1E,wBAAAA,OAAAA,CAAOmD,EAAE,CACNC,KAAK,CAAC2B,6BAAAA,CAAAA,CACNC,UAAU,CAAC;4BACV1B,KAAO,EAAA;gCACL2B,UAAY,EAAA;oCACVC,GAAKN,EAAAA;AACP;AACF;yBAEDO,CAAAA,CAAAA,KAAK,CAAC,CAACC,KAAAA,GAAAA;AACN,4BAAA,IAAIA,iBAAiBC,KAAO,EAAA;AAC1BrF,gCAAAA,OAAAA,CAAOsF,GAAG,CAACF,KAAK,CAAC,yCAAA,EAA2CA,MAAMG,OAAO,CAAA;AAC3E;AACF,yBAAA,CAAA;AACJ,qBAAA;oBACAC,OAAS,EAAA;AACX;AACF,aAAA,CAAA;AAEA5D,YAAAA,KAAAA,CAAMC,aAAa,GAAG,IAAA;AACxB,SAAA;QAEA,MAAM4D,OAAAA,CAAAA,GAAAA;YACJzF,OAAOsE,CAAAA,IAAI,CAACoB,MAAM,CAAC,oBAAA,CAAA;AACrB;AACF,KAAA;AACF;;;;"}
1
+ {"version":3,"file":"lifecycles.js","sources":["../../../../server/src/history/services/lifecycles.ts"],"sourcesContent":["import type { Core, Modules, UID } from '@strapi/types';\nimport { contentTypes } from '@strapi/utils';\n\nimport { omit, castArray } from 'lodash/fp';\n\nimport { getService } from '../utils';\nimport { FIELDS_TO_IGNORE, HISTORY_VERSION_UID } from '../constants';\n\nimport type { CreateHistoryVersion } from '../../../../shared/contracts/history-versions';\nimport { createServiceUtils } from './utils';\n\n/**\n * Filters out actions that should not create a history version.\n */\nconst shouldCreateHistoryVersion = (\n context: Modules.Documents.Middleware.Context\n): context is Modules.Documents.Middleware.Context & {\n action: 'create' | 'update' | 'clone' | 'publish' | 'unpublish' | 'discardDraft';\n contentType: UID.CollectionType;\n} => {\n // Ignore requests that are not related to the content manager\n if (!strapi.requestContext.get()?.request.url.startsWith('/content-manager')) {\n return false;\n }\n\n // NOTE: cannot do type narrowing with array includes\n if (\n context.action !== 'create' &&\n context.action !== 'update' &&\n context.action !== 'clone' &&\n context.action !== 'publish' &&\n context.action !== 'unpublish' &&\n context.action !== 'discardDraft'\n ) {\n return false;\n }\n\n /**\n * When a document is published, the draft version of the document is also updated.\n * It creates confusion for users because they see two history versions each publish action.\n * To avoid this, we silence the update action during a publish request,\n * so that they only see the published version of the document in the history.\n */\n if (\n context.action === 'update' &&\n strapi.requestContext.get()?.request.url.endsWith('/actions/publish')\n ) {\n return false;\n }\n\n // Ignore content types not created by the user\n if (!context.contentType.uid.startsWith('api::')) {\n return false;\n }\n\n return true;\n};\n\n/**\n * Returns the content type schema (and its components schemas).\n * Used to determine if changes were made in the content type builder since a history version was created.\n * And therefore which fields can be restored and which cannot.\n */\nconst getSchemas = (uid: UID.CollectionType) => {\n const attributesSchema = strapi.getModel(uid).attributes;\n\n // TODO: Handle nested components\n const componentsSchemas = Object.keys(attributesSchema).reduce(\n (currentComponentSchemas, key) => {\n const fieldSchema = attributesSchema[key];\n\n if (fieldSchema.type === 'component') {\n const componentSchema = strapi.getModel(fieldSchema.component).attributes;\n return {\n ...currentComponentSchemas,\n [fieldSchema.component]: componentSchema,\n };\n }\n\n // Ignore anything that's not a component\n return currentComponentSchemas;\n },\n {} as CreateHistoryVersion['componentsSchemas']\n );\n\n return {\n schema: omit(FIELDS_TO_IGNORE, attributesSchema) as CreateHistoryVersion['schema'],\n componentsSchemas,\n };\n};\n\nconst createLifecyclesService = ({ strapi }: { strapi: Core.Strapi }) => {\n const state: {\n isInitialized: boolean;\n } = {\n isInitialized: false,\n };\n\n const serviceUtils = createServiceUtils({ strapi });\n const { persistTablesWithPrefix } = strapi.service('admin::persist-tables');\n\n return {\n async bootstrap() {\n // Prevent initializing the service twice\n if (state.isInitialized) {\n return;\n }\n\n // Avoid data loss in case users temporarily don't have a license\n await persistTablesWithPrefix('strapi_history_versions');\n\n strapi.documents.use(async (context, next) => {\n const result = (await next()) as any;\n\n if (!shouldCreateHistoryVersion(context)) {\n return result;\n }\n\n // On create/clone actions, the documentId is not available before creating the action is executed\n const documentId =\n context.action === 'create' || context.action === 'clone'\n ? result.documentId\n : context.params.documentId;\n\n // Apply default locale if not available in the request\n const defaultLocale = await serviceUtils.getDefaultLocale();\n const locales = castArray(context.params?.locale || defaultLocale);\n if (!locales.length) {\n return result;\n }\n\n // All schemas related to the content type\n const uid = context.contentType.uid;\n const schemas = getSchemas(uid);\n const model = strapi.getModel(uid);\n\n const isLocalizedContentType = serviceUtils.isLocalizedContentType(model);\n\n // Find all affected entries\n const localeEntries = await strapi.db.query(uid).findMany({\n where: {\n documentId,\n ...(isLocalizedContentType ? { locale: { $in: locales } } : {}),\n ...(contentTypes.hasDraftAndPublish(strapi.contentTypes[uid])\n ? { publishedAt: null }\n : {}),\n },\n populate: serviceUtils.getDeepPopulate(uid, true /* use database syntax */),\n });\n\n await strapi.db.transaction(async ({ onCommit }) => {\n // .createVersion() is executed asynchronously,\n // onCommit prevents creating a history version\n // when the transaction has already been committed\n onCommit(async () => {\n for (const entry of localeEntries) {\n const status = await serviceUtils.getVersionStatus(uid, entry);\n\n await getService(strapi, 'history').createVersion({\n contentType: uid,\n data: omit(FIELDS_TO_IGNORE, entry) as Modules.Documents.AnyDocument,\n relatedDocumentId: documentId,\n locale: entry.locale,\n status,\n ...schemas,\n });\n }\n });\n });\n\n return result;\n });\n\n // Schedule a job to delete expired history versions every day at midnight\n strapi.cron.add({\n deleteHistoryDaily: {\n async task() {\n const BATCH_SIZE = 1000;\n\n const retentionDaysInMilliseconds =\n serviceUtils.getRetentionDays() * 24 * 60 * 60 * 1000;\n const expirationDate = new Date(Date.now() - retentionDaysInMilliseconds);\n\n // Delete in batches of 1000 to avoid a single query that\n // exhausts the DB connection pool and blocks other operations.\n let deleted: number;\n do {\n // Fetch up to BATCH_SIZE expired IDs\n const expiredVersions = await strapi.db.query(HISTORY_VERSION_UID).findMany({\n select: ['id'],\n where: {\n created_at: {\n $lt: expirationDate,\n },\n },\n limit: BATCH_SIZE,\n });\n\n const ids = expiredVersions.map((v: { id: number | string }) => v.id);\n deleted = ids.length;\n\n // Delete this batch by ID\n if (deleted > 0) {\n await strapi.db.query(HISTORY_VERSION_UID).deleteMany({\n where: {\n id: { $in: ids },\n },\n });\n }\n\n // If we got a full batch, there are likely more rows to delete — loop again.\n // If we got fewer, we've handled everything and can stop.\n } while (deleted >= BATCH_SIZE);\n },\n options: '0 0 * * *',\n },\n });\n\n state.isInitialized = true;\n },\n\n async destroy() {\n strapi.cron.remove('deleteHistoryDaily');\n },\n };\n};\n\nexport { createLifecyclesService };\n"],"names":["shouldCreateHistoryVersion","context","strapi","requestContext","get","request","url","startsWith","action","endsWith","contentType","uid","getSchemas","attributesSchema","getModel","attributes","componentsSchemas","Object","keys","reduce","currentComponentSchemas","key","fieldSchema","type","componentSchema","component","schema","omit","FIELDS_TO_IGNORE","createLifecyclesService","state","isInitialized","serviceUtils","createServiceUtils","persistTablesWithPrefix","service","bootstrap","documents","use","next","result","documentId","params","defaultLocale","getDefaultLocale","locales","castArray","locale","length","schemas","model","isLocalizedContentType","localeEntries","db","query","findMany","where","$in","contentTypes","hasDraftAndPublish","publishedAt","populate","getDeepPopulate","transaction","onCommit","entry","status","getVersionStatus","getService","createVersion","data","relatedDocumentId","cron","add","deleteHistoryDaily","task","BATCH_SIZE","retentionDaysInMilliseconds","getRetentionDays","expirationDate","Date","now","deleted","expiredVersions","HISTORY_VERSION_UID","select","created_at","$lt","limit","ids","map","v","id","deleteMany","options","destroy","remove"],"mappings":";;;;;;;;AAWA;;IAGA,MAAM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AAK,CAAC8B,6BAAAA,CAAAA,CAAqBS,UAAU,CAAC;oCACpDrC,KAAO,EAAA;wCACLoC,EAAI,EAAA;4CAAEnC,GAAKgC,EAAAA;AAAI;AACjB;AACF,iCAAA,CAAA;AACF;;;AAIF,yBAAA,OAASP,WAAWN,UAAY;AAClC,qBAAA;oBACAkB,OAAS,EAAA;AACX;AACF,aAAA,CAAA;AAEAhE,YAAAA,KAAAA,CAAMC,aAAa,GAAG,IAAA;AACxB,SAAA;QAEA,MAAMgE,OAAAA,CAAAA,GAAAA;YACJ7F,OAAOsE,CAAAA,IAAI,CAACwB,MAAM,CAAC,oBAAA,CAAA;AACrB;AACF,KAAA;AACF;;;;"}
@@ -126,19 +126,40 @@ const createLifecyclesService = ({ strapi: strapi1 })=>{
126
126
  strapi1.cron.add({
127
127
  deleteHistoryDaily: {
128
128
  async task () {
129
+ const BATCH_SIZE = 1000;
129
130
  const retentionDaysInMilliseconds = serviceUtils.getRetentionDays() * 24 * 60 * 60 * 1000;
130
131
  const expirationDate = new Date(Date.now() - retentionDaysInMilliseconds);
131
- strapi1.db.query(HISTORY_VERSION_UID).deleteMany({
132
- where: {
133
- created_at: {
134
- $lt: expirationDate
135
- }
136
- }
137
- }).catch((error)=>{
138
- if (error instanceof Error) {
139
- strapi1.log.error('Error deleting expired history versions', error.message);
132
+ // Delete in batches of 1000 to avoid a single query that
133
+ // exhausts the DB connection pool and blocks other operations.
134
+ let deleted;
135
+ do {
136
+ // Fetch up to BATCH_SIZE expired IDs
137
+ const expiredVersions = await strapi1.db.query(HISTORY_VERSION_UID).findMany({
138
+ select: [
139
+ 'id'
140
+ ],
141
+ where: {
142
+ created_at: {
143
+ $lt: expirationDate
144
+ }
145
+ },
146
+ limit: BATCH_SIZE
147
+ });
148
+ const ids = expiredVersions.map((v)=>v.id);
149
+ deleted = ids.length;
150
+ // Delete this batch by ID
151
+ if (deleted > 0) {
152
+ await strapi1.db.query(HISTORY_VERSION_UID).deleteMany({
153
+ where: {
154
+ id: {
155
+ $in: ids
156
+ }
157
+ }
158
+ });
140
159
  }
141
- });
160
+ // If we got a full batch, there are likely more rows to delete — loop again.
161
+ // If we got fewer, we've handled everything and can stop.
162
+ }while (deleted >= BATCH_SIZE)
142
163
  },
143
164
  options: '0 0 * * *'
144
165
  }
@@ -1 +1 @@
1
- {"version":3,"file":"lifecycles.mjs","sources":["../../../../server/src/history/services/lifecycles.ts"],"sourcesContent":["import type { Core, Modules, UID } from '@strapi/types';\nimport { contentTypes } from '@strapi/utils';\n\nimport { omit, castArray } from 'lodash/fp';\n\nimport { getService } from '../utils';\nimport { FIELDS_TO_IGNORE, HISTORY_VERSION_UID } from '../constants';\n\nimport type { CreateHistoryVersion } from '../../../../shared/contracts/history-versions';\nimport { createServiceUtils } from './utils';\n\n/**\n * Filters out actions that should not create a history version.\n */\nconst shouldCreateHistoryVersion = (\n context: Modules.Documents.Middleware.Context\n): context is Modules.Documents.Middleware.Context & {\n action: 'create' | 'update' | 'clone' | 'publish' | 'unpublish' | 'discardDraft';\n contentType: UID.CollectionType;\n} => {\n // Ignore requests that are not related to the content manager\n if (!strapi.requestContext.get()?.request.url.startsWith('/content-manager')) {\n return false;\n }\n\n // NOTE: cannot do type narrowing with array includes\n if (\n context.action !== 'create' &&\n context.action !== 'update' &&\n context.action !== 'clone' &&\n context.action !== 'publish' &&\n context.action !== 'unpublish' &&\n context.action !== 'discardDraft'\n ) {\n return false;\n }\n\n /**\n * When a document is published, the draft version of the document is also updated.\n * It creates confusion for users because they see two history versions each publish action.\n * To avoid this, we silence the update action during a publish request,\n * so that they only see the published version of the document in the history.\n */\n if (\n context.action === 'update' &&\n strapi.requestContext.get()?.request.url.endsWith('/actions/publish')\n ) {\n return false;\n }\n\n // Ignore content types not created by the user\n if (!context.contentType.uid.startsWith('api::')) {\n return false;\n }\n\n return true;\n};\n\n/**\n * Returns the content type schema (and its components schemas).\n * Used to determine if changes were made in the content type builder since a history version was created.\n * And therefore which fields can be restored and which cannot.\n */\nconst getSchemas = (uid: UID.CollectionType) => {\n const attributesSchema = strapi.getModel(uid).attributes;\n\n // TODO: Handle nested components\n const componentsSchemas = Object.keys(attributesSchema).reduce(\n (currentComponentSchemas, key) => {\n const fieldSchema = attributesSchema[key];\n\n if (fieldSchema.type === 'component') {\n const componentSchema = strapi.getModel(fieldSchema.component).attributes;\n return {\n ...currentComponentSchemas,\n [fieldSchema.component]: componentSchema,\n };\n }\n\n // Ignore anything that's not a component\n return currentComponentSchemas;\n },\n {} as CreateHistoryVersion['componentsSchemas']\n );\n\n return {\n schema: omit(FIELDS_TO_IGNORE, attributesSchema) as CreateHistoryVersion['schema'],\n componentsSchemas,\n };\n};\n\nconst createLifecyclesService = ({ strapi }: { strapi: Core.Strapi }) => {\n const state: {\n isInitialized: boolean;\n } = {\n isInitialized: false,\n };\n\n const serviceUtils = createServiceUtils({ strapi });\n const { persistTablesWithPrefix } = strapi.service('admin::persist-tables');\n\n return {\n async bootstrap() {\n // Prevent initializing the service twice\n if (state.isInitialized) {\n return;\n }\n\n // Avoid data loss in case users temporarily don't have a license\n await persistTablesWithPrefix('strapi_history_versions');\n\n strapi.documents.use(async (context, next) => {\n const result = (await next()) as any;\n\n if (!shouldCreateHistoryVersion(context)) {\n return result;\n }\n\n // On create/clone actions, the documentId is not available before creating the action is executed\n const documentId =\n context.action === 'create' || context.action === 'clone'\n ? result.documentId\n : context.params.documentId;\n\n // Apply default locale if not available in the request\n const defaultLocale = await serviceUtils.getDefaultLocale();\n const locales = castArray(context.params?.locale || defaultLocale);\n if (!locales.length) {\n return result;\n }\n\n // All schemas related to the content type\n const uid = context.contentType.uid;\n const schemas = getSchemas(uid);\n const model = strapi.getModel(uid);\n\n const isLocalizedContentType = serviceUtils.isLocalizedContentType(model);\n\n // Find all affected entries\n const localeEntries = await strapi.db.query(uid).findMany({\n where: {\n documentId,\n ...(isLocalizedContentType ? { locale: { $in: locales } } : {}),\n ...(contentTypes.hasDraftAndPublish(strapi.contentTypes[uid])\n ? { publishedAt: null }\n : {}),\n },\n populate: serviceUtils.getDeepPopulate(uid, true /* use database syntax */),\n });\n\n await strapi.db.transaction(async ({ onCommit }) => {\n // .createVersion() is executed asynchronously,\n // onCommit prevents creating a history version\n // when the transaction has already been committed\n onCommit(async () => {\n for (const entry of localeEntries) {\n const status = await serviceUtils.getVersionStatus(uid, entry);\n\n await getService(strapi, 'history').createVersion({\n contentType: uid,\n data: omit(FIELDS_TO_IGNORE, entry) as Modules.Documents.AnyDocument,\n relatedDocumentId: documentId,\n locale: entry.locale,\n status,\n ...schemas,\n });\n }\n });\n });\n\n return result;\n });\n\n // Schedule a job to delete expired history versions every day at midnight\n strapi.cron.add({\n deleteHistoryDaily: {\n async task() {\n const retentionDaysInMilliseconds =\n serviceUtils.getRetentionDays() * 24 * 60 * 60 * 1000;\n const expirationDate = new Date(Date.now() - retentionDaysInMilliseconds);\n\n strapi.db\n .query(HISTORY_VERSION_UID)\n .deleteMany({\n where: {\n created_at: {\n $lt: expirationDate,\n },\n },\n })\n .catch((error) => {\n if (error instanceof Error) {\n strapi.log.error('Error deleting expired history versions', error.message);\n }\n });\n },\n options: '0 0 * * *',\n },\n });\n\n state.isInitialized = true;\n },\n\n async destroy() {\n strapi.cron.remove('deleteHistoryDaily');\n },\n };\n};\n\nexport { createLifecyclesService };\n"],"names":["shouldCreateHistoryVersion","context","strapi","requestContext","get","request","url","startsWith","action","endsWith","contentType","uid","getSchemas","attributesSchema","getModel","attributes","componentsSchemas","Object","keys","reduce","currentComponentSchemas","key","fieldSchema","type","componentSchema","component","schema","omit","FIELDS_TO_IGNORE","createLifecyclesService","state","isInitialized","serviceUtils","createServiceUtils","persistTablesWithPrefix","service","bootstrap","documents","use","next","result","documentId","params","defaultLocale","getDefaultLocale","locales","castArray","locale","length","schemas","model","isLocalizedContentType","localeEntries","db","query","findMany","where","$in","contentTypes","hasDraftAndPublish","publishedAt","populate","getDeepPopulate","transaction","onCommit","entry","status","getVersionStatus","getService","createVersion","data","relatedDocumentId","cron","add","deleteHistoryDaily","task","retentionDaysInMilliseconds","getRetentionDays","expirationDate","Date","now","HISTORY_VERSION_UID","deleteMany","created_at","$lt","catch","error","Error","log","message","options","destroy","remove"],"mappings":";;;;;;AAWA;;IAGA,MAAMA,6BAA6B,CACjCC,OAAAA,GAAAA;;IAMA,IAAI,CAACC,OAAOC,cAAc,CAACC,GAAG,EAAIC,EAAAA,OAAAA,CAAQC,GAAIC,CAAAA,UAAAA,CAAW,kBAAqB,CAAA,EAAA;QAC5E,OAAO,KAAA;AACT;;IAGA,IACEN,OAAAA,CAAQO,MAAM,KAAK,QAAA,IACnBP,QAAQO,MAAM,KAAK,QACnBP,IAAAA,OAAAA,CAAQO,MAAM,KAAK,WACnBP,OAAQO,CAAAA,MAAM,KAAK,SAAA,IACnBP,OAAQO,CAAAA,MAAM,KAAK,WACnBP,IAAAA,OAAAA,CAAQO,MAAM,KAAK,cACnB,EAAA;QACA,OAAO,KAAA;AACT;AAEA;;;;;AAKC,MACD,IACEP,OAAAA,CAAQO,MAAM,KAAK,QACnBN,IAAAA,MAAAA,CAAOC,cAAc,CAACC,GAAG,EAAA,EAAIC,OAAQC,CAAAA,GAAAA,CAAIG,SAAS,kBAClD,CAAA,EAAA;QACA,OAAO,KAAA;AACT;;IAGA,IAAI,CAACR,QAAQS,WAAW,CAACC,GAAG,CAACJ,UAAU,CAAC,OAAU,CAAA,EAAA;QAChD,OAAO,KAAA;AACT;IAEA,OAAO,IAAA;AACT,CAAA;AAEA;;;;IAKA,MAAMK,aAAa,CAACD,GAAAA,GAAAA;AAClB,IAAA,MAAME,gBAAmBX,GAAAA,MAAAA,CAAOY,QAAQ,CAACH,KAAKI,UAAU;;IAGxD,MAAMC,iBAAAA,GAAoBC,OAAOC,IAAI,CAACL,kBAAkBM,MAAM,CAC5D,CAACC,uBAAyBC,EAAAA,GAAAA,GAAAA;QACxB,MAAMC,WAAAA,GAAcT,gBAAgB,CAACQ,GAAI,CAAA;QAEzC,IAAIC,WAAAA,CAAYC,I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A,KAAAA,CAAMC,aAAa,GAAG,IAAA;AACxB,SAAA;QAEA,MAAM4D,OAAAA,CAAAA,GAAAA;YACJzF,OAAOsE,CAAAA,IAAI,CAACoB,MAAM,CAAC,oBAAA,CAAA;AACrB;AACF,KAAA;AACF;;;;"}
1
+ {"version":3,"file":"lifecycles.mjs","sources":["../../../../server/src/history/services/lifecycles.ts"],"sourcesContent":["import type { Core, Modules, UID } from '@strapi/types';\nimport { contentTypes } from '@strapi/utils';\n\nimport { omit, castArray } from 'lodash/fp';\n\nimport { getService } from '../utils';\nimport { FIELDS_TO_IGNORE, HISTORY_VERSION_UID } from '../constants';\n\nimport type { CreateHistoryVersion } from '../../../../shared/contracts/history-versions';\nimport { createServiceUtils } from './utils';\n\n/**\n * Filters out actions that should not create a history version.\n */\nconst shouldCreateHistoryVersion = (\n context: Modules.Documents.Middleware.Context\n): context is Modules.Documents.Middleware.Context & {\n action: 'create' | 'update' | 'clone' | 'publish' | 'unpublish' | 'discardDraft';\n contentType: UID.CollectionType;\n} => {\n // Ignore requests that are not related to the content manager\n if (!strapi.requestContext.get()?.request.url.startsWith('/content-manager')) {\n return false;\n }\n\n // NOTE: cannot do type narrowing with array includes\n if (\n context.action !== 'create' &&\n context.action !== 'update' &&\n context.action !== 'clone' &&\n context.action !== 'publish' &&\n context.action !== 'unpublish' &&\n context.action !== 'discardDraft'\n ) {\n return false;\n }\n\n /**\n * When a document is published, the draft version of the document is also updated.\n * It creates confusion for users because they see two history versions each publish action.\n * To avoid this, we silence the update action during a publish request,\n * so that they only see the published version of the document in the history.\n */\n if (\n context.action === 'update' &&\n strapi.requestContext.get()?.request.url.endsWith('/actions/publish')\n ) {\n return false;\n }\n\n // Ignore content types not created by the user\n if (!context.contentType.uid.startsWith('api::')) {\n return false;\n }\n\n return true;\n};\n\n/**\n * Returns the content type schema (and its components schemas).\n * Used to determine if changes were made in the content type builder since a history version was created.\n * And therefore which fields can be restored and which cannot.\n */\nconst getSchemas = (uid: UID.CollectionType) => {\n const attributesSchema = strapi.getModel(uid).attributes;\n\n // TODO: Handle nested components\n const componentsSchemas = Object.keys(attributesSchema).reduce(\n (currentComponentSchemas, key) => {\n const fieldSchema = attributesSchema[key];\n\n if (fieldSchema.type === 'component') {\n const componentSchema = strapi.getModel(fieldSchema.component).attributes;\n return {\n ...currentComponentSchemas,\n [fieldSchema.component]: componentSchema,\n };\n }\n\n // Ignore anything that's not a component\n return currentComponentSchemas;\n },\n {} as CreateHistoryVersion['componentsSchemas']\n );\n\n return {\n schema: omit(FIELDS_TO_IGNORE, attributesSchema) as CreateHistoryVersion['schema'],\n componentsSchemas,\n };\n};\n\nconst createLifecyclesService = ({ strapi }: { strapi: Core.Strapi }) => {\n const state: {\n isInitialized: boolean;\n } = {\n isInitialized: false,\n };\n\n const serviceUtils = createServiceUtils({ strapi });\n const { persistTablesWithPrefix } = strapi.service('admin::persist-tables');\n\n return {\n async bootstrap() {\n // Prevent initializing the service twice\n if (state.isInitialized) {\n return;\n }\n\n // Avoid data loss in case users temporarily don't have a license\n await persistTablesWithPrefix('strapi_history_versions');\n\n strapi.documents.use(async (context, next) => {\n const result = (await next()) as any;\n\n if (!shouldCreateHistoryVersion(context)) {\n return result;\n }\n\n // On create/clone actions, the documentId is not available before creating the action is executed\n const documentId =\n context.action === 'create' || context.action === 'clone'\n ? result.documentId\n : context.params.documentId;\n\n // Apply default locale if not available in the request\n const defaultLocale = await serviceUtils.getDefaultLocale();\n const locales = castArray(context.params?.locale || defaultLocale);\n if (!locales.length) {\n return result;\n }\n\n // All schemas related to the content type\n const uid = context.contentType.uid;\n const schemas = getSchemas(uid);\n const model = strapi.getModel(uid);\n\n const isLocalizedContentType = serviceUtils.isLocalizedContentType(model);\n\n // Find all affected entries\n const localeEntries = await strapi.db.query(uid).findMany({\n where: {\n documentId,\n ...(isLocalizedContentType ? { locale: { $in: locales } } : {}),\n ...(contentTypes.hasDraftAndPublish(strapi.contentTypes[uid])\n ? { publishedAt: null }\n : {}),\n },\n populate: serviceUtils.getDeepPopulate(uid, true /* use database syntax */),\n });\n\n await strapi.db.transaction(async ({ onCommit }) => {\n // .createVersion() is executed asynchronously,\n // onCommit prevents creating a history version\n // when the transaction has already been committed\n onCommit(async () => {\n for (const entry of localeEntries) {\n const status = await serviceUtils.getVersionStatus(uid, entry);\n\n await getService(strapi, 'history').createVersion({\n contentType: uid,\n data: omit(FIELDS_TO_IGNORE, entry) as Modules.Documents.AnyDocument,\n relatedDocumentId: documentId,\n locale: entry.locale,\n status,\n ...schemas,\n });\n }\n });\n });\n\n return result;\n });\n\n // Schedule a job to delete expired history versions every day at midnight\n strapi.cron.add({\n deleteHistoryDaily: {\n async task() {\n const BATCH_SIZE = 1000;\n\n const retentionDaysInMilliseconds =\n serviceUtils.getRetentionDays() * 24 * 60 * 60 * 1000;\n const expirationDate = new Date(Date.now() - retentionDaysInMilliseconds);\n\n // Delete in batches of 1000 to avoid a single query that\n // exhausts the DB connection pool and blocks other operations.\n let deleted: number;\n do {\n // Fetch up to BATCH_SIZE expired IDs\n const expiredVersions = await strapi.db.query(HISTORY_VERSION_UID).findMany({\n select: ['id'],\n where: {\n created_at: {\n $lt: expirationDate,\n },\n },\n limit: BATCH_SIZE,\n });\n\n const ids = expiredVersions.map((v: { id: number | string }) => v.id);\n deleted = ids.length;\n\n // Delete this batch by ID\n if (deleted > 0) {\n await strapi.db.query(HISTORY_VERSION_UID).deleteMany({\n where: {\n id: { $in: ids },\n },\n });\n }\n\n // If we got a full batch, there are likely more rows to delete — loop again.\n // If we got fewer, we've handled everything and can stop.\n } while (deleted >= BATCH_SIZE);\n },\n options: '0 0 * * *',\n },\n });\n\n state.isInitialized = true;\n },\n\n async destroy() {\n strapi.cron.remove('deleteHistoryDaily');\n },\n };\n};\n\nexport { createLifecyclesService };\n"],"names":["shouldCreateHistoryVersion","context","strapi","requestContext","get","request","url","startsWith","action","endsWith","contentType","uid","getSchemas","attributesSchema","getModel","attributes","componentsSchemas","Object","keys","reduce","currentComponentSchemas","key","fieldSchema","type","componentSchema","component","schema","omit","FIELDS_TO_IGNORE","createLifecyclesService","state","isInitialized","serviceUtils","createServiceUtils","persistTablesWithPrefix","service","bootstrap","documents","use","next","result","documentId","params","defaultLocale","getDefaultLocale","locales","castArray","locale","length","schemas","model","isLocalizedContentType","localeEntries","db","query","findMany","where","$in","contentTypes","hasDraftAndPublish","publishedAt","populate","getDeepPopulate","transaction","onCommit","entry","status","getVersionStatus","getService","createVersion","data","relatedDocumentId","cron","add","deleteHistoryDaily","task","BATCH_SIZE","retentionDaysInMilliseconds","getRetentionDays","expirationDate","Date","now","deleted","expiredVersions","HISTORY_VERSION_UID","select","created_at","$lt","limit","ids","map","v","id","deleteMany","options","destroy","remove"],"mappings":";;;;;;AAWA;;IAGA,MAAMA,6BAA6B,CACjCC,OAAAA,GAAAA;;IAMA,IAAI,CAACC,OAAOC,cAAc,CAACC,GAAG,EAAIC,EAAAA,OAAAA,CAAQC,GAAIC,CAAAA,UAAAA,CAAW,kBAAqB,CAAA,EAAA;QAC5E,OAAO,KAAA;AACT;;IAGA,IACEN,OAAAA,CAAQO,MAAM,KAAK,QAAA,IACnBP,QAAQO,MAAM,KAAK,QACnBP,IAAAA,OAAAA,CAAQO,MAAM,KAAK,WACnBP,OAAQO,CAAAA,MAAM,KAAK,SAAA,IACnBP,OAAQO,CAAAA,MAAM,KAAK,WACnBP,IAAAA,OAAAA,CAAQO,MAAM,KAAK,cACnB,EAAA;QACA,OAAO,KAAA;AACT;AAEA;;;;;AAKC,MACD,IACEP,OAAAA,CAAQO,MAAM,KAAK,QACnBN,IAAAA,MAAAA,CAAOC,cAAc,CAACC,GAAG,EAAA,EAAIC,OAAQC,CAAAA,GAAAA,CAAIG,SAAS,kBAClD,CAAA,EAAA;QACA,OAAO,KAAA;AACT;;IAGA,IAAI,CAACR,QAAQS,WAAW,CAACC,GAAG,CAACJ,UAAU,CAAC,OAAU,CAAA,EAAA;QAChD,OAAO,KAAA;AACT;IAEA,OAAO,IAAA;AACT,CAAA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CAAAA,EAAE,CAACC,KAAK,CAAC8B,mBAAqB7B,CAAAA,CAAAA,QAAQ,CAAC;gCAC1E8B,MAAQ,EAAA;AAAC,oCAAA;AAAK,iCAAA;gCACd7B,KAAO,EAAA;oCACL8B,UAAY,EAAA;wCACVC,GAAKR,EAAAA;AACP;AACF,iCAAA;gCACAS,KAAOZ,EAAAA;AACT,6BAAA,CAAA;AAEA,4BAAA,MAAMa,MAAMN,eAAgBO,CAAAA,GAAG,CAAC,CAACC,CAAAA,GAA+BA,EAAEC,EAAE,CAAA;AACpEV,4BAAAA,OAAAA,GAAUO,IAAIzC,MAAM;;AAGpB,4BAAA,IAAIkC,UAAU,CAAG,EAAA;AACf,gCAAA,MAAMhF,QAAOmD,EAAE,CAACC,KAAK,CAAC8B,mBAAAA,CAAAA,CAAqBS,UAAU,CAAC;oCACpDrC,KAAO,EAAA;wCACLoC,EAAI,EAAA;4CAAEnC,GAAKgC,EAAAA;AAAI;AACjB;AACF,iCAAA,CAAA;AACF;;;AAIF,yBAAA,OAASP,WAAWN,UAAY;AAClC,qBAAA;oBACAkB,OAAS,EAAA;AACX;AACF,aAAA,CAAA;AAEAhE,YAAAA,KAAAA,CAAMC,aAAa,GAAG,IAAA;AACxB,SAAA;QAEA,MAAMgE,OAAAA,CAAAA,GAAAA;YACJ7F,OAAOsE,CAAAA,IAAI,CAACwB,MAAM,CAAC,oBAAA,CAAA;AACrB;AACF,KAAA;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"lifecycles.d.ts","sourceRoot":"","sources":["../../../../../server/src/history/services/lifecycles.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAgB,MAAM,eAAe,CAAC;AA2FxD,QAAA,MAAM,uBAAuB,eAAgB;IAAE,MAAM,EAAE,KAAK,MAAM,CAAA;CAAE;;;CAoHnE,CAAC;AAEF,OAAO,EAAE,uBAAuB,EAAE,CAAC"}
1
+ {"version":3,"file":"lifecycles.d.ts","sourceRoot":"","sources":["../../../../../server/src/history/services/lifecycles.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAgB,MAAM,eAAe,CAAC;AA2FxD,QAAA,MAAM,uBAAuB,eAAgB;IAAE,MAAM,EAAE,KAAK,MAAM,CAAA;CAAE;;;CAsInE,CAAC;AAEF,OAAO,EAAE,uBAAuB,EAAE,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@strapi/content-manager",
3
- "version": "5.36.0",
3
+ "version": "5.36.1",
4
4
  "description": "A powerful UI to easily manage your data.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -69,8 +69,8 @@
69
69
  "@sindresorhus/slugify": "1.1.0",
70
70
  "@strapi/design-system": "2.1.2",
71
71
  "@strapi/icons": "2.1.2",
72
- "@strapi/types": "5.36.0",
73
- "@strapi/utils": "5.36.0",
72
+ "@strapi/types": "5.36.1",
73
+ "@strapi/utils": "5.36.1",
74
74
  "codemirror5": "npm:codemirror@^5.65.11",
75
75
  "date-fns": "2.30.0",
76
76
  "fractional-indexing": "3.2.0",
@@ -89,7 +89,7 @@
89
89
  "markdown-it-sub": "^1.0.0",
90
90
  "markdown-it-sup": "1.0.0",
91
91
  "prismjs": "1.30.0",
92
- "qs": "6.14.1",
92
+ "qs": "6.14.2",
93
93
  "react-dnd": "16.0.1",
94
94
  "react-dnd-html5-backend": "16.0.1",
95
95
  "react-helmet": "^6.1.0",
@@ -104,8 +104,8 @@
104
104
  "yup": "0.32.9"
105
105
  },
106
106
  "devDependencies": {
107
- "@strapi/admin": "5.36.0",
108
- "@strapi/database": "5.36.0",
107
+ "@strapi/admin": "5.36.1",
108
+ "@strapi/database": "5.36.1",
109
109
  "@testing-library/react": "16.3.0",
110
110
  "@types/jest": "29.5.2",
111
111
  "@types/lodash": "^4.14.191",
@@ -114,14 +114,14 @@
114
114
  "msw": "1.3.0",
115
115
  "react": "18.3.1",
116
116
  "react-dom": "18.3.1",
117
- "react-router-dom": "6.22.3",
117
+ "react-router-dom": "6.30.3",
118
118
  "styled-components": "6.1.8"
119
119
  },
120
120
  "peerDependencies": {
121
121
  "@strapi/admin": "^5.0.0",
122
122
  "react": "^17.0.0 || ^18.0.0",
123
123
  "react-dom": "^17.0.0 || ^18.0.0",
124
- "react-router-dom": "^6.0.0",
124
+ "react-router-dom": "^6.30.3",
125
125
  "styled-components": "^6.0.0"
126
126
  },
127
127
  "engines": {