@strapi/core 5.0.0-rc.2 → 5.0.0-rc.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Strapi.js +2 -2
- package/dist/Strapi.js.map +1 -1
- package/dist/configuration/get-dirs.js +2 -2
- package/dist/configuration/get-dirs.js.map +1 -1
- package/dist/configuration/index.js +2 -2
- package/dist/configuration/index.js.map +1 -1
- package/dist/core-api/controller/collection-type.js +3 -3
- package/dist/core-api/controller/collection-type.js.map +1 -1
- package/dist/core-api/controller/index.js +2 -2
- package/dist/core-api/controller/index.js.map +1 -1
- package/dist/core-api/controller/single-type.js +2 -2
- package/dist/core-api/controller/single-type.js.map +1 -1
- package/dist/core-api/controller/transform.js +8 -8
- package/dist/core-api/controller/transform.js.map +1 -1
- package/dist/core-api/service/collection-type.d.ts +2 -2
- package/dist/core-api/service/pagination.js +8 -8
- package/dist/core-api/service/pagination.js.map +1 -1
- package/dist/domain/content-type/index.js +4 -4
- package/dist/domain/content-type/index.js.map +1 -1
- package/dist/ee/index.js +3 -3
- package/dist/ee/index.js.map +1 -1
- package/dist/factories.js +4 -4
- package/dist/factories.js.map +1 -1
- package/dist/factories.mjs.map +1 -1
- package/dist/loaders/apis.js +2 -2
- package/dist/loaders/apis.js.map +1 -1
- package/dist/loaders/plugins/get-enabled-plugins.d.ts.map +1 -1
- package/dist/loaders/plugins/get-enabled-plugins.js +39 -11
- package/dist/loaders/plugins/get-enabled-plugins.js.map +1 -1
- package/dist/loaders/plugins/get-enabled-plugins.mjs +9 -3
- package/dist/loaders/plugins/get-enabled-plugins.mjs.map +1 -1
- package/dist/loaders/plugins/get-user-plugins-config.js +2 -2
- package/dist/loaders/plugins/get-user-plugins-config.js.map +1 -1
- package/dist/loaders/plugins/index.d.ts.map +1 -1
- package/dist/loaders/plugins/index.js +34 -7
- package/dist/loaders/plugins/index.js.map +1 -1
- package/dist/loaders/plugins/index.mjs +9 -1
- package/dist/loaders/plugins/index.mjs.map +1 -1
- package/dist/middlewares/body.js +2 -2
- package/dist/middlewares/body.js.map +1 -1
- package/dist/middlewares/public.js +2 -2
- package/dist/middlewares/public.js.map +1 -1
- package/dist/middlewares/query.js.map +1 -1
- package/dist/middlewares/query.mjs.map +1 -1
- package/dist/middlewares/responses.js +2 -2
- package/dist/middlewares/responses.js.map +1 -1
- package/dist/middlewares/security.d.ts.map +1 -1
- package/dist/middlewares/security.js +4 -4
- package/dist/middlewares/security.js.map +1 -1
- package/dist/middlewares/security.mjs +1 -1
- package/dist/middlewares/security.mjs.map +1 -1
- package/dist/middlewares/session.js +2 -2
- package/dist/middlewares/session.js.map +1 -1
- package/dist/migrations/database/5.0.0-discard-drafts.d.ts +12 -9
- package/dist/migrations/database/5.0.0-discard-drafts.d.ts.map +1 -1
- package/dist/migrations/database/5.0.0-discard-drafts.js +50 -11
- package/dist/migrations/database/5.0.0-discard-drafts.js.map +1 -1
- package/dist/migrations/database/5.0.0-discard-drafts.mjs +51 -12
- package/dist/migrations/database/5.0.0-discard-drafts.mjs.map +1 -1
- package/dist/providers/admin.d.ts.map +1 -1
- package/dist/providers/admin.js.map +1 -1
- package/dist/providers/admin.mjs.map +1 -1
- package/dist/registries/apis.js +2 -2
- package/dist/registries/apis.js.map +1 -1
- package/dist/registries/components.js +2 -2
- package/dist/registries/components.js.map +1 -1
- package/dist/registries/content-types.js +3 -3
- package/dist/registries/content-types.js.map +1 -1
- package/dist/registries/controllers.js +3 -3
- package/dist/registries/controllers.js.map +1 -1
- package/dist/registries/custom-fields.js +4 -4
- package/dist/registries/custom-fields.js.map +1 -1
- package/dist/registries/hooks.js +2 -2
- package/dist/registries/hooks.js.map +1 -1
- package/dist/registries/middlewares.js +3 -3
- package/dist/registries/middlewares.js.map +1 -1
- package/dist/registries/modules.js +3 -3
- package/dist/registries/modules.js.map +1 -1
- package/dist/registries/plugins.js +2 -2
- package/dist/registries/plugins.js.map +1 -1
- package/dist/registries/policies.d.ts +1 -1
- package/dist/registries/policies.d.ts.map +1 -1
- package/dist/registries/policies.js +5 -5
- package/dist/registries/policies.js.map +1 -1
- package/dist/registries/policies.mjs +1 -1
- package/dist/registries/policies.mjs.map +1 -1
- package/dist/registries/services.js +3 -3
- package/dist/registries/services.js.map +1 -1
- package/dist/services/auth/index.js +3 -3
- package/dist/services/auth/index.js.map +1 -1
- package/dist/services/content-api/index.d.ts +10 -12
- package/dist/services/content-api/index.d.ts.map +1 -1
- package/dist/services/content-api/permissions/index.d.ts +10 -12
- package/dist/services/content-api/permissions/index.d.ts.map +1 -1
- package/dist/services/content-api/permissions/providers/action.d.ts +5 -6
- package/dist/services/content-api/permissions/providers/action.d.ts.map +1 -1
- package/dist/services/content-api/permissions/providers/condition.d.ts +5 -6
- package/dist/services/content-api/permissions/providers/condition.d.ts.map +1 -1
- package/dist/services/core-store.js +3 -3
- package/dist/services/core-store.js.map +1 -1
- package/dist/services/cron.d.ts +3 -3
- package/dist/services/cron.d.ts.map +1 -1
- package/dist/services/cron.js +3 -3
- package/dist/services/cron.js.map +1 -1
- package/dist/services/cron.mjs.map +1 -1
- package/dist/services/document-service/attributes/index.js +2 -2
- package/dist/services/document-service/attributes/index.js.map +1 -1
- package/dist/services/document-service/attributes/transforms.js +3 -3
- package/dist/services/document-service/attributes/transforms.js.map +1 -1
- package/dist/services/document-service/components.js +15 -15
- package/dist/services/document-service/components.js.map +1 -1
- package/dist/services/document-service/draft-and-publish.js +16 -16
- package/dist/services/document-service/draft-and-publish.js.map +1 -1
- package/dist/services/document-service/entries.js +5 -5
- package/dist/services/document-service/entries.js.map +1 -1
- package/dist/services/document-service/internationalization.js +9 -9
- package/dist/services/document-service/internationalization.js.map +1 -1
- package/dist/services/document-service/params.js +2 -2
- package/dist/services/document-service/params.js.map +1 -1
- package/dist/services/document-service/repository.d.ts.map +1 -1
- package/dist/services/document-service/repository.js +51 -15
- package/dist/services/document-service/repository.js.map +1 -1
- package/dist/services/document-service/repository.mjs +43 -7
- package/dist/services/document-service/repository.mjs.map +1 -1
- package/dist/services/document-service/transform/id-transform.js +2 -2
- package/dist/services/document-service/transform/id-transform.js.map +1 -1
- package/dist/services/document-service/transform/query.js +3 -3
- package/dist/services/document-service/transform/query.js.map +1 -1
- package/dist/services/document-service/transform/relations/extract/data-ids.js +2 -2
- package/dist/services/document-service/transform/relations/extract/data-ids.js.map +1 -1
- package/dist/services/document-service/transform/relations/transform/data-ids.js +2 -2
- package/dist/services/document-service/transform/relations/transform/data-ids.js.map +1 -1
- package/dist/services/document-service/transform/relations/utils/dp.js +2 -2
- package/dist/services/document-service/transform/relations/utils/dp.js.map +1 -1
- package/dist/services/document-service/transform/relations/utils/map-relation.js +6 -6
- package/dist/services/document-service/transform/relations/utils/map-relation.js.map +1 -1
- package/dist/services/document-service/utils/populate.d.ts.map +1 -1
- package/dist/services/document-service/utils/populate.js +3 -1
- package/dist/services/document-service/utils/populate.js.map +1 -1
- package/dist/services/document-service/utils/populate.mjs +3 -1
- package/dist/services/document-service/utils/populate.mjs.map +1 -1
- package/dist/services/document-service/utils/unidirectional-relations.d.ts +33 -0
- package/dist/services/document-service/utils/unidirectional-relations.d.ts.map +1 -0
- package/dist/services/document-service/utils/unidirectional-relations.js +58 -0
- package/dist/services/document-service/utils/unidirectional-relations.js.map +1 -0
- package/dist/services/document-service/utils/unidirectional-relations.mjs +58 -0
- package/dist/services/document-service/utils/unidirectional-relations.mjs.map +1 -0
- package/dist/services/entity-validator/blocks-validator.d.ts +1 -2
- package/dist/services/entity-validator/blocks-validator.d.ts.map +1 -1
- package/dist/services/entity-validator/blocks-validator.js +4 -3
- package/dist/services/entity-validator/blocks-validator.js.map +1 -1
- package/dist/services/entity-validator/blocks-validator.mjs +3 -3
- package/dist/services/entity-validator/blocks-validator.mjs.map +1 -1
- package/dist/services/entity-validator/index.d.ts +2 -1
- package/dist/services/entity-validator/index.d.ts.map +1 -1
- package/dist/services/entity-validator/index.js +28 -33
- package/dist/services/entity-validator/index.js.map +1 -1
- package/dist/services/entity-validator/index.mjs +14 -19
- package/dist/services/entity-validator/index.mjs.map +1 -1
- package/dist/services/entity-validator/validators.d.ts +32 -23
- package/dist/services/entity-validator/validators.d.ts.map +1 -1
- package/dist/services/entity-validator/validators.js +136 -63
- package/dist/services/entity-validator/validators.js.map +1 -1
- package/dist/services/entity-validator/validators.mjs +135 -63
- package/dist/services/entity-validator/validators.mjs.map +1 -1
- package/dist/services/server/compose-endpoint.js +7 -7
- package/dist/services/server/compose-endpoint.js.map +1 -1
- package/dist/services/server/koa.js +3 -3
- package/dist/services/server/koa.js.map +1 -1
- package/dist/services/server/middleware.js +3 -3
- package/dist/services/server/middleware.js.map +1 -1
- package/dist/services/server/routing.js +2 -2
- package/dist/services/server/routing.js.map +1 -1
- package/dist/services/utils/dynamic-zones.js +5 -5
- package/dist/services/utils/dynamic-zones.js.map +1 -1
- package/dist/utils/cron.js +3 -3
- package/dist/utils/cron.js.map +1 -1
- package/dist/utils/filepath-to-prop-path.d.ts +1 -1
- package/dist/utils/filepath-to-prop-path.d.ts.map +1 -1
- package/dist/utils/filepath-to-prop-path.js +27 -6
- package/dist/utils/filepath-to-prop-path.js.map +1 -1
- package/dist/utils/filepath-to-prop-path.mjs +25 -5
- package/dist/utils/filepath-to-prop-path.mjs.map +1 -1
- package/dist/utils/is-initialized.js +3 -3
- package/dist/utils/is-initialized.js.map +1 -1
- package/dist/utils/startup-logger.js +4 -4
- package/dist/utils/startup-logger.js.map +1 -1
- package/dist/utils/startup-logger.mjs +3 -3
- package/dist/utils/startup-logger.mjs.map +1 -1
- package/dist/utils/transform-content-types-to-models.d.ts +2 -2
- package/dist/utils/transform-content-types-to-models.d.ts.map +1 -1
- package/dist/utils/transform-content-types-to-models.js +6 -5
- package/dist/utils/transform-content-types-to-models.js.map +1 -1
- package/dist/utils/transform-content-types-to-models.mjs +5 -4
- package/dist/utils/transform-content-types-to-models.mjs.map +1 -1
- package/package.json +15 -15
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"validators.mjs","sources":["../../../src/services/entity-validator/validators.ts"],"sourcesContent":["import _ from 'lodash';\nimport { yup } from '@strapi/utils';\nimport type { Schema, Struct, Modules } from '@strapi/types';\nimport blocksValidator from './blocks-validator';\n\nimport type { ComponentContext } from '.';\n\ninterface ValidatorMetas<TAttribute extends Schema.Attribute.AnyAttribute> {\n attr: TAttribute;\n model: Struct.ContentTypeSchema;\n updatedAttribute: { name: string; value: unknown };\n entity: Modules.EntityValidator.Entity;\n componentContext: ComponentContext;\n}\n\ninterface ValidatorOptions {\n isDraft: boolean;\n locale?: string;\n}\n\n/* Validator utils */\n\n/**\n * Adds minLength validator\n */\nconst addMinLengthValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n },\n { isDraft }: ValidatorOptions\n) => {\n return attr.minLength && _.isInteger(attr.minLength) && !isDraft\n ? validator.min(attr.minLength)\n : validator;\n};\n\n/**\n * Adds maxLength validator\n * @returns {StringSchema}\n */\nconst addMaxLengthValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n }\n) => {\n return attr.maxLength && _.isInteger(attr.maxLength) ? validator.max(attr.maxLength) : validator;\n};\n\n/**\n * Adds min integer validator\n * @returns {NumberSchema}\n */\nconst addMinIntegerValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n }\n) => (_.isNumber(attr.min) ? validator.min(_.toInteger(attr.min)) : validator);\n\n/**\n * Adds max integer validator\n */\nconst addMaxIntegerValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n }\n) => (_.isNumber(attr.max) ? validator.max(_.toInteger(attr.max)) : validator);\n\n/**\n * Adds min float/decimal validator\n */\nconst addMinFloatValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n }\n) => (_.isNumber(attr.min) ? validator.min(attr.min) : validator);\n\n/**\n * Adds max float/decimal validator\n */\nconst addMaxFloatValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n }\n) => (_.isNumber(attr.max) ? validator.max(attr.max) : validator);\n\n/**\n * Adds regex validator\n */\nconst addStringRegexValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n }\n) => {\n return 'regex' in attr && !_.isUndefined(attr.regex)\n ? validator.matches(new RegExp(attr.regex), { excludeEmptyString: !attr.required })\n : validator;\n};\n\n/**\n * Adds unique validator\n */\nconst addUniqueValidator = <T extends yup.AnySchema>(\n validator: T,\n {\n attr,\n model,\n updatedAttribute,\n entity,\n componentContext,\n }: ValidatorMetas<Schema.Attribute.AnyAttribute & Schema.Attribute.UniqueOption>,\n options: ValidatorOptions\n): T => {\n if (attr.type !== 'uid' && !attr.unique) {\n return validator;\n }\n\n return validator.test('unique', 'This attribute must be unique', async (value) => {\n const isPublish = options.isDraft === false;\n\n /**\n * If the attribute value is `null` we want to skip the unique validation.\n * Otherwise it'll only accept a single `null` entry in the database.\n */\n if (_.isNil(value)) {\n return true;\n }\n\n /**\n * If we are updating a draft and the value is unchanged we skip the unique verification. This will\n * prevent the validator to be triggered in case the user activated the\n * unique constraint after already creating multiple entries with\n * the same attribute value for that field.\n */\n if (!isPublish && value === entity?.[updatedAttribute.name]) {\n return true;\n }\n\n let queryUid: string;\n let queryWhere: Record<string, any> = {};\n\n const hasPathToComponent = componentContext?.pathToComponent?.length > 0;\n if (hasPathToComponent) {\n const hasRepeatableData = componentContext.repeatableData.length > 0;\n if (hasRepeatableData) {\n // If we are validating a unique field within a repeatable component,\n // we first need to ensure that the repeatable in the current entity is\n // valid against itself.\n\n const { name: updatedName, value: updatedValue } = updatedAttribute;\n // Construct the full path to the unique field within the component.\n const pathToCheck = [...componentContext.pathToComponent.slice(1), updatedName].join('.');\n\n // Extract the values from the repeatable data using the constructed path\n const values = componentContext.repeatableData.map((item) => {\n return pathToCheck.split('.').reduce((acc, key) => acc[key], item as any);\n });\n\n // Check if the value is repeated in the current entity\n const isUpdatedAttributeRepeatedInThisEntity =\n values.filter((value) => value === updatedValue).length > 1;\n\n if (isUpdatedAttributeRepeatedInThisEntity) {\n return false;\n }\n }\n\n /**\n * When `componentContext` is present it means we are dealing with a unique\n * field within a component.\n *\n * The unique validation must consider the specific context of the\n * component, which will always be contained within a parent content type\n * and may also be nested within another component.\n *\n * We construct a query that takes into account the parent's model UID,\n * dimensions (such as draft and publish state/locale) and excludes the current\n * content type entity by its ID if provided.\n */\n const {\n model: parentModel,\n options: parentOptions,\n id: excludeId,\n } = componentContext.parentContent;\n queryUid = parentModel.uid;\n\n const whereConditions: Record<string, any> = {};\n const isParentDraft = parentOptions && parentOptions.isDraft;\n\n whereConditions.publishedAt = isParentDraft ? null : { $notNull: true };\n\n if (parentOptions?.locale) {\n whereConditions.locale = parentOptions.locale;\n }\n\n if (excludeId && !Number.isNaN(excludeId)) {\n whereConditions.id = { $ne: excludeId };\n }\n\n queryWhere = {\n ...componentContext.pathToComponent.reduceRight((acc, key) => ({ [key]: acc }), {\n [updatedAttribute.name]: value,\n }),\n\n ...whereConditions,\n };\n } else {\n /**\n * Here we are validating a scalar unique field from the content type's schema.\n * We construct a query to check if the value is unique\n * considering dimensions (e.g. locale, publication state) and excluding the current entity by its ID if available.\n */\n queryUid = model.uid;\n const scalarAttributeWhere: Record<string, any> = {\n [updatedAttribute.name]: value,\n };\n\n scalarAttributeWhere.publishedAt = options.isDraft ? null : { $notNull: true };\n\n if (options?.locale) {\n scalarAttributeWhere.locale = options.locale;\n }\n\n if (entity?.id) {\n scalarAttributeWhere.id = { $ne: entity.id };\n }\n\n queryWhere = scalarAttributeWhere;\n }\n\n // The validation should pass if there is no other record found from the query\n // TODO query not working for dynamic zones (type === relation)\n return !(await strapi.db.query(queryUid).findOne({ where: queryWhere }));\n });\n};\n\n/* Type validators */\n\nconst stringValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID\n >,\n options: ValidatorOptions\n) => {\n let schema = yup.string().transform((val, originalVal) => originalVal);\n\n schema = addMinLengthValidator(schema, metas, options);\n schema = addMaxLengthValidator(schema, metas);\n schema = addStringRegexValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst emailValidator = (\n metas: ValidatorMetas<Schema.Attribute.Email>,\n options: ValidatorOptions\n) => {\n const schema = stringValidator(metas, options);\n return schema.email().min(1, '${path} cannot be empty');\n};\n\nconst uidValidator = (metas: ValidatorMetas<Schema.Attribute.UID>, options: ValidatorOptions) => {\n const schema = stringValidator(metas, options);\n\n return schema.matches(/^[A-Za-z0-9-_.~]*$/);\n};\n\nconst enumerationValidator = ({ attr }: { attr: Schema.Attribute.Enumeration }) => {\n return yup\n .string()\n .oneOf((Array.isArray(attr.enum) ? attr.enum : [attr.enum]).concat(null as any));\n};\n\nconst integerValidator = (\n metas: ValidatorMetas<Schema.Attribute.Integer | Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n let schema = yup.number().integer();\n\n schema = addMinIntegerValidator(schema, metas);\n schema = addMaxIntegerValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst floatValidator = (\n metas: ValidatorMetas<Schema.Attribute.Decimal | Schema.Attribute.Float>,\n options: ValidatorOptions\n) => {\n let schema = yup.number();\n schema = addMinFloatValidator(schema, metas);\n schema = addMaxFloatValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nconst bigintegerValidator = (\n metas: ValidatorMetas<Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nconst datesValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.Date\n | Schema.Attribute.DateTime\n | Schema.Attribute.Time\n | Schema.Attribute.Timestamp\n >,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nexport default {\n string: stringValidator,\n text: stringValidator,\n richtext: stringValidator,\n password: stringValidator,\n email: emailValidator,\n enumeration: enumerationValidator,\n boolean: () => yup.boolean(),\n uid: uidValidator,\n json: () => yup.mixed(),\n integer: integerValidator,\n biginteger: bigintegerValidator,\n float: floatValidator,\n decimal: floatValidator,\n date: datesValidator,\n time: datesValidator,\n datetime: datesValidator,\n timestamp: datesValidator,\n blocks: blocksValidator,\n};\n"],"names":["value"],"mappings":";;;AAyBA,MAAM,wBAAwB,CAC5B,WACA;AAAA,EACE;AACF,GASA,EAAE,cACC;AACH,SAAO,KAAK,aAAa,EAAE,UAAU,KAAK,SAAS,KAAK,CAAC,UACrD,UAAU,IAAI,KAAK,SAAS,IAC5B;AACN;AAMA,MAAM,wBAAwB,CAC5B,WACA;AAAA,EACE;AACF,MASG;AACI,SAAA,KAAK,aAAa,EAAE,UAAU,KAAK,SAAS,IAAI,UAAU,IAAI,KAAK,SAAS,IAAI;AACzF;AAMA,MAAM,yBAAyB,CAC7B,WACA;AAAA,EACE;AACF,MAGI,EAAE,SAAS,KAAK,GAAG,IAAI,UAAU,IAAI,EAAE,UAAU,KAAK,GAAG,CAAC,IAAI;AAKpE,MAAM,yBAAyB,CAC7B,WACA;AAAA,EACE;AACF,MAGI,EAAE,SAAS,KAAK,GAAG,IAAI,UAAU,IAAI,EAAE,UAAU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BAAmB,QAAQ,OAAO,OAAO;AAClD;AAEA,MAAe,aAAA;AAAA,EACb,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,UAAU;AAAA,EACV,UAAU;AAAA,EACV,OAAO;AAAA,EACP,aAAa;AAAA,EACb,SAAS,MAAM,IAAI,QAAQ;AAAA,EAC3B,KAAK;AAAA,EACL,MAAM,MAAM,IAAI,MAAM;AAAA,EACtB,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AAAA,EACN,UAAU;AAAA,EACV,WAAW;AAAA,EACX,QAAQ;AACV;"}
|
1
|
+
{"version":3,"file":"validators.mjs","sources":["../../../src/services/entity-validator/validators.ts"],"sourcesContent":["/**\n * Validators check if the entry data meets specific criteria before saving or publishing.\n * (e.g., length, range, format).\n *\n * Drafts have limited validations (mainly max constraints),\n * while published content undergoes full validation.\n *\n * The system also takes locales into account when validating data.\n * E.g, unique fields must be unique within the same locale.\n */\nimport _ from 'lodash';\nimport { yup } from '@strapi/utils';\nimport type { Schema, Struct, Modules } from '@strapi/types';\nimport { blocksValidator } from './blocks-validator';\n\nimport type { ComponentContext } from '.';\n\nexport interface ValidatorMetas<\n TAttribute extends Schema.Attribute.AnyAttribute = Schema.Attribute.AnyAttribute,\n TValue extends Schema.Attribute.Value<TAttribute> = Schema.Attribute.Value<TAttribute>,\n> {\n attr: TAttribute;\n model: Struct.Schema;\n updatedAttribute: {\n name: string;\n value: TValue;\n };\n componentContext?: ComponentContext;\n entity?: Modules.EntityValidator.Entity;\n}\n\ninterface ValidatorOptions {\n isDraft: boolean;\n locale?: string;\n}\n\n/* Validator utils */\n\n/**\n * Adds minLength validator\n */\nconst addMinLengthValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n },\n { isDraft }: ValidatorOptions\n) => {\n return attr.minLength && _.isInteger(attr.minLength) && !isDraft\n ? validator.min(attr.minLength)\n : validator;\n};\n\n/**\n * Adds maxLength validator\n * @returns {StringSchema}\n */\nconst addMaxLengthValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n }\n) => {\n return attr.maxLength && _.isInteger(attr.maxLength) ? validator.max(attr.maxLength) : validator;\n};\n\n/**\n * Adds min integer validator\n * @returns {NumberSchema}\n */\nconst addMinIntegerValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n },\n { isDraft }: ValidatorOptions\n) => (_.isNumber(attr.min) && !isDraft ? validator.min(_.toInteger(attr.min)) : validator);\n\n/**\n * Adds max integer validator\n */\nconst addMaxIntegerValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Integer | Schema.Attribute.BigInteger;\n }\n) => (_.isNumber(attr.max) ? validator.max(_.toInteger(attr.max)) : validator);\n\n/**\n * Adds min float/decimal validator\n */\nconst addMinFloatValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n },\n { isDraft }: ValidatorOptions\n) => (_.isNumber(attr.min) && !isDraft ? validator.min(attr.min) : validator);\n\n/**\n * Adds max float/decimal validator\n */\nconst addMaxFloatValidator = (\n validator: yup.NumberSchema,\n {\n attr,\n }: {\n attr: Schema.Attribute.Decimal | Schema.Attribute.Float;\n }\n) => (_.isNumber(attr.max) ? validator.max(attr.max) : validator);\n\n/**\n * Adds regex validator\n */\nconst addStringRegexValidator = (\n validator: yup.StringSchema,\n {\n attr,\n }: {\n attr:\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID;\n },\n { isDraft }: ValidatorOptions\n) => {\n return 'regex' in attr && !_.isUndefined(attr.regex) && !isDraft\n ? validator.matches(new RegExp(attr.regex), { excludeEmptyString: !attr.required })\n : validator;\n};\n\nconst addUniqueValidator = <T extends yup.AnySchema>(\n validator: T,\n {\n attr,\n model,\n updatedAttribute,\n entity,\n componentContext,\n }: ValidatorMetas<Schema.Attribute.AnyAttribute & Schema.Attribute.UniqueOption>,\n options: ValidatorOptions\n): T => {\n if (attr.type !== 'uid' && !attr.unique) {\n return validator;\n }\n\n const validateUniqueFieldWithinComponent = async (value: any): Promise<boolean> => {\n if (!componentContext) {\n return false;\n }\n\n // If we are validating a unique field within a repeatable component,\n // we first need to ensure that the repeatable in the current entity is\n // valid against itself.\n const hasRepeatableData = componentContext.repeatableData.length > 0;\n if (hasRepeatableData) {\n const { name: updatedName, value: updatedValue } = updatedAttribute;\n // Construct the full path to the unique field within the component.\n const pathToCheck = [...componentContext.pathToComponent.slice(1), updatedName].join('.');\n\n // Extract the values from the repeatable data using the constructed path\n const values = componentContext.repeatableData.map((item) => {\n return pathToCheck.split('.').reduce((acc, key) => acc[key], item as any);\n });\n\n // Check if the value is repeated in the current entity\n const isUpdatedAttributeRepeatedInThisEntity =\n values.filter((value) => value === updatedValue).length > 1;\n\n if (isUpdatedAttributeRepeatedInThisEntity) {\n return false;\n }\n }\n\n /**\n * When `componentContext` is present it means we are dealing with a unique\n * field within a component.\n *\n * The unique validation must consider the specific context of the\n * component, which will always be contained within a parent content type\n * and may also be nested within another component.\n *\n * We construct a query that takes into account the parent's model UID,\n * dimensions (such as draft and publish state/locale) and excludes the current\n * content type entity by its ID if provided.\n */\n const {\n model: parentModel,\n options: parentOptions,\n id: excludeId,\n } = componentContext.parentContent;\n\n const whereConditions: Record<string, any> = {};\n const isParentDraft = parentOptions && parentOptions.isDraft;\n\n whereConditions.publishedAt = isParentDraft ? null : { $notNull: true };\n\n if (parentOptions?.locale) {\n whereConditions.locale = parentOptions.locale;\n }\n\n if (excludeId && !Number.isNaN(excludeId)) {\n whereConditions.id = { $ne: excludeId };\n }\n\n const queryUid = parentModel.uid;\n const queryWhere = {\n ...componentContext.pathToComponent.reduceRight((acc, key) => ({ [key]: acc }), {\n [updatedAttribute.name]: value,\n }),\n\n ...whereConditions,\n };\n\n // The validation should pass if there is no other record found from the query\n return !(await strapi.db.query(queryUid).findOne({ where: queryWhere }));\n };\n\n const validateUniqueFieldWithinDynamicZoneComponent = async (\n startOfPath: string\n ): Promise<boolean> => {\n if (!componentContext) {\n return false;\n }\n\n const targetComponentUID = model.uid;\n // Ensure that the value is unique within the dynamic zone in this entity.\n const countOfValueInThisEntity = (componentContext?.fullDynamicZoneContent ?? []).reduce(\n (acc, component) => {\n if (component.__component !== targetComponentUID) {\n return acc;\n }\n\n const updatedValue = component[updatedAttribute.name];\n return updatedValue === updatedAttribute.value ? acc + 1 : acc;\n },\n 0\n );\n\n if (countOfValueInThisEntity > 1) {\n // If the value is repeated in the current entity, the validation fails.\n return false;\n }\n\n // Build a query for the parent content type to find all entities in the\n // same locale and publication state\n type QueryType = {\n select: string[];\n where: {\n published_at?: { $eq: null } | { $ne: null };\n id?: { $ne: number };\n locale?: string;\n };\n populate: {\n [key: string]: {\n on: {\n [key: string]: {\n select: string[];\n where: { [key: string]: string | number | boolean };\n };\n };\n };\n };\n };\n\n // Populate the dynamic zone for any components that share the same value\n // as the updated attribute.\n const query: QueryType = {\n select: ['id'],\n where: {},\n populate: {\n [startOfPath]: {\n on: {\n [targetComponentUID]: {\n select: ['id'],\n where: { [updatedAttribute.name]: updatedAttribute.value },\n },\n },\n },\n },\n };\n\n const { options, id } = componentContext.parentContent;\n\n if (options?.isDraft !== undefined) {\n query.where.published_at = options.isDraft ? { $eq: null } : { $ne: null };\n }\n\n if (id) {\n query.where.id = { $ne: id };\n }\n\n if (options?.locale) {\n query.where.locale = options.locale;\n }\n\n const parentModelQueryResult = await strapi.db\n .query(componentContext.parentContent.model.uid)\n .findMany(query);\n\n // Filter the results to only include results that have components in the\n // dynamic zone that match the target component type.\n const filteredResults = parentModelQueryResult\n .filter((result) => Array.isArray(result[startOfPath]) && result[startOfPath].length)\n .flatMap((result) => result[startOfPath])\n .filter((dynamicZoneComponent) => dynamicZoneComponent.__component === targetComponentUID);\n\n if (filteredResults.length >= 1) {\n return false;\n }\n\n return true;\n };\n\n return validator.test('unique', 'This attribute must be unique', async (value) => {\n /**\n * If the attribute value is `null` or an empty string we want to skip the unique validation.\n * Otherwise it'll only accept a single entry with that value in the database.\n */\n if (_.isNil(value) || value === '') {\n return true;\n }\n\n /**\n * We don't validate any unique constraint for draft entries.\n */\n if (options.isDraft) {\n return true;\n }\n\n const hasPathToComponent = componentContext && componentContext.pathToComponent.length > 0;\n if (hasPathToComponent) {\n // Detect if we are validating within a dynamiczone by checking if the first\n // path is a dynamiczone attribute in the parent content type.\n const startOfPath = componentContext.pathToComponent[0];\n const testingDZ =\n componentContext.parentContent.model.attributes[startOfPath].type === 'dynamiczone';\n\n if (testingDZ) {\n return validateUniqueFieldWithinDynamicZoneComponent(startOfPath);\n }\n\n return validateUniqueFieldWithinComponent(value);\n }\n\n /**\n * Here we are validating a scalar unique field from the content type's schema.\n * We construct a query to check if the value is unique\n * considering dimensions (e.g. locale, publication state) and excluding the current entity by its ID if available.\n */\n const scalarAttributeWhere: Record<string, any> = {\n [updatedAttribute.name]: value,\n publishedAt: { $notNull: true },\n };\n\n if (options?.locale) {\n scalarAttributeWhere.locale = options.locale;\n }\n\n if (entity?.id) {\n scalarAttributeWhere.id = { $ne: entity.id };\n }\n\n // The validation should pass if there is no other record found from the query\n return !(await strapi.db\n .query(model.uid)\n .findOne({ where: scalarAttributeWhere, select: ['id'] }));\n });\n};\n\n/* Type validators */\n\nconst stringValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.String\n | Schema.Attribute.Text\n | Schema.Attribute.RichText\n | Schema.Attribute.Password\n | Schema.Attribute.Email\n | Schema.Attribute.UID\n >,\n options: ValidatorOptions\n) => {\n let schema = yup.string().transform((val, originalVal) => originalVal);\n\n schema = addMinLengthValidator(schema, metas, options);\n schema = addMaxLengthValidator(schema, metas);\n schema = addStringRegexValidator(schema, metas, options);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nexport const emailValidator = (\n metas: ValidatorMetas<Schema.Attribute.Email>,\n options: ValidatorOptions\n) => {\n const schema = stringValidator(metas, options);\n\n if (options.isDraft) {\n return schema;\n }\n\n return schema.email().min(\n 1,\n // eslint-disable-next-line no-template-curly-in-string\n '${path} cannot be empty'\n );\n};\n\nexport const uidValidator = (\n metas: ValidatorMetas<Schema.Attribute.UID>,\n options: ValidatorOptions\n) => {\n const schema = stringValidator(metas, options);\n\n if (options.isDraft) {\n return schema;\n }\n\n return schema.matches(/^[A-Za-z0-9-_.~]*$/);\n};\n\nexport const enumerationValidator = ({ attr }: { attr: Schema.Attribute.Enumeration }) => {\n return yup\n .string()\n .oneOf((Array.isArray(attr.enum) ? attr.enum : [attr.enum]).concat(null as any));\n};\n\nexport const integerValidator = (\n metas: ValidatorMetas<Schema.Attribute.Integer | Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n let schema = yup.number().integer();\n\n schema = addMinIntegerValidator(schema, metas, options);\n schema = addMaxIntegerValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nexport const floatValidator = (\n metas: ValidatorMetas<Schema.Attribute.Decimal | Schema.Attribute.Float>,\n options: ValidatorOptions\n) => {\n let schema = yup.number();\n\n schema = addMinFloatValidator(schema, metas, options);\n schema = addMaxFloatValidator(schema, metas);\n schema = addUniqueValidator(schema, metas, options);\n\n return schema;\n};\n\nexport const bigintegerValidator = (\n metas: ValidatorMetas<Schema.Attribute.BigInteger>,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nexport const datesValidator = (\n metas: ValidatorMetas<\n | Schema.Attribute.Date\n | Schema.Attribute.DateTime\n | Schema.Attribute.Time\n | Schema.Attribute.Timestamp\n >,\n options: ValidatorOptions\n) => {\n const schema = yup.mixed();\n return addUniqueValidator(schema, metas, options);\n};\n\nexport const Validators = {\n string: stringValidator,\n text: stringValidator,\n richtext: stringValidator,\n password: stringValidator,\n email: emailValidator,\n enumeration: enumerationValidator,\n boolean: () => yup.boolean(),\n uid: uidValidator,\n json: () => yup.mixed(),\n integer: integerValidator,\n biginteger: bigintegerValidator,\n float: floatValidator,\n decimal: floatValidator,\n date: datesValidator,\n time: datesValidator,\n datetime: datesValidator,\n timestamp: datesValidator,\n blocks: blocksValidator,\n};\n"],"names":["value","options"],"mappings":";;;AAyCA,MAAM,wBAAwB,CAC5B,WACA;AAAA,EACE;AACF,GASA,EAAE,cACC;AACH,SAAO,KAAK,aAAa,EAAE,UAAU,KAAK,SAAS,KAAK,CAAC,UACrD,UAAU,IAAI,KAAK,SAAS,IAC5B;AACN;AAMA,MAAM,wBAAwB,CAC5B,WACA;AAAA,EACE;AACF,MASG;AACI,SAAA,KAAK,aAAa,EAAE,UAAU,KAAK,SAAS,IAAI,UAAU,IAAI,KAAK,SAAS,IAAI;AACzF;AAMA,MAAM,yBAAyB,CAC7B,WACA;AAAA,EACE;AACF,GAGA,EAAE,QAAQ,MACN,EAAE,SAAS,KAAK,GAAG,KAAK,CAAC,UAAU,UAAU,IAAI,EAAE,UAAU,KAAK,GAAG,CAAC,IAAI;AAKhF,MAAM,yBAAyB,CAC7B,WACA;AAAA,EACE;AACF,MAGI,EAAE,SAAS,KAAK,GAAG,IAAI,UAAU,IAAI,EAAE,UAAU,KAAK,GAAG,CAAC,IAAI;AAKpE,MAAM,uBAAuB,CAC3B,WACA;AAAA,EACE;AACF,GAGA,EAAE,QACE,MAAA,EAAE,SAAS,KAAK,GAAG,KAAK,CAAC,UAAU,UAAU,IAAI,KAAK,GAAG,IAAI;AAKnE,MAAM,uBAAuB,CAC3B,WACA;AAAA,EACE;AACF,M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,KAAK;AACpC,WAAA,mBAAmB,QAAQ,OAAO,OAAO;AAE3C,SAAA;AACT;AAEa,MAAA,iBAAiB,CAC5B,OACA,YACG;AACC,MAAA,SAAS,IAAI;AAER,WAAA,qBAAqB,QAAQ,OAAO,OAAO;AAC3C,WAAA,qBAAqB,QAAQ,KAAK;AAClC,WAAA,mBAAmB,QAAQ,OAAO,OAAO;AAE3C,SAAA;AACT;AAEa,MAAA,sBAAsB,CACjC,OACA,YACG;AACG,QAAA,SAAS,IAAI;AACZ,SAAA,mBAAmB,QAAQ,OAAO,OAAO;AAClD;AAEa,MAAA,iBAAiB,CAC5B,OAMA,YACG;AACG,QAAA,SAAS,IAAI;AACZ,SAAA,mBAAmB,QAAQ,OAAO,OAAO;AAClD;AAEO,MAAM,aAAa;AAAA,EACxB,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,UAAU;AAAA,EACV,UAAU;AAAA,EACV,OAAO;AAAA,EACP,aAAa;AAAA,EACb,SAAS,MAAM,IAAI,QAAQ;AAAA,EAC3B,KAAK;AAAA,EACL,MAAM,MAAM,IAAI,MAAM;AAAA,EACtB,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AAAA,EACN,UAAU;AAAA,EACV,WAAW;AAAA,EACX,QAAQ;AACV;"}
|
@@ -1,5 +1,5 @@
|
|
1
1
|
"use strict";
|
2
|
-
const
|
2
|
+
const fp = require("lodash/fp");
|
3
3
|
const strapiUtils = require("@strapi/utils");
|
4
4
|
const compose = require("koa-compose");
|
5
5
|
const middleware = require("./middleware.js");
|
@@ -7,9 +7,9 @@ const policy = require("./policy.js");
|
|
7
7
|
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
|
8
8
|
const compose__default = /* @__PURE__ */ _interopDefault(compose);
|
9
9
|
const getMethod = (route) => {
|
10
|
-
return
|
10
|
+
return fp.trim(fp.toLower(route.method));
|
11
11
|
};
|
12
|
-
const getPath = (route) =>
|
12
|
+
const getPath = (route) => fp.trim(route.path);
|
13
13
|
const createRouteInfoMiddleware = (routeInfo) => (ctx, next) => {
|
14
14
|
const route = {
|
15
15
|
...routeInfo,
|
@@ -18,7 +18,7 @@ const createRouteInfoMiddleware = (routeInfo) => (ctx, next) => {
|
|
18
18
|
ctx.state.route = route;
|
19
19
|
return next();
|
20
20
|
};
|
21
|
-
const getAuthConfig =
|
21
|
+
const getAuthConfig = fp.prop("config.auth");
|
22
22
|
const createAuthorizeMiddleware = (strapi) => async (ctx, next) => {
|
23
23
|
const { auth, route } = ctx.state;
|
24
24
|
const authService = strapi.get("auth");
|
@@ -43,7 +43,7 @@ const createAuthenticateMiddleware = (strapi) => async (ctx, next) => {
|
|
43
43
|
};
|
44
44
|
const returnBodyMiddleware = async (ctx, next) => {
|
45
45
|
const values = await next();
|
46
|
-
if (
|
46
|
+
if (fp.isNil(ctx.body) && !fp.isNil(values)) {
|
47
47
|
ctx.body = values;
|
48
48
|
}
|
49
49
|
};
|
@@ -63,7 +63,7 @@ const createEndpointComposer = (strapi) => {
|
|
63
63
|
policy.createPolicicesMiddleware(route, strapi),
|
64
64
|
...middlewares,
|
65
65
|
returnBodyMiddleware,
|
66
|
-
...
|
66
|
+
...fp.castArray(action)
|
67
67
|
]);
|
68
68
|
router[method](path, routeHandler);
|
69
69
|
} catch (error) {
|
@@ -101,7 +101,7 @@ const getAction = (route, strapi) => {
|
|
101
101
|
if (Array.isArray(handler) || typeof handler === "function") {
|
102
102
|
return handler;
|
103
103
|
}
|
104
|
-
const { controllerName, actionName } = extractHandlerParts(
|
104
|
+
const { controllerName, actionName } = extractHandlerParts(fp.trim(handler));
|
105
105
|
const controller = getController(controllerName, { pluginName, apiName, type }, strapi);
|
106
106
|
if (typeof controller[actionName] !== "function") {
|
107
107
|
throw new Error(`Handler not found "${handler}"`);
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"compose-endpoint.js","sources":["../../../src/services/server/compose-endpoint.ts"],"sourcesContent":["import { toLower, castArray, trim, prop, isNil } from 'lodash/fp';\nimport type { Core, UID } from '@strapi/types';\nimport { errors } from '@strapi/utils';\nimport Router from '@koa/router';\n\nimport compose from 'koa-compose';\nimport { resolveRouteMiddlewares } from './middleware';\nimport { createPolicicesMiddleware } from './policy';\n\nconst getMethod = (route: Core.Route) => {\n return trim(toLower(route.method)) as Lowercase<Core.Route['method']>;\n};\n\nconst getPath = (route: Core.Route) => trim(route.path);\n\nconst createRouteInfoMiddleware =\n (routeInfo: Core.Route): Core.MiddlewareHandler =>\n (ctx, next) => {\n const route = {\n ...routeInfo,\n config: routeInfo.config || {},\n };\n\n ctx.state.route = route;\n return next();\n };\n\nconst getAuthConfig = prop('config.auth');\n\nconst createAuthorizeMiddleware =\n (strapi: Core.Strapi): Core.MiddlewareHandler =>\n async (ctx, next) => {\n const { auth, route } = ctx.state;\n\n const authService = strapi.get('auth');\n\n try {\n await authService.verify(auth, getAuthConfig(route));\n\n return await next();\n } catch (error) {\n if (error instanceof errors.UnauthorizedError) {\n return ctx.unauthorized();\n }\n\n if (error instanceof errors.ForbiddenError) {\n // allow PolicyError as an exception to throw a publicly visible message in the API\n if (error instanceof errors.PolicyError) {\n throw error;\n }\n return ctx.forbidden();\n }\n\n throw error;\n }\n };\n\nconst createAuthenticateMiddleware =\n (strapi: Core.Strapi): Core.MiddlewareHandler =>\n async (ctx, next) => {\n return strapi.get('auth').authenticate(ctx, next);\n };\n\nconst returnBodyMiddleware: Core.MiddlewareHandler = async (ctx, next) => {\n const values = await next();\n\n if (isNil(ctx.body) && !isNil(values)) {\n ctx.body = values;\n }\n};\n\nexport default (strapi: Core.Strapi) => {\n const authenticate = createAuthenticateMiddleware(strapi);\n const authorize = createAuthorizeMiddleware(strapi);\n\n return (route: Core.Route, { router }: { router: Router }) => {\n try {\n const method = getMethod(route);\n const path = getPath(route);\n\n const middlewares = resolveRouteMiddlewares(route, strapi);\n\n const action = getAction(route, strapi);\n\n const routeHandler = compose([\n createRouteInfoMiddleware(route),\n authenticate,\n authorize,\n createPolicicesMiddleware(route, strapi),\n ...middlewares,\n returnBodyMiddleware,\n ...castArray(action),\n ]);\n\n router[method](path, routeHandler);\n } catch (error) {\n if (error instanceof Error) {\n error.message = `Error creating endpoint ${route.method} ${route.path}: ${error.message}`;\n }\n\n throw error;\n }\n };\n};\n\nconst getController = (\n name: string,\n { pluginName, apiName }: Core.RouteInfo,\n strapi: Core.Strapi\n) => {\n let ctrl: Core.Controller | undefined;\n\n if (pluginName) {\n if (pluginName === 'admin') {\n ctrl = strapi.controller(`admin::${name}`);\n } else {\n ctrl = strapi.plugin(pluginName).controller(name);\n }\n } else if (apiName) {\n ctrl = strapi.controller(`api::${apiName}.${name}`);\n }\n\n if (!ctrl) {\n return strapi.controller(name as UID.Controller);\n }\n\n return ctrl;\n};\n\nconst extractHandlerParts = (name: string) => {\n const controllerName = name.slice(0, name.lastIndexOf('.'));\n const actionName = name.slice(name.lastIndexOf('.') + 1);\n\n return { controllerName, actionName };\n};\n\nconst getAction = (route: Core.Route, strapi: Core.Strapi) => {\n const { handler, info } = route;\n const { pluginName, apiName, type } = info ?? {};\n\n if (Array.isArray(handler) || typeof handler === 'function') {\n return handler;\n }\n\n const { controllerName, actionName } = extractHandlerParts(trim(handler));\n\n const controller = getController(controllerName, { pluginName, apiName, type }, strapi);\n\n if (typeof controller[actionName] !== 'function') {\n throw new Error(`Handler not found \"${handler}\"`);\n }\n\n if (Symbol.for('__type__') in controller[actionName]) {\n (controller[actionName] as any)[Symbol.for('__type__')].push(type);\n } else {\n (controller[actionName] as any)[Symbol.for('__type__')] = [type];\n }\n\n return controller[actionName].bind(controller);\n};\n"],"names":["trim","toLower","prop","errors","isNil","resolveRouteMiddlewares","compose","createPolicicesMiddleware","castArray"],"mappings":";;;;;;;;AASA,MAAM,YAAY,CAAC,UAAsB;AACvC,SAAOA,
|
1
|
+
{"version":3,"file":"compose-endpoint.js","sources":["../../../src/services/server/compose-endpoint.ts"],"sourcesContent":["import { toLower, castArray, trim, prop, isNil } from 'lodash/fp';\nimport type { Core, UID } from '@strapi/types';\nimport { errors } from '@strapi/utils';\nimport Router from '@koa/router';\n\nimport compose from 'koa-compose';\nimport { resolveRouteMiddlewares } from './middleware';\nimport { createPolicicesMiddleware } from './policy';\n\nconst getMethod = (route: Core.Route) => {\n return trim(toLower(route.method)) as Lowercase<Core.Route['method']>;\n};\n\nconst getPath = (route: Core.Route) => trim(route.path);\n\nconst createRouteInfoMiddleware =\n (routeInfo: Core.Route): Core.MiddlewareHandler =>\n (ctx, next) => {\n const route = {\n ...routeInfo,\n config: routeInfo.config || {},\n };\n\n ctx.state.route = route;\n return next();\n };\n\nconst getAuthConfig = prop('config.auth');\n\nconst createAuthorizeMiddleware =\n (strapi: Core.Strapi): Core.MiddlewareHandler =>\n async (ctx, next) => {\n const { auth, route } = ctx.state;\n\n const authService = strapi.get('auth');\n\n try {\n await authService.verify(auth, getAuthConfig(route));\n\n return await next();\n } catch (error) {\n if (error instanceof errors.UnauthorizedError) {\n return ctx.unauthorized();\n }\n\n if (error instanceof errors.ForbiddenError) {\n // allow PolicyError as an exception to throw a publicly visible message in the API\n if (error instanceof errors.PolicyError) {\n throw error;\n }\n return ctx.forbidden();\n }\n\n throw error;\n }\n };\n\nconst createAuthenticateMiddleware =\n (strapi: Core.Strapi): Core.MiddlewareHandler =>\n async (ctx, next) => {\n return strapi.get('auth').authenticate(ctx, next);\n };\n\nconst returnBodyMiddleware: Core.MiddlewareHandler = async (ctx, next) => {\n const values = await next();\n\n if (isNil(ctx.body) && !isNil(values)) {\n ctx.body = values;\n }\n};\n\nexport default (strapi: Core.Strapi) => {\n const authenticate = createAuthenticateMiddleware(strapi);\n const authorize = createAuthorizeMiddleware(strapi);\n\n return (route: Core.Route, { router }: { router: Router }) => {\n try {\n const method = getMethod(route);\n const path = getPath(route);\n\n const middlewares = resolveRouteMiddlewares(route, strapi);\n\n const action = getAction(route, strapi);\n\n const routeHandler = compose([\n createRouteInfoMiddleware(route),\n authenticate,\n authorize,\n createPolicicesMiddleware(route, strapi),\n ...middlewares,\n returnBodyMiddleware,\n ...castArray(action),\n ]);\n\n router[method](path, routeHandler);\n } catch (error) {\n if (error instanceof Error) {\n error.message = `Error creating endpoint ${route.method} ${route.path}: ${error.message}`;\n }\n\n throw error;\n }\n };\n};\n\nconst getController = (\n name: string,\n { pluginName, apiName }: Core.RouteInfo,\n strapi: Core.Strapi\n) => {\n let ctrl: Core.Controller | undefined;\n\n if (pluginName) {\n if (pluginName === 'admin') {\n ctrl = strapi.controller(`admin::${name}`);\n } else {\n ctrl = strapi.plugin(pluginName).controller(name);\n }\n } else if (apiName) {\n ctrl = strapi.controller(`api::${apiName}.${name}`);\n }\n\n if (!ctrl) {\n return strapi.controller(name as UID.Controller);\n }\n\n return ctrl;\n};\n\nconst extractHandlerParts = (name: string) => {\n const controllerName = name.slice(0, name.lastIndexOf('.'));\n const actionName = name.slice(name.lastIndexOf('.') + 1);\n\n return { controllerName, actionName };\n};\n\nconst getAction = (route: Core.Route, strapi: Core.Strapi) => {\n const { handler, info } = route;\n const { pluginName, apiName, type } = info ?? {};\n\n if (Array.isArray(handler) || typeof handler === 'function') {\n return handler;\n }\n\n const { controllerName, actionName } = extractHandlerParts(trim(handler));\n\n const controller = getController(controllerName, { pluginName, apiName, type }, strapi);\n\n if (typeof controller[actionName] !== 'function') {\n throw new Error(`Handler not found \"${handler}\"`);\n }\n\n if (Symbol.for('__type__') in controller[actionName]) {\n (controller[actionName] as any)[Symbol.for('__type__')].push(type);\n } else {\n (controller[actionName] as any)[Symbol.for('__type__')] = [type];\n }\n\n return controller[actionName].bind(controller);\n};\n"],"names":["trim","toLower","prop","errors","isNil","resolveRouteMiddlewares","compose","createPolicicesMiddleware","castArray"],"mappings":";;;;;;;;AASA,MAAM,YAAY,CAAC,UAAsB;AACvC,SAAOA,GAAK,KAAAC,GAAA,QAAQ,MAAM,MAAM,CAAC;AACnC;AAEA,MAAM,UAAU,CAAC,UAAsBD,GAA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A,EACT;AAEA,QAAM,EAAE,gBAAgB,eAAe,oBAAoBR,GAAA,KAAK,OAAO,CAAC;AAElE,QAAA,aAAa,cAAc,gBAAgB,EAAE,YAAY,SAAS,QAAQ,MAAM;AAEtF,MAAI,OAAO,WAAW,UAAU,MAAM,YAAY;AAChD,UAAM,IAAI,MAAM,sBAAsB,OAAO,GAAG;AAAA,EAClD;AAEA,MAAI,OAAO,IAAI,UAAU,KAAK,WAAW,UAAU,GAAG;AACnD,eAAW,UAAU,EAAU,OAAO,IAAI,UAAU,CAAC,EAAE,KAAK,IAAI;AAAA,EAAA,OAC5D;AACJ,eAAW,UAAU,EAAU,OAAO,IAAI,UAAU,CAAC,IAAI,CAAC,IAAI;AAAA,EACjE;AAEA,SAAO,WAAW,UAAU,EAAE,KAAK,UAAU;AAC/C;;"}
|
@@ -1,5 +1,5 @@
|
|
1
1
|
"use strict";
|
2
|
-
const
|
2
|
+
const fp = require("lodash/fp");
|
3
3
|
const Koa = require("koa");
|
4
4
|
const createError = require("http-errors");
|
5
5
|
const delegate = require("delegates");
|
@@ -14,7 +14,7 @@ const addCustomMethods = (app) => {
|
|
14
14
|
const delegator = delegate__default.default(app.context, "response");
|
15
15
|
statuses__default.default.codes.filter((code) => code >= 400 && code < 600).forEach((code) => {
|
16
16
|
const name = statuses__default.default(code);
|
17
|
-
const camelCasedName =
|
17
|
+
const camelCasedName = fp.camelCase(name);
|
18
18
|
app.response[camelCasedName] = function responseCode(message = name, details = {}) {
|
19
19
|
const httpError = createError__default.default(code, message, { details });
|
20
20
|
const { status, body } = errors.formatHttpError(httpError);
|
@@ -32,7 +32,7 @@ const addCustomMethods = (app) => {
|
|
32
32
|
this.body = data;
|
33
33
|
};
|
34
34
|
app.response.deleted = function deleted(data) {
|
35
|
-
if (
|
35
|
+
if (fp.isNil(data)) {
|
36
36
|
this.status = 204;
|
37
37
|
} else {
|
38
38
|
this.status = 200;
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"koa.js","sources":["../../../src/services/server/koa.ts"],"sourcesContent":["import { isNil, camelCase } from 'lodash/fp';\nimport Koa from 'koa';\nimport createError from 'http-errors';\nimport delegate from 'delegates';\nimport statuses from 'statuses';\nimport { formatHttpError } from '../errors';\n\ndeclare module 'koa' {\n interface BaseResponse {\n send: (data: any, status?: number) => void;\n created: (data: any) => void;\n deleted: (data: any) => void;\n _explicitStatus: boolean;\n [key: string]: (message: string, details?: unknown) => void;\n }\n}\n\nconst addCustomMethods = (app: Koa) => {\n const delegator = delegate(app.context, 'response');\n\n /* errors */\n statuses.codes\n .filter((code) => code >= 400 && code < 600)\n .forEach((code) => {\n const name = statuses(code);\n\n const camelCasedName = camelCase(name);\n app.response[camelCasedName] = function responseCode(message = name, details = {}) {\n const httpError = createError(code, message, { details });\n const { status, body } = formatHttpError(httpError);\n this.status = status;\n this.body = body;\n };\n delegator.method(camelCasedName);\n });\n\n /* send, created, deleted */\n app.response.send = function send(data, status = 200) {\n this.status = status;\n this.body = data;\n };\n\n app.response.created = function created(data) {\n this.status = 201;\n this.body = data;\n };\n\n app.response.deleted = function deleted(data) {\n if (isNil(data)) {\n this.status = 204;\n } else {\n this.status = 200;\n this.body = data;\n }\n };\n\n delegator.method('send').method('created').method('deleted');\n\n return app;\n};\n\nconst createKoaApp = ({ proxy, keys }: { proxy: boolean; keys: string[] }) => {\n const app = new Koa({ proxy });\n app.keys = keys;\n\n addCustomMethods(app);\n\n return app;\n};\n\nexport default createKoaApp;\n"],"names":["delegate","statuses","camelCase","createError","formatHttpError","isNil","Koa"],"mappings":";;;;;;;;;;;;AAiBA,MAAM,mBAAmB,CAAC,QAAa;AACrC,QAAM,YAAYA,kBAAA,QAAS,IAAI,SAAS,UAAU;AAGzCC,oBAAAA,QAAA,MACN,OAAO,CAAC,SAAS,QAAQ,OAAO,OAAO,GAAG,EAC1C,QAAQ,CAAC,SAAS;AACX,UAAA,OAAOA,0BAAS,IAAI;AAEpB,UAAA,iBAAiBC,
|
1
|
+
{"version":3,"file":"koa.js","sources":["../../../src/services/server/koa.ts"],"sourcesContent":["import { isNil, camelCase } from 'lodash/fp';\nimport Koa from 'koa';\nimport createError from 'http-errors';\nimport delegate from 'delegates';\nimport statuses from 'statuses';\nimport { formatHttpError } from '../errors';\n\ndeclare module 'koa' {\n interface BaseResponse {\n send: (data: any, status?: number) => void;\n created: (data: any) => void;\n deleted: (data: any) => void;\n _explicitStatus: boolean;\n [key: string]: (message: string, details?: unknown) => void;\n }\n}\n\nconst addCustomMethods = (app: Koa) => {\n const delegator = delegate(app.context, 'response');\n\n /* errors */\n statuses.codes\n .filter((code) => code >= 400 && code < 600)\n .forEach((code) => {\n const name = statuses(code);\n\n const camelCasedName = camelCase(name);\n app.response[camelCasedName] = function responseCode(message = name, details = {}) {\n const httpError = createError(code, message, { details });\n const { status, body } = formatHttpError(httpError);\n this.status = status;\n this.body = body;\n };\n delegator.method(camelCasedName);\n });\n\n /* send, created, deleted */\n app.response.send = function send(data, status = 200) {\n this.status = status;\n this.body = data;\n };\n\n app.response.created = function created(data) {\n this.status = 201;\n this.body = data;\n };\n\n app.response.deleted = function deleted(data) {\n if (isNil(data)) {\n this.status = 204;\n } else {\n this.status = 200;\n this.body = data;\n }\n };\n\n delegator.method('send').method('created').method('deleted');\n\n return app;\n};\n\nconst createKoaApp = ({ proxy, keys }: { proxy: boolean; keys: string[] }) => {\n const app = new Koa({ proxy });\n app.keys = keys;\n\n addCustomMethods(app);\n\n return app;\n};\n\nexport default createKoaApp;\n"],"names":["delegate","statuses","camelCase","createError","formatHttpError","isNil","Koa"],"mappings":";;;;;;;;;;;;AAiBA,MAAM,mBAAmB,CAAC,QAAa;AACrC,QAAM,YAAYA,kBAAA,QAAS,IAAI,SAAS,UAAU;AAGzCC,oBAAAA,QAAA,MACN,OAAO,CAAC,SAAS,QAAQ,OAAO,OAAO,GAAG,EAC1C,QAAQ,CAAC,SAAS;AACX,UAAA,OAAOA,0BAAS,IAAI;AAEpB,UAAA,iBAAiBC,aAAU,IAAI;AACjC,QAAA,SAAS,cAAc,IAAI,SAAS,aAAa,UAAU,MAAM,UAAU,IAAI;AACjF,YAAM,YAAYC,qBAAAA,QAAY,MAAM,SAAS,EAAE,SAAS;AACxD,YAAM,EAAE,QAAQ,KAAK,IAAIC,uBAAgB,SAAS;AAClD,WAAK,SAAS;AACd,WAAK,OAAO;AAAA,IAAA;AAEd,cAAU,OAAO,cAAc;AAAA,EAAA,CAChC;AAGH,MAAI,SAAS,OAAO,SAAS,KAAK,MAAM,SAAS,KAAK;AACpD,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EAAA;AAGd,MAAI,SAAS,UAAU,SAAS,QAAQ,MAAM;AAC5C,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EAAA;AAGd,MAAI,SAAS,UAAU,SAAS,QAAQ,MAAM;AACxC,QAAAC,GAAAA,MAAM,IAAI,GAAG;AACf,WAAK,SAAS;AAAA,IAAA,OACT;AACL,WAAK,SAAS;AACd,WAAK,OAAO;AAAA,IACd;AAAA,EAAA;AAGF,YAAU,OAAO,MAAM,EAAE,OAAO,SAAS,EAAE,OAAO,SAAS;AAEpD,SAAA;AACT;AAEA,MAAM,eAAe,CAAC,EAAE,OAAO,WAA+C;AAC5E,QAAM,MAAM,IAAIC,aAAAA,QAAI,EAAE,MAAO,CAAA;AAC7B,MAAI,OAAO;AAEX,mBAAiB,GAAG;AAEb,SAAA;AACT;;"}
|
@@ -1,7 +1,7 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
3
3
|
const path = require("path");
|
4
|
-
const
|
4
|
+
const fp = require("lodash/fp");
|
5
5
|
const strapiUtils = require("@strapi/utils");
|
6
6
|
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
|
7
7
|
const path__default = /* @__PURE__ */ _interopDefault(path);
|
@@ -16,13 +16,13 @@ const instantiateMiddleware = (middlewareFactory, name, config, strapi) => {
|
|
16
16
|
};
|
17
17
|
const resolveRouteMiddlewares = (route, strapi) => {
|
18
18
|
const middlewaresConfig = route?.config?.middlewares ?? [];
|
19
|
-
if (!
|
19
|
+
if (!fp.isArray(middlewaresConfig)) {
|
20
20
|
throw new Error("Route middlewares config must be an array");
|
21
21
|
}
|
22
22
|
const middlewares = resolveMiddlewares(middlewaresConfig, strapi);
|
23
23
|
return middlewares.map(({ handler }) => handler);
|
24
24
|
};
|
25
|
-
const dummyMiddleware = (
|
25
|
+
const dummyMiddleware = (_, next) => next();
|
26
26
|
const resolveMiddlewares = (config, strapi) => {
|
27
27
|
const middlewares = [];
|
28
28
|
for (const item of config) {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"middleware.js","sources":["../../../src/services/server/middleware.ts"],"sourcesContent":["import path from 'path';\nimport { isArray } from 'lodash/fp';\nimport { importDefault } from '@strapi/utils';\nimport type { Core } from '@strapi/types';\n\nconst instantiateMiddleware = (\n middlewareFactory: Core.MiddlewareFactory,\n name: string,\n config: unknown,\n strapi: Core.Strapi\n) => {\n try {\n return middlewareFactory(config, { strapi });\n } catch (e) {\n if (e instanceof Error) {\n throw new Error(`Middleware \"${name}\": ${e.message}`);\n }\n }\n};\n\nconst resolveRouteMiddlewares = (route: Core.Route, strapi: Core.Strapi) => {\n const middlewaresConfig = route?.config?.middlewares ?? [];\n\n if (!isArray(middlewaresConfig)) {\n throw new Error('Route middlewares config must be an array');\n }\n\n const middlewares = resolveMiddlewares(middlewaresConfig, strapi);\n\n return middlewares.map(({ handler }) => handler);\n};\n\nconst dummyMiddleware: Core.MiddlewareHandler = (_, next) => next();\n\n/**\n * Initialize every configured middlewares\n */\nconst resolveMiddlewares = (\n config: Array<Core.MiddlewareName | Core.MiddlewareConfig | Core.MiddlewareHandler>,\n strapi: Core.Strapi\n) => {\n const middlewares: {\n name: string | null;\n handler: Core.MiddlewareHandler;\n }[] = [];\n\n for (const item of config) {\n if (typeof item === 'function') {\n middlewares.push({\n name: null,\n handler: item,\n });\n\n continue;\n }\n\n if (typeof item === 'string') {\n const middlewareFactory = strapi.middleware(item);\n\n if (!middlewareFactory) {\n throw new Error(`Middleware ${item} not found.`);\n }\n\n middlewares.push({\n name: item,\n handler: instantiateMiddleware(middlewareFactory, item, {}, strapi) ?? dummyMiddleware,\n });\n\n continue;\n }\n\n if (typeof item === 'object' && item !== null) {\n const { name, resolve, config = {} } = item;\n\n if (name) {\n const middlewareFactory = strapi.middleware(name);\n middlewares.push({\n name,\n handler:\n instantiateMiddleware(middlewareFactory, name, config, strapi) ?? dummyMiddleware,\n });\n\n continue;\n }\n\n if (resolve) {\n const resolvedMiddlewareFactory = resolveCustomMiddleware(resolve, strapi);\n middlewares.push({\n name: resolve,\n handler:\n instantiateMiddleware(resolvedMiddlewareFactory, resolve, config, strapi) ??\n dummyMiddleware,\n });\n\n continue;\n }\n\n throw new Error('Invalid middleware configuration. Missing name or resolve properties.');\n }\n\n throw new Error(\n 'Middleware config must either be a string or an object {name?: string, resolve?: string, config: any}.'\n );\n }\n\n return middlewares;\n};\n\n/**\n * Resolve middleware from package name or path\n */\nconst resolveCustomMiddleware = (resolve: string, strapi: Core.Strapi) => {\n let modulePath;\n\n try {\n modulePath = require.resolve(resolve);\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'MODULE_NOT_FOUND') {\n modulePath = path.resolve(strapi.dirs.dist.root, resolve);\n } else {\n throw error;\n }\n }\n\n try {\n return importDefault(modulePath);\n } catch (err) {\n throw new Error(`Could not load middleware \"${modulePath}\".`);\n }\n};\n\nexport { resolveRouteMiddlewares, resolveMiddlewares };\n"],"names":["isArray","
|
1
|
+
{"version":3,"file":"middleware.js","sources":["../../../src/services/server/middleware.ts"],"sourcesContent":["import path from 'path';\nimport { isArray } from 'lodash/fp';\nimport { importDefault } from '@strapi/utils';\nimport type { Core } from '@strapi/types';\n\nconst instantiateMiddleware = (\n middlewareFactory: Core.MiddlewareFactory,\n name: string,\n config: unknown,\n strapi: Core.Strapi\n) => {\n try {\n return middlewareFactory(config, { strapi });\n } catch (e) {\n if (e instanceof Error) {\n throw new Error(`Middleware \"${name}\": ${e.message}`);\n }\n }\n};\n\nconst resolveRouteMiddlewares = (route: Core.Route, strapi: Core.Strapi) => {\n const middlewaresConfig = route?.config?.middlewares ?? [];\n\n if (!isArray(middlewaresConfig)) {\n throw new Error('Route middlewares config must be an array');\n }\n\n const middlewares = resolveMiddlewares(middlewaresConfig, strapi);\n\n return middlewares.map(({ handler }) => handler);\n};\n\nconst dummyMiddleware: Core.MiddlewareHandler = (_, next) => next();\n\n/**\n * Initialize every configured middlewares\n */\nconst resolveMiddlewares = (\n config: Array<Core.MiddlewareName | Core.MiddlewareConfig | Core.MiddlewareHandler>,\n strapi: Core.Strapi\n) => {\n const middlewares: {\n name: string | null;\n handler: Core.MiddlewareHandler;\n }[] = [];\n\n for (const item of config) {\n if (typeof item === 'function') {\n middlewares.push({\n name: null,\n handler: item,\n });\n\n continue;\n }\n\n if (typeof item === 'string') {\n const middlewareFactory = strapi.middleware(item);\n\n if (!middlewareFactory) {\n throw new Error(`Middleware ${item} not found.`);\n }\n\n middlewares.push({\n name: item,\n handler: instantiateMiddleware(middlewareFactory, item, {}, strapi) ?? dummyMiddleware,\n });\n\n continue;\n }\n\n if (typeof item === 'object' && item !== null) {\n const { name, resolve, config = {} } = item;\n\n if (name) {\n const middlewareFactory = strapi.middleware(name);\n middlewares.push({\n name,\n handler:\n instantiateMiddleware(middlewareFactory, name, config, strapi) ?? dummyMiddleware,\n });\n\n continue;\n }\n\n if (resolve) {\n const resolvedMiddlewareFactory = resolveCustomMiddleware(resolve, strapi);\n middlewares.push({\n name: resolve,\n handler:\n instantiateMiddleware(resolvedMiddlewareFactory, resolve, config, strapi) ??\n dummyMiddleware,\n });\n\n continue;\n }\n\n throw new Error('Invalid middleware configuration. Missing name or resolve properties.');\n }\n\n throw new Error(\n 'Middleware config must either be a string or an object {name?: string, resolve?: string, config: any}.'\n );\n }\n\n return middlewares;\n};\n\n/**\n * Resolve middleware from package name or path\n */\nconst resolveCustomMiddleware = (resolve: string, strapi: Core.Strapi) => {\n let modulePath;\n\n try {\n modulePath = require.resolve(resolve);\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'MODULE_NOT_FOUND') {\n modulePath = path.resolve(strapi.dirs.dist.root, resolve);\n } else {\n throw error;\n }\n }\n\n try {\n return importDefault(modulePath);\n } catch (err) {\n throw new Error(`Could not load middleware \"${modulePath}\".`);\n }\n};\n\nexport { resolveRouteMiddlewares, resolveMiddlewares };\n"],"names":["isArray","config","path","importDefault"],"mappings":";;;;;;;AAKA,MAAM,wBAAwB,CAC5B,mBACA,MACA,QACA,WACG;AACC,MAAA;AACF,WAAO,kBAAkB,QAAQ,EAAE,OAAQ,CAAA;AAAA,WACpC,GAAG;AACV,QAAI,aAAa,OAAO;AACtB,YAAM,IAAI,MAAM,eAAe,IAAI,MAAM,EAAE,OAAO,EAAE;AAAA,IACtD;AAAA,EACF;AACF;AAEM,MAAA,0BAA0B,CAAC,OAAmB,WAAwB;AAC1E,QAAM,oBAAoB,OAAO,QAAQ,eAAe,CAAA;AAEpD,MAAA,CAACA,GAAAA,QAAQ,iBAAiB,GAAG;AACzB,UAAA,IAAI,MAAM,2CAA2C;AAAA,EAC7D;AAEM,QAAA,cAAc,mBAAmB,mBAAmB,MAAM;AAEhE,SAAO,YAAY,IAAI,CAAC,EAAE,cAAc,OAAO;AACjD;AAEA,MAAM,kBAA0C,CAAC,GAAG,SAAS,KAAK;AAK5D,MAAA,qBAAqB,CACzB,QACA,WACG;AACH,QAAM,cAGA,CAAA;AAEN,aAAW,QAAQ,QAAQ;AACrB,QAAA,OAAO,SAAS,YAAY;AAC9B,kBAAY,KAAK;AAAA,QACf,MAAM;AAAA,QACN,SAAS;AAAA,MAAA,CACV;AAED;AAAA,IACF;AAEI,QAAA,OAAO,SAAS,UAAU;AACtB,YAAA,oBAAoB,OAAO,WAAW,IAAI;AAEhD,UAAI,CAAC,mBAAmB;AACtB,cAAM,IAAI,MAAM,cAAc,IAAI,aA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value: "Module" });
|
3
3
|
const Router = require("@koa/router");
|
4
|
-
const
|
4
|
+
const fp = require("lodash/fp");
|
5
5
|
const strapiUtils = require("@strapi/utils");
|
6
6
|
const composeEndpoint = require("./compose-endpoint.js");
|
7
7
|
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
|
@@ -76,7 +76,7 @@ const createRouteManager = (strapi, opts = {}) => {
|
|
76
76
|
} else if (routes.routes) {
|
77
77
|
const subRouter = new Router__default.default({ prefix: routes.prefix });
|
78
78
|
routes.routes.forEach((route) => {
|
79
|
-
const hasPrefix =
|
79
|
+
const hasPrefix = fp.has("prefix", route.config);
|
80
80
|
createRoute(route, hasPrefix ? router : subRouter);
|
81
81
|
});
|
82
82
|
return router.use(subRouter.routes(), subRouter.allowedMethods());
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"routing.js","sources":["../../../src/services/server/routing.ts"],"sourcesContent":["import Router from '@koa/router';\nimport { has } from 'lodash/fp';\nimport { yup } from '@strapi/utils';\nimport type { Core } from '@strapi/types';\n\nimport createEndpointComposer from './compose-endpoint';\n\nconst policyOrMiddlewareSchema = yup.lazy((value) => {\n if (typeof value === 'string') {\n return yup.string().required();\n }\n\n if (typeof value === 'function') {\n return yup.mixed().isFunction();\n }\n\n return yup.object({\n name: yup.string().required(),\n options: yup.object().notRequired(), // any options\n });\n});\n\nconst routeSchema = yup.object({\n method: yup.string().oneOf(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'ALL']).required(),\n path: yup.string().required(),\n handler: yup.lazy((value) => {\n if (typeof value === 'string') {\n return yup.string().required();\n }\n\n if (Array.isArray(value)) {\n return yup.array().required();\n }\n\n return yup.mixed().isFunction().required();\n }),\n config: yup\n .object({\n auth: yup.lazy((value) => {\n if (value === false) {\n return yup.boolean().required();\n }\n\n return yup.object({\n scope: yup.array().of(yup.string()).required(),\n });\n }),\n policies: yup\n .array()\n // FIXME: fixed in yup v1\n .of(policyOrMiddlewareSchema as any)\n .notRequired(),\n middlewares: yup\n .array()\n // FIXME: fixed in yup v1\n .of(policyOrMiddlewareSchema as any)\n .notRequired(),\n })\n .notRequired(),\n});\n\nconst validateRouteConfig = (routeConfig: Core.RouteInput) => {\n try {\n return routeSchema.validateSync(routeConfig, {\n strict: true,\n abortEarly: false,\n stripUnknown: true,\n });\n } catch (error) {\n if (error instanceof yup.ValidationError) {\n throw new Error(`Invalid route config ${error.message}`);\n }\n }\n};\n\nconst createRouteManager = (strapi: Core.Strapi, opts: { type?: string } = {}) => {\n const { type } = opts;\n\n const composeEndpoint = createEndpointComposer(strapi);\n\n const createRoute = (route: Core.RouteInput, router: Router) => {\n validateRouteConfig(route);\n\n // NOTE: the router type is used to tag controller actions and for authentication / authorization so we need to pass this info down to the route level\n const routeWithInfo = Object.assign(route, {\n info: {\n ...(route.info ?? {}),\n type: type || 'api',\n },\n });\n\n composeEndpoint(routeWithInfo, { router });\n };\n\n const addRoutes = (routes: Core.Router | Core.RouteInput[], router: Router) => {\n if (Array.isArray(routes)) {\n routes.forEach((route) => createRoute(route, router));\n } else if (routes.routes) {\n const subRouter = new Router({ prefix: routes.prefix });\n\n routes.routes.forEach((route) => {\n const hasPrefix = has('prefix', route.config);\n createRoute(route, hasPrefix ? router : subRouter);\n });\n\n return router.use(subRouter.routes(), subRouter.allowedMethods());\n }\n };\n\n return {\n addRoutes,\n };\n};\n\nexport { validateRouteConfig, createRouteManager };\n"],"names":["yup","composeEndpoint","createEndpointComposer","Router","has"],"mappings":";;;;;;;;AAOA,MAAM,2BAA2BA,YAAA,IAAI,KAAK,CAAC,UAAU;AAC/C,MAAA,OAAO,UAAU,UAAU;AACtB,WAAAA,gBAAI,SAAS;EACtB;AAEI,MAAA,OAAO,UAAU,YAAY;AACxB,WAAAA,gBAAI,QAAQ;EACrB;AAEA,SAAOA,YAAAA,IAAI,OAAO;AAAA,IAChB,MAAMA,YAAA,IAAI,OAAO,EAAE,SAAS;AAAA,IAC5B,SAASA,YAAA,IAAI,OAAO,EAAE,YAAY;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BAAqB,CAAC,QAAqB,OAA0B,OAAO;AAC1E,QAAA,EAAE,KAAS,IAAA;AAEX,QAAAC,oBAAkBC,gBAAuB,MAAM;AAE/C,QAAA,cAAc,CAAC,OAAwB,WAAmB;AAC9D,wBAAoB,KAAK;AAGnB,UAAA,gBAAgB,OAAO,OAAO,OAAO;AAAA,MACzC,MAAM;AAAA,QACJ,GAAI,MAAM,QAAQ,CAAC;AAAA,QACnB,MAAM,QAAQ;AAAA,MAChB;AAAA,IAAA,CACD;AAEeD,sBAAA,eAAe,EAAE,OAAA,CAAQ;AAAA,EAAA;AAGrC,QAAA,YAAY,CAAC,QAAyC,WAAmB;AACzE,QAAA,MAAM,QAAQ,MAAM,GAAG;AACzB,aAAO,QAAQ,CAAC,UAAU,YAAY,OAAO,MAAM,CAAC;AAAA,IAAA,WAC3C,OAAO,QAAQ;AACxB,YAAM,YAAY,IAAIE,wBAAO,EAAE,QAAQ,OAAO,QAAQ;AAE/C,aAAA,OAAO,QAAQ,CAAC,UAAU;AAC/B,cAAM,YAAYC,
|
1
|
+
{"version":3,"file":"routing.js","sources":["../../../src/services/server/routing.ts"],"sourcesContent":["import Router from '@koa/router';\nimport { has } from 'lodash/fp';\nimport { yup } from '@strapi/utils';\nimport type { Core } from '@strapi/types';\n\nimport createEndpointComposer from './compose-endpoint';\n\nconst policyOrMiddlewareSchema = yup.lazy((value) => {\n if (typeof value === 'string') {\n return yup.string().required();\n }\n\n if (typeof value === 'function') {\n return yup.mixed().isFunction();\n }\n\n return yup.object({\n name: yup.string().required(),\n options: yup.object().notRequired(), // any options\n });\n});\n\nconst routeSchema = yup.object({\n method: yup.string().oneOf(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'ALL']).required(),\n path: yup.string().required(),\n handler: yup.lazy((value) => {\n if (typeof value === 'string') {\n return yup.string().required();\n }\n\n if (Array.isArray(value)) {\n return yup.array().required();\n }\n\n return yup.mixed().isFunction().required();\n }),\n config: yup\n .object({\n auth: yup.lazy((value) => {\n if (value === false) {\n return yup.boolean().required();\n }\n\n return yup.object({\n scope: yup.array().of(yup.string()).required(),\n });\n }),\n policies: yup\n .array()\n // FIXME: fixed in yup v1\n .of(policyOrMiddlewareSchema as any)\n .notRequired(),\n middlewares: yup\n .array()\n // FIXME: fixed in yup v1\n .of(policyOrMiddlewareSchema as any)\n .notRequired(),\n })\n .notRequired(),\n});\n\nconst validateRouteConfig = (routeConfig: Core.RouteInput) => {\n try {\n return routeSchema.validateSync(routeConfig, {\n strict: true,\n abortEarly: false,\n stripUnknown: true,\n });\n } catch (error) {\n if (error instanceof yup.ValidationError) {\n throw new Error(`Invalid route config ${error.message}`);\n }\n }\n};\n\nconst createRouteManager = (strapi: Core.Strapi, opts: { type?: string } = {}) => {\n const { type } = opts;\n\n const composeEndpoint = createEndpointComposer(strapi);\n\n const createRoute = (route: Core.RouteInput, router: Router) => {\n validateRouteConfig(route);\n\n // NOTE: the router type is used to tag controller actions and for authentication / authorization so we need to pass this info down to the route level\n const routeWithInfo = Object.assign(route, {\n info: {\n ...(route.info ?? {}),\n type: type || 'api',\n },\n });\n\n composeEndpoint(routeWithInfo, { router });\n };\n\n const addRoutes = (routes: Core.Router | Core.RouteInput[], router: Router) => {\n if (Array.isArray(routes)) {\n routes.forEach((route) => createRoute(route, router));\n } else if (routes.routes) {\n const subRouter = new Router({ prefix: routes.prefix });\n\n routes.routes.forEach((route) => {\n const hasPrefix = has('prefix', route.config);\n createRoute(route, hasPrefix ? router : subRouter);\n });\n\n return router.use(subRouter.routes(), subRouter.allowedMethods());\n }\n };\n\n return {\n addRoutes,\n };\n};\n\nexport { validateRouteConfig, createRouteManager };\n"],"names":["yup","composeEndpoint","createEndpointComposer","Router","has"],"mappings":";;;;;;;;AAOA,MAAM,2BAA2BA,YAAA,IAAI,KAAK,CAAC,UAAU;AAC/C,MAAA,OAAO,UAAU,UAAU;AACtB,WAAAA,gBAAI,SAAS;EACtB;AAEI,MAAA,OAAO,UAAU,YAAY;AACxB,WAAAA,gBA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ACf;AAAA,WACM,OAAO;AACV,QAAA,iBAAiBA,gBAAI,iBAAiB;AACxC,YAAM,IAAI,MAAM,wBAAwB,MAAM,OAAO,EAAE;AAAA,IACzD;AAAA,EACF;AACF;AAEA,MAAM,qBAAqB,CAAC,QAAqB,OAA0B,OAAO;AAC1E,QAAA,EAAE,KAAS,IAAA;AAEX,QAAAC,oBAAkBC,gBAAuB,MAAM;AAE/C,QAAA,cAAc,CAAC,OAAwB,WAAmB;AAC9D,wBAAoB,KAAK;AAGnB,UAAA,gBAAgB,OAAO,OAAO,OAAO;AAAA,MACzC,MAAM;AAAA,QACJ,GAAI,MAAM,QAAQ,CAAC;AAAA,QACnB,MAAM,QAAQ;AAAA,MAChB;AAAA,IAAA,CACD;AAEeD,sBAAA,eAAe,EAAE,OAAA,CAAQ;AAAA,EAAA;AAGrC,QAAA,YAAY,CAAC,QAAyC,WAAmB;AACzE,QAAA,MAAM,QAAQ,MAAM,GAAG;AACzB,aAAO,QAAQ,CAAC,UAAU,YAAY,OAAO,MAAM,CAAC;AAAA,IAAA,WAC3C,OAAO,QAAQ;AACxB,YAAM,YAAY,IAAIE,wBAAO,EAAE,QAAQ,OAAO,QAAQ;AAE/C,aAAA,OAAO,QAAQ,CAAC,UAAU;AAC/B,cAAM,YAAYC,GAAA,IAAI,UAAU,MAAM,MAAM;AAChC,oBAAA,OAAO,YAAY,SAAS,SAAS;AAAA,MAAA,CAClD;AAED,aAAO,OAAO,IAAI,UAAU,UAAU,UAAU,gBAAgB;AAAA,IAClE;AAAA,EAAA;AAGK,SAAA;AAAA,IACL;AAAA,EAAA;AAEJ;;;"}
|
@@ -1,11 +1,11 @@
|
|
1
1
|
"use strict";
|
2
|
-
const
|
2
|
+
const fp = require("lodash/fp");
|
3
3
|
const getNumberOfDynamicZones = () => {
|
4
4
|
const contentTypes = strapi.contentTypes;
|
5
|
-
return
|
6
|
-
|
7
|
-
|
8
|
-
|
5
|
+
return fp.pipe(
|
6
|
+
fp.map("attributes"),
|
7
|
+
fp.flatMap(fp.values),
|
8
|
+
fp.sumBy((item) => {
|
9
9
|
if (item.type === "dynamiczone") {
|
10
10
|
return 1;
|
11
11
|
}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"dynamic-zones.js","sources":["../../../src/services/utils/dynamic-zones.ts"],"sourcesContent":["import { map, values, sumBy, pipe, flatMap } from 'lodash/fp';\nimport type { Schema, UID } from '@strapi/types';\n\nconst getNumberOfDynamicZones = () => {\n const contentTypes: Record<UID.ContentType, Schema.ContentType> = strapi.contentTypes;\n\n return pipe(\n map('attributes'),\n flatMap(values),\n sumBy((item) => {\n if (item.type === 'dynamiczone') {\n return 1;\n }\n return 0;\n })\n )(contentTypes);\n};\n\nexport default getNumberOfDynamicZones;\n"],"names":["pipe","map","flatMap","values","sumBy"],"mappings":";;AAGA,MAAM,0BAA0B,MAAM;AACpC,QAAM,eAA4D,OAAO;AAElE,SAAAA,
|
1
|
+
{"version":3,"file":"dynamic-zones.js","sources":["../../../src/services/utils/dynamic-zones.ts"],"sourcesContent":["import { map, values, sumBy, pipe, flatMap } from 'lodash/fp';\nimport type { Schema, UID } from '@strapi/types';\n\nconst getNumberOfDynamicZones = () => {\n const contentTypes: Record<UID.ContentType, Schema.ContentType> = strapi.contentTypes;\n\n return pipe(\n map('attributes'),\n flatMap(values),\n sumBy((item) => {\n if (item.type === 'dynamiczone') {\n return 1;\n }\n return 0;\n })\n )(contentTypes);\n};\n\nexport default getNumberOfDynamicZones;\n"],"names":["pipe","map","flatMap","values","sumBy"],"mappings":";;AAGA,MAAM,0BAA0B,MAAM;AACpC,QAAM,eAA4D,OAAO;AAElE,SAAAA,GAAA;AAAA,IACLC,GAAAA,IAAI,YAAY;AAAA,IAChBC,GAAAA,QAAQC,GAAAA,MAAM;AAAA,IACdC,GAAA,MAAM,CAAC,SAAS;AACV,UAAA,KAAK,SAAS,eAAe;AACxB,eAAA;AAAA,MACT;AACO,aAAA;AAAA,IAAA,CACR;AAAA,IACD,YAAY;AAChB;;"}
|
package/dist/utils/cron.js
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
3
|
-
const
|
3
|
+
const fp = require("lodash/fp");
|
4
4
|
const INTEGER_REGEX = /^\d+$/;
|
5
5
|
const STEP_REGEX = /^\*\/\d+$/;
|
6
6
|
const COMPONENTS = [
|
@@ -24,13 +24,13 @@ const shift = (component, index, date) => {
|
|
24
24
|
if (STEP_REGEX.test(component)) {
|
25
25
|
const [, step] = component.split("/");
|
26
26
|
const frequency = Math.floor(limit / Number(step));
|
27
|
-
const list = Array.from({ length: frequency }, (
|
27
|
+
const list = Array.from({ length: frequency }, (_, index2) => index2 * Number(step));
|
28
28
|
return list.map((value) => (value + currentValue) % limit + offset).sort((a, b) => a - b);
|
29
29
|
}
|
30
30
|
return component;
|
31
31
|
};
|
32
32
|
const shiftCronExpression = (rule, date = /* @__PURE__ */ new Date()) => {
|
33
|
-
const components = rule.trim().split(" ").filter(
|
33
|
+
const components = rule.trim().split(" ").filter(fp.negate(fp.isEmpty));
|
34
34
|
const secondsIncluded = components.length === 6;
|
35
35
|
return components.map((component, index) => shift(component, secondsIncluded ? index : index + 1, date)).join(" ");
|
36
36
|
};
|
package/dist/utils/cron.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"cron.js","sources":["../../src/utils/cron.ts"],"sourcesContent":["import { isEmpty, negate } from 'lodash/fp';\n\nconst DATE_FUNCTIONS = [\n 'getSeconds',\n 'getMinutes',\n 'getHours',\n 'getDate',\n 'getMonth',\n 'getDay',\n] as const;\n\nconst INTEGER_REGEX = /^\\d+$/;\nconst STEP_REGEX = /^\\*\\/\\d+$/;\nconst COMPONENTS: {\n limit: number;\n zeroBasedIndices: boolean;\n functionName: (typeof DATE_FUNCTIONS)[number];\n}[] = [\n { limit: 60, zeroBasedIndices: true, functionName: 'getSeconds' },\n { limit: 60, zeroBasedIndices: true, functionName: 'getMinutes' },\n { limit: 24, zeroBasedIndices: true, functionName: 'getHours' },\n { limit: 31, zeroBasedIndices: false, functionName: 'getDate' },\n { limit: 12, zeroBasedIndices: false, functionName: 'getMonth' },\n { limit: 7, zeroBasedIndices: true, functionName: 'getDay' },\n];\n\nconst shift = (component: string, index: number, date: Date) => {\n if (component === '*') {\n return '*';\n }\n\n const { limit, zeroBasedIndices, functionName } = COMPONENTS[index];\n const offset = +!zeroBasedIndices;\n const currentValue = date[functionName]();\n\n if (INTEGER_REGEX.test(component)) {\n return ((Number.parseInt(component, 10) + currentValue) % limit) + offset;\n }\n\n if (STEP_REGEX.test(component)) {\n const [, step] = component.split('/');\n const frequency = Math.floor(limit / Number(step));\n const list = Array.from({ length: frequency }, (_, index) => index * Number(step));\n return list.map((value) => ((value + currentValue) % limit) + offset).sort((a, b) => a - b);\n }\n\n // Unsupported syntax\n return component;\n};\n\n/**\n * Simulate an interval by shifting a cron expression using the specified date.\n * @param {string} rule A cron expression you want to shift.\n * @param {Date} date The date that's gonna be used as the start of the \"interval\", it defaults to now.\n * @returns The shifted cron expression.\n */\nexport const shiftCronExpression = (rule: string, date = new Date()) => {\n const components = rule.trim().split(' ').filter(negate(isEmpty));\n const secondsIncluded = components.length === 6;\n return components\n .map((component, index) => shift(component, secondsIncluded ? index : index + 1, date))\n .join(' ');\n};\n"],"names":["
|
1
|
+
{"version":3,"file":"cron.js","sources":["../../src/utils/cron.ts"],"sourcesContent":["import { isEmpty, negate } from 'lodash/fp';\n\nconst DATE_FUNCTIONS = [\n 'getSeconds',\n 'getMinutes',\n 'getHours',\n 'getDate',\n 'getMonth',\n 'getDay',\n] as const;\n\nconst INTEGER_REGEX = /^\\d+$/;\nconst STEP_REGEX = /^\\*\\/\\d+$/;\nconst COMPONENTS: {\n limit: number;\n zeroBasedIndices: boolean;\n functionName: (typeof DATE_FUNCTIONS)[number];\n}[] = [\n { limit: 60, zeroBasedIndices: true, functionName: 'getSeconds' },\n { limit: 60, zeroBasedIndices: true, functionName: 'getMinutes' },\n { limit: 24, zeroBasedIndices: true, functionName: 'getHours' },\n { limit: 31, zeroBasedIndices: false, functionName: 'getDate' },\n { limit: 12, zeroBasedIndices: false, functionName: 'getMonth' },\n { limit: 7, zeroBasedIndices: true, functionName: 'getDay' },\n];\n\nconst shift = (component: string, index: number, date: Date) => {\n if (component === '*') {\n return '*';\n }\n\n const { limit, zeroBasedIndices, functionName } = COMPONENTS[index];\n const offset = +!zeroBasedIndices;\n const currentValue = date[functionName]();\n\n if (INTEGER_REGEX.test(component)) {\n return ((Number.parseInt(component, 10) + currentValue) % limit) + offset;\n }\n\n if (STEP_REGEX.test(component)) {\n const [, step] = component.split('/');\n const frequency = Math.floor(limit / Number(step));\n const list = Array.from({ length: frequency }, (_, index) => index * Number(step));\n return list.map((value) => ((value + currentValue) % limit) + offset).sort((a, b) => a - b);\n }\n\n // Unsupported syntax\n return component;\n};\n\n/**\n * Simulate an interval by shifting a cron expression using the specified date.\n * @param {string} rule A cron expression you want to shift.\n * @param {Date} date The date that's gonna be used as the start of the \"interval\", it defaults to now.\n * @returns The shifted cron expression.\n */\nexport const shiftCronExpression = (rule: string, date = new Date()) => {\n const components = rule.trim().split(' ').filter(negate(isEmpty));\n const secondsIncluded = components.length === 6;\n return components\n .map((component, index) => shift(component, secondsIncluded ? index : index + 1, date))\n .join(' ');\n};\n"],"names":["index","negate","isEmpty"],"mappings":";;;AAWA,MAAM,gBAAgB;AACtB,MAAM,aAAa;AACnB,MAAM,aAIA;AAAA,EACJ,EAAE,OAAO,IAAI,kBAAkB,MAAM,cAAc,aAAa;AAAA,EAChE,EAAE,OAAO,IAAI,kBAAkB,MAAM,cAAc,aAAa;AAAA,EAChE,EAAE,OAAO,IAAI,kBAAkB,MAAM,cAAc,WAAW;AAAA,EAC9D,EAAE,OAAO,IAAI,kBAAkB,OAAO,cAAc,UAAU;AAAA,EAC9D,EAAE,OAAO,IAAI,kBAAkB,OAAO,cAAc,WAAW;AAAA,EAC/D,EAAE,OAAO,GAAG,kBAAkB,MAAM,cAAc,SAAS;AAC7D;AAEA,MAAM,QAAQ,CAAC,WAAmB,OAAe,SAAe;AAC9D,MAAI,cAAc,KAAK;AACd,WAAA;AAAA,EACT;AAEA,QAAM,EAAE,OAAO,kBAAkB,aAAa,IAAI,WAAW,KAAK;AAC5D,QAAA,SAAS,CAAC,CAAC;AACX,QAAA,eAAe,KAAK,YAAY;AAElC,MAAA,cAAc,KAAK,SAAS,GAAG;AACjC,YAAS,OAAO,SAAS,WAAW,EAAE,IAAI,gBAAgB,QAAS;AAAA,EACrE;AAEI,MAAA,WAAW,KAAK,SAAS,GAAG;AAC9B,UAAM,CAAG,EAAA,IAAI,IAAI,UAAU,MAAM,GAAG;AACpC,UAAM,YAAY,KAAK,MAAM,QAAQ,OAAO,IAAI,CAAC;AACjD,UAAM,OAAO,MAAM,KAAK,EAAE,QAAQ,UAAA,GAAa,CAAC,GAAGA,WAAUA,SAAQ,OAAO,IAAI,CAAC;AACjF,WAAO,KAAK,IAAI,CAAC,WAAY,QAAQ,gBAAgB,QAAS,MAAM,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AAAA,EAC5F;AAGO,SAAA;AACT;AAQO,MAAM,sBAAsB,CAAC,MAAc,OAAO,oBAAI,WAAW;AAChE,QAAA,aAAa,KAAK,KAAA,EAAO,MAAM,GAAG,EAAE,OAAOC,GAAAA,OAAOC,GAAO,OAAA,CAAC;AAC1D,QAAA,kBAAkB,WAAW,WAAW;AAC9C,SAAO,WACJ,IAAI,CAAC,WAAW,UAAU,MAAM,WAAW,kBAAkB,QAAQ,QAAQ,GAAG,IAAI,CAAC,EACrF,KAAK,GAAG;AACb;;"}
|
@@ -1,5 +1,5 @@
|
|
1
1
|
/**
|
2
2
|
* Returns a path (as an array) from a file path
|
3
3
|
*/
|
4
|
-
export declare const filePathToPropPath: (
|
4
|
+
export declare const filePathToPropPath: (entryPath: string, useFileNameAsKey?: boolean) => string[];
|
5
5
|
//# sourceMappingURL=filepath-to-prop-path.d.ts.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"filepath-to-prop-path.d.ts","sourceRoot":"","sources":["../../src/utils/filepath-to-prop-path.ts"],"names":[],"mappings":"
|
1
|
+
{"version":3,"file":"filepath-to-prop-path.d.ts","sourceRoot":"","sources":["../../src/utils/filepath-to-prop-path.ts"],"names":[],"mappings":"AAGA;;GAEG;AACH,eAAO,MAAM,kBAAkB,cAClB,MAAM,qBACC,OAAO,KACxB,MAAM,EAqBR,CAAC"}
|
@@ -1,12 +1,33 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
3
|
-
const
|
3
|
+
const path = require("node:path");
|
4
|
+
const fp = require("lodash/fp");
|
4
5
|
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
|
5
|
-
const
|
6
|
-
const
|
7
|
-
|
8
|
-
const
|
9
|
-
|
6
|
+
const path__default = /* @__PURE__ */ _interopDefault(path);
|
7
|
+
const fp__default = /* @__PURE__ */ _interopDefault(fp);
|
8
|
+
const filePathToPropPath = (entryPath, useFileNameAsKey = true) => {
|
9
|
+
const transform = fp__default.default.pipe(
|
10
|
+
// Remove the relative path prefixes: './' for posix (and some win32) and ".\" for win32
|
11
|
+
removeRelativePrefix,
|
12
|
+
// Remove the path metadata and extensions
|
13
|
+
fp__default.default.replace(/(\.settings|\.json|\.js)/g, ""),
|
14
|
+
// Transform to lowercase
|
15
|
+
// Note: We're using fp.toLower instead of fp.lowercase as the latest removes special characters such as "/"
|
16
|
+
fp__default.default.toLower,
|
17
|
+
// Split the cleaned path by matching every possible separator (either "/" or "\" depending on the OS)
|
18
|
+
fp__default.default.split(new RegExp(`[\\${path__default.default.win32.sep}|${path__default.default.posix.sep}]`, "g")),
|
19
|
+
// Make sure to remove leading '.' from the different path parts
|
20
|
+
fp__default.default.map(fp__default.default.trimCharsStart(".")),
|
21
|
+
// join + split in case some '.' characters are still present in different parts of the path
|
22
|
+
fp__default.default.join("."),
|
23
|
+
fp__default.default.split("."),
|
24
|
+
// Remove the last portion of the path array if the file name shouldn't be used as a key
|
25
|
+
useFileNameAsKey ? fp__default.default.identity : fp__default.default.slice(0, -1)
|
26
|
+
);
|
27
|
+
return transform(entryPath);
|
28
|
+
};
|
29
|
+
const removeRelativePrefix = (filePath) => {
|
30
|
+
return filePath.startsWith(`.${path__default.default.win32.sep}`) || filePath.startsWith(`.${path__default.default.posix.sep}`) ? filePath.slice(2) : filePath;
|
10
31
|
};
|
11
32
|
exports.filePathToPropPath = filePathToPropPath;
|
12
33
|
//# sourceMappingURL=filepath-to-prop-path.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"filepath-to-prop-path.js","sources":["../../src/utils/filepath-to-prop-path.ts"],"sourcesContent":["import
|
1
|
+
{"version":3,"file":"filepath-to-prop-path.js","sources":["../../src/utils/filepath-to-prop-path.ts"],"sourcesContent":["import path from 'node:path';\nimport fp from 'lodash/fp';\n\n/**\n * Returns a path (as an array) from a file path\n */\nexport const filePathToPropPath = (\n entryPath: string,\n useFileNameAsKey: boolean = true\n): string[] => {\n const transform = fp.pipe(\n // Remove the relative path prefixes: './' for posix (and some win32) and \".\\\" for win32\n removeRelativePrefix,\n // Remove the path metadata and extensions\n fp.replace(/(\\.settings|\\.json|\\.js)/g, ''),\n // Transform to lowercase\n // Note: We're using fp.toLower instead of fp.lowercase as the latest removes special characters such as \"/\"\n fp.toLower,\n // Split the cleaned path by matching every possible separator (either \"/\" or \"\\\" depending on the OS)\n fp.split(new RegExp(`[\\\\${path.win32.sep}|${path.posix.sep}]`, 'g')),\n // Make sure to remove leading '.' from the different path parts\n fp.map(fp.trimCharsStart('.')),\n // join + split in case some '.' characters are still present in different parts of the path\n fp.join('.'),\n fp.split('.'),\n // Remove the last portion of the path array if the file name shouldn't be used as a key\n useFileNameAsKey ? fp.identity : fp.slice(0, -1)\n );\n\n return transform(entryPath) as string[];\n};\n\nconst removeRelativePrefix = (filePath: string) => {\n return filePath.startsWith(`.${path.win32.sep}`) || filePath.startsWith(`.${path.posix.sep}`)\n ? filePath.slice(2)\n : filePath;\n};\n"],"names":["fp","path"],"mappings":";;;;;;;AAMO,MAAM,qBAAqB,CAChC,WACA,mBAA4B,SACf;AACb,QAAM,YAAYA,YAAAA,QAAG;AAAA;AAAA,IAEnB;AAAA;AAAA,IAEAA,oBAAG,QAAQ,6BAA6B,EAAE;AAAA;AAAA;AAAA,IAG1CA,YAAAA,QAAG;AAAA;AAAA,IAEHA,YAAG,QAAA,MAAM,IAAI,OAAO,MAAMC,cAAK,QAAA,MAAM,GAAG,IAAIA,cAAK,QAAA,MAAM,GAAG,KAAK,GAAG,CAAC;AAAA;AAAA,IAEnED,YAAAA,QAAG,IAAIA,YAAAA,QAAG,eAAe,GAAG,CAAC;AAAA;AAAA,IAE7BA,YAAA,QAAG,KAAK,GAAG;AAAA,IACXA,YAAA,QAAG,MAAM,GAAG;AAAA;AAAA,IAEZ,mBAAmBA,YAAG,QAAA,WAAWA,YAAAA,QAAG,MAAM,GAAG,EAAE;AAAA,EAAA;AAGjD,SAAO,UAAU,SAAS;AAC5B;AAEA,MAAM,uBAAuB,CAAC,aAAqB;AACjD,SAAO,SAAS,WAAW,IAAIC,cAAAA,QAAK,MAAM,GAAG,EAAE,KAAK,SAAS,WAAW,IAAIA,cAAAA,QAAK,MAAM,GAAG,EAAE,IACxF,SAAS,MAAM,CAAC,IAChB;AACN;;"}
|
@@ -1,8 +1,28 @@
|
|
1
|
-
import
|
2
|
-
|
3
|
-
|
4
|
-
const
|
5
|
-
|
1
|
+
import path from "node:path";
|
2
|
+
import fp from "lodash/fp";
|
3
|
+
const filePathToPropPath = (entryPath, useFileNameAsKey = true) => {
|
4
|
+
const transform = fp.pipe(
|
5
|
+
// Remove the relative path prefixes: './' for posix (and some win32) and ".\" for win32
|
6
|
+
removeRelativePrefix,
|
7
|
+
// Remove the path metadata and extensions
|
8
|
+
fp.replace(/(\.settings|\.json|\.js)/g, ""),
|
9
|
+
// Transform to lowercase
|
10
|
+
// Note: We're using fp.toLower instead of fp.lowercase as the latest removes special characters such as "/"
|
11
|
+
fp.toLower,
|
12
|
+
// Split the cleaned path by matching every possible separator (either "/" or "\" depending on the OS)
|
13
|
+
fp.split(new RegExp(`[\\${path.win32.sep}|${path.posix.sep}]`, "g")),
|
14
|
+
// Make sure to remove leading '.' from the different path parts
|
15
|
+
fp.map(fp.trimCharsStart(".")),
|
16
|
+
// join + split in case some '.' characters are still present in different parts of the path
|
17
|
+
fp.join("."),
|
18
|
+
fp.split("."),
|
19
|
+
// Remove the last portion of the path array if the file name shouldn't be used as a key
|
20
|
+
useFileNameAsKey ? fp.identity : fp.slice(0, -1)
|
21
|
+
);
|
22
|
+
return transform(entryPath);
|
23
|
+
};
|
24
|
+
const removeRelativePrefix = (filePath) => {
|
25
|
+
return filePath.startsWith(`.${path.win32.sep}`) || filePath.startsWith(`.${path.posix.sep}`) ? filePath.slice(2) : filePath;
|
6
26
|
};
|
7
27
|
export {
|
8
28
|
filePathToPropPath
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"filepath-to-prop-path.mjs","sources":["../../src/utils/filepath-to-prop-path.ts"],"sourcesContent":["import
|
1
|
+
{"version":3,"file":"filepath-to-prop-path.mjs","sources":["../../src/utils/filepath-to-prop-path.ts"],"sourcesContent":["import path from 'node:path';\nimport fp from 'lodash/fp';\n\n/**\n * Returns a path (as an array) from a file path\n */\nexport const filePathToPropPath = (\n entryPath: string,\n useFileNameAsKey: boolean = true\n): string[] => {\n const transform = fp.pipe(\n // Remove the relative path prefixes: './' for posix (and some win32) and \".\\\" for win32\n removeRelativePrefix,\n // Remove the path metadata and extensions\n fp.replace(/(\\.settings|\\.json|\\.js)/g, ''),\n // Transform to lowercase\n // Note: We're using fp.toLower instead of fp.lowercase as the latest removes special characters such as \"/\"\n fp.toLower,\n // Split the cleaned path by matching every possible separator (either \"/\" or \"\\\" depending on the OS)\n fp.split(new RegExp(`[\\\\${path.win32.sep}|${path.posix.sep}]`, 'g')),\n // Make sure to remove leading '.' from the different path parts\n fp.map(fp.trimCharsStart('.')),\n // join + split in case some '.' characters are still present in different parts of the path\n fp.join('.'),\n fp.split('.'),\n // Remove the last portion of the path array if the file name shouldn't be used as a key\n useFileNameAsKey ? fp.identity : fp.slice(0, -1)\n );\n\n return transform(entryPath) as string[];\n};\n\nconst removeRelativePrefix = (filePath: string) => {\n return filePath.startsWith(`.${path.win32.sep}`) || filePath.startsWith(`.${path.posix.sep}`)\n ? filePath.slice(2)\n : filePath;\n};\n"],"names":[],"mappings":";;AAMO,MAAM,qBAAqB,CAChC,WACA,mBAA4B,SACf;AACb,QAAM,YAAY,GAAG;AAAA;AAAA,IAEnB;AAAA;AAAA,IAEA,GAAG,QAAQ,6BAA6B,EAAE;AAAA;AAAA;AAAA,IAG1C,GAAG;AAAA;AAAA,IAEH,GAAG,MAAM,IAAI,OAAO,MAAM,KAAK,MAAM,GAAG,IAAI,KAAK,MAAM,GAAG,KAAK,GAAG,CAAC;AAAA;AAAA,IAEnE,GAAG,IAAI,GAAG,eAAe,GAAG,CAAC;AAAA;AAAA,IAE7B,GAAG,KAAK,GAAG;AAAA,IACX,GAAG,MAAM,GAAG;AAAA;AAAA,IAEZ,mBAAmB,GAAG,WAAW,GAAG,MAAM,GAAG,EAAE;AAAA,EAAA;AAGjD,SAAO,UAAU,SAAS;AAC5B;AAEA,MAAM,uBAAuB,CAAC,aAAqB;AACjD,SAAO,SAAS,WAAW,IAAI,KAAK,MAAM,GAAG,EAAE,KAAK,SAAS,WAAW,IAAI,KAAK,MAAM,GAAG,EAAE,IACxF,SAAS,MAAM,CAAC,IAChB;AACN;"}
|
@@ -1,13 +1,13 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
3
|
-
const
|
3
|
+
const fp = require("lodash/fp");
|
4
4
|
const isInitialized = async (strapi) => {
|
5
5
|
try {
|
6
|
-
if (
|
6
|
+
if (fp.isEmpty(strapi.admin)) {
|
7
7
|
return true;
|
8
8
|
}
|
9
9
|
const anyAdministrator = await strapi.db.query("admin::user").findOne({ select: ["id"] });
|
10
|
-
return !
|
10
|
+
return !fp.isNil(anyAdministrator);
|
11
11
|
} catch (err) {
|
12
12
|
strapi.stopWithError(err);
|
13
13
|
}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"is-initialized.js","sources":["../../src/utils/is-initialized.ts"],"sourcesContent":["import { isEmpty, isNil } from 'lodash/fp';\n\nimport type { Core } from '@strapi/types';\n\n/**\n * Test if the strapi application is considered as initialized (1st user has been created)\n */\nexport const isInitialized = async (strapi: Core.Strapi): Promise<boolean> => {\n try {\n if (isEmpty(strapi.admin)) {\n return true;\n }\n\n // test if there is at least one admin\n const anyAdministrator = await strapi.db.query('admin::user').findOne({ select: ['id'] });\n\n return !isNil(anyAdministrator);\n } catch (err) {\n strapi.stopWithError(err);\n }\n};\n"],"names":["isEmpty","isNil"],"mappings":";;;AAOa,MAAA,gBAAgB,OAAO,WAA0C;AACxE,MAAA;AACE,QAAAA,
|
1
|
+
{"version":3,"file":"is-initialized.js","sources":["../../src/utils/is-initialized.ts"],"sourcesContent":["import { isEmpty, isNil } from 'lodash/fp';\n\nimport type { Core } from '@strapi/types';\n\n/**\n * Test if the strapi application is considered as initialized (1st user has been created)\n */\nexport const isInitialized = async (strapi: Core.Strapi): Promise<boolean> => {\n try {\n if (isEmpty(strapi.admin)) {\n return true;\n }\n\n // test if there is at least one admin\n const anyAdministrator = await strapi.db.query('admin::user').findOne({ select: ['id'] });\n\n return !isNil(anyAdministrator);\n } catch (err) {\n strapi.stopWithError(err);\n }\n};\n"],"names":["isEmpty","isNil"],"mappings":";;;AAOa,MAAA,gBAAgB,OAAO,WAA0C;AACxE,MAAA;AACE,QAAAA,GAAA,QAAQ,OAAO,KAAK,GAAG;AAClB,aAAA;AAAA,IACT;AAGA,UAAM,mBAAmB,MAAM,OAAO,GAAG,MAAM,aAAa,EAAE,QAAQ,EAAE,QAAQ,CAAC,IAAI,EAAG,CAAA;AAEjF,WAAA,CAACC,GAAAA,MAAM,gBAAgB;AAAA,WACvB,KAAK;AACZ,WAAO,cAAc,GAAG;AAAA,EAC1B;AACF;;"}
|
@@ -2,17 +2,17 @@
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
3
3
|
const chalk = require("chalk");
|
4
4
|
const CLITable = require("cli-table3");
|
5
|
-
const
|
5
|
+
const fp = require("lodash/fp");
|
6
6
|
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
|
7
7
|
const chalk__default = /* @__PURE__ */ _interopDefault(chalk);
|
8
8
|
const CLITable__default = /* @__PURE__ */ _interopDefault(CLITable);
|
9
|
-
const
|
9
|
+
const fp__default = /* @__PURE__ */ _interopDefault(fp);
|
10
10
|
const createStartupLogger = (app) => {
|
11
11
|
return {
|
12
12
|
logStats() {
|
13
13
|
const columns = Math.min(process.stderr.columns, 80) - 2;
|
14
14
|
console.log();
|
15
|
-
console.log(chalk__default.default.black.bgWhite(
|
15
|
+
console.log(chalk__default.default.black.bgWhite(fp__default.default.padEnd(columns, " Project information")));
|
16
16
|
console.log();
|
17
17
|
const infoTable = new CLITable__default.default({
|
18
18
|
colWidths: [20, 50],
|
@@ -29,7 +29,7 @@ const createStartupLogger = (app) => {
|
|
29
29
|
);
|
30
30
|
console.log(infoTable.toString());
|
31
31
|
console.log();
|
32
|
-
console.log(chalk__default.default.black.bgWhite(
|
32
|
+
console.log(chalk__default.default.black.bgWhite(fp__default.default.padEnd(columns, " Actions available")));
|
33
33
|
console.log();
|
34
34
|
},
|
35
35
|
logFirstStartupMessage() {
|