@strapi/core 5.59.0 → 5.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core-api/routes/index.js +10 -45
- package/dist/core-api/routes/index.js.map +1 -1
- package/dist/core-api/routes/index.mjs +10 -25
- package/dist/core-api/routes/index.mjs.map +1 -1
- package/dist/core-api/routes/response.d.ts +28 -0
- package/dist/core-api/routes/response.d.ts.map +1 -0
- package/dist/core-api/routes/response.js +63 -0
- package/dist/core-api/routes/response.js.map +1 -0
- package/dist/core-api/routes/response.mjs +40 -0
- package/dist/core-api/routes/response.mjs.map +1 -0
- package/dist/package.json.js +17 -21
- package/dist/package.json.js.map +1 -1
- package/dist/package.json.mjs +17 -21
- package/dist/package.json.mjs.map +1 -1
- package/dist/providers/admin.d.ts.map +1 -1
- package/dist/providers/admin.js +8 -0
- package/dist/providers/admin.js.map +1 -1
- package/dist/providers/admin.mjs +8 -0
- package/dist/providers/admin.mjs.map +1 -1
- package/dist/providers/webhooks.d.ts.map +1 -1
- package/dist/providers/webhooks.js +1 -0
- package/dist/providers/webhooks.js.map +1 -1
- package/dist/providers/webhooks.mjs +1 -0
- package/dist/providers/webhooks.mjs.map +1 -1
- package/dist/services/config.js +1 -1
- package/dist/services/config.js.map +1 -1
- package/dist/services/config.mjs +2 -2
- package/dist/services/config.mjs.map +1 -1
- package/dist/services/document-service/components.d.ts +14 -1
- package/dist/services/document-service/components.d.ts.map +1 -1
- package/dist/services/document-service/components.js +413 -18
- package/dist/services/document-service/components.js.map +1 -1
- package/dist/services/document-service/components.mjs +414 -20
- package/dist/services/document-service/components.mjs.map +1 -1
- package/dist/services/document-service/events.d.ts.map +1 -1
- package/dist/services/document-service/events.js +8 -2
- package/dist/services/document-service/events.js.map +1 -1
- package/dist/services/document-service/events.mjs +8 -2
- package/dist/services/document-service/events.mjs.map +1 -1
- package/dist/services/document-service/middlewares/middleware-manager.d.ts +1 -1
- package/dist/services/document-service/middlewares/middleware-manager.d.ts.map +1 -1
- package/dist/services/document-service/middlewares/middleware-manager.js +6 -1
- package/dist/services/document-service/middlewares/middleware-manager.js.map +1 -1
- package/dist/services/document-service/middlewares/middleware-manager.mjs +6 -1
- package/dist/services/document-service/middlewares/middleware-manager.mjs.map +1 -1
- package/dist/services/entity-validator/index.d.ts.map +1 -1
- package/dist/services/entity-validator/index.js +41 -6
- package/dist/services/entity-validator/index.js.map +1 -1
- package/dist/services/entity-validator/index.mjs +42 -7
- package/dist/services/entity-validator/index.mjs.map +1 -1
- package/dist/services/event-hub.d.ts +1 -0
- package/dist/services/event-hub.d.ts.map +1 -1
- package/dist/services/event-hub.js +7 -0
- package/dist/services/event-hub.js.map +1 -1
- package/dist/services/event-hub.mjs +7 -0
- package/dist/services/event-hub.mjs.map +1 -1
- package/dist/services/mcp/handlers/handlePost.d.ts.map +1 -1
- package/dist/services/mcp/handlers/handlePost.js +5 -2
- package/dist/services/mcp/handlers/handlePost.js.map +1 -1
- package/dist/services/mcp/handlers/handlePost.mjs +5 -2
- package/dist/services/mcp/handlers/handlePost.mjs.map +1 -1
- package/dist/services/mcp/internal/McpConfiguration.d.ts +2 -0
- package/dist/services/mcp/internal/McpConfiguration.d.ts.map +1 -1
- package/dist/services/mcp/internal/McpConfiguration.js +17 -0
- package/dist/services/mcp/internal/McpConfiguration.js.map +1 -1
- package/dist/services/mcp/internal/McpConfiguration.mjs +17 -1
- package/dist/services/mcp/internal/McpConfiguration.mjs.map +1 -1
- package/dist/services/mcp/internal/McpServerFactory.d.ts +6 -1
- package/dist/services/mcp/internal/McpServerFactory.d.ts.map +1 -1
- package/dist/services/mcp/internal/McpServerFactory.js +11 -3
- package/dist/services/mcp/internal/McpServerFactory.js.map +1 -1
- package/dist/services/mcp/internal/McpServerFactory.mjs +12 -4
- package/dist/services/mcp/internal/McpServerFactory.mjs.map +1 -1
- package/dist/services/mcp/internal/resolveToolSchemaScope.d.ts +16 -0
- package/dist/services/mcp/internal/resolveToolSchemaScope.d.ts.map +1 -0
- package/dist/services/mcp/internal/resolveToolSchemaScope.js +40 -0
- package/dist/services/mcp/internal/resolveToolSchemaScope.js.map +1 -0
- package/dist/services/mcp/internal/resolveToolSchemaScope.mjs +38 -0
- package/dist/services/mcp/internal/resolveToolSchemaScope.mjs.map +1 -0
- package/dist/services/mcp/tool-registry.d.ts +5 -0
- package/dist/services/mcp/tool-registry.d.ts.map +1 -1
- package/dist/services/mcp/tool-registry.js +30 -1
- package/dist/services/mcp/tool-registry.js.map +1 -1
- package/dist/services/mcp/tool-registry.mjs +30 -1
- package/dist/services/mcp/tool-registry.mjs.map +1 -1
- package/dist/services/webhook-runner.d.ts +5 -6
- package/dist/services/webhook-runner.d.ts.map +1 -1
- package/dist/services/webhook-runner.js +45 -8
- package/dist/services/webhook-runner.js.map +1 -1
- package/dist/services/webhook-runner.mjs +45 -8
- package/dist/services/webhook-runner.mjs.map +1 -1
- package/dist/services/webhook-store.d.ts.map +1 -1
- package/dist/services/webhook-store.js +21 -2
- package/dist/services/webhook-store.js.map +1 -1
- package/dist/services/webhook-store.mjs +21 -2
- package/dist/services/webhook-store.mjs.map +1 -1
- package/package.json +17 -21
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../../../src/services/entity-validator/index.ts"],"sourcesContent":["/**\n * Entity validator\n * Module that will validate input data for entity creation or edition\n */\n\nimport { uniqBy, castArray, isNil, isArray, mergeWith, get, has, isEmpty, isObject } from 'lodash';\nimport jsonLogic from 'json-logic-js';\nimport * as strapiUtils from '@strapi/utils';\nimport type { Modules, UID, Struct, Schema } from '@strapi/types';\nimport { Validators, ValidatorMetas } from './validators';\n\ntype CreateOrUpdate = 'creation' | 'update';\n\nconst { yup, validateYupSchema } = strapiUtils;\nconst { isMediaAttribute, isScalarAttribute, getWritableAttributes } = strapiUtils.contentTypes;\nconst { isAnyToOne } = strapiUtils.relations;\nconst { ValidationError } = strapiUtils.errors;\n\ntype ID = { id: string | number };\n\ntype RelationSource = string | number | ID;\n\nexport type ComponentContext = {\n parentContent: {\n // The model of the parent content type that contains the current component.\n model: Struct.Schema;\n // The numeric id of the parent entity that contains the component.\n id?: number;\n // The options passed to the entity validator. From which we can extract\n // entity dimensions such as locale and publication state.\n options?: ValidatorContext;\n };\n // The path to the component within the parent content type schema.\n pathToComponent: string[];\n // If working with a repeatable component this contains the\n // full data of the repeatable component in the current entity.\n repeatableData: Modules.EntityValidator.Entity[];\n fullDynamicZoneContent?: Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n};\n\ninterface WithComponentContext {\n componentContext?: ComponentContext;\n}\n\ninterface ValidatorMeta<TAttribute = Schema.Attribute.AnyAttribute> extends WithComponentContext {\n attr: TAttribute;\n updatedAttribute: { name: string; value: any };\n}\n\ninterface ValidatorContext {\n isDraft?: boolean;\n locale?: string | null;\n strictRelations?: boolean;\n}\n\ninterface ModelValidatorMetas extends WithComponentContext {\n model: Struct.Schema;\n data: Record<string, unknown>;\n entity?: Modules.EntityValidator.Entity;\n}\n\nconst isInteger = (value: unknown): value is number => Number.isInteger(value);\n\nconst addMinMax = <\n T extends {\n min(value: number): T;\n max(value: number): T;\n },\n>(\n validator: T,\n {\n attr,\n updatedAttribute,\n }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.MinMaxOption<string | number>>\n): T => {\n let nextValidator: T = validator;\n\n if (\n isInteger(attr.min) &&\n (('required' in attr && attr.required) ||\n (Array.isArray(updatedAttribute.value) && updatedAttribute.value.length > 0))\n ) {\n nextValidator = nextValidator.min(attr.min);\n }\n if (isInteger(attr.max)) {\n nextValidator = nextValidator.max(attr.max);\n }\n return nextValidator;\n};\n\nconst addRequiredValidation = (createOrUpdate: CreateOrUpdate) => {\n return <T extends strapiUtils.yup.AnySchema>(\n validator: T,\n {\n attr: { required },\n }: ValidatorMeta<Partial<Schema.Attribute.AnyAttribute & Schema.Attribute.RequiredOption>>\n ): T => {\n let nextValidator = validator;\n\n if (required) {\n if (createOrUpdate === 'creation') {\n nextValidator = nextValidator.notNil();\n } else if (createOrUpdate === 'update') {\n nextValidator = nextValidator.notNull();\n }\n } else {\n nextValidator = nextValidator.nullable();\n }\n return nextValidator;\n };\n};\n\nconst addDefault = (createOrUpdate: CreateOrUpdate) => {\n return (\n validator: strapiUtils.yup.BaseSchema,\n { attr }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.DefaultOption<unknown>>\n ) => {\n let nextValidator = validator;\n\n if (createOrUpdate === 'creation') {\n if (\n ((attr.type === 'component' && attr.repeatable) || attr.type === 'dynamiczone') &&\n !attr.required\n ) {\n nextValidator = nextValidator.default([]);\n } else {\n nextValidator = nextValidator.default(attr.default);\n }\n } else {\n nextValidator = nextValidator.default(undefined);\n }\n\n return nextValidator;\n };\n};\n\nconst preventCast = (validator: strapiUtils.yup.AnySchema) =>\n validator.transform((val, originalVal) => originalVal);\n\nconst createComponentValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n {\n attr,\n updatedAttribute,\n componentContext,\n }: ValidatorMeta<Schema.Attribute.Component<UID.Component, boolean>>,\n options: ValidatorContext\n ): strapiUtils.yup.AnySchema => {\n const model = strapi.getModel(attr.component);\n if (!model) {\n throw new Error('Validation failed: Model not found');\n }\n\n if (attr?.repeatable) {\n // FIXME: yup v1\n\n let validator = yup\n .array()\n .of(\n yup.lazy((item) =>\n createModelValidator(createOrUpdate)(\n { componentContext, model, data: item },\n options\n ).notNull()\n ) as any\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!options.isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n }\n\n let validator = createModelValidator(createOrUpdate)(\n {\n model,\n data: updatedAttribute.value,\n componentContext,\n },\n options\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !options.isDraft && attr.required },\n updatedAttribute,\n });\n\n return validator;\n };\n\nconst createDzValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n { attr, updatedAttribute, componentContext }: ValidatorMeta,\n options: ValidatorContext\n ): strapiUtils.yup.AnySchema => {\n let validator;\n\n validator = yup.array().of(\n yup.lazy((item) => {\n const model = strapi.getModel(get(item, '__component'));\n const schema = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(strapi.components)),\n })\n .notNull();\n\n return model\n ? schema.concat(\n createModelValidator(createOrUpdate)({ model, data: item, componentContext }, options)\n )\n : schema;\n }) as any // FIXME: yup v1\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!options.isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n };\n\n/**\n * A relation/media value can be supplied in several shapes: a bare id, an array of ids,\n * or a connect/set object (`{ connect: [...] }` / `{ set: [...] }`). This normalises all\n * of them to \"does this attach at least one entry?\" so required validation is consistent\n * regardless of the input shape (mirrors `buildRelationsStore`'s source extraction).\n */\nconst hasRelationValue = (value: unknown): boolean => {\n if (isNil(value)) {\n return false;\n }\n\n if (Array.isArray(value)) {\n return value.length > 0;\n }\n\n if (isObject(value)) {\n const connect = (value as { connect?: unknown }).connect;\n const set = (value as { set?: unknown }).set;\n\n if (!isNil(connect)) {\n return Array.isArray(connect) ? connect.length > 0 : true;\n }\n if (!isNil(set)) {\n return Array.isArray(set) ? set.length > 0 : true;\n }\n\n // Any other object shape (e.g. a bare `{ id }`) counts as a value.\n return true;\n }\n\n return true;\n};\n\n/**\n * A disconnect-only update payload removes entries without adding or replacing any:\n * actual removals in `disconnect`, no `set`, and no effective additions in `connect`.\n * `connect` counts as \"no additions\" when absent OR an empty array — the Content Manager\n * initializes every relation as `{ connect: [], disconnect: [] }` and keeps `connect: []`\n * in place when the user only removes entries, so `{ connect: [], disconnect: [id] }`\n * is the shape real admin saves produce. A payload with empty `disconnect` (nothing\n * removed) is NOT disconnect-only — it's the CM's untouched-relation no-op.\n */\nconst isDisconnectOnly = (value: unknown): boolean => {\n if (!isObject(value)) {\n return false;\n }\n\n const { connect, set, disconnect } = value as {\n connect?: unknown;\n set?: unknown;\n disconnect?: unknown;\n };\n\n if (!isNil(set)) {\n return false;\n }\n\n const hasAdditions = !isNil(connect) && (!Array.isArray(connect) || connect.length > 0);\n if (hasAdditions) {\n return false;\n }\n\n return !isNil(disconnect) && (!Array.isArray(disconnect) || disconnect.length > 0);\n};\n\n/**\n * Decides whether a required media/relation value should be rejected as empty,\n * mirroring the scalar `required` semantics:\n *\n * - creation (`notNil` analogue): an absent key is a failure — the field must be\n * populated, so anything without a value (`undefined`/`null`/`[]`/empty `set`/`connect`)\n * is rejected.\n * - update (`notNull` analogue): an absent key keeps the existing value, so it passes.\n * Only reject when the request is present AND leaves the field empty. A bare\n * `{ connect: [] }` (no `set`) neither adds nor removes anything → treated as a no-op\n * that passes; `{ set: [] }` / `null` / `[]` explicitly empty the field → rejected.\n *\n * `isToOne` marks a to-one relation / single media, which can hold at most one entry.\n * For those, a disconnect-only update (`{ disconnect: [...] }` with no `connect`/`set`)\n * always leaves the field empty — no DB read needed — so it is rejected on non-draft\n * updates. To-many fields can still hold other entries after a disconnect, so their\n * resulting state can't be known without a DB read and they fall through to a pass\n * (publish re-validates the populated draft for D&P types; documented limitation for\n * non-D&P, tied to the null→[] follow-up).\n *\n * On creation there are no existing rows, so a disconnect-only payload attaches nothing\n * and always leaves the field empty — for both to-one and to-many — so it is rejected\n * regardless of `isToOne`.\n */\nconst relationRequiredFails = (\n createOrUpdate: CreateOrUpdate,\n value: unknown,\n isToOne: boolean\n): boolean => {\n if (createOrUpdate === 'creation') {\n // No existing rows on create, so a disconnect attaches nothing and the field stays\n // empty for both to-one and to-many — reject it before the generic value check, which\n // would otherwise treat the bare `{ disconnect: [...] }` object as a present value.\n if (isDisconnectOnly(value)) {\n return true;\n }\n }\n\n if (createOrUpdate === 'update') {\n // Absent key on update = keep the existing value.\n if (value === undefined) {\n return false;\n }\n\n if (isDisconnectOnly(value)) {\n // A disconnect on a to-one/single field deterministically empties it; on a to-many\n // field the resulting state depends on the current DB rows, so we can't reject here.\n return isToOne;\n }\n\n // A connect-only empty is a no-op, not an emptying operation.\n if (isObject(value) && !isNil((value as { connect?: unknown }).connect)) {\n const connect = (value as { connect?: unknown }).connect;\n const hasSet = !isNil((value as { set?: unknown }).set);\n if (!hasSet && Array.isArray(connect) && connect.length === 0) {\n return false;\n }\n }\n }\n\n return !hasRelationValue(value);\n};\n\nconst createMediaAttributeValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n { attr, updatedAttribute }: ValidatorMeta<Schema.Attribute.Media>,\n options: ValidatorContext\n ): strapiUtils.yup.AnySchema => {\n // Media values arrive in several shapes (a bare id, an array of ids, or a\n // `{ connect }` / `{ set }` object on update). `yup.mixed()` accepts all of them;\n // coercing `multiple` media to `yup.array()` would reject the connect/set object\n // syntax that update requests legitimately send. Required-ness is asserted below\n // via `relationRequiredFails`, which understands every shape.\n let validator: strapiUtils.yup.AnySchema = yup.mixed();\n\n // Relational required constraints are only enforced under the strictRelations flag,\n // and never for drafts (mirrors scalar `required` handling via `!isDraft`).\n if (options.strictRelations && !options.isDraft && attr.required) {\n // A media value can arrive as an id, an array, or a connect/set object, so a simple\n // `.notNil()`/`.min()` is not enough — normalise the shape before asserting.\n // Single media holds at most one file, so a disconnect-only update always empties it.\n const isToOne = !attr.multiple;\n validator = validator.test(\n 'required-media',\n `${updatedAttribute.name} must be defined.`,\n () => !relationRequiredFails(createOrUpdate, updatedAttribute.value, isToOne)\n );\n }\n\n return validator;\n };\n\nconst createRelationValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n { attr, updatedAttribute }: ValidatorMeta<Schema.Attribute.Relation>,\n options: ValidatorContext\n ): strapiUtils.yup.AnySchema => {\n let validator: strapiUtils.yup.AnySchema;\n\n if (Array.isArray(updatedAttribute.value)) {\n validator = yup.array().of(yup.mixed());\n } else {\n validator = yup.mixed();\n }\n\n // Relational required constraints are only enforced under the strictRelations flag,\n // and never for drafts (mirrors scalar `required` handling via `!isDraft`).\n if (options.strictRelations && !options.isDraft && attr.required) {\n // A relation value can arrive as an id, an array, or a connect/set object, so a\n // simple `.notNil()`/`.min()` is not enough — normalise the shape before asserting.\n // A to-one relation holds at most one target, so a disconnect-only update always empties it.\n const isToOne = isAnyToOne(attr);\n validator = validator.test(\n 'required-relation',\n `${updatedAttribute.name} must be defined.`,\n () => !relationRequiredFails(createOrUpdate, updatedAttribute.value, isToOne)\n );\n }\n\n return validator;\n };\n\nconst createScalarAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMeta, options: ValidatorContext) => {\n let validator;\n\n if (has(Validators, metas.attr.type)) {\n validator = (Validators as any)[metas.attr.type](metas, options);\n } else {\n // No validators specified - fall back to mixed\n validator = yup.mixed();\n }\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !options.isDraft && metas.attr.required },\n updatedAttribute: metas.updatedAttribute,\n });\n\n return validator;\n };\n\nconst createAttributeValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (metas: ValidatorMetas, options: ValidatorContext): strapiUtils.yup.AnySchema => {\n let validator = yup.mixed();\n\n // If field is conditionally invisible, skip all validation for it\n if (metas.attr.conditions?.visible) {\n const isVisible = jsonLogic.apply(metas.attr.conditions.visible, metas.data);\n\n if (!isVisible) {\n return yup.mixed().notRequired(); // Completely skip validation\n }\n }\n\n if (isMediaAttribute(metas.attr)) {\n validator = createMediaAttributeValidator(createOrUpdate)(\n {\n attr: metas.attr as Schema.Attribute.Media,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n } else if (isScalarAttribute(metas.attr)) {\n validator = createScalarAttributeValidator(createOrUpdate)(metas, options);\n } else {\n if (metas.attr.type === 'component' && metas.componentContext) {\n // Build the path to the component within the parent content type schema.\n const pathToComponent = [\n ...(metas?.componentContext?.pathToComponent ?? []),\n metas.updatedAttribute.name,\n ];\n\n // If working with a repeatable component, determine the repeatable data\n // based on the component's path.\n\n // In order to validate the repeatable within this entity we need\n // access to the full repeatable data. In case we are validating a\n // nested component within a repeatable.\n // Hence why we set this up when the path to the component is only one level deep.\n const repeatableData = (\n metas.attr.repeatable && pathToComponent.length === 1\n ? metas.updatedAttribute.value\n : metas.componentContext?.repeatableData\n ) as Modules.EntityValidator.Entity[];\n\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n pathToComponent,\n repeatableData,\n };\n\n validator = createComponentValidator(createOrUpdate)(\n {\n componentContext: newComponentContext,\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n } else if (metas.attr.type === 'dynamiczone' && metas.componentContext) {\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n fullDynamicZoneContent: metas.updatedAttribute.value,\n pathToComponent: [...metas.componentContext.pathToComponent, metas.updatedAttribute.name],\n };\n\n Object.assign(metas, { componentContext: newComponentContext });\n\n validator = createDzValidator(createOrUpdate)(metas, options);\n } else if (metas.attr.type === 'relation') {\n validator = createRelationValidator(createOrUpdate)(\n {\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n }\n\n validator = preventCast(validator);\n }\n\n validator = addDefault(createOrUpdate)(validator, metas);\n\n return validator;\n };\n\nconst createModelValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n { componentContext, model, data, entity }: ModelValidatorMetas,\n options: ValidatorContext\n ): strapiUtils.yup.AnyObjectSchema => {\n const writableAttributes = model ? getWritableAttributes(model as any) : [];\n\n const schema = writableAttributes.reduce(\n (validators, attributeName) => {\n const metas = {\n attr: model.attributes[attributeName],\n updatedAttribute: { name: attributeName, value: get(data, attributeName) },\n data,\n model,\n entity,\n componentContext,\n };\n\n const validator = createAttributeValidator(createOrUpdate)(metas, options);\n\n validators[attributeName] = validator;\n\n return validators;\n },\n {} as Record<string, strapiUtils.yup.BaseSchema>\n );\n\n return yup.object().shape(schema);\n };\n\nconst createValidateEntity = (createOrUpdate: CreateOrUpdate) => {\n return async <\n TUID extends UID.ContentType,\n TData extends Modules.EntityService.Params.Data.Input<TUID>,\n >(\n model: Schema.ContentType<TUID>,\n data: TData | Partial<TData> | undefined,\n options?: ValidatorContext,\n entity?: Modules.EntityValidator.Entity\n ): Promise<TData> => {\n if (!isObject(data)) {\n const { displayName } = model.info;\n\n throw new ValidationError(\n `Invalid payload submitted for the ${createOrUpdate} of an entity of type ${displayName}. Expected an object, but got ${typeof data}`\n );\n }\n\n const validator = createModelValidator(createOrUpdate)(\n {\n model,\n data,\n entity,\n componentContext: {\n // Set up the initial component context.\n // Keeping track of parent content type context in which a component will be used.\n // This is necessary to validate component field constraints such as uniqueness.\n parentContent: {\n id: entity?.id,\n model,\n options,\n },\n pathToComponent: [],\n repeatableData: [],\n },\n },\n {\n isDraft: options?.isDraft ?? false,\n locale: options?.locale ?? null,\n strictRelations: options?.strictRelations ?? false,\n }\n )\n .test(\n 'relations-test',\n 'check that all relations exist',\n async function relationsValidation(data) {\n try {\n await checkRelationsExist(buildRelationsStore({ uid: model.uid, data }));\n } catch (e) {\n return this.createError({\n path: this.path,\n message: (e instanceof ValidationError && e.message) || 'Invalid relations',\n });\n }\n return true;\n }\n )\n .required();\n\n return validateYupSchema(validator, {\n strict: false,\n abortEarly: false,\n })(data);\n };\n};\n\n/**\n * Builds an object containing all the media and relations being associated with an entity\n */\nconst buildRelationsStore = <TUID extends UID.Schema>({\n uid,\n data,\n}: {\n uid: TUID;\n data: Record<string, unknown> | null;\n}): Record<string, ID[]> => {\n if (!uid) {\n throw new ValidationError(`Cannot build relations store: \"uid\" is undefined`);\n }\n\n if (isEmpty(data)) {\n return {};\n }\n\n const currentModel = strapi.getModel(uid);\n\n return Object.keys(currentModel.attributes).reduce(\n (result, attributeName: string) => {\n const attribute = currentModel.attributes[attributeName];\n const value = data[attributeName];\n\n if (isNil(value)) {\n return result;\n }\n\n switch (attribute.type) {\n case 'relation':\n case 'media': {\n if (\n attribute.type === 'relation' &&\n (attribute.relation === 'morphToMany' || attribute.relation === 'morphToOne')\n ) {\n // TODO: handle polymorphic relations\n break;\n }\n\n const target =\n // eslint-disable-next-line no-nested-ternary\n attribute.type === 'media' ? 'plugin::upload.file' : attribute.target;\n // As there are multiple formats supported for associating relations\n // with an entity, the value here can be an: array, object or number.\n let source: RelationSource[];\n if (Array.isArray(value)) {\n source = value;\n } else if (isObject(value)) {\n if ('connect' in value && !isNil(value.connect)) {\n source = value.connect as RelationSource[];\n } else if ('set' in value && !isNil(value.set)) {\n source = value.set as RelationSource[];\n } else {\n source = [];\n }\n } else {\n source = castArray(value as RelationSource);\n }\n const idArray = source.map((v) => ({\n id: typeof v === 'object' ? v.id : v,\n }));\n\n // Update the relationStore to keep track of all associations being made\n // with relations and media.\n result[target] = result[target] || [];\n result[target].push(...idArray);\n break;\n }\n case 'component': {\n return castArray(value).reduce((relationsStore, componentValue) => {\n if (!attribute.component) {\n throw new ValidationError(\n `Cannot build relations store from component, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: attribute.component,\n data: componentValue as Record<string, unknown>,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n case 'dynamiczone': {\n return castArray(value).reduce((relationsStore, dzValue) => {\n const value = dzValue as Record<string, unknown>;\n if (!value.__component) {\n throw new ValidationError(\n `Cannot build relations store from dynamiczone, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: value.__component as UID.Component,\n data: value,\n }),\n (objValue, srcValue) => {\n if (isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n default:\n break;\n }\n\n return result;\n },\n {} as Record<string, ID[]>\n );\n};\n\n/**\n * Iterate through the relations store and validates that every relation or media\n * mentioned exists\n */\nconst checkRelationsExist = async (relationsStore: Record<string, ID[]> = {}) => {\n const promises: Promise<void>[] = [];\n\n for (const [key, value] of Object.entries(relationsStore)) {\n const evaluate = async () => {\n const uniqueValues = uniqBy(value, `id`);\n const count = await strapi.db.query(key as UID.Schema).count({\n where: {\n id: {\n $in: uniqueValues.map((v) => v.id),\n },\n },\n });\n\n if (count !== uniqueValues.length) {\n throw new ValidationError(\n `${\n uniqueValues.length - count\n } relation(s) of type ${key} associated with this entity do not exist`\n );\n }\n };\n promises.push(evaluate());\n }\n\n return Promise.all(promises);\n};\n\nconst entityValidator: Modules.EntityValidator.EntityValidator = {\n validateEntityCreation: createValidateEntity('creation'),\n validateEntityUpdate: createValidateEntity('update'),\n};\n\nexport default entityValidator;\n"],"names":["yup","validateYupSchema","strapiUtils","isMediaAttribute","isScalarAttribute","getWritableAttributes","contentTypes","isAnyToOne","relations","ValidationError","errors","isInteger","value","Number","addMinMax","validator","attr","updatedAttribute","nextValidator","min","required","Array","isArray","length","max","addRequiredValidation","createOrUpdate","notNil","notNull","nullable","addDefault","type","repeatable","default","undefined","preventCast","transform","val","originalVal","createComponentValidator","componentContext","options","model","strapi","getModel","component","Error","array","of","lazy","item","createModelValidator","data","isDraft","createDzValidator","get","schema","object","shape","__component","string","oneOf","Object","keys","components","concat","hasRelationValue","isNil","isObject","connect","set","isDisconnectOnly","disconnect","hasAdditions","relationRequiredFails","isToOne","hasSet","createMediaAttributeValidator","mixed","strictRelations","multiple","test","name","createRelationValidator","createScalarAttributeValidator","metas","has","Validators","createAttributeValidator","conditions","visible","isVisible","jsonLogic","apply","notRequired","pathToComponent","repeatableData","newComponentContext","fullDynamicZoneContent","assign","entity","writableAttributes","reduce","validators","attributeName","attributes","createValidateEntity","displayName","info","parentContent","id","locale","relationsValidation","checkRelationsExist","buildRelationsStore","uid","e","createError","path","message","strict","abortEarly","isEmpty","currentModel","result","attribute","relation","target","source","castArray","idArray","map","v","push","relationsStore","componentValue","mergeWith","objValue","srcValue","dzValue","promises","key","entries","evaluate","uniqueValues","uniqBy","count","db","query","where","$in","Promise","all","entityValidator","validateEntityCreation","validateEntityUpdate"],"mappings":";;;;;AAaA,MAAM,E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EAAO,CAAC,EAAE,CAAC,CAAA;YACvC,MAAMsI,KAAAA,GAAQ,MAAMvG,MAAAA,CAAOwG,EAAE,CAACC,KAAK,CAACP,GAAAA,CAAAA,CAAmBK,KAAK,CAAC;gBAC3DG,KAAAA,EAAO;oBACLvC,EAAAA,EAAI;AACFwC,wBAAAA,GAAAA,EAAKN,aAAab,GAAG,CAAC,CAACC,CAAAA,GAAMA,EAAEtB,EAAE;AACnC;AACF;AACF,aAAA,CAAA;YAEA,IAAIoC,KAAAA,KAAUF,YAAAA,CAAazH,MAAM,EAAE;gBACjC,MAAM,IAAId,eAAAA,CACR,CAAA,EACEuI,YAAAA,CAAazH,MAAM,GAAG2H,KAAAA,CACvB,qBAAqB,EAAEL,GAAAA,CAAI,yCAAyC,CAAC,CAAA;AAE1E,YAAA;AACF,QAAA,CAAA;AACAD,QAAAA,QAAAA,CAASP,IAAI,CAACU,QAAAA,EAAAA,CAAAA;AAChB,IAAA;IAEA,OAAOQ,OAAAA,CAAQC,GAAG,CAACZ,QAAAA,CAAAA;AACrB,CAAA;AAEA,MAAMa,eAAAA,GAA2D;AAC/DC,IAAAA,sBAAAA,EAAwBhD,oBAAAA,CAAqB,UAAA,CAAA;AAC7CiD,IAAAA,oBAAAA,EAAsBjD,oBAAAA,CAAqB,QAAA;AAC7C;;;;"}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../../../src/services/entity-validator/index.ts"],"sourcesContent":["/**\n * Entity validator\n * Module that will validate input data for entity creation or edition\n */\n\nimport { uniqBy, castArray, isNil, mergeWith, get, has, isEmpty, isObject } from 'lodash';\nimport jsonLogic from 'json-logic-js';\nimport * as strapiUtils from '@strapi/utils';\nimport type { Modules, UID, Struct, Schema } from '@strapi/types';\nimport { Validators, ValidatorMetas } from './validators';\n\ntype CreateOrUpdate = 'creation' | 'update';\n\nconst { yup, validateYupSchema } = strapiUtils;\nconst { isMediaAttribute, isScalarAttribute, getWritableAttributes } = strapiUtils.contentTypes;\nconst { isAnyToOne } = strapiUtils.relations;\nconst { ValidationError } = strapiUtils.errors;\n\ntype ID = { id: string | number };\n\ntype RelationSource = string | number | ID;\n\nexport type ComponentContext = {\n parentContent: {\n // The model of the parent content type that contains the current component.\n model: Struct.Schema;\n // The numeric id of the parent entity that contains the component.\n id?: number;\n // The options passed to the entity validator. From which we can extract\n // entity dimensions such as locale and publication state.\n options?: ValidatorContext;\n };\n // The path to the component within the parent content type schema.\n pathToComponent: string[];\n // If working with a repeatable component this contains the\n // full data of the repeatable component in the current entity.\n repeatableData: Modules.EntityValidator.Entity[];\n fullDynamicZoneContent?: Schema.Attribute.Value<Schema.Attribute.DynamicZone>;\n};\n\ninterface WithComponentContext {\n componentContext?: ComponentContext;\n}\n\ninterface ValidatorMeta<TAttribute = Schema.Attribute.AnyAttribute> extends WithComponentContext {\n attr: TAttribute;\n updatedAttribute: { name: string; value: any };\n}\n\ninterface ValidatorContext {\n isDraft?: boolean;\n locale?: string | null;\n strictRelations?: boolean;\n}\n\ninterface ModelValidatorMetas extends WithComponentContext {\n model: Struct.Schema;\n data: Record<string, unknown>;\n entity?: Modules.EntityValidator.Entity;\n}\n\nconst isInteger = (value: unknown): value is number => Number.isInteger(value);\n\nconst addMinMax = <\n T extends {\n min(value: number): T;\n max(value: number): T;\n },\n>(\n validator: T,\n {\n attr,\n updatedAttribute,\n }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.MinMaxOption<string | number>>\n): T => {\n let nextValidator: T = validator;\n\n if (\n isInteger(attr.min) &&\n (('required' in attr && attr.required) ||\n (Array.isArray(updatedAttribute.value) && updatedAttribute.value.length > 0))\n ) {\n nextValidator = nextValidator.min(attr.min);\n }\n if (isInteger(attr.max)) {\n nextValidator = nextValidator.max(attr.max);\n }\n return nextValidator;\n};\n\nconst addRequiredValidation = (createOrUpdate: CreateOrUpdate) => {\n return <T extends strapiUtils.yup.AnySchema>(\n validator: T,\n {\n attr: { required },\n }: ValidatorMeta<Partial<Schema.Attribute.AnyAttribute & Schema.Attribute.RequiredOption>>\n ): T => {\n let nextValidator = validator;\n\n if (required) {\n if (createOrUpdate === 'creation') {\n nextValidator = nextValidator.notNil();\n } else if (createOrUpdate === 'update') {\n nextValidator = nextValidator.notNull();\n }\n } else {\n nextValidator = nextValidator.nullable();\n }\n return nextValidator;\n };\n};\n\nconst addDefault = (createOrUpdate: CreateOrUpdate) => {\n return (\n validator: strapiUtils.yup.BaseSchema,\n { attr }: ValidatorMeta<Schema.Attribute.AnyAttribute & Schema.Attribute.DefaultOption<unknown>>\n ) => {\n let nextValidator = validator;\n\n if (createOrUpdate === 'creation') {\n if (\n ((attr.type === 'component' && attr.repeatable) || attr.type === 'dynamiczone') &&\n !attr.required\n ) {\n nextValidator = nextValidator.default([]);\n } else {\n nextValidator = nextValidator.default(attr.default);\n }\n } else {\n nextValidator = nextValidator.default(undefined);\n }\n\n return nextValidator;\n };\n};\n\nconst preventCast = (validator: strapiUtils.yup.AnySchema) =>\n validator.transform((val, originalVal) => originalVal);\n\n/**\n * On update, a component sent without an `id` is created, not updated (see\n * `updateOrCreateComponent` in the document service). Its fields have no previous value to keep,\n * so in a non-draft write they are validated as on creation.\n */\nconst getComponentCreateOrUpdate = (\n createOrUpdate: CreateOrUpdate,\n componentData: unknown,\n options: ValidatorContext\n): CreateOrUpdate => {\n if (\n createOrUpdate === 'update' &&\n options.isDraft !== true &&\n isObject(componentData) &&\n get(componentData, 'id') === undefined\n ) {\n return 'creation';\n }\n\n return createOrUpdate;\n};\n\nconst createComponentValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n {\n attr,\n updatedAttribute,\n componentContext,\n }: ValidatorMeta<Schema.Attribute.Component<UID.Component, boolean>>,\n options: ValidatorContext\n ): strapiUtils.yup.AnySchema => {\n const model = strapi.getModel(attr.component);\n if (!model) {\n throw new Error('Validation failed: Model not found');\n }\n\n if (attr?.repeatable) {\n // FIXME: yup v1\n\n let validator = yup\n .array()\n .of(\n yup.lazy((item) =>\n createModelValidator(getComponentCreateOrUpdate(createOrUpdate, item, options))(\n { componentContext, model, data: item },\n options\n ).notNull()\n ) as any\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!options.isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n }\n\n let validator = createModelValidator(\n getComponentCreateOrUpdate(createOrUpdate, updatedAttribute.value, options)\n )(\n {\n model,\n data: updatedAttribute.value,\n componentContext,\n },\n options\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !options.isDraft && attr.required },\n updatedAttribute,\n });\n\n return validator;\n };\n\nconst createDzValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n { attr, updatedAttribute, componentContext }: ValidatorMeta,\n options: ValidatorContext\n ): strapiUtils.yup.AnySchema => {\n let validator;\n\n validator = yup.array().of(\n yup.lazy((item) => {\n const model = strapi.getModel(get(item, '__component'));\n const schema = yup\n .object()\n .shape({\n __component: yup.string().required().oneOf(Object.keys(strapi.components)),\n })\n .notNull();\n\n return model\n ? schema.concat(\n createModelValidator(getComponentCreateOrUpdate(createOrUpdate, item, options))(\n { model, data: item, componentContext },\n options\n )\n )\n : schema;\n }) as any // FIXME: yup v1\n );\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: true },\n updatedAttribute,\n });\n\n if (!options.isDraft) {\n validator = addMinMax(validator, { attr, updatedAttribute });\n }\n\n return validator;\n };\n\n/**\n * A relation/media value can be supplied in several shapes: a bare id, an array of ids,\n * or a connect/set object (`{ connect: [...] }` / `{ set: [...] }`). This normalises all\n * of them to \"does this attach at least one entry?\" so required validation is consistent\n * regardless of the input shape (mirrors `buildRelationsStore`'s source extraction).\n */\nconst hasRelationValue = (value: unknown): boolean => {\n if (isNil(value)) {\n return false;\n }\n\n if (Array.isArray(value)) {\n return value.length > 0;\n }\n\n if (isObject(value)) {\n const connect = (value as { connect?: unknown }).connect;\n const set = (value as { set?: unknown }).set;\n\n if (!isNil(connect)) {\n return Array.isArray(connect) ? connect.length > 0 : true;\n }\n if (!isNil(set)) {\n return Array.isArray(set) ? set.length > 0 : true;\n }\n\n // Any other object shape (e.g. a bare `{ id }`) counts as a value.\n return true;\n }\n\n return true;\n};\n\n/**\n * A disconnect-only update payload removes entries without adding or replacing any:\n * actual removals in `disconnect`, no `set`, and no effective additions in `connect`.\n * `connect` counts as \"no additions\" when absent OR an empty array — the Content Manager\n * initializes every relation as `{ connect: [], disconnect: [] }` and keeps `connect: []`\n * in place when the user only removes entries, so `{ connect: [], disconnect: [id] }`\n * is the shape real admin saves produce. A payload with empty `disconnect` (nothing\n * removed) is NOT disconnect-only — it's the CM's untouched-relation no-op.\n */\nconst isDisconnectOnly = (value: unknown): boolean => {\n if (!isObject(value)) {\n return false;\n }\n\n const { connect, set, disconnect } = value as {\n connect?: unknown;\n set?: unknown;\n disconnect?: unknown;\n };\n\n if (!isNil(set)) {\n return false;\n }\n\n const hasAdditions = !isNil(connect) && (!Array.isArray(connect) || connect.length > 0);\n if (hasAdditions) {\n return false;\n }\n\n return !isNil(disconnect) && (!Array.isArray(disconnect) || disconnect.length > 0);\n};\n\n/**\n * Decides whether a required media/relation value should be rejected as empty,\n * mirroring the scalar `required` semantics:\n *\n * - creation (`notNil` analogue): an absent key is a failure — the field must be\n * populated, so anything without a value (`undefined`/`null`/`[]`/empty `set`/`connect`)\n * is rejected.\n * - update (`notNull` analogue): an absent key keeps the existing value, so it passes.\n * Only reject when the request is present AND leaves the field empty. A bare\n * `{ connect: [] }` (no `set`) neither adds nor removes anything → treated as a no-op\n * that passes; `{ set: [] }` / `null` / `[]` explicitly empty the field → rejected.\n *\n * `isToOne` marks a to-one relation / single media, which can hold at most one entry.\n * For those, a disconnect-only update (`{ disconnect: [...] }` with no `connect`/`set`)\n * always leaves the field empty — no DB read needed — so it is rejected on non-draft\n * updates. To-many fields can still hold other entries after a disconnect, so their\n * resulting state can't be known without a DB read and they fall through to a pass\n * (publish re-validates the populated draft for D&P types; documented limitation for\n * non-D&P, tied to the null→[] follow-up).\n *\n * On creation there are no existing rows, so a disconnect-only payload attaches nothing\n * and always leaves the field empty — for both to-one and to-many — so it is rejected\n * regardless of `isToOne`.\n */\nconst relationRequiredFails = (\n createOrUpdate: CreateOrUpdate,\n value: unknown,\n isToOne: boolean\n): boolean => {\n if (createOrUpdate === 'creation') {\n // No existing rows on create, so a disconnect attaches nothing and the field stays\n // empty for both to-one and to-many — reject it before the generic value check, which\n // would otherwise treat the bare `{ disconnect: [...] }` object as a present value.\n if (isDisconnectOnly(value)) {\n return true;\n }\n }\n\n if (createOrUpdate === 'update') {\n // Absent key on update = keep the existing value.\n if (value === undefined) {\n return false;\n }\n\n if (isDisconnectOnly(value)) {\n // A disconnect on a to-one/single field deterministically empties it; on a to-many\n // field the resulting state depends on the current DB rows, so we can't reject here.\n return isToOne;\n }\n\n // A connect-only empty is a no-op, not an emptying operation.\n if (isObject(value) && !isNil((value as { connect?: unknown }).connect)) {\n const connect = (value as { connect?: unknown }).connect;\n const hasSet = !isNil((value as { set?: unknown }).set);\n if (!hasSet && Array.isArray(connect) && connect.length === 0) {\n return false;\n }\n }\n }\n\n return !hasRelationValue(value);\n};\n\nconst createMediaAttributeValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n { attr, updatedAttribute }: ValidatorMeta<Schema.Attribute.Media>,\n options: ValidatorContext\n ): strapiUtils.yup.AnySchema => {\n // Media values arrive in several shapes (a bare id, an array of ids, or a\n // `{ connect }` / `{ set }` object on update). `yup.mixed()` accepts all of them;\n // coercing `multiple` media to `yup.array()` would reject the connect/set object\n // syntax that update requests legitimately send. Required-ness is asserted below\n // via `relationRequiredFails`, which understands every shape.\n let validator: strapiUtils.yup.AnySchema = yup.mixed();\n\n // Relational required constraints are only enforced under the strictRelations flag,\n // and never for drafts (mirrors scalar `required` handling via `!isDraft`).\n if (options.strictRelations && !options.isDraft && attr.required) {\n // A media value can arrive as an id, an array, or a connect/set object, so a simple\n // `.notNil()`/`.min()` is not enough — normalise the shape before asserting.\n // Single media holds at most one file, so a disconnect-only update always empties it.\n const isToOne = !attr.multiple;\n validator = validator.test(\n 'required-media',\n `${updatedAttribute.name} must be defined.`,\n () => !relationRequiredFails(createOrUpdate, updatedAttribute.value, isToOne)\n );\n }\n\n return validator;\n };\n\nconst createRelationValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n { attr, updatedAttribute }: ValidatorMeta<Schema.Attribute.Relation>,\n options: ValidatorContext\n ): strapiUtils.yup.AnySchema => {\n let validator: strapiUtils.yup.AnySchema;\n\n if (Array.isArray(updatedAttribute.value)) {\n validator = yup.array().of(yup.mixed());\n } else {\n validator = yup.mixed();\n }\n\n // Relational required constraints are only enforced under the strictRelations flag,\n // and never for drafts (mirrors scalar `required` handling via `!isDraft`).\n if (options.strictRelations && !options.isDraft && attr.required) {\n // A relation value can arrive as an id, an array, or a connect/set object, so a\n // simple `.notNil()`/`.min()` is not enough — normalise the shape before asserting.\n // A to-one relation holds at most one target, so a disconnect-only update always empties it.\n const isToOne = isAnyToOne(attr);\n validator = validator.test(\n 'required-relation',\n `${updatedAttribute.name} must be defined.`,\n () => !relationRequiredFails(createOrUpdate, updatedAttribute.value, isToOne)\n );\n }\n\n return validator;\n };\n\nconst createScalarAttributeValidator =\n (createOrUpdate: CreateOrUpdate) => (metas: ValidatorMeta, options: ValidatorContext) => {\n let validator;\n\n if (has(Validators, metas.attr.type)) {\n validator = (Validators as any)[metas.attr.type](metas, options);\n } else {\n // No validators specified - fall back to mixed\n validator = yup.mixed();\n }\n\n validator = addRequiredValidation(createOrUpdate)(validator, {\n attr: { required: !options.isDraft && metas.attr.required },\n updatedAttribute: metas.updatedAttribute,\n });\n\n return validator;\n };\n\nconst createAttributeValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (metas: ValidatorMetas, options: ValidatorContext): strapiUtils.yup.AnySchema => {\n let validator = yup.mixed();\n\n // If field is conditionally invisible, skip all validation for it\n if (metas.attr.conditions?.visible) {\n const isVisible = jsonLogic.apply(metas.attr.conditions.visible, metas.data);\n\n if (!isVisible) {\n return yup.mixed().notRequired(); // Completely skip validation\n }\n }\n\n if (isMediaAttribute(metas.attr)) {\n validator = createMediaAttributeValidator(createOrUpdate)(\n {\n attr: metas.attr as Schema.Attribute.Media,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n } else if (isScalarAttribute(metas.attr)) {\n validator = createScalarAttributeValidator(createOrUpdate)(metas, options);\n } else {\n if (metas.attr.type === 'component' && metas.componentContext) {\n // Build the path to the component within the parent content type schema.\n const pathToComponent = [\n ...(metas?.componentContext?.pathToComponent ?? []),\n metas.updatedAttribute.name,\n ];\n\n // If working with a repeatable component, determine the repeatable data\n // based on the component's path.\n\n // In order to validate the repeatable within this entity we need\n // access to the full repeatable data. In case we are validating a\n // nested component within a repeatable.\n // Hence why we set this up when the path to the component is only one level deep.\n const repeatableData = (\n metas.attr.repeatable && pathToComponent.length === 1\n ? metas.updatedAttribute.value\n : metas.componentContext?.repeatableData\n ) as Modules.EntityValidator.Entity[];\n\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n pathToComponent,\n repeatableData,\n };\n\n validator = createComponentValidator(createOrUpdate)(\n {\n componentContext: newComponentContext,\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n } else if (metas.attr.type === 'dynamiczone' && metas.componentContext) {\n const newComponentContext: ComponentContext = {\n ...metas.componentContext,\n fullDynamicZoneContent: metas.updatedAttribute.value,\n pathToComponent: [...metas.componentContext.pathToComponent, metas.updatedAttribute.name],\n };\n\n Object.assign(metas, { componentContext: newComponentContext });\n\n validator = createDzValidator(createOrUpdate)(metas, options);\n } else if (metas.attr.type === 'relation') {\n validator = createRelationValidator(createOrUpdate)(\n {\n attr: metas.attr,\n updatedAttribute: metas.updatedAttribute,\n },\n options\n );\n }\n\n validator = preventCast(validator);\n }\n\n validator = addDefault(createOrUpdate)(validator, metas);\n\n return validator;\n };\n\n/**\n * Conditional visibility is evaluated against the written data. On creation, an attribute\n * missing from the payload is stored with its schema default, so the condition must see that\n * default. On update, a missing attribute keeps its stored value, which is not known here.\n * Only used to evaluate conditions: the validated payload is left untouched.\n */\nconst getVisibilityData = (\n createOrUpdate: CreateOrUpdate,\n model: Struct.Schema,\n data: Record<string, unknown>\n): Record<string, unknown> => {\n if (createOrUpdate !== 'creation' || isObject(data) === false) {\n return data;\n }\n\n return Object.entries(model.attributes).reduce((visibilityData, [attributeName, attribute]) => {\n if (\n visibilityData[attributeName] !== undefined ||\n 'default' in attribute === false ||\n attribute.default === undefined\n ) {\n return visibilityData;\n }\n\n const defaultValue =\n typeof attribute.default === 'function' ? attribute.default() : attribute.default;\n\n return { ...visibilityData, [attributeName]: defaultValue };\n }, data);\n};\n\nconst createModelValidator =\n (createOrUpdate: CreateOrUpdate) =>\n (\n { componentContext, model, data, entity }: ModelValidatorMetas,\n options: ValidatorContext\n ): strapiUtils.yup.AnyObjectSchema => {\n const writableAttributes = model ? getWritableAttributes(model as any) : [];\n const visibilityData = model ? getVisibilityData(createOrUpdate, model, data) : data;\n\n const schema = writableAttributes.reduce(\n (validators, attributeName) => {\n const metas = {\n attr: model.attributes[attributeName],\n updatedAttribute: { name: attributeName, value: get(data, attributeName) },\n data: visibilityData,\n model,\n entity,\n componentContext,\n };\n\n const validator = createAttributeValidator(createOrUpdate)(metas, options);\n\n validators[attributeName] = validator;\n\n return validators;\n },\n {} as Record<string, strapiUtils.yup.BaseSchema>\n );\n\n return yup.object().shape(schema);\n };\n\nconst createValidateEntity = (createOrUpdate: CreateOrUpdate) => {\n return async <\n TUID extends UID.ContentType,\n TData extends Modules.EntityService.Params.Data.Input<TUID>,\n >(\n model: Schema.ContentType<TUID>,\n data: TData | Partial<TData> | undefined,\n options?: ValidatorContext,\n entity?: Modules.EntityValidator.Entity\n ): Promise<TData> => {\n if (!isObject(data)) {\n const { displayName } = model.info;\n\n throw new ValidationError(\n `Invalid payload submitted for the ${createOrUpdate} of an entity of type ${displayName}. Expected an object, but got ${typeof data}`\n );\n }\n\n const validator = createModelValidator(createOrUpdate)(\n {\n model,\n data,\n entity,\n componentContext: {\n // Set up the initial component context.\n // Keeping track of parent content type context in which a component will be used.\n // This is necessary to validate component field constraints such as uniqueness.\n parentContent: {\n id: entity?.id,\n model,\n options,\n },\n pathToComponent: [],\n repeatableData: [],\n },\n },\n {\n isDraft: options?.isDraft ?? false,\n locale: options?.locale ?? null,\n strictRelations: options?.strictRelations ?? false,\n }\n )\n .test(\n 'relations-test',\n 'check that all relations exist',\n async function relationsValidation(data) {\n try {\n await checkRelationsExist(buildRelationsStore({ uid: model.uid, data }));\n } catch (e) {\n return this.createError({\n path: this.path,\n message: (e instanceof ValidationError && e.message) || 'Invalid relations',\n });\n }\n return true;\n }\n )\n .required();\n\n return validateYupSchema(validator, {\n strict: false,\n abortEarly: false,\n })(data);\n };\n};\n\n/**\n * Builds an object containing all the media and relations being associated with an entity\n */\nconst buildRelationsStore = <TUID extends UID.Schema>({\n uid,\n data,\n}: {\n uid: TUID;\n data: Record<string, unknown> | null;\n}): Record<string, ID[]> => {\n if (!uid) {\n throw new ValidationError(`Cannot build relations store: \"uid\" is undefined`);\n }\n\n if (isEmpty(data)) {\n return {};\n }\n\n const currentModel = strapi.getModel(uid);\n\n return Object.keys(currentModel.attributes).reduce(\n (result, attributeName: string) => {\n const attribute = currentModel.attributes[attributeName];\n const value = data[attributeName];\n\n if (isNil(value)) {\n return result;\n }\n\n switch (attribute.type) {\n case 'relation':\n case 'media': {\n if (\n attribute.type === 'relation' &&\n (attribute.relation === 'morphToMany' || attribute.relation === 'morphToOne')\n ) {\n // TODO: handle polymorphic relations\n break;\n }\n\n const target =\n // eslint-disable-next-line no-nested-ternary\n attribute.type === 'media' ? 'plugin::upload.file' : attribute.target;\n // As there are multiple formats supported for associating relations\n // with an entity, the value here can be an: array, object or number.\n let source: RelationSource[];\n if (Array.isArray(value)) {\n source = value;\n } else if (isObject(value)) {\n if ('connect' in value && !isNil(value.connect)) {\n source = value.connect as RelationSource[];\n } else if ('set' in value && !isNil(value.set)) {\n source = value.set as RelationSource[];\n } else {\n source = [];\n }\n } else {\n source = castArray(value as RelationSource);\n }\n const idArray = source.map((v) => ({\n id: typeof v === 'object' ? v.id : v,\n }));\n\n // Update the relationStore to keep track of all associations being made\n // with relations and media.\n result[target] = result[target] || [];\n result[target].push(...idArray);\n break;\n }\n case 'component': {\n return castArray(value).reduce((relationsStore, componentValue) => {\n if (!attribute.component) {\n throw new ValidationError(\n `Cannot build relations store from component, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: attribute.component,\n data: componentValue as Record<string, unknown>,\n }),\n (objValue, srcValue) => {\n if (Array.isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n case 'dynamiczone': {\n return castArray(value).reduce((relationsStore, dzValue) => {\n const value = dzValue as Record<string, unknown>;\n if (!value.__component) {\n throw new ValidationError(\n `Cannot build relations store from dynamiczone, component identifier is undefined`\n );\n }\n\n return mergeWith(\n relationsStore,\n buildRelationsStore({\n uid: value.__component as UID.Component,\n data: value,\n }),\n (objValue, srcValue) => {\n if (Array.isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n }\n );\n }, result) as Record<string, ID[]>;\n }\n default:\n break;\n }\n\n return result;\n },\n {} as Record<string, ID[]>\n );\n};\n\n/**\n * Iterate through the relations store and validates that every relation or media\n * mentioned exists\n */\nconst checkRelationsExist = async (relationsStore: Record<string, ID[]> = {}) => {\n const promises: Promise<void>[] = [];\n\n for (const [key, value] of Object.entries(relationsStore)) {\n const evaluate = async () => {\n const uniqueValues = uniqBy(value, `id`);\n\n // Relations sent with empty connect and disconnect lists leave nothing to look up\n if (uniqueValues.length === 0) {\n return;\n }\n\n const count = await strapi.db.query(key as UID.Schema).count({\n where: {\n id: {\n $in: uniqueValues.map((v) => v.id),\n },\n },\n });\n\n if (count !== uniqueValues.length) {\n throw new ValidationError(\n `${\n uniqueValues.length - count\n } relation(s) of type ${key} associated with this entity do not exist`\n );\n }\n };\n promises.push(evaluate());\n }\n\n return Promise.all(promises);\n};\n\nconst entityValidator: Modules.EntityValidator.EntityValidator = {\n validateEntityCreation: createValidateEntity('creation'),\n validateEntityUpdate: createValidateEntity('update'),\n};\n\nexport default entityValidator;\n"],"names":["yup","validateYupSchema","strapiUtils","isMediaAttribute","isScalarAttribute","getWritableAttributes","contentTypes","isAnyToOne","relations","ValidationError","errors","isInteger","value","Number","addMinMax","validator","attr","updatedAttribute","nextValidator","min","required","Array","isArray","length","max","addRequiredValidation","createOrUpdate","notNil","notNull","nullable","addDefault","type","repeatable","default","undefined","preventCast","transform","val","originalVal","getComponentCreateOrUpdate","componentData","options","isDraft","isObject","get","createComponentValidator","componentContext","model","strapi","getModel","component","Error","array","of","lazy","item","createModelValidator","data","createDzValidator","schema","object","shape","__component","string","oneOf","Object","keys","components","concat","hasRelationValue","isNil","connect","set","isDisconnectOnly","disconnect","hasAdditions","relationRequiredFails","isToOne","hasSet","createMediaAttributeValidator","mixed","strictRelations","multiple","test","name","createRelationValidator","createScalarAttributeValidator","metas","has","Validators","createAttributeValidator","conditions","visible","isVisible","jsonLogic","apply","notRequired","pathToComponent","repeatableData","newComponentContext","fullDynamicZoneContent","assign","getVisibilityData","entries","attributes","reduce","visibilityData","attributeName","attribute","defaultValue","entity","writableAttributes","validators","createValidateEntity","displayName","info","parentContent","id","locale","relationsValidation","checkRelationsExist","buildRelationsStore","uid","e","createError","path","message","strict","abortEarly","isEmpty","currentModel","result","relation","target","source","castArray","idArray","map","v","push","relationsStore","componentValue","mergeWith","objValue","srcValue","dzValue","promises","key","evaluate","uniqueValues","uniqBy","count","db","query","where","$in","Promise","all","entityValidator","validateEntityCreation","validateEntityUpdate"],"mappings":";;;;;AAaA,MAAM,EAAEA,GAAG,EAAEC,iBAAiB,EAAE,GAAGC,WAAAA;AACnC,MAAM,EAAEC,gBAAgB,EAAEC,iBAAiB,EAAEC,qBAAqB,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D,MAAAA,CAAOsC,OAAO,CAACqC,cAAAA,CAAAA,CAAiB;AACzD,QAAA,MAAMQ,QAAAA,GAAW,UAAA;AACf,YAAA,MAAMC,YAAAA,GAAeC,MAAAA,CAAO1I,KAAAA,EAAO,CAAC,EAAE,CAAC,CAAA;;YAGvC,IAAIyI,YAAAA,CAAa9H,MAAM,KAAK,CAAA,EAAG;AAC7B,gBAAA;AACF,YAAA;YAEA,MAAMgI,KAAAA,GAAQ,MAAMvG,MAAAA,CAAOwG,EAAE,CAACC,KAAK,CAACN,GAAAA,CAAAA,CAAmBI,KAAK,CAAC;gBAC3DG,KAAAA,EAAO;oBACLrC,EAAAA,EAAI;AACFsC,wBAAAA,GAAAA,EAAKN,aAAaZ,GAAG,CAAC,CAACC,CAAAA,GAAMA,EAAErB,EAAE;AACnC;AACF;AACF,aAAA,CAAA;YAEA,IAAIkC,KAAAA,KAAUF,YAAAA,CAAa9H,MAAM,EAAE;gBACjC,MAAM,IAAId,eAAAA,CACR,CAAA,EACE4I,YAAAA,CAAa9H,MAAM,GAAGgI,KAAAA,CACvB,qBAAqB,EAAEJ,GAAAA,CAAI,yCAAyC,CAAC,CAAA;AAE1E,YAAA;AACF,QAAA,CAAA;AACAD,QAAAA,QAAAA,CAASP,IAAI,CAACS,QAAAA,EAAAA,CAAAA;AAChB,IAAA;IAEA,OAAOQ,OAAAA,CAAQC,GAAG,CAACX,QAAAA,CAAAA;AACrB,CAAA;AAEA,MAAMY,eAAAA,GAA2D;AAC/DC,IAAAA,sBAAAA,EAAwB9C,oBAAAA,CAAqB,UAAA,CAAA;AAC7C+C,IAAAA,oBAAAA,EAAsB/C,oBAAAA,CAAqB,QAAA;AAC7C;;;;"}
|
|
@@ -12,6 +12,7 @@ export interface EventHub {
|
|
|
12
12
|
removeAllListeners(): EventHub;
|
|
13
13
|
removeAllSubscribers(): EventHub;
|
|
14
14
|
addListener(eventName: string, listener: Listener): () => void;
|
|
15
|
+
hasListeners(eventName: string): boolean;
|
|
15
16
|
}
|
|
16
17
|
/**
|
|
17
18
|
* The event hub is Strapi's event control center.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-hub.d.ts","sourceRoot":"","sources":["../../src/services/event-hub.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,UAAU,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAC9E,MAAM,MAAM,QAAQ,GAAG,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAEzD,MAAM,WAAW,QAAQ;IACvB,IAAI,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3D,SAAS,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,IAAI,CAAC;IAC9C,WAAW,CAAC,UAAU,EAAE,UAAU,GAAG,IAAI,CAAC;IAC1C,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,MAAM,IAAI,CAAC;IACtD,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IACjD,IAAI,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,MAAM,IAAI,CAAC;IACxD,OAAO,IAAI,QAAQ,CAAC;IACpB,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC5D,kBAAkB,IAAI,QAAQ,CAAC;IAC/B,oBAAoB,IAAI,QAAQ,CAAC;IACjC,WAAW,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,MAAM,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"event-hub.d.ts","sourceRoot":"","sources":["../../src/services/event-hub.ts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|
78
78
|
},
|
|
79
|
+
hasListeners (eventName) {
|
|
80
|
+
// Subscribers other than the default one receive every event
|
|
81
|
+
const hasCustomSubscriber = subscribers.some((subscriber)=>subscriber !== defaultSubscriber);
|
|
82
|
+
// Listeners are only reached through the default subscriber
|
|
83
|
+
const hasEventListener = subscribers.includes(defaultSubscriber) && (listeners.get(eventName)?.length ?? 0) > 0;
|
|
84
|
+
return hasCustomSubscriber || hasEventListener;
|
|
85
|
+
},
|
|
79
86
|
destroy () {
|
|
80
87
|
this.removeAllListeners();
|
|
81
88
|
this.removeAllSubscribers();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-hub.js","sources":["../../src/services/event-hub.ts"],"sourcesContent":["export type Subscriber = (eventName: string, ...args: any[]) => Promise<void>;\nexport type Listener = (...args: any[]) => Promise<void>;\n\nexport interface EventHub {\n emit(eventName: string, ...args: unknown[]): Promise<void>;\n subscribe(subscriber: Subscriber): () => void;\n unsubscribe(subscriber: Subscriber): void;\n on(eventName: string, listener: Listener): () => void;\n off(eventName: string, listener: Listener): void;\n once(eventName: string, listener: Listener): () => void;\n destroy(): EventHub;\n removeListener(eventName: string, listener: Listener): void;\n removeAllListeners(): EventHub;\n removeAllSubscribers(): EventHub;\n addListener(eventName: string, listener: Listener): () => void;\n}\n\n/**\n * The event hub is Strapi's event control center.\n */\nexport default function createEventHub(): EventHub {\n const listeners = new Map();\n\n // Default subscriber to easily add listeners with the on() method\n const defaultSubscriber = async (eventName: string, ...args: unknown[]) => {\n if (listeners.has(eventName)) {\n // Iterate over a copy so that a listener removed during the emit (e.g. a once() listener)\n // does not make the loop skip the next listener\n for (const listener of listeners.get(eventName).slice()) {\n await listener(...args);\n }\n }\n };\n\n // Store of subscribers that will be called when an event is emitted\n const subscribers = [defaultSubscriber];\n\n const eventHub: EventHub = {\n async emit(eventName, ...args) {\n for (const subscriber of subscribers) {\n await subscriber(eventName, ...args);\n }\n },\n\n subscribe(subscriber) {\n subscribers.push(subscriber);\n\n // Return a function to remove the subscriber\n return () => {\n eventHub.unsubscribe(subscriber);\n };\n },\n\n unsubscribe(subscriber) {\n const subscriberIndex = subscribers.indexOf(subscriber);\n\n // Only remove the subscriber if it exists\n if (subscriberIndex >= 0) {\n subscribers.splice(subscriberIndex, 1);\n }\n },\n\n on(eventName, listener) {\n if (!listeners.has(eventName)) {\n listeners.set(eventName, [listener]);\n } else {\n listeners.get(eventName).push(listener);\n }\n\n // Return a function to remove the listener\n return () => {\n eventHub.off(eventName, listener);\n };\n },\n\n off(eventName, listener) {\n const eventListeners = listeners.get(eventName);\n\n if (eventListeners === undefined) {\n return;\n }\n\n const listenerIndex = eventListeners.indexOf(listener);\n\n // Only remove the listener if it exists\n if (listenerIndex >= 0) {\n eventListeners.splice(listenerIndex, 1);\n }\n },\n\n once(eventName, listener) {\n let fired = false;\n\n // Remove the registered wrapper, not the original listener which is not in the list\n const wrapper: Listener = async (...args) => {\n // An emit that copied the listener list before the removal can still call the wrapper\n if (fired === true) {\n return;\n }\n\n fired = true;\n eventHub.off(eventName, wrapper);\n return listener(...args);\n };\n\n return eventHub.on(eventName, wrapper);\n },\n\n destroy() {\n this.removeAllListeners();\n this.removeAllSubscribers();\n return this;\n },\n\n removeListener(eventName, listener) {\n return eventHub.off(eventName, listener);\n },\n\n removeAllListeners() {\n listeners.clear();\n return this;\n },\n\n removeAllSubscribers() {\n subscribers.length = 0;\n return this;\n },\n\n addListener(eventName, listener) {\n return eventHub.on(eventName, listener);\n },\n };\n\n return eventHub;\n}\n"],"names":["createEventHub","listeners","Map","defaultSubscriber","eventName","args","has","listener","get","slice","subscribers","eventHub","emit","subscriber","subscribe","push","unsubscribe","subscriberIndex","indexOf","splice","on","set","off","eventListeners","undefined","listenerIndex","once","fired","wrapper","destroy","removeAllListeners","removeAllSubscribers","removeListener","clear","
|
|
1
|
+
{"version":3,"file":"event-hub.js","sources":["../../src/services/event-hub.ts"],"sourcesContent":["export type Subscriber = (eventName: string, ...args: any[]) => Promise<void>;\nexport type Listener = (...args: any[]) => Promise<void>;\n\nexport interface EventHub {\n emit(eventName: string, ...args: unknown[]): Promise<void>;\n subscribe(subscriber: Subscriber): () => void;\n unsubscribe(subscriber: Subscriber): void;\n on(eventName: string, listener: Listener): () => void;\n off(eventName: string, listener: Listener): void;\n once(eventName: string, listener: Listener): () => void;\n destroy(): EventHub;\n removeListener(eventName: string, listener: Listener): void;\n removeAllListeners(): EventHub;\n removeAllSubscribers(): EventHub;\n addListener(eventName: string, listener: Listener): () => void;\n hasListeners(eventName: string): boolean;\n}\n\n/**\n * The event hub is Strapi's event control center.\n */\nexport default function createEventHub(): EventHub {\n const listeners = new Map();\n\n // Default subscriber to easily add listeners with the on() method\n const defaultSubscriber = async (eventName: string, ...args: unknown[]) => {\n if (listeners.has(eventName)) {\n // Iterate over a copy so that a listener removed during the emit (e.g. a once() listener)\n // does not make the loop skip the next listener\n for (const listener of listeners.get(eventName).slice()) {\n await listener(...args);\n }\n }\n };\n\n // Store of subscribers that will be called when an event is emitted\n const subscribers = [defaultSubscriber];\n\n const eventHub: EventHub = {\n async emit(eventName, ...args) {\n for (const subscriber of subscribers) {\n await subscriber(eventName, ...args);\n }\n },\n\n subscribe(subscriber) {\n subscribers.push(subscriber);\n\n // Return a function to remove the subscriber\n return () => {\n eventHub.unsubscribe(subscriber);\n };\n },\n\n unsubscribe(subscriber) {\n const subscriberIndex = subscribers.indexOf(subscriber);\n\n // Only remove the subscriber if it exists\n if (subscriberIndex >= 0) {\n subscribers.splice(subscriberIndex, 1);\n }\n },\n\n on(eventName, listener) {\n if (!listeners.has(eventName)) {\n listeners.set(eventName, [listener]);\n } else {\n listeners.get(eventName).push(listener);\n }\n\n // Return a function to remove the listener\n return () => {\n eventHub.off(eventName, listener);\n };\n },\n\n off(eventName, listener) {\n const eventListeners = listeners.get(eventName);\n\n if (eventListeners === undefined) {\n return;\n }\n\n const listenerIndex = eventListeners.indexOf(listener);\n\n // Only remove the listener if it exists\n if (listenerIndex >= 0) {\n eventListeners.splice(listenerIndex, 1);\n }\n },\n\n once(eventName, listener) {\n let fired = false;\n\n // Remove the registered wrapper, not the original listener which is not in the list\n const wrapper: Listener = async (...args) => {\n // An emit that copied the listener list before the removal can still call the wrapper\n if (fired === true) {\n return;\n }\n\n fired = true;\n eventHub.off(eventName, wrapper);\n return listener(...args);\n };\n\n return eventHub.on(eventName, wrapper);\n },\n\n hasListeners(eventName) {\n // Subscribers other than the default one receive every event\n const hasCustomSubscriber = subscribers.some(\n (subscriber) => subscriber !== defaultSubscriber\n );\n // Listeners are only reached through the default subscriber\n const hasEventListener =\n subscribers.includes(defaultSubscriber) && (listeners.get(eventName)?.length ?? 0) > 0;\n\n return hasCustomSubscriber || hasEventListener;\n },\n\n destroy() {\n this.removeAllListeners();\n this.removeAllSubscribers();\n return this;\n },\n\n removeListener(eventName, listener) {\n return eventHub.off(eventName, listener);\n },\n\n removeAllListeners() {\n listeners.clear();\n return this;\n },\n\n removeAllSubscribers() {\n subscribers.length = 0;\n return this;\n },\n\n addListener(eventName, listener) {\n return eventHub.on(eventName, listener);\n },\n };\n\n return eventHub;\n}\n"],"names":["createEventHub","listeners","Map","defaultSubscriber","eventName","args","has","listener","get","slice","subscribers","eventHub","emit","subscriber","subscribe","push","unsubscribe","subscriberIndex","indexOf","splice","on","set","off","eventListeners","undefined","listenerIndex","once","fired","wrapper","hasListeners","hasCustomSubscriber","some","hasEventListener","includes","length","destroy","removeAllListeners","removeAllSubscribers","removeListener","clear","addListener"],"mappings":";;AAkBA;;AAEC,IACc,SAASA,cAAAA,GAAAA;AACtB,IAAA,MAAMC,YAAY,IAAIC,GAAAA,EAAAA;;IAGtB,MAAMC,iBAAAA,GAAoB,OAAOC,SAAAA,EAAmB,GAAGC,IAAAA,GAAAA;QACrD,IAAIJ,SAAAA,CAAUK,GAAG,CAACF,SAAAA,CAAAA,EAAY;;;AAG5B,YAAA,KAAK,MAAMG,QAAAA,IAAYN,SAAAA,CAAUO,GAAG,CAACJ,SAAAA,CAA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AAuBF,CAAAA,SAAAA,CAAUO,GAAG,CAACJ,SAAAA,CAAAA,EAAY8B,MAAAA,IAAU,CAAA,IAAK,CAAA;AAEvF,YAAA,OAAOJ,mBAAAA,IAAuBE,gBAAAA;AAChC,QAAA,CAAA;AAEAG,QAAAA,OAAAA,CAAAA,GAAAA;AACE,YAAA,IAAI,CAACC,kBAAkB,EAAA;AACvB,YAAA,IAAI,CAACC,oBAAoB,EAAA;AACzB,YAAA,OAAO,IAAI;AACb,QAAA,CAAA;QAEAC,cAAAA,CAAAA,CAAelC,SAAS,EAAEG,QAAQ,EAAA;YAChC,OAAOI,QAAAA,CAASW,GAAG,CAAClB,SAAAA,EAAWG,QAAAA,CAAAA;AACjC,QAAA,CAAA;AAEA6B,QAAAA,kBAAAA,CAAAA,GAAAA;AACEnC,YAAAA,SAAAA,CAAUsC,KAAK,EAAA;AACf,YAAA,OAAO,IAAI;AACb,QAAA,CAAA;AAEAF,QAAAA,oBAAAA,CAAAA,GAAAA;AACE3B,YAAAA,WAAAA,CAAYwB,MAAM,GAAG,CAAA;AACrB,YAAA,OAAO,IAAI;AACb,QAAA,CAAA;QAEAM,WAAAA,CAAAA,CAAYpC,SAAS,EAAEG,QAAQ,EAAA;YAC7B,OAAOI,QAAAA,CAASS,EAAE,CAAChB,SAAAA,EAAWG,QAAAA,CAAAA;AAChC,QAAA;AACF,KAAA;IAEA,OAAOI,QAAAA;AACT;;;;"}
|
|
@@ -74,6 +74,13 @@
|
|
|
74
74
|
};
|
|
75
75
|
return eventHub.on(eventName, wrapper);
|
|
76
76
|
},
|
|
77
|
+
hasListeners (eventName) {
|
|
78
|
+
// Subscribers other than the default one receive every event
|
|
79
|
+
const hasCustomSubscriber = subscribers.some((subscriber)=>subscriber !== defaultSubscriber);
|
|
80
|
+
// Listeners are only reached through the default subscriber
|
|
81
|
+
const hasEventListener = subscribers.includes(defaultSubscriber) && (listeners.get(eventName)?.length ?? 0) > 0;
|
|
82
|
+
return hasCustomSubscriber || hasEventListener;
|
|
83
|
+
},
|
|
77
84
|
destroy () {
|
|
78
85
|
this.removeAllListeners();
|
|
79
86
|
this.removeAllSubscribers();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-hub.mjs","sources":["../../src/services/event-hub.ts"],"sourcesContent":["export type Subscriber = (eventName: string, ...args: any[]) => Promise<void>;\nexport type Listener = (...args: any[]) => Promise<void>;\n\nexport interface EventHub {\n emit(eventName: string, ...args: unknown[]): Promise<void>;\n subscribe(subscriber: Subscriber): () => void;\n unsubscribe(subscriber: Subscriber): void;\n on(eventName: string, listener: Listener): () => void;\n off(eventName: string, listener: Listener): void;\n once(eventName: string, listener: Listener): () => void;\n destroy(): EventHub;\n removeListener(eventName: string, listener: Listener): void;\n removeAllListeners(): EventHub;\n removeAllSubscribers(): EventHub;\n addListener(eventName: string, listener: Listener): () => void;\n}\n\n/**\n * The event hub is Strapi's event control center.\n */\nexport default function createEventHub(): EventHub {\n const listeners = new Map();\n\n // Default subscriber to easily add listeners with the on() method\n const defaultSubscriber = async (eventName: string, ...args: unknown[]) => {\n if (listeners.has(eventName)) {\n // Iterate over a copy so that a listener removed during the emit (e.g. a once() listener)\n // does not make the loop skip the next listener\n for (const listener of listeners.get(eventName).slice()) {\n await listener(...args);\n }\n }\n };\n\n // Store of subscribers that will be called when an event is emitted\n const subscribers = [defaultSubscriber];\n\n const eventHub: EventHub = {\n async emit(eventName, ...args) {\n for (const subscriber of subscribers) {\n await subscriber(eventName, ...args);\n }\n },\n\n subscribe(subscriber) {\n subscribers.push(subscriber);\n\n // Return a function to remove the subscriber\n return () => {\n eventHub.unsubscribe(subscriber);\n };\n },\n\n unsubscribe(subscriber) {\n const subscriberIndex = subscribers.indexOf(subscriber);\n\n // Only remove the subscriber if it exists\n if (subscriberIndex >= 0) {\n subscribers.splice(subscriberIndex, 1);\n }\n },\n\n on(eventName, listener) {\n if (!listeners.has(eventName)) {\n listeners.set(eventName, [listener]);\n } else {\n listeners.get(eventName).push(listener);\n }\n\n // Return a function to remove the listener\n return () => {\n eventHub.off(eventName, listener);\n };\n },\n\n off(eventName, listener) {\n const eventListeners = listeners.get(eventName);\n\n if (eventListeners === undefined) {\n return;\n }\n\n const listenerIndex = eventListeners.indexOf(listener);\n\n // Only remove the listener if it exists\n if (listenerIndex >= 0) {\n eventListeners.splice(listenerIndex, 1);\n }\n },\n\n once(eventName, listener) {\n let fired = false;\n\n // Remove the registered wrapper, not the original listener which is not in the list\n const wrapper: Listener = async (...args) => {\n // An emit that copied the listener list before the removal can still call the wrapper\n if (fired === true) {\n return;\n }\n\n fired = true;\n eventHub.off(eventName, wrapper);\n return listener(...args);\n };\n\n return eventHub.on(eventName, wrapper);\n },\n\n destroy() {\n this.removeAllListeners();\n this.removeAllSubscribers();\n return this;\n },\n\n removeListener(eventName, listener) {\n return eventHub.off(eventName, listener);\n },\n\n removeAllListeners() {\n listeners.clear();\n return this;\n },\n\n removeAllSubscribers() {\n subscribers.length = 0;\n return this;\n },\n\n addListener(eventName, listener) {\n return eventHub.on(eventName, listener);\n },\n };\n\n return eventHub;\n}\n"],"names":["createEventHub","listeners","Map","defaultSubscriber","eventName","args","has","listener","get","slice","subscribers","eventHub","emit","subscriber","subscribe","push","unsubscribe","subscriberIndex","indexOf","splice","on","set","off","eventListeners","undefined","listenerIndex","once","fired","wrapper","destroy","removeAllListeners","removeAllSubscribers","removeListener","clear","
|
|
1
|
+
{"version":3,"file":"event-hub.mjs","sources":["../../src/services/event-hub.ts"],"sourcesContent":["export type Subscriber = (eventName: string, ...args: any[]) => Promise<void>;\nexport type Listener = (...args: any[]) => Promise<void>;\n\nexport interface EventHub {\n emit(eventName: string, ...args: unknown[]): Promise<void>;\n subscribe(subscriber: Subscriber): () => void;\n unsubscribe(subscriber: Subscriber): void;\n on(eventName: string, listener: Listener): () => void;\n off(eventName: string, listener: Listener): void;\n once(eventName: string, listener: Listener): () => void;\n destroy(): EventHub;\n removeListener(eventName: string, listener: Listener): void;\n removeAllListeners(): EventHub;\n removeAllSubscribers(): EventHub;\n addListener(eventName: string, listener: Listener): () => void;\n hasListeners(eventName: string): boolean;\n}\n\n/**\n * The event hub is Strapi's event control center.\n */\nexport default function createEventHub(): EventHub {\n const listeners = new Map();\n\n // Default subscriber to easily add listeners with the on() method\n const defaultSubscriber = async (eventName: string, ...args: unknown[]) => {\n if (listeners.has(eventName)) {\n // Iterate over a copy so that a listener removed during the emit (e.g. a once() listener)\n // does not make the loop skip the next listener\n for (const listener of listeners.get(eventName).slice()) {\n await listener(...args);\n }\n }\n };\n\n // Store of subscribers that will be called when an event is emitted\n const subscribers = [defaultSubscriber];\n\n const eventHub: EventHub = {\n async emit(eventName, ...args) {\n for (const subscriber of subscribers) {\n await subscriber(eventName, ...args);\n }\n },\n\n subscribe(subscriber) {\n subscribers.push(subscriber);\n\n // Return a function to remove the subscriber\n return () => {\n eventHub.unsubscribe(subscriber);\n };\n },\n\n unsubscribe(subscriber) {\n const subscriberIndex = subscribers.indexOf(subscriber);\n\n // Only remove the subscriber if it exists\n if (subscriberIndex >= 0) {\n subscribers.splice(subscriberIndex, 1);\n }\n },\n\n on(eventName, listener) {\n if (!listeners.has(eventName)) {\n listeners.set(eventName, [listener]);\n } else {\n listeners.get(eventName).push(listener);\n }\n\n // Return a function to remove the listener\n return () => {\n eventHub.off(eventName, listener);\n };\n },\n\n off(eventName, listener) {\n const eventListeners = listeners.get(eventName);\n\n if (eventListeners === undefined) {\n return;\n }\n\n const listenerIndex = eventListeners.indexOf(listener);\n\n // Only remove the listener if it exists\n if (listenerIndex >= 0) {\n eventListeners.splice(listenerIndex, 1);\n }\n },\n\n once(eventName, listener) {\n let fired = false;\n\n // Remove the registered wrapper, not the original listener which is not in the list\n const wrapper: Listener = async (...args) => {\n // An emit that copied the listener list before the removal can still call the wrapper\n if (fired === true) {\n return;\n }\n\n fired = true;\n eventHub.off(eventName, wrapper);\n return listener(...args);\n };\n\n return eventHub.on(eventName, wrapper);\n },\n\n hasListeners(eventName) {\n // Subscribers other than the default one receive every event\n const hasCustomSubscriber = subscribers.some(\n (subscriber) => subscriber !== defaultSubscriber\n );\n // Listeners are only reached through the default subscriber\n const hasEventListener =\n subscribers.includes(defaultSubscriber) && (listeners.get(eventName)?.length ?? 0) > 0;\n\n return hasCustomSubscriber || hasEventListener;\n },\n\n destroy() {\n this.removeAllListeners();\n this.removeAllSubscribers();\n return this;\n },\n\n removeListener(eventName, listener) {\n return eventHub.off(eventName, listener);\n },\n\n removeAllListeners() {\n listeners.clear();\n return this;\n },\n\n removeAllSubscribers() {\n subscribers.length = 0;\n return this;\n },\n\n addListener(eventName, listener) {\n return eventHub.on(eventName, listener);\n },\n };\n\n return eventHub;\n}\n"],"names":["createEventHub","listeners","Map","defaultSubscriber","eventName","args","has","listener","get","slice","subscribers","eventHub","emit","subscriber","subscribe","push","unsubscribe","subscriberIndex","indexOf","splice","on","set","off","eventListeners","undefined","listenerIndex","once","fired","wrapper","hasListeners","hasCustomSubscriber","some","hasEventListener","includes","length","destroy","removeAllListeners","removeAllSubscribers","removeListener","clear","addListener"],"mappings":"AAkBA;;AAEC,IACc,SAASA,cAAAA,GAAAA;AACtB,IAAA,MAAMC,YAAY,IAAIC,GAAAA,EAAAA;;IAGtB,MAAMC,iBAAAA,GAAoB,OAAOC,SAAAA,EAAmB,GAAGC,IAAAA,GAAAA;QACrD,IAAIJ,SAAAA,CAAUK,GAAG,CAACF,SAAAA,CAAAA,EAAY;;;AAG5B,YAAA,KAAK,MAAMG,QAAAA,IAAYN,SAAAA,CAAUO,GAAG,CAACJ,SAAAA,CAAAA,CAAWK,KAAK,EAAA,CAAI;AACvD,gBAAA,MAAMF,QAAAA,CAAAA,GAAYF,IAAAA,CAAAA;AACpB,YAAA;AACF,QAAA;AACF,IAAA,CAAA;;AAGA,IAAA,MAAMK,WAAAA,GAAc;AAACP,QAAAA;AAAkB,KAAA;AAEvC,IAAA,MAAMQ,QAAAA,GAAqB;AACzB,QAAA,MAAMC,IAAAA,CAAAA,CAAKR,SAAS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EAAA;AACzB,YAAA,OAAO,IAAI;AACb,QAAA,CAAA;QAEAC,cAAAA,CAAAA,CAAelC,SAAS,EAAEG,QAAQ,EAAA;YAChC,OAAOI,QAAAA,CAASW,GAAG,CAAClB,SAAAA,EAAWG,QAAAA,CAAAA;AACjC,QAAA,CAAA;AAEA6B,QAAAA,kBAAAA,CAAAA,GAAAA;AACEnC,YAAAA,SAAAA,CAAUsC,KAAK,EAAA;AACf,YAAA,OAAO,IAAI;AACb,QAAA,CAAA;AAEAF,QAAAA,oBAAAA,CAAAA,GAAAA;AACE3B,YAAAA,WAAAA,CAAYwB,MAAM,GAAG,CAAA;AACrB,YAAA,OAAO,IAAI;AACb,QAAA,CAAA;QAEAM,WAAAA,CAAAA,CAAYpC,SAAS,EAAEG,QAAQ,EAAA;YAC7B,OAAOI,QAAAA,CAASS,EAAE,CAAChB,SAAAA,EAAWG,QAAAA,CAAAA;AAChC,QAAA;AACF,KAAA;IAEA,OAAOI,QAAAA;AACT;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handlePost.d.ts","sourceRoot":"","sources":["../../../../src/services/mcp/handlers/handlePost.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"handlePost.d.ts","sourceRoot":"","sources":["../../../../src/services/mcp/handlers/handlePost.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAU1C,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAEtD,eAAO,MAAM,iBAAiB,GAAI,MAAM,sBAAsB,KAAG,IAAI,CAAC,iBA6ErE,CAAC"}
|
|
@@ -4,6 +4,7 @@ var node = require('@modelcontextprotocol/node');
|
|
|
4
4
|
var metrics = require('../metrics/metrics.js');
|
|
5
5
|
var sendJsonRpcError = require('../utils/sendJsonRpcError.js');
|
|
6
6
|
var withTimeout = require('../utils/withTimeout.js');
|
|
7
|
+
var resolveToolSchemaScope = require('../internal/resolveToolSchemaScope.js');
|
|
7
8
|
|
|
8
9
|
const createPostHandler = (deps)=>{
|
|
9
10
|
const { strapi, authenticationStrategy, config, createServerWithRegistries, capabilityDefinitions } = deps;
|
|
@@ -27,19 +28,21 @@ const createPostHandler = (deps)=>{
|
|
|
27
28
|
// Let audit logs pick up MCP actions and tag their origin.
|
|
28
29
|
ctx.state.user = authResult.user;
|
|
29
30
|
ctx.state.auditSource = 'mcp';
|
|
31
|
+
const requestBody = ctx.request.body ?? null;
|
|
30
32
|
const { mcpServer } = createServerWithRegistries({
|
|
31
33
|
strapi,
|
|
32
34
|
definitions: capabilityDefinitions,
|
|
33
35
|
isDevMode: config.isDevMode(),
|
|
34
36
|
ability: authResult.ability,
|
|
35
|
-
user: authResult.user
|
|
37
|
+
user: authResult.user,
|
|
38
|
+
toolSchemaScope: resolveToolSchemaScope.resolveToolSchemaScope(requestBody),
|
|
39
|
+
maxToolInputElements: config.maxToolInputElements
|
|
36
40
|
});
|
|
37
41
|
const transport = new node.NodeStreamableHTTPServerTransport({
|
|
38
42
|
sessionIdGenerator: undefined
|
|
39
43
|
});
|
|
40
44
|
try {
|
|
41
45
|
await withTimeout.withTimeout(mcpServer.connect(transport), config.connectTimeoutMs, 'mcpServer.connect');
|
|
42
|
-
const requestBody = ctx.request.body ?? null;
|
|
43
46
|
await withTimeout.withTimeout(transport.handleRequest(req, res, requestBody), config.requestTimeoutMs, 'transport.handleRequest');
|
|
44
47
|
} finally{
|
|
45
48
|
await mcpServer.close();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handlePost.js","sources":["../../../../src/services/mcp/handlers/handlePost.ts"],"sourcesContent":["import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';\nimport type { Core } from '@strapi/types';\nimport {\n classifyMcpRequestFailure,\n sendDidNotAuthenticateMcpRequest,\n sendDidNotHandleMcpRequest,\n sendDidUseMcpServer,\n} from '../metrics/metrics';\nimport { sendJsonRpcError } from '../utils/sendJsonRpcError';\nimport { withTimeout } from '../utils/withTimeout';\nimport type { McpHandlerDependencies } from './types';\n\nexport const createPostHandler = (deps: McpHandlerDependencies): Core.MiddlewareHandler => {\n const {\n strapi,\n authenticationStrategy,\n config,\n createServerWithRegistries,\n capabilityDefinitions,\n } = deps;\n\n return async (ctx) => {\n // Opt out of Koa's response phase — the MCP SDK writes directly to ctx.res\n // (via res.writeHead / res.end / SSE streaming). Without this, Koa's respond()\n // would also try to write ctx.body to the socket after the handler returns.\n ctx.respond = false;\n const req = ctx.req;\n const res = ctx.res;\n\n let hadAuthenticatedMcpRequest = false;\n\n try {\n const authResult = await authenticationStrategy.authenticate(ctx);\n if (authResult.authenticated === false) {\n sendDidNotAuthenticateMcpRequest(strapi, authResult.reason);\n sendJsonRpcError(res, 'AUTHENTICATION_REQUIRED');\n return;\n }\n\n hadAuthenticatedMcpRequest = true;\n sendDidUseMcpServer(strapi);\n\n // Let audit logs pick up MCP actions and tag their origin.\n ctx.state.user = authResult.user;\n ctx.state.auditSource = 'mcp';\n\n const { mcpServer } = createServerWithRegistries({\n strapi,\n definitions: capabilityDefinitions,\n isDevMode: config.isDevMode(),\n ability: authResult.ability,\n user: authResult.user,\n });\n\n const transport = new NodeStreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n });\n\n try {\n await withTimeout(\n mcpServer.connect(transport),\n config.connectTimeoutMs,\n 'mcpServer.connect'\n );\n\n
|
|
1
|
+
{"version":3,"file":"handlePost.js","sources":["../../../../src/services/mcp/handlers/handlePost.ts"],"sourcesContent":["import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';\nimport type { Core } from '@strapi/types';\nimport {\n classifyMcpRequestFailure,\n sendDidNotAuthenticateMcpRequest,\n sendDidNotHandleMcpRequest,\n sendDidUseMcpServer,\n} from '../metrics/metrics';\nimport { sendJsonRpcError } from '../utils/sendJsonRpcError';\nimport { withTimeout } from '../utils/withTimeout';\nimport { resolveToolSchemaScope } from '../internal/resolveToolSchemaScope';\nimport type { McpHandlerDependencies } from './types';\n\nexport const createPostHandler = (deps: McpHandlerDependencies): Core.MiddlewareHandler => {\n const {\n strapi,\n authenticationStrategy,\n config,\n createServerWithRegistries,\n capabilityDefinitions,\n } = deps;\n\n return async (ctx) => {\n // Opt out of Koa's response phase — the MCP SDK writes directly to ctx.res\n // (via res.writeHead / res.end / SSE streaming). Without this, Koa's respond()\n // would also try to write ctx.body to the socket after the handler returns.\n ctx.respond = false;\n const req = ctx.req;\n const res = ctx.res;\n\n let hadAuthenticatedMcpRequest = false;\n\n try {\n const authResult = await authenticationStrategy.authenticate(ctx);\n if (authResult.authenticated === false) {\n sendDidNotAuthenticateMcpRequest(strapi, authResult.reason);\n sendJsonRpcError(res, 'AUTHENTICATION_REQUIRED');\n return;\n }\n\n hadAuthenticatedMcpRequest = true;\n sendDidUseMcpServer(strapi);\n\n // Let audit logs pick up MCP actions and tag their origin.\n ctx.state.user = authResult.user;\n ctx.state.auditSource = 'mcp';\n\n const requestBody = ctx.request.body ?? null;\n const { mcpServer } = createServerWithRegistries({\n strapi,\n definitions: capabilityDefinitions,\n isDevMode: config.isDevMode(),\n ability: authResult.ability,\n user: authResult.user,\n toolSchemaScope: resolveToolSchemaScope(requestBody),\n maxToolInputElements: config.maxToolInputElements,\n });\n\n const transport = new NodeStreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n });\n\n try {\n await withTimeout(\n mcpServer.connect(transport),\n config.connectTimeoutMs,\n 'mcpServer.connect'\n );\n\n await withTimeout(\n transport.handleRequest(req, res, requestBody),\n config.requestTimeoutMs,\n 'transport.handleRequest'\n );\n } finally {\n await mcpServer.close();\n }\n } catch (error) {\n strapi.log.error('[MCP] Error handling POST request', {\n error: error instanceof Error ? error.message : 'Unknown error',\n stack: error instanceof Error ? error.stack : undefined,\n });\n\n sendJsonRpcError(res, 'INTERNAL_ERROR');\n\n if (hadAuthenticatedMcpRequest) {\n sendDidNotHandleMcpRequest(strapi, classifyMcpRequestFailure(error));\n }\n }\n };\n};\n"],"names":["createPostHandler","deps","strapi","authenticationStrategy","config","createServerWithRegistries","capabilityDefinitions","ctx","respond","req","res","hadAuthenticatedMcpRequest","authResult","authenticate","authenticated","sendDidNotAuthenticateMcpRequest","reason","sendJsonRpcError","sendDidUseMcpServer","state","user","auditSource","requestBody","request","body","mcpServer","definitions","isDevMode","ability","toolSchemaScope","resolveToolSchemaScope","maxToolInputElements","transport","NodeStreamableHTTPServerTransport","sessionIdGenerator","undefined","withTimeout","connect","connectTimeoutMs","handleRequest","requestTimeoutMs","close","error","log","Error","message","stack","sendDidNotHandleMcpRequest","classifyMcpRequestFailure"],"mappings":";;;;;;;;AAaO,MAAMA,oBAAoB,CAACC,IAAAA,GAAAA;IAChC,MAAM,EACJC,MAAM,EACNC,sBAAsB,EACtBC,MAAM,EACNC,0BAA0B,EAC1BC,qBAAqB,EACtB,GAAGL,IAAAA;AAEJ,IAAA,OAAO,OAAOM,GAAAA,GAAAA;;;;AAIZA,QAAAA,GAAAA,CAAIC,OAAO,GAAG,KAAA;QACd,MAAMC,GAAAA,GAAMF,IAAIE,GAAG;QACnB,MAAMC,GAAAA,GAAMH,IAAIG,GAAG;AAEnB,QAAA,IAAIC,0BAAAA,GAA6B,KAAA;QAEjC,IAAI;AACF,YAAA,MAAMC,UAAAA,GAAa,MAAMT,sBAAAA,CAAuBU,YAAY,CAACN,GAAAA,CAAAA;YAC7D,IAAIK,UAAAA,CAAWE,aAAa,KAAK,KAAA,EAAO;gBACtCC,wCAAAA,CAAiCb,MAAAA,EAAQU,WAAWI,MAAM,CAAA;AAC1DC,gBAAAA,iCAAAA,CAAiBP,GAAAA,EAAK,yBAAA,CAAA;AACtB,gBAAA;AACF,YAAA;YAEAC,0BAAAA,GAA6B,IAAA;YAC7BO,2BAAAA,CAAoBhB,MAAAA,CAAAA;;AAGpBK,YAAAA,GAAAA,CAAIY,KAAK,CAACC,IAAI,GAAGR,WAAWQ,I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,KAAK,GAAGX;AAChD,aAAA,CAAA;AAEAlB,YAAAA,iCAAAA,CAAiBP,GAAAA,EAAK,gBAAA,CAAA;AAEtB,YAAA,IAAIC,0BAAAA,EAA4B;AAC9BoC,gBAAAA,kCAAAA,CAA2B7C,QAAQ8C,iCAAAA,CAA0BN,KAAAA,CAAAA,CAAAA;AAC/D,YAAA;AACF,QAAA;AACF,IAAA,CAAA;AACF;;;;"}
|
|
@@ -2,6 +2,7 @@ import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';
|
|
|
2
2
|
import { sendDidNotAuthenticateMcpRequest, sendDidUseMcpServer, sendDidNotHandleMcpRequest, classifyMcpRequestFailure } from '../metrics/metrics.mjs';
|
|
3
3
|
import { sendJsonRpcError } from '../utils/sendJsonRpcError.mjs';
|
|
4
4
|
import { withTimeout } from '../utils/withTimeout.mjs';
|
|
5
|
+
import { resolveToolSchemaScope } from '../internal/resolveToolSchemaScope.mjs';
|
|
5
6
|
|
|
6
7
|
const createPostHandler = (deps)=>{
|
|
7
8
|
const { strapi, authenticationStrategy, config, createServerWithRegistries, capabilityDefinitions } = deps;
|
|
@@ -25,19 +26,21 @@ const createPostHandler = (deps)=>{
|
|
|
25
26
|
// Let audit logs pick up MCP actions and tag their origin.
|
|
26
27
|
ctx.state.user = authResult.user;
|
|
27
28
|
ctx.state.auditSource = 'mcp';
|
|
29
|
+
const requestBody = ctx.request.body ?? null;
|
|
28
30
|
const { mcpServer } = createServerWithRegistries({
|
|
29
31
|
strapi,
|
|
30
32
|
definitions: capabilityDefinitions,
|
|
31
33
|
isDevMode: config.isDevMode(),
|
|
32
34
|
ability: authResult.ability,
|
|
33
|
-
user: authResult.user
|
|
35
|
+
user: authResult.user,
|
|
36
|
+
toolSchemaScope: resolveToolSchemaScope(requestBody),
|
|
37
|
+
maxToolInputElements: config.maxToolInputElements
|
|
34
38
|
});
|
|
35
39
|
const transport = new NodeStreamableHTTPServerTransport({
|
|
36
40
|
sessionIdGenerator: undefined
|
|
37
41
|
});
|
|
38
42
|
try {
|
|
39
43
|
await withTimeout(mcpServer.connect(transport), config.connectTimeoutMs, 'mcpServer.connect');
|
|
40
|
-
const requestBody = ctx.request.body ?? null;
|
|
41
44
|
await withTimeout(transport.handleRequest(req, res, requestBody), config.requestTimeoutMs, 'transport.handleRequest');
|
|
42
45
|
} finally{
|
|
43
46
|
await mcpServer.close();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handlePost.mjs","sources":["../../../../src/services/mcp/handlers/handlePost.ts"],"sourcesContent":["import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';\nimport type { Core } from '@strapi/types';\nimport {\n classifyMcpRequestFailure,\n sendDidNotAuthenticateMcpRequest,\n sendDidNotHandleMcpRequest,\n sendDidUseMcpServer,\n} from '../metrics/metrics';\nimport { sendJsonRpcError } from '../utils/sendJsonRpcError';\nimport { withTimeout } from '../utils/withTimeout';\nimport type { McpHandlerDependencies } from './types';\n\nexport const createPostHandler = (deps: McpHandlerDependencies): Core.MiddlewareHandler => {\n const {\n strapi,\n authenticationStrategy,\n config,\n createServerWithRegistries,\n capabilityDefinitions,\n } = deps;\n\n return async (ctx) => {\n // Opt out of Koa's response phase — the MCP SDK writes directly to ctx.res\n // (via res.writeHead / res.end / SSE streaming). Without this, Koa's respond()\n // would also try to write ctx.body to the socket after the handler returns.\n ctx.respond = false;\n const req = ctx.req;\n const res = ctx.res;\n\n let hadAuthenticatedMcpRequest = false;\n\n try {\n const authResult = await authenticationStrategy.authenticate(ctx);\n if (authResult.authenticated === false) {\n sendDidNotAuthenticateMcpRequest(strapi, authResult.reason);\n sendJsonRpcError(res, 'AUTHENTICATION_REQUIRED');\n return;\n }\n\n hadAuthenticatedMcpRequest = true;\n sendDidUseMcpServer(strapi);\n\n // Let audit logs pick up MCP actions and tag their origin.\n ctx.state.user = authResult.user;\n ctx.state.auditSource = 'mcp';\n\n const { mcpServer } = createServerWithRegistries({\n strapi,\n definitions: capabilityDefinitions,\n isDevMode: config.isDevMode(),\n ability: authResult.ability,\n user: authResult.user,\n });\n\n const transport = new NodeStreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n });\n\n try {\n await withTimeout(\n mcpServer.connect(transport),\n config.connectTimeoutMs,\n 'mcpServer.connect'\n );\n\n
|
|
1
|
+
{"version":3,"file":"handlePost.mjs","sources":["../../../../src/services/mcp/handlers/handlePost.ts"],"sourcesContent":["import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';\nimport type { Core } from '@strapi/types';\nimport {\n classifyMcpRequestFailure,\n sendDidNotAuthenticateMcpRequest,\n sendDidNotHandleMcpRequest,\n sendDidUseMcpServer,\n} from '../metrics/metrics';\nimport { sendJsonRpcError } from '../utils/sendJsonRpcError';\nimport { withTimeout } from '../utils/withTimeout';\nimport { resolveToolSchemaScope } from '../internal/resolveToolSchemaScope';\nimport type { McpHandlerDependencies } from './types';\n\nexport const createPostHandler = (deps: McpHandlerDependencies): Core.MiddlewareHandler => {\n const {\n strapi,\n authenticationStrategy,\n config,\n createServerWithRegistries,\n capabilityDefinitions,\n } = deps;\n\n return async (ctx) => {\n // Opt out of Koa's response phase — the MCP SDK writes directly to ctx.res\n // (via res.writeHead / res.end / SSE streaming). Without this, Koa's respond()\n // would also try to write ctx.body to the socket after the handler returns.\n ctx.respond = false;\n const req = ctx.req;\n const res = ctx.res;\n\n let hadAuthenticatedMcpRequest = false;\n\n try {\n const authResult = await authenticationStrategy.authenticate(ctx);\n if (authResult.authenticated === false) {\n sendDidNotAuthenticateMcpRequest(strapi, authResult.reason);\n sendJsonRpcError(res, 'AUTHENTICATION_REQUIRED');\n return;\n }\n\n hadAuthenticatedMcpRequest = true;\n sendDidUseMcpServer(strapi);\n\n // Let audit logs pick up MCP actions and tag their origin.\n ctx.state.user = authResult.user;\n ctx.state.auditSource = 'mcp';\n\n const requestBody = ctx.request.body ?? null;\n const { mcpServer } = createServerWithRegistries({\n strapi,\n definitions: capabilityDefinitions,\n isDevMode: config.isDevMode(),\n ability: authResult.ability,\n user: authResult.user,\n toolSchemaScope: resolveToolSchemaScope(requestBody),\n maxToolInputElements: config.maxToolInputElements,\n });\n\n const transport = new NodeStreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n });\n\n try {\n await withTimeout(\n mcpServer.connect(transport),\n config.connectTimeoutMs,\n 'mcpServer.connect'\n );\n\n await withTimeout(\n transport.handleRequest(req, res, requestBody),\n config.requestTimeoutMs,\n 'transport.handleRequest'\n );\n } finally {\n await mcpServer.close();\n }\n } catch (error) {\n strapi.log.error('[MCP] Error handling POST request', {\n error: error instanceof Error ? error.message : 'Unknown error',\n stack: error instanceof Error ? error.stack : undefined,\n });\n\n sendJsonRpcError(res, 'INTERNAL_ERROR');\n\n if (hadAuthenticatedMcpRequest) {\n sendDidNotHandleMcpRequest(strapi, classifyMcpRequestFailure(error));\n }\n }\n };\n};\n"],"names":["createPostHandler","deps","strapi","authenticationStrategy","config","createServerWithRegistries","capabilityDefinitions","ctx","respond","req","res","hadAuthenticatedMcpRequest","authResult","authenticate","authenticated","sendDidNotAuthenticateMcpRequest","reason","sendJsonRpcError","sendDidUseMcpServer","state","user","auditSource","requestBody","request","body","mcpServer","definitions","isDevMode","ability","toolSchemaScope","resolveToolSchemaScope","maxToolInputElements","transport","NodeStreamableHTTPServerTransport","sessionIdGenerator","undefined","withTimeout","connect","connectTimeoutMs","handleRequest","requestTimeoutMs","close","error","log","Error","message","stack","sendDidNotHandleMcpRequest","classifyMcpRequestFailure"],"mappings":";;;;;;AAaO,MAAMA,oBAAoB,CAACC,IAAAA,GAAAA;IAChC,MAAM,EACJC,MAAM,EACNC,sBAAsB,EACtBC,MAAM,EACNC,0BAA0B,EAC1BC,qBAAqB,EACtB,GAAGL,IAAAA;AAEJ,IAAA,OAAO,OAAOM,GAAAA,GAAAA;;;;AAIZA,QAAAA,GAAAA,CAAIC,OAAO,GAAG,KAAA;QACd,MAAMC,GAAAA,GAAMF,IAAIE,GAAG;QACnB,MAAMC,GAAAA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;gBAGF,MAAMF,WAAAA,CACJJ,UAAUO,aAAa,CAAC9B,KAAKC,GAAAA,EAAKY,WAAAA,CAAAA,EAClClB,MAAAA,CAAOoC,gBAAgB,EACvB,yBAAA,CAAA;YAEJ,CAAA,QAAU;AACR,gBAAA,MAAMf,UAAUgB,KAAK,EAAA;AACvB,YAAA;AACF,QAAA,CAAA,CAAE,OAAOC,KAAAA,EAAO;AACdxC,YAAAA,MAAAA,CAAOyC,GAAG,CAACD,KAAK,CAAC,mCAAA,EAAqC;AACpDA,gBAAAA,KAAAA,EAAOA,KAAAA,YAAiBE,KAAAA,GAAQF,KAAAA,CAAMG,OAAO,GAAG,eAAA;AAChDC,gBAAAA,KAAAA,EAAOJ,KAAAA,YAAiBE,KAAAA,GAAQF,KAAAA,CAAMI,KAAK,GAAGX;AAChD,aAAA,CAAA;AAEAlB,YAAAA,gBAAAA,CAAiBP,GAAAA,EAAK,gBAAA,CAAA;AAEtB,YAAA,IAAIC,0BAAAA,EAA4B;AAC9BoC,gBAAAA,0BAAAA,CAA2B7C,QAAQ8C,yBAAAA,CAA0BN,KAAAA,CAAAA,CAAAA;AAC/D,YAAA;AACF,QAAA;AACF,IAAA,CAAA;AACF;;;;"}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import type { Core } from '@strapi/types';
|
|
2
|
+
export declare const DEFAULT_MAX_TOOL_INPUT_ELEMENTS = 10000;
|
|
2
3
|
export declare class McpConfiguration {
|
|
3
4
|
#private;
|
|
4
5
|
readonly path: string;
|
|
5
6
|
readonly connectTimeoutMs: number;
|
|
6
7
|
readonly requestTimeoutMs: number;
|
|
8
|
+
readonly maxToolInputElements: number;
|
|
7
9
|
constructor(strapi: Core.Strapi);
|
|
8
10
|
isEnabled(): boolean;
|
|
9
11
|
isDevMode(): boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"McpConfiguration.d.ts","sourceRoot":"","sources":["../../../../src/services/mcp/internal/McpConfiguration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAE1C,qBAAa,gBAAgB;;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAElC,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"McpConfiguration.d.ts","sourceRoot":"","sources":["../../../../src/services/mcp/internal/McpConfiguration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAE1C,eAAO,MAAM,+BAA+B,QAAS,CAAC;AAyBtD,qBAAa,gBAAgB;;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAElC,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAElC,QAAQ,CAAC,oBAAoB,EAAE,MAAM,CAAC;gBAI1B,MAAM,EAAE,IAAI,CAAC,MAAM;IAQ/B,SAAS,IAAI,OAAO;IAIpB,SAAS,IAAI,OAAO;CAGrB"}
|
|
@@ -10,6 +10,21 @@ var id = 0;
|
|
|
10
10
|
function _class_private_field_loose_key(name) {
|
|
11
11
|
return "__private_" + id++ + "_" + name;
|
|
12
12
|
}
|
|
13
|
+
const DEFAULT_MAX_TOOL_INPUT_ELEMENTS = 10000;
|
|
14
|
+
// The SDK throws on any value that is not a number >= 1, so only a valid value may reach it.
|
|
15
|
+
const resolveMaxToolInputElements = (strapi)=>{
|
|
16
|
+
const raw = strapi.config.get('server.mcp.maxToolInputElements');
|
|
17
|
+
if (raw === undefined) {
|
|
18
|
+
return DEFAULT_MAX_TOOL_INPUT_ELEMENTS;
|
|
19
|
+
}
|
|
20
|
+
// env() returns strings
|
|
21
|
+
const value = typeof raw === 'string' && raw.trim() !== '' ? Number(raw) : raw;
|
|
22
|
+
if (value === Infinity || Number.isInteger(value) && value >= 1) {
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
strapi.log.warn(`[MCP] Invalid server.mcp.maxToolInputElements (${String(raw)}). ` + `Expected an integer >= 1 or Infinity. Using ${DEFAULT_MAX_TOOL_INPUT_ELEMENTS}.`);
|
|
26
|
+
return DEFAULT_MAX_TOOL_INPUT_ELEMENTS;
|
|
27
|
+
};
|
|
13
28
|
var _strapi = /*#__PURE__*/ _class_private_field_loose_key("_strapi");
|
|
14
29
|
class McpConfiguration {
|
|
15
30
|
isEnabled() {
|
|
@@ -27,8 +42,10 @@ class McpConfiguration {
|
|
|
27
42
|
this.path = '/mcp';
|
|
28
43
|
this.connectTimeoutMs = strapi.config.get('server.mcp.connectTimeoutMs', 5 * 1000); // 5 seconds
|
|
29
44
|
this.requestTimeoutMs = strapi.config.get('server.mcp.requestTimeoutMs', 60 * 1000); // 60 seconds
|
|
45
|
+
this.maxToolInputElements = resolveMaxToolInputElements(strapi);
|
|
30
46
|
}
|
|
31
47
|
}
|
|
32
48
|
|
|
49
|
+
exports.DEFAULT_MAX_TOOL_INPUT_ELEMENTS = DEFAULT_MAX_TOOL_INPUT_ELEMENTS;
|
|
33
50
|
exports.McpConfiguration = McpConfiguration;
|
|
34
51
|
//# sourceMappingURL=McpConfiguration.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"McpConfiguration.js","sources":["../../../../src/services/mcp/internal/McpConfiguration.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport class McpConfiguration {\n readonly path: string;\n\n readonly connectTimeoutMs: number;\n\n readonly requestTimeoutMs: number;\n\n #strapi: Core.Strapi;\n\n constructor(strapi: Core.Strapi) {\n this.#strapi = strapi;\n this.path = '/mcp';\n this.connectTimeoutMs = strapi.config.get('server.mcp.connectTimeoutMs', 5 * 1000); // 5 seconds\n this.requestTimeoutMs = strapi.config.get('server.mcp.requestTimeoutMs', 60 * 1000); // 60 seconds\n }\n\n isEnabled(): boolean {\n return this.#strapi.config.get<boolean>('server.mcp.enabled', false) === true;\n }\n\n isDevMode(): boolean {\n return this.#strapi.config.get('autoReload', false);\n }\n}\n"],"names":["
|
|
1
|
+
{"version":3,"file":"McpConfiguration.js","sources":["../../../../src/services/mcp/internal/McpConfiguration.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport const DEFAULT_MAX_TOOL_INPUT_ELEMENTS = 10_000;\n\n// The SDK throws on any value that is not a number >= 1, so only a valid value may reach it.\nconst resolveMaxToolInputElements = (strapi: Core.Strapi): number => {\n const raw = strapi.config.get<unknown>('server.mcp.maxToolInputElements');\n\n if (raw === undefined) {\n return DEFAULT_MAX_TOOL_INPUT_ELEMENTS;\n }\n\n // env() returns strings\n const value = typeof raw === 'string' && raw.trim() !== '' ? Number(raw) : raw;\n\n if (value === Infinity || (Number.isInteger(value) && (value as number) >= 1)) {\n return value as number;\n }\n\n strapi.log.warn(\n `[MCP] Invalid server.mcp.maxToolInputElements (${String(raw)}). ` +\n `Expected an integer >= 1 or Infinity. Using ${DEFAULT_MAX_TOOL_INPUT_ELEMENTS}.`\n );\n\n return DEFAULT_MAX_TOOL_INPUT_ELEMENTS;\n};\n\nexport class McpConfiguration {\n readonly path: string;\n\n readonly connectTimeoutMs: number;\n\n readonly requestTimeoutMs: number;\n\n readonly maxToolInputElements: number;\n\n #strapi: Core.Strapi;\n\n constructor(strapi: Core.Strapi) {\n this.#strapi = strapi;\n this.path = '/mcp';\n this.connectTimeoutMs = strapi.config.get('server.mcp.connectTimeoutMs', 5 * 1000); // 5 seconds\n this.requestTimeoutMs = strapi.config.get('server.mcp.requestTimeoutMs', 60 * 1000); // 60 seconds\n this.maxToolInputElements = resolveMaxToolInputElements(strapi);\n }\n\n isEnabled(): boolean {\n return this.#strapi.config.get<boolean>('server.mcp.enabled', false) === true;\n }\n\n isDevMode(): boolean {\n return this.#strapi.config.get('autoReload', false);\n }\n}\n"],"names":["DEFAULT_MAX_TOOL_INPUT_ELEMENTS","resolveMaxToolInputElements","strapi","raw","config","get","undefined","value","trim","Number","Infinity","isInteger","log","warn","String","McpConfiguration","isEnabled","isDevMode","path","connectTimeoutMs","requestTimeoutMs","maxToolInputElements"],"mappings":";;;;;;;;;;;;AAEO,MAAMA,kCAAkC;AAE/C;AACA,MAAMC,8BAA8B,CAACC,MAAAA,GAAAA;AACnC,IAAA,MAAMC,GAAAA,GAAMD,MAAAA,CAAOE,MAAM,CAACC,GAAG,CAAU,iCAAA,CAAA;AAEvC,IAAA,IAAIF,QAAQG,SAAAA,EAAW;QACrB,OAAON,+BAAAA;AACT,IAAA;;IAGA,MAAMO,KAAAA,GAAQ,OAAOJ,GAAAA,KAAQ,QAAA,IAAYA,IAAIK,IAAI,EAAA,KAAO,EAAA,GAAKC,MAAAA,CAAON,GAAAA,CAAAA,GAAOA,GAAAA;IAE3E,IAAII,KAAAA,KAAUG,YAAaD,MAAAA,CAAOE,SAAS,CAACJ,KAAAA,CAAAA,IAAWA,SAAoB,CAAA,EAAI;QAC7E,OAAOA,KAAAA;AACT,IAAA;AAEAL,IAAAA,MAAAA,CAAOU,GAAG,CAACC,IAAI,CACb,CAAC,+CAA+C,EAAEC,MAAAA,CAAOX,GAAAA,CAAAA,CAAK,GAAG,CAAC,GAChE,CAAC,4CAA4C,EAAEH,+BAAAA,CAAgC,CAAC,CAAC,CAAA;IAGrF,OAAOA,+BAAAA;AACT,CAAA;AAWE,IAAA,OAAA,iBAAA,8BAAA,CAAA,SAAA,CAAA;AATK,MAAMe,gBAAAA,CAAAA;IAmBXC,SAAAA,GAAqB;QACnB,OAAO,+BAAA,CAAA,IAAI,EAAC,OAAA,CAAA,CAAA,OAAA,CAAA,CAAQZ,MAAM,CAACC,GAAG,CAAU,oBAAA,EAAsB,KAAA,CAAA,KAAW,IAAA;AAC3E,IAAA;IAEAY,SAAAA,GAAqB;QACnB,OAAO,+BAAA,CAAA,IAAI,EAAC,OAAA,CAAA,CAAA,SAAQb,MAAM,CAACC,GAAG,CAAC,YAAA,EAAc,K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