@strapi/core 5.48.0 → 5.49.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/Strapi.js +9 -5
- package/dist/Strapi.js.map +1 -1
- package/dist/Strapi.mjs +0 -1
- package/dist/Strapi.mjs.map +1 -1
- package/dist/ai.d.ts +2 -0
- package/dist/ai.d.ts.map +1 -0
- package/dist/ai.js +8 -0
- package/dist/ai.js.map +1 -0
- package/dist/ai.mjs +3 -0
- package/dist/ai.mjs.map +1 -0
- package/dist/configuration/config-loader.js +11 -6
- package/dist/configuration/config-loader.js.map +1 -1
- package/dist/configuration/index.js +22 -15
- package/dist/configuration/index.js.map +1 -1
- package/dist/configuration/urls.js +11 -7
- package/dist/configuration/urls.js.map +1 -1
- package/dist/core-api/routes/index.js +3 -2
- package/dist/core-api/routes/index.js.map +1 -1
- package/dist/core-api/routes/validation/common.js +3 -2
- package/dist/core-api/routes/validation/common.js.map +1 -1
- package/dist/core-api/routes/validation/content-type.js +3 -2
- package/dist/core-api/routes/validation/content-type.js.map +1 -1
- package/dist/core-api/routes/validation/mappers.js +3 -2
- package/dist/core-api/routes/validation/mappers.js.map +1 -1
- package/dist/core-api/routes/validation/utils.js +3 -2
- package/dist/core-api/routes/validation/utils.js.map +1 -1
- package/dist/domain/content-type/index.js +9 -5
- package/dist/domain/content-type/index.js.map +1 -1
- package/dist/domain/content-type/validator.js +6 -2
- package/dist/domain/content-type/validator.js.map +1 -1
- package/dist/domain/module/index.js +6 -2
- package/dist/domain/module/index.js.map +1 -1
- package/dist/ee/license.js +8 -3
- package/dist/ee/license.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -0
- package/dist/index.mjs.map +1 -1
- package/dist/loaders/admin.js +5 -1
- package/dist/loaders/admin.js.map +1 -1
- package/dist/loaders/apis.js +16 -11
- package/dist/loaders/apis.js.map +1 -1
- package/dist/loaders/components.js +6 -2
- package/dist/loaders/components.js.map +1 -1
- package/dist/loaders/middlewares.js +6 -2
- package/dist/loaders/middlewares.js.map +1 -1
- package/dist/loaders/plugins/get-enabled-plugins.js +5 -1
- package/dist/loaders/plugins/get-enabled-plugins.js.map +1 -1
- package/dist/loaders/plugins/get-user-plugins-config.js +6 -2
- package/dist/loaders/plugins/get-user-plugins-config.js.map +1 -1
- package/dist/loaders/plugins/index.js +8 -4
- package/dist/loaders/plugins/index.js.map +1 -1
- package/dist/loaders/policies.js +6 -2
- package/dist/loaders/policies.js.map +1 -1
- package/dist/mcp.d.ts +4 -0
- package/dist/mcp.d.ts.map +1 -0
- package/dist/mcp.js +12 -0
- package/dist/mcp.js.map +1 -0
- package/dist/mcp.mjs +4 -0
- package/dist/mcp.mjs.map +1 -0
- package/dist/middlewares/body.js +8 -3
- package/dist/middlewares/body.js.map +1 -1
- package/dist/middlewares/compression.js +5 -1
- package/dist/middlewares/compression.js.map +1 -1
- package/dist/middlewares/cors.js +5 -1
- package/dist/middlewares/cors.js.map +1 -1
- package/dist/middlewares/favicon.js +5 -1
- package/dist/middlewares/favicon.js.map +1 -1
- package/dist/middlewares/ip.js +5 -1
- package/dist/middlewares/ip.js.map +1 -1
- package/dist/middlewares/public.js +5 -1
- package/dist/middlewares/public.js.map +1 -1
- package/dist/middlewares/query.js +6 -2
- package/dist/middlewares/query.js.map +1 -1
- package/dist/middlewares/security.js +5 -1
- package/dist/middlewares/security.js.map +1 -1
- package/dist/migrations/database/5.0.0-discard-drafts.js +5 -1
- package/dist/migrations/database/5.0.0-discard-drafts.js.map +1 -1
- package/dist/migrations/first-published-at.js +5 -1
- package/dist/migrations/first-published-at.js.map +1 -1
- package/dist/package.json.js +19 -18
- package/dist/package.json.js.map +1 -1
- package/dist/package.json.mjs +19 -18
- package/dist/package.json.mjs.map +1 -1
- package/dist/registries/sanitizers.js +7 -3
- package/dist/registries/sanitizers.js.map +1 -1
- package/dist/registries/validators.js +7 -3
- package/dist/registries/validators.js.map +1 -1
- package/dist/services/auth/index.js +7 -3
- package/dist/services/auth/index.js.map +1 -1
- package/dist/services/content-api/index.js +10 -6
- package/dist/services/content-api/index.js.map +1 -1
- package/dist/services/content-api/permissions/engine.js +5 -1
- package/dist/services/content-api/permissions/engine.js.map +1 -1
- package/dist/services/content-api/permissions/index.js +10 -6
- package/dist/services/content-api/permissions/index.js.map +1 -1
- package/dist/services/document-service/attributes/transforms.js +5 -1
- package/dist/services/document-service/attributes/transforms.js.map +1 -1
- package/dist/services/document-service/components.d.ts.map +1 -1
- package/dist/services/document-service/components.js +14 -10
- package/dist/services/document-service/components.js.map +1 -1
- package/dist/services/document-service/components.mjs.map +1 -1
- package/dist/services/document-service/draft-and-publish.js +1 -1
- package/dist/services/document-service/draft-and-publish.js.map +1 -1
- package/dist/services/document-service/draft-and-publish.mjs +1 -1
- package/dist/services/document-service/draft-and-publish.mjs.map +1 -1
- package/dist/services/document-service/entries.d.ts.map +1 -1
- package/dist/services/document-service/entries.js +6 -2
- package/dist/services/document-service/entries.js.map +1 -1
- package/dist/services/document-service/entries.mjs +7 -3
- package/dist/services/document-service/entries.mjs.map +1 -1
- package/dist/services/document-service/internationalization.js.map +1 -1
- package/dist/services/document-service/internationalization.mjs.map +1 -1
- package/dist/services/document-service/transform/data.d.ts +2 -0
- package/dist/services/document-service/transform/data.d.ts.map +1 -1
- package/dist/services/document-service/transform/data.js +7 -1
- package/dist/services/document-service/transform/data.js.map +1 -1
- package/dist/services/document-service/transform/data.mjs +7 -2
- package/dist/services/document-service/transform/data.mjs.map +1 -1
- package/dist/services/document-service/utils/populate.d.ts +1 -1
- package/dist/services/document-service/utils/populate.d.ts.map +1 -1
- package/dist/services/document-service/utils/populate.js.map +1 -1
- package/dist/services/document-service/utils/populate.mjs.map +1 -1
- package/dist/services/entity-service/index.js +9 -4
- package/dist/services/entity-service/index.js.map +1 -1
- package/dist/services/entity-validator/index.d.ts.map +1 -1
- package/dist/services/entity-validator/index.js +9 -4
- package/dist/services/entity-validator/index.js.map +1 -1
- package/dist/services/entity-validator/index.mjs.map +1 -1
- package/dist/services/entity-validator/validators.js +10 -6
- package/dist/services/entity-validator/validators.js.map +1 -1
- package/dist/services/errors.js +7 -3
- package/dist/services/errors.js.map +1 -1
- package/dist/services/fs.js +10 -5
- package/dist/services/fs.js.map +1 -1
- package/dist/services/mcp/prompt-registry.d.ts +31 -3
- package/dist/services/mcp/prompt-registry.d.ts.map +1 -1
- package/dist/services/mcp/prompt-registry.js +31 -0
- package/dist/services/mcp/prompt-registry.js.map +1 -1
- package/dist/services/mcp/prompt-registry.mjs +31 -1
- package/dist/services/mcp/prompt-registry.mjs.map +1 -1
- package/dist/services/mcp/resource-registry.d.ts +31 -1
- package/dist/services/mcp/resource-registry.d.ts.map +1 -1
- package/dist/services/mcp/resource-registry.js +31 -0
- package/dist/services/mcp/resource-registry.js.map +1 -1
- package/dist/services/mcp/resource-registry.mjs +31 -1
- package/dist/services/mcp/resource-registry.mjs.map +1 -1
- package/dist/services/mcp/tool-registry.d.ts +36 -9
- package/dist/services/mcp/tool-registry.d.ts.map +1 -1
- package/dist/services/mcp/tool-registry.js +35 -3
- package/dist/services/mcp/tool-registry.js.map +1 -1
- package/dist/services/mcp/tool-registry.mjs +35 -3
- package/dist/services/mcp/tool-registry.mjs.map +1 -1
- package/dist/services/mcp/tools/log.d.ts +15 -85
- package/dist/services/mcp/tools/log.d.ts.map +1 -1
- package/dist/services/metrics/admin-user-hash.js +5 -1
- package/dist/services/metrics/admin-user-hash.js.map +1 -1
- package/dist/services/metrics/is-truthy.js +5 -1
- package/dist/services/metrics/is-truthy.js.map +1 -1
- package/dist/services/metrics/sender.js +17 -9
- package/dist/services/metrics/sender.js.map +1 -1
- package/dist/services/server/api.js +5 -1
- package/dist/services/server/api.js.map +1 -1
- package/dist/services/server/compose-endpoint.js +5 -1
- package/dist/services/server/compose-endpoint.js.map +1 -1
- package/dist/services/server/http-server.js +5 -1
- package/dist/services/server/http-server.js.map +1 -1
- package/dist/services/server/index.js +5 -1
- package/dist/services/server/index.js.map +1 -1
- package/dist/services/server/koa.js +12 -5
- package/dist/services/server/koa.js.map +1 -1
- package/dist/services/server/middleware.js +5 -1
- package/dist/services/server/middleware.js.map +1 -1
- package/dist/services/server/openapi.js +11 -6
- package/dist/services/server/openapi.js.map +1 -1
- package/dist/services/server/register-routes.js +8 -4
- package/dist/services/server/register-routes.js.map +1 -1
- package/dist/services/server/routing.js +5 -1
- package/dist/services/server/routing.js.map +1 -1
- package/dist/services/session-manager.js +14 -9
- package/dist/services/session-manager.js.map +1 -1
- package/dist/services/webhook-runner.js +7 -2
- package/dist/services/webhook-runner.js.map +1 -1
- package/dist/services/worker-queue.js +5 -1
- package/dist/services/worker-queue.js.map +1 -1
- package/dist/utils/filepath-to-prop-path.js +13 -8
- package/dist/utils/filepath-to-prop-path.js.map +1 -1
- package/dist/utils/load-config-file.js +7 -2
- package/dist/utils/load-config-file.js.map +1 -1
- package/dist/utils/load-files.js +12 -6
- package/dist/utils/load-files.js.map +1 -1
- package/dist/utils/open-browser.js +5 -1
- package/dist/utils/open-browser.js.map +1 -1
- package/dist/utils/resolve-working-dirs.js +6 -2
- package/dist/utils/resolve-working-dirs.js.map +1 -1
- package/dist/utils/startup-logger.js +27 -21
- package/dist/utils/startup-logger.js.map +1 -1
- package/dist/utils/transform-content-types-to-models.d.ts.map +1 -1
- package/dist/utils/transform-content-types-to-models.js +15 -6
- package/dist/utils/transform-content-types-to-models.js.map +1 -1
- package/dist/utils/transform-content-types-to-models.mjs +5 -1
- package/dist/utils/transform-content-types-to-models.mjs.map +1 -1
- package/dist/utils/update-notifier/index.d.ts.map +1 -1
- package/dist/utils/update-notifier/index.js +21 -8
- package/dist/utils/update-notifier/index.js.map +1 -1
- package/dist/utils/update-notifier/index.mjs +6 -1
- package/dist/utils/update-notifier/index.mjs.map +1 -1
- package/package.json +19 -18
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../src/domain/content-type/index.ts"],"sourcesContent":["import { cloneDeep } from 'lodash/fp';\nimport _ from 'lodash';\nimport { yup, contentTypes as contentTypesUtils } from '@strapi/utils';\nimport type { Schema } from '@strapi/types';\nimport { validateContentTypeDefinition } from './validator';\n\nexport type ContentTypeDefinition = {\n schema: Schema.ContentType;\n actions: Record<string, unknown>;\n lifecycles: Record<string, unknown>;\n};\n\nconst {\n CREATED_AT_ATTRIBUTE,\n UPDATED_AT_ATTRIBUTE,\n PUBLISHED_AT_ATTRIBUTE,\n FIRST_PUBLISHED_AT_ATTRIBUTE,\n CREATED_BY_ATTRIBUTE,\n UPDATED_BY_ATTRIBUTE,\n} = contentTypesUtils.constants;\n\nconst createContentType = (uid: string, definition: ContentTypeDefinition) => {\n try {\n validateContentTypeDefinition(definition);\n } catch (e) {\n if (e instanceof yup.ValidationError) {\n throw new Error(`Content Type Definition is invalid for ${uid}'.\\n${e.errors}`);\n }\n\n throw e;\n }\n\n const { schema, actions, lifecycles } = cloneDeep(definition);\n\n // general info\n Object.assign(schema, {\n uid,\n modelType: 'contentType',\n kind: schema.kind || 'collectionType',\n __schema__: pickSchema(definition.schema),\n modelName: definition.schema.info.singularName,\n actions,\n lifecycles,\n });\n\n addTimestamps(schema);\n\n // Published at is added regardless of draft and publish being enabled\n // In case it is not enabled, value will be always published, and it will not contain a draft\n addDraftAndPublish(schema);\n\n addCreatorFields(schema);\n\n addFirstPublishedAt(schema);\n\n return schema;\n};\n\nconst addTimestamps = (schema: Schema.ContentType) => {\n // attributes\n Object.assign(schema.attributes, {\n [CREATED_AT_ATTRIBUTE]: {\n type: 'datetime',\n },\n // TODO: handle on edit set to new date\n [UPDATED_AT_ATTRIBUTE]: {\n type: 'datetime',\n },\n });\n};\n\nconst addDraftAndPublish = (schema: Schema.ContentType) => {\n if (!_.has(schema, 'options.draftAndPublish')) {\n _.set(schema, 'options.draftAndPublish', false); // Disabled by default\n }\n\n schema.attributes[PUBLISHED_AT_ATTRIBUTE] = {\n type: 'datetime',\n configurable: false,\n writable: true,\n visible: true,\n default() {\n return new Date();\n },\n };\n};\n\nconst addFirstPublishedAt = (schema: Schema.ContentType) => {\n const isEnabled = contentTypesUtils.hasFirstPublishedAtField(schema);\n\n // Note: As an expertimental feature, we are okay if this data is deleted if this feature is\n // switched off. Once \"preserve_attributes\" come into play, this will be updated.\n if (isEnabled) {\n strapi.log.warn(`Experimental feature enabled: firstPublishedAt on ${schema.collectionName}`);\n schema.attributes[FIRST_PUBLISHED_AT_ATTRIBUTE] = {\n type: 'datetime',\n configurable: false,\n writable: true,\n visible: false,\n private: !isEnabled,\n };\n }\n};\n\nconst addCreatorFields = (schema: Schema.ContentType) => {\n const isPrivate = !_.get(schema, 'options.populateCreatorFields', false);\n\n schema.attributes[CREATED_BY_ATTRIBUTE] = {\n type: 'relation',\n relation: 'oneToOne',\n target: 'admin::user',\n configurable: false,\n writable: false,\n visible: false,\n useJoinTable: false,\n private: isPrivate,\n };\n\n schema.attributes[UPDATED_BY_ATTRIBUTE] = {\n type: 'relation',\n relation: 'oneToOne',\n target: 'admin::user',\n configurable: false,\n writable: false,\n visible: false,\n useJoinTable: false,\n private: isPrivate,\n };\n};\n\nconst getGlobalId = (schema: Schema.ContentType, prefix?: string) => {\n const modelName = schema.info.singularName;\n const globalId = prefix ? `${prefix}-${modelName}` : modelName;\n\n return schema.globalId || _.upperFirst(_.camelCase(globalId));\n};\n\nconst pickSchema = (model: Schema.ContentType) => {\n const schema = _.cloneDeep(\n _.pick(model, [\n 'connection',\n 'collectionName',\n 'info',\n 'options',\n 'pluginOptions',\n 'attributes',\n 'kind',\n ])\n );\n\n schema.kind = model.kind || 'collectionType';\n return schema;\n};\n\nexport { createContentType, getGlobalId };\n"],"names":["CREATED_AT_ATTRIBUTE","UPDATED_AT_ATTRIBUTE","PUBLISHED_AT_ATTRIBUTE","FIRST_PUBLISHED_AT_ATTRIBUTE","CREATED_BY_ATTRIBUTE","UPDATED_BY_ATTRIBUTE","contentTypesUtils","constants","createContentType","uid","definition","validateContentTypeDefinition","e","yup","ValidationError","Error","errors","schema","actions","lifecycles","cloneDeep","Object","assign","modelType","kind","__schema__","pickSchema","modelName","info","singularName","addTimestamps","addDraftAndPublish","addCreatorFields","addFirstPublishedAt","attributes","type","_","has","set","configurable","writable","visible","default","Date","isEnabled","hasFirstPublishedAtField","strapi","log","warn","collectionName","private","isPrivate","get","relation","target","useJoinTable","getGlobalId","prefix","globalId","upperFirst","camelCase","model","pick"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/domain/content-type/index.ts"],"sourcesContent":["import { cloneDeep } from 'lodash/fp';\nimport _ from 'lodash';\nimport { yup, contentTypes as contentTypesUtils } from '@strapi/utils';\nimport type { Schema } from '@strapi/types';\nimport { validateContentTypeDefinition } from './validator';\n\nexport type ContentTypeDefinition = {\n schema: Schema.ContentType;\n actions: Record<string, unknown>;\n lifecycles: Record<string, unknown>;\n};\n\nconst {\n CREATED_AT_ATTRIBUTE,\n UPDATED_AT_ATTRIBUTE,\n PUBLISHED_AT_ATTRIBUTE,\n FIRST_PUBLISHED_AT_ATTRIBUTE,\n CREATED_BY_ATTRIBUTE,\n UPDATED_BY_ATTRIBUTE,\n} = contentTypesUtils.constants;\n\nconst createContentType = (uid: string, definition: ContentTypeDefinition) => {\n try {\n validateContentTypeDefinition(definition);\n } catch (e) {\n if (e instanceof yup.ValidationError) {\n throw new Error(`Content Type Definition is invalid for ${uid}'.\\n${e.errors}`);\n }\n\n throw e;\n }\n\n const { schema, actions, lifecycles } = cloneDeep(definition);\n\n // general info\n Object.assign(schema, {\n uid,\n modelType: 'contentType',\n kind: schema.kind || 'collectionType',\n __schema__: pickSchema(definition.schema),\n modelName: definition.schema.info.singularName,\n actions,\n lifecycles,\n });\n\n addTimestamps(schema);\n\n // Published at is added regardless of draft and publish being enabled\n // In case it is not enabled, value will be always published, and it will not contain a draft\n addDraftAndPublish(schema);\n\n addCreatorFields(schema);\n\n addFirstPublishedAt(schema);\n\n return schema;\n};\n\nconst addTimestamps = (schema: Schema.ContentType) => {\n // attributes\n Object.assign(schema.attributes, {\n [CREATED_AT_ATTRIBUTE]: {\n type: 'datetime',\n },\n // TODO: handle on edit set to new date\n [UPDATED_AT_ATTRIBUTE]: {\n type: 'datetime',\n },\n });\n};\n\nconst addDraftAndPublish = (schema: Schema.ContentType) => {\n if (!_.has(schema, 'options.draftAndPublish')) {\n _.set(schema, 'options.draftAndPublish', false); // Disabled by default\n }\n\n schema.attributes[PUBLISHED_AT_ATTRIBUTE] = {\n type: 'datetime',\n configurable: false,\n writable: true,\n visible: true,\n default() {\n return new Date();\n },\n };\n};\n\nconst addFirstPublishedAt = (schema: Schema.ContentType) => {\n const isEnabled = contentTypesUtils.hasFirstPublishedAtField(schema);\n\n // Note: As an expertimental feature, we are okay if this data is deleted if this feature is\n // switched off. Once \"preserve_attributes\" come into play, this will be updated.\n if (isEnabled) {\n strapi.log.warn(`Experimental feature enabled: firstPublishedAt on ${schema.collectionName}`);\n schema.attributes[FIRST_PUBLISHED_AT_ATTRIBUTE] = {\n type: 'datetime',\n configurable: false,\n writable: true,\n visible: false,\n private: !isEnabled,\n };\n }\n};\n\nconst addCreatorFields = (schema: Schema.ContentType) => {\n const isPrivate = !_.get(schema, 'options.populateCreatorFields', false);\n\n schema.attributes[CREATED_BY_ATTRIBUTE] = {\n type: 'relation',\n relation: 'oneToOne',\n target: 'admin::user',\n configurable: false,\n writable: false,\n visible: false,\n useJoinTable: false,\n private: isPrivate,\n };\n\n schema.attributes[UPDATED_BY_ATTRIBUTE] = {\n type: 'relation',\n relation: 'oneToOne',\n target: 'admin::user',\n configurable: false,\n writable: false,\n visible: false,\n useJoinTable: false,\n private: isPrivate,\n };\n};\n\nconst getGlobalId = (schema: Schema.ContentType, prefix?: string) => {\n const modelName = schema.info.singularName;\n const globalId = prefix ? `${prefix}-${modelName}` : modelName;\n\n return schema.globalId || _.upperFirst(_.camelCase(globalId));\n};\n\nconst pickSchema = (model: Schema.ContentType) => {\n const schema = _.cloneDeep(\n _.pick(model, [\n 'connection',\n 'collectionName',\n 'info',\n 'options',\n 'pluginOptions',\n 'attributes',\n 'kind',\n ])\n );\n\n schema.kind = model.kind || 'collectionType';\n return schema;\n};\n\nexport { createContentType, getGlobalId };\n"],"names":["CREATED_AT_ATTRIBUTE","UPDATED_AT_ATTRIBUTE","PUBLISHED_AT_ATTRIBUTE","FIRST_PUBLISHED_AT_ATTRIBUTE","CREATED_BY_ATTRIBUTE","UPDATED_BY_ATTRIBUTE","contentTypesUtils","constants","createContentType","uid","definition","validateContentTypeDefinition","e","yup","ValidationError","Error","errors","schema","actions","lifecycles","cloneDeep","Object","assign","modelType","kind","__schema__","pickSchema","modelName","info","singularName","addTimestamps","addDraftAndPublish","addCreatorFields","addFirstPublishedAt","attributes","type","_","has","set","configurable","writable","visible","default","Date","isEnabled","hasFirstPublishedAtField","strapi","log","warn","collectionName","private","isPrivate","get","relation","target","useJoinTable","getGlobalId","prefix","globalId","upperFirst","camelCase","model","pick"],"mappings":";;;;;;;;;;;AAYA,MAAM,EACJA,oBAAoB,EACpBC,oBAAoB,EACpBC,sBAAsB,EACtBC,4BAA4B,EAC5BC,oBAAoB,EACpBC,oBAAoB,EACrB,GAAGC,yBAAkBC,SAAS;AAE/B,MAAMC,iBAAAA,GAAoB,CAACC,GAAAA,EAAaC,UAAAA,GAAAA;IACtC,IAAI;QACFC,uCAAAA,CAA8BD,UAAAA,CAAAA;AAChC,IAAA,CAAA,CAAE,OAAOE,CAAAA,EAAG;QACV,IAAIA,CAAAA,YAAaC,eAAAA,CAAIC,eAAe,EAAE;YACpC,MAAM,IAAIC,KAAAA,CAAM,CAAC,uCAAuC,EAAEN,IAAI,IAAI,EAAEG,CAAAA,CAAEI,MAAM,CAAA,CAAE,CAAA;AAChF,QAAA;QAEA,MAAMJ,CAAAA;AACR,IAAA;IAEA,MAAM,EAAEK,MAAM,EAAEC,OAAO,EAAEC,UAAU,EAAE,GAAGC,Y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AAA;AACF,CAAA;AAEA,MAAMK,WAAAA,GAAc,CAACvC,MAAAA,EAA4BwC,MAAAA,GAAAA;AAC/C,IAAA,MAAM9B,SAAAA,GAAYV,MAAAA,CAAOW,IAAI,CAACC,YAAY;AAC1C,IAAA,MAAM6B,WAAWD,MAAAA,GAAS,CAAA,EAAGA,OAAO,CAAC,EAAE9B,WAAW,GAAGA,SAAAA;IAErD,OAAOV,MAAAA,CAAOyC,QAAQ,IAAItB,kBAAAA,CAAEuB,UAAU,CAACvB,kBAAAA,CAAEwB,SAAS,CAACF,QAAAA,CAAAA,CAAAA;AACrD;AAEA,MAAMhC,aAAa,CAACmC,KAAAA,GAAAA;AAClB,IAAA,MAAM5C,SAASmB,kBAAAA,CAAEhB,SAAS,CACxBgB,kBAAAA,CAAE0B,IAAI,CAACD,KAAAA,EAAO;AACZ,QAAA,YAAA;AACA,QAAA,gBAAA;AACA,QAAA,MAAA;AACA,QAAA,SAAA;AACA,QAAA,eAAA;AACA,QAAA,YAAA;AACA,QAAA;AACD,KAAA,CAAA,CAAA;AAGH5C,IAAAA,MAAAA,CAAOO,IAAI,GAAGqC,KAAAA,CAAMrC,IAAI,IAAI,gBAAA;IAC5B,OAAOP,MAAAA;AACT,CAAA;;;;;"}
|
|
@@ -3,6 +3,10 @@
|
|
|
3
3
|
var _ = require('lodash');
|
|
4
4
|
var strapiUtils = require('@strapi/utils');
|
|
5
5
|
|
|
6
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
7
|
+
|
|
8
|
+
var ___default = /*#__PURE__*/_interopDefault(_);
|
|
9
|
+
|
|
6
10
|
const LIFECYCLES = [
|
|
7
11
|
'beforeCreate',
|
|
8
12
|
'afterCreate',
|
|
@@ -35,7 +39,7 @@ const LIFECYCLES = [
|
|
|
35
39
|
* TODO V5: check if we can avoid this coupling by moving this logic
|
|
36
40
|
* into the GraphQL plugin.
|
|
37
41
|
*/ const GRAPHQL_ENUM_REGEX = /^[_A-Za-z][_0-9A-Za-z]*$/;
|
|
38
|
-
const lifecyclesShape =
|
|
42
|
+
const lifecyclesShape = ___default.default.mapValues(___default.default.keyBy(LIFECYCLES), ()=>strapiUtils.yup.mixed().nullable().isFunction());
|
|
39
43
|
const contentTypeSchemaValidator = strapiUtils.yup.object().shape({
|
|
40
44
|
schema: strapiUtils.yup.object().shape({
|
|
41
45
|
info: strapiUtils.yup.object().shape({
|
|
@@ -65,7 +69,7 @@ const contentTypeSchemaValidator = strapiUtils.yup.object().shape({
|
|
|
65
69
|
});
|
|
66
70
|
}
|
|
67
71
|
// should not collide
|
|
68
|
-
const duplicates =
|
|
72
|
+
const duplicates = ___default.default.uniq(regressedValues.filter((value, index, values)=>values.indexOf(value) !== index));
|
|
69
73
|
if (duplicates.length) {
|
|
70
74
|
const message = `Some enumeration values of the field '${attrName}' collide when normalized: ${duplicates.join(', ')}. Please modify your enumeration.`;
|
|
71
75
|
return this.createError({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator.js","sources":["../../../src/domain/content-type/validator.ts"],"sourcesContent":["import _ from 'lodash';\nimport { yup, strings } from '@strapi/utils';\nimport type { Schema } from '@strapi/types';\n\nconst LIFECYCLES = [\n 'beforeCreate',\n 'afterCreate',\n 'beforeFindOne',\n 'afterFindOne',\n 'beforeFindMany',\n 'afterFindMany',\n 'beforeCount',\n 'afterCount',\n 'beforeCreateMany',\n 'afterCreateMany',\n 'beforeUpdate',\n 'afterUpdate',\n 'beforeUpdateMany',\n 'afterUpdateMany',\n 'beforeDelete',\n 'afterDelete',\n 'beforeDeleteMany',\n 'afterDeleteMany',\n] as const;\n\n/**\n * For enumerations the least common denomiator is GraphQL, where\n * values needs to match the secure name regex:\n * GraphQL Spec https://spec.graphql.org/June2018/#sec-Names\n *\n * Therefore we need to make sure our users only use values, which\n * can be returned by GraphQL, by checking the regressed values\n * agains the GraphQL regex.\n *\n * TODO V5: check if we can avoid this coupling by moving this logic\n * into the GraphQL plugin.\n */\nconst GRAPHQL_ENUM_REGEX = /^[_A-Za-z][_0-9A-Za-z]*$/;\n\nconst lifecyclesShape = _.mapValues(_.keyBy(LIFECYCLES), () => yup.mixed().nullable().isFunction());\n\nconst contentTypeSchemaValidator = yup.object().shape({\n schema: yup.object().shape({\n info: yup\n .object()\n .shape({\n displayName: yup.string().required(),\n singularName: yup.string().isKebabCase().required(),\n pluralName: yup.string().isKebabCase().required(),\n })\n .required(),\n attributes: yup.object().test({\n name: 'valuesCollide',\n message: 'Some values collide when normalized',\n test(attributes: Schema.ContentType['attributes']) {\n for (const attrName of Object.keys(attributes)) {\n const attr = attributes[attrName];\n if (attr.type === 'enumeration') {\n const regressedValues = attr.enum.map(strings.toRegressedEnumValue);\n\n // should match the GraphQL regex\n if (!regressedValues.every((value: string) => GRAPHQL_ENUM_REGEX.test(value))) {\n const message = `Invalid enumeration value. Values should have at least one alphabetical character preceding the first occurence of a number. Update your enumeration '${attrName}'.`;\n\n return this.createError({ message });\n }\n\n // should not contain empty values\n if (regressedValues.some((value: string) => value === '')) {\n return this.createError({\n message: `At least one value of the enumeration '${attrName}' appears to be empty. Only alphanumerical characters are taken into account.`,\n });\n }\n\n // should not collide\n const duplicates = _.uniq(\n regressedValues.filter(\n (value: string, index: number, values: string[]) => values.indexOf(value) !== index\n )\n );\n\n if (duplicates.length) {\n const message = `Some enumeration values of the field '${attrName}' collide when normalized: ${duplicates.join(\n ', '\n )}. Please modify your enumeration.`;\n\n return this.createError({ message });\n }\n }\n }\n\n return true;\n },\n }),\n }),\n actions: yup.object().onlyContainsFunctions(),\n lifecycles: yup.object().shape(lifecyclesShape).noUnknown(),\n});\n\nconst validateContentTypeDefinition = (data: unknown) => {\n return contentTypeSchemaValidator.validateSync(data, { strict: true, abortEarly: false });\n};\n\nexport { validateContentTypeDefinition };\n"],"names":["LIFECYCLES","GRAPHQL_ENUM_REGEX","lifecyclesShape","_","mapValues","keyBy","yup","mixed","nullable","isFunction","contentTypeSchemaValidator","object","shape","schema","info","displayName","string","required","singularName","isKebabCase","pluralName","attributes","test","name","message","attrName","Object","keys","attr","type","regressedValues","enum","map","strings","toRegressedEnumValue","every","value","createError","some","duplicates","uniq","filter","index","values","indexOf","length","join","actions","onlyContainsFunctions","lifecycles","noUnknown","validateContentTypeDefinition","data","validateSync","strict","abortEarly"],"mappings":"
|
|
1
|
+
{"version":3,"file":"validator.js","sources":["../../../src/domain/content-type/validator.ts"],"sourcesContent":["import _ from 'lodash';\nimport { yup, strings } from '@strapi/utils';\nimport type { Schema } from '@strapi/types';\n\nconst LIFECYCLES = [\n 'beforeCreate',\n 'afterCreate',\n 'beforeFindOne',\n 'afterFindOne',\n 'beforeFindMany',\n 'afterFindMany',\n 'beforeCount',\n 'afterCount',\n 'beforeCreateMany',\n 'afterCreateMany',\n 'beforeUpdate',\n 'afterUpdate',\n 'beforeUpdateMany',\n 'afterUpdateMany',\n 'beforeDelete',\n 'afterDelete',\n 'beforeDeleteMany',\n 'afterDeleteMany',\n] as const;\n\n/**\n * For enumerations the least common denomiator is GraphQL, where\n * values needs to match the secure name regex:\n * GraphQL Spec https://spec.graphql.org/June2018/#sec-Names\n *\n * Therefore we need to make sure our users only use values, which\n * can be returned by GraphQL, by checking the regressed values\n * agains the GraphQL regex.\n *\n * TODO V5: check if we can avoid this coupling by moving this logic\n * into the GraphQL plugin.\n */\nconst GRAPHQL_ENUM_REGEX = /^[_A-Za-z][_0-9A-Za-z]*$/;\n\nconst lifecyclesShape = _.mapValues(_.keyBy(LIFECYCLES), () => yup.mixed().nullable().isFunction());\n\nconst contentTypeSchemaValidator = yup.object().shape({\n schema: yup.object().shape({\n info: yup\n .object()\n .shape({\n displayName: yup.string().required(),\n singularName: yup.string().isKebabCase().required(),\n pluralName: yup.string().isKebabCase().required(),\n })\n .required(),\n attributes: yup.object().test({\n name: 'valuesCollide',\n message: 'Some values collide when normalized',\n test(attributes: Schema.ContentType['attributes']) {\n for (const attrName of Object.keys(attributes)) {\n const attr = attributes[attrName];\n if (attr.type === 'enumeration') {\n const regressedValues = attr.enum.map(strings.toRegressedEnumValue);\n\n // should match the GraphQL regex\n if (!regressedValues.every((value: string) => GRAPHQL_ENUM_REGEX.test(value))) {\n const message = `Invalid enumeration value. Values should have at least one alphabetical character preceding the first occurence of a number. Update your enumeration '${attrName}'.`;\n\n return this.createError({ message });\n }\n\n // should not contain empty values\n if (regressedValues.some((value: string) => value === '')) {\n return this.createError({\n message: `At least one value of the enumeration '${attrName}' appears to be empty. Only alphanumerical characters are taken into account.`,\n });\n }\n\n // should not collide\n const duplicates = _.uniq(\n regressedValues.filter(\n (value: string, index: number, values: string[]) => values.indexOf(value) !== index\n )\n );\n\n if (duplicates.length) {\n const message = `Some enumeration values of the field '${attrName}' collide when normalized: ${duplicates.join(\n ', '\n )}. Please modify your enumeration.`;\n\n return this.createError({ message });\n }\n }\n }\n\n return true;\n },\n }),\n }),\n actions: yup.object().onlyContainsFunctions(),\n lifecycles: yup.object().shape(lifecyclesShape).noUnknown(),\n});\n\nconst validateContentTypeDefinition = (data: unknown) => {\n return contentTypeSchemaValidator.validateSync(data, { strict: true, abortEarly: false });\n};\n\nexport { validateContentTypeDefinition };\n"],"names":["LIFECYCLES","GRAPHQL_ENUM_REGEX","lifecyclesShape","_","mapValues","keyBy","yup","mixed","nullable","isFunction","contentTypeSchemaValidator","object","shape","schema","info","displayName","string","required","singularName","isKebabCase","pluralName","attributes","test","name","message","attrName","Object","keys","attr","type","regressedValues","enum","map","strings","toRegressedEnumValue","every","value","createError","some","duplicates","uniq","filter","index","values","indexOf","length","join","actions","onlyContainsFunctions","lifecycles","noUnknown","validateContentTypeDefinition","data","validateSync","strict","abortEarly"],"mappings":";;;;;;;;;AAIA,MAAMA,UAAAA,GAAa;AACjB,IAAA,cAAA;AACA,IAAA,aAAA;AACA,IAAA,eAAA;AACA,IAAA,cAAA;AACA,IAAA,gBAAA;AACA,IAAA,eAAA;AACA,IAAA,aAAA;AACA,IAAA,YAAA;AACA,IAAA,kBAAA;AACA,IAAA,iBAAA;AAC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M,EAAA,CAAGqC,qBAAqB,EAAA;AAC3CC,IAAAA,UAAAA,EAAY3C,gBAAIK,MAAM,EAAA,CAAGC,KAAK,CAACV,iBAAiBgD,SAAS;AAC3D,CAAA,CAAA;AAEA,MAAMC,gCAAgC,CAACC,IAAAA,GAAAA;IACrC,OAAO1C,0BAAAA,CAA2B2C,YAAY,CAACD,IAAAA,EAAM;QAAEE,MAAAA,EAAQ,IAAA;QAAMC,UAAAA,EAAY;AAAM,KAAA,CAAA;AACzF;;;;"}
|
|
@@ -5,9 +5,13 @@ var strapiUtils = require('@strapi/utils');
|
|
|
5
5
|
var namespace = require('../../registries/namespace.js');
|
|
6
6
|
var validation = require('./validation.js');
|
|
7
7
|
|
|
8
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
9
|
+
|
|
10
|
+
var ___default = /*#__PURE__*/_interopDefault(_);
|
|
11
|
+
|
|
8
12
|
// Removes the namespace from a map with keys prefixed with a namespace
|
|
9
13
|
const removeNamespacedKeys = (map, namespace$1)=>{
|
|
10
|
-
return
|
|
14
|
+
return ___default.default.mapKeys(map, (value, key)=>namespace.removeNamespace(key, namespace$1));
|
|
11
15
|
};
|
|
12
16
|
const defaultModule = {
|
|
13
17
|
config: {},
|
|
@@ -19,7 +23,7 @@ const defaultModule = {
|
|
|
19
23
|
middlewares: {}
|
|
20
24
|
};
|
|
21
25
|
const createModule = (namespace, rawModule, strapi)=>{
|
|
22
|
-
|
|
26
|
+
___default.default.defaults(rawModule, defaultModule);
|
|
23
27
|
try {
|
|
24
28
|
validation.validateModule(rawModule);
|
|
25
29
|
} catch (e) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../src/domain/module/index.ts"],"sourcesContent":["import _, { type PropertyPath, flatten } from 'lodash';\nimport { yup } from '@strapi/utils';\nimport type { Core, UID, Struct } from '@strapi/types';\n\nimport { removeNamespace } from '../../registries/namespace';\nimport { validateModule } from './validation';\n\ninterface LifecyclesState {\n bootstrap?: boolean;\n register?: boolean;\n destroy?: boolean;\n}\n\nexport interface RawModule {\n config?: Record<string, unknown>;\n routes?: Core.Module['routes'];\n controllers?: Core.Module['controllers'];\n services?: Core.Module['services'];\n contentTypes?: Core.Module['contentTypes'];\n policies?: Core.Module['policies'];\n middlewares?: Core.Module['middlewares'];\n bootstrap?: (params: { strapi: Core.Strapi }) => Promise<void>;\n register?: (params: { strapi: Core.Strapi }) => Promise<void>;\n destroy?: (params: { strapi: Core.Strapi }) => Promise<void>;\n}\n\nexport interface Module {\n bootstrap: () => Promise<void>;\n register: () => Promise<void>;\n destroy: () => Promise<void>;\n load: () => void;\n routes: Core.Module['routes'];\n config<T = unknown>(key: PropertyPath, defaultVal?: T): T; // TODO: this mirrors ConfigProvider.get, we should use it directly\n contentType: (ctName: UID.ContentType) => Struct.ContentTypeSchema;\n contentTypes: Record<string, Struct.ContentTypeSchema>;\n service: (serviceName: UID.Service) => Core.Service;\n services: Record<string, Core.Service>;\n policy: (policyName: UID.Policy) => Core.Policy;\n policies: Record<string, Core.Policy>;\n middleware: (middlewareName: UID.Middleware) => Core.Middleware;\n middlewares: Record<string, Core.Middleware>;\n controller: (controllerName: UID.Controller) => Core.Controller;\n controllers: Record<string, Core.Controller>;\n}\n\n// Removes the namespace from a map with keys prefixed with a namespace\nconst removeNamespacedKeys = <T extends Record<string, unknown>>(map: T, namespace: string) => {\n return _.mapKeys(map, (value, key) => removeNamespace(key, namespace));\n};\n\nconst defaultModule = {\n config: {},\n routes: [],\n controllers: {},\n services: {},\n contentTypes: {},\n policies: {},\n middlewares: {},\n};\n\nexport const createModule = (\n namespace: string,\n rawModule: RawModule,\n strapi: Core.Strapi\n): Module => {\n _.defaults(rawModule, defaultModule);\n\n try {\n validateModule(rawModule);\n } catch (e) {\n if (e instanceof yup.ValidationError) {\n throw new Error(`strapi-server.js is invalid for '${namespace}'.\\n${e.errors.join('\\n')}`);\n }\n }\n\n const called: LifecyclesState = {};\n return {\n async bootstrap() {\n if (called.bootstrap) {\n throw new Error(`Bootstrap for ${namespace} has already been called`);\n }\n called.bootstrap = true;\n await (rawModule.bootstrap && rawModule.bootstrap({ strapi }));\n },\n async register() {\n if (called.register) {\n throw new Error(`Register for ${namespace} has already been called`);\n }\n called.register = true;\n await (rawModule.register && rawModule.register({ strapi }));\n },\n async destroy() {\n if (called.destroy) {\n throw new Error(`Destroy for ${namespace} has already been called`);\n }\n called.destroy = true;\n await (rawModule.destroy && rawModule.destroy({ strapi }));\n },\n load() {\n strapi.get('content-types').add(namespace, rawModule.contentTypes);\n strapi.get('services').add(namespace, rawModule.services);\n strapi.get('policies').add(namespace, rawModule.policies);\n strapi.get('middlewares').add(namespace, rawModule.middlewares);\n strapi.get('controllers').add(namespace, rawModule.controllers);\n strapi.get('config').set(namespace, rawModule.config);\n },\n get routes() {\n return rawModule.routes ?? {};\n },\n set routes(routes: Record<string, Core.Router>) {\n rawModule.routes = routes;\n },\n config(path: PropertyPath, defaultValue: unknown) {\n const pathArray = flatten([namespace, path]);\n return strapi.get('config').get(pathArray, defaultValue);\n },\n contentType(ctName: UID.ContentType) {\n return strapi.get('content-types').get(`${namespace}.${ctName}`);\n },\n get contentTypes() {\n const contentTypes = strapi.get('content-types').getAll(namespace);\n return removeNamespacedKeys(contentTypes, namespace);\n },\n service(serviceName: UID.Service) {\n return strapi.get('services').get(`${namespace}.${serviceName}`);\n },\n get services() {\n const services = strapi.get('services').getAll(namespace);\n return removeNamespacedKeys(services, namespace);\n },\n policy(policyName: UID.Policy) {\n return strapi.get('policies').get(`${namespace}.${policyName}`);\n },\n get policies() {\n const policies = strapi.get('policies').getAll(namespace);\n return removeNamespacedKeys(policies, namespace);\n },\n middleware(middlewareName: UID.Middleware) {\n return strapi.get('middlewares').get(`${namespace}.${middlewareName}`);\n },\n get middlewares() {\n const middlewares = strapi.get('middlewares').getAll(namespace);\n return removeNamespacedKeys(middlewares, namespace);\n },\n controller(controllerName: UID.Controller) {\n return strapi.get('controllers').get(`${namespace}.${controllerName}`);\n },\n get controllers() {\n const controllers = strapi.get('controllers').getAll(namespace);\n return removeNamespacedKeys(controllers, namespace);\n },\n };\n};\n"],"names":["removeNamespacedKeys","map","namespace","_","mapKeys","value","key","removeNamespace","defaultModule","config","routes","controllers","services","contentTypes","policies","middlewares","createModule","rawModule","strapi","defaults","validateModule","e","yup","ValidationError","Error","errors","join","called","bootstrap","register","destroy","load","get","add","set","path","defaultValue","pathArray","flatten","contentType","ctName","getAll","service","serviceName","policy","policyName","middleware","middlewareName","controller","controllerName"],"mappings":";;;;;;;AA6CA;AACA,MAAMA,oBAAAA,GAAuB,CAAoCC,GAAAA,EAAQC,WAAAA,GAAAA;IACvE,OAAOC,CAAAA,CAAEC,OAAO,CAACH,GAAAA,EAAK,CAACI,KAAAA,EAAOC,GAAAA,GAAQC,0BAAgBD,GAAAA,EAAKJ,WAAAA,CAAAA,CAAAA;AAC7D,CAAA;AAEA,MAAMM,aAAAA,GAAgB;AACpBC,IAAAA,MAAAA,EAAQ,EAAC;AACTC,IAAAA,MAAAA,EAAQ,EAAE;AACVC,IAAAA,WAAAA,EAAa,EAAC;AACdC,IAAAA,QAAAA,EAAU,EAAC;AACXC,IAAAA,YAAAA,EAAc,EAAC;AACfC,IAAAA,QAAAA,EAAU,EAAC;AACXC,IAAAA,WAAAA,EAAa;AACf,CAAA;AAEO,MAAMC,YAAAA,GAAe,CAC1Bd,SAAAA,EACAe,SAAAA,EACAC,MAAAA,GAAAA;IAEAf,CAAAA,CAAEgB,QAAQ,CAACF,SAAAA,EAAWT,aAAAA,CAAAA;IAEtB,IAAI;QACFY,yBAAAA,CAAeH,SAAAA,CAAAA;AACjB,IAAA,CAAA,CAAE,OAAOI,CAAAA,EAAG;QACV,IAAIA,CAAAA,YAAaC,eAAAA,CAAIC,eAAe,EAAE;AACpC,YAAA,MAAM,IAAIC,KAAAA,CAAM,CAAC,iCAAiC,EAAEtB,SAAAA,CAAU,IAAI,EAAEmB,CAAAA,CAAEI,MAAM,CAAC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AAA;YACvC,OAAO7B,MAAAA,CAAOc,GAAG,CAAC,aAAA,CAAA,CAAeA,GAAG,CAAC,CAAA,EAAG9B,SAAAA,CAAU,CAAC,EAAE6C,cAAAA,CAAAA,CAAgB,CAAA;AACvE,QAAA,CAAA;AACA,QAAA,IAAIhC,WAAAA,CAAAA,GAAc;AAChB,YAAA,MAAMA,cAAcG,MAAAA,CAAOc,GAAG,CAAC,aAAA,CAAA,CAAeS,MAAM,CAACvC,SAAAA,CAAAA;AACrD,YAAA,OAAOF,qBAAqBe,WAAAA,EAAab,SAAAA,CAAAA;AAC3C,QAAA,CAAA;AACA8C,QAAAA,UAAAA,CAAAA,CAAWC,cAA8B,EAAA;YACvC,OAAO/B,MAAAA,CAAOc,GAAG,CAAC,aAAA,CAAA,CAAeA,GAAG,CAAC,CAAA,EAAG9B,SAAAA,CAAU,CAAC,EAAE+C,cAAAA,CAAAA,CAAgB,CAAA;AACvE,QAAA,CAAA;AACA,QAAA,IAAItC,WAAAA,CAAAA,GAAc;AAChB,YAAA,MAAMA,cAAcO,MAAAA,CAAOc,GAAG,CAAC,aAAA,CAAA,CAAeS,MAAM,CAACvC,SAAAA,CAAAA;AACrD,YAAA,OAAOF,qBAAqBW,WAAAA,EAAaT,SAAAA,CAAAA;AAC3C,QAAA;AACF,KAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/domain/module/index.ts"],"sourcesContent":["import _, { type PropertyPath, flatten } from 'lodash';\nimport { yup } from '@strapi/utils';\nimport type { Core, UID, Struct } from '@strapi/types';\n\nimport { removeNamespace } from '../../registries/namespace';\nimport { validateModule } from './validation';\n\ninterface LifecyclesState {\n bootstrap?: boolean;\n register?: boolean;\n destroy?: boolean;\n}\n\nexport interface RawModule {\n config?: Record<string, unknown>;\n routes?: Core.Module['routes'];\n controllers?: Core.Module['controllers'];\n services?: Core.Module['services'];\n contentTypes?: Core.Module['contentTypes'];\n policies?: Core.Module['policies'];\n middlewares?: Core.Module['middlewares'];\n bootstrap?: (params: { strapi: Core.Strapi }) => Promise<void>;\n register?: (params: { strapi: Core.Strapi }) => Promise<void>;\n destroy?: (params: { strapi: Core.Strapi }) => Promise<void>;\n}\n\nexport interface Module {\n bootstrap: () => Promise<void>;\n register: () => Promise<void>;\n destroy: () => Promise<void>;\n load: () => void;\n routes: Core.Module['routes'];\n config<T = unknown>(key: PropertyPath, defaultVal?: T): T; // TODO: this mirrors ConfigProvider.get, we should use it directly\n contentType: (ctName: UID.ContentType) => Struct.ContentTypeSchema;\n contentTypes: Record<string, Struct.ContentTypeSchema>;\n service: (serviceName: UID.Service) => Core.Service;\n services: Record<string, Core.Service>;\n policy: (policyName: UID.Policy) => Core.Policy;\n policies: Record<string, Core.Policy>;\n middleware: (middlewareName: UID.Middleware) => Core.Middleware;\n middlewares: Record<string, Core.Middleware>;\n controller: (controllerName: UID.Controller) => Core.Controller;\n controllers: Record<string, Core.Controller>;\n}\n\n// Removes the namespace from a map with keys prefixed with a namespace\nconst removeNamespacedKeys = <T extends Record<string, unknown>>(map: T, namespace: string) => {\n return _.mapKeys(map, (value, key) => removeNamespace(key, namespace));\n};\n\nconst defaultModule = {\n config: {},\n routes: [],\n controllers: {},\n services: {},\n contentTypes: {},\n policies: {},\n middlewares: {},\n};\n\nexport const createModule = (\n namespace: string,\n rawModule: RawModule,\n strapi: Core.Strapi\n): Module => {\n _.defaults(rawModule, defaultModule);\n\n try {\n validateModule(rawModule);\n } catch (e) {\n if (e instanceof yup.ValidationError) {\n throw new Error(`strapi-server.js is invalid for '${namespace}'.\\n${e.errors.join('\\n')}`);\n }\n }\n\n const called: LifecyclesState = {};\n return {\n async bootstrap() {\n if (called.bootstrap) {\n throw new Error(`Bootstrap for ${namespace} has already been called`);\n }\n called.bootstrap = true;\n await (rawModule.bootstrap && rawModule.bootstrap({ strapi }));\n },\n async register() {\n if (called.register) {\n throw new Error(`Register for ${namespace} has already been called`);\n }\n called.register = true;\n await (rawModule.register && rawModule.register({ strapi }));\n },\n async destroy() {\n if (called.destroy) {\n throw new Error(`Destroy for ${namespace} has already been called`);\n }\n called.destroy = true;\n await (rawModule.destroy && rawModule.destroy({ strapi }));\n },\n load() {\n strapi.get('content-types').add(namespace, rawModule.contentTypes);\n strapi.get('services').add(namespace, rawModule.services);\n strapi.get('policies').add(namespace, rawModule.policies);\n strapi.get('middlewares').add(namespace, rawModule.middlewares);\n strapi.get('controllers').add(namespace, rawModule.controllers);\n strapi.get('config').set(namespace, rawModule.config);\n },\n get routes() {\n return rawModule.routes ?? {};\n },\n set routes(routes: Record<string, Core.Router>) {\n rawModule.routes = routes;\n },\n config(path: PropertyPath, defaultValue: unknown) {\n const pathArray = flatten([namespace, path]);\n return strapi.get('config').get(pathArray, defaultValue);\n },\n contentType(ctName: UID.ContentType) {\n return strapi.get('content-types').get(`${namespace}.${ctName}`);\n },\n get contentTypes() {\n const contentTypes = strapi.get('content-types').getAll(namespace);\n return removeNamespacedKeys(contentTypes, namespace);\n },\n service(serviceName: UID.Service) {\n return strapi.get('services').get(`${namespace}.${serviceName}`);\n },\n get services() {\n const services = strapi.get('services').getAll(namespace);\n return removeNamespacedKeys(services, namespace);\n },\n policy(policyName: UID.Policy) {\n return strapi.get('policies').get(`${namespace}.${policyName}`);\n },\n get policies() {\n const policies = strapi.get('policies').getAll(namespace);\n return removeNamespacedKeys(policies, namespace);\n },\n middleware(middlewareName: UID.Middleware) {\n return strapi.get('middlewares').get(`${namespace}.${middlewareName}`);\n },\n get middlewares() {\n const middlewares = strapi.get('middlewares').getAll(namespace);\n return removeNamespacedKeys(middlewares, namespace);\n },\n controller(controllerName: UID.Controller) {\n return strapi.get('controllers').get(`${namespace}.${controllerName}`);\n },\n get controllers() {\n const controllers = strapi.get('controllers').getAll(namespace);\n return removeNamespacedKeys(controllers, namespace);\n },\n };\n};\n"],"names":["removeNamespacedKeys","map","namespace","_","mapKeys","value","key","removeNamespace","defaultModule","config","routes","controllers","services","contentTypes","policies","middlewares","createModule","rawModule","strapi","defaults","validateModule","e","yup","ValidationError","Error","errors","join","called","bootstrap","register","destroy","load","get","add","set","path","defaultValue","pathArray","flatten","contentType","ctName","getAll","service","serviceName","policy","policyName","middleware","middlewareName","controller","controllerName"],"mappings":";;;;;;;;;;;AA6CA;AACA,MAAMA,oBAAAA,GAAuB,CAAoCC,GAAAA,EAAQC,WAAAA,GAAAA;IACvE,OAAOC,kBAAAA,CAAEC,OAAO,CAACH,GAAAA,EAAK,CAACI,KAAAA,EAAOC,GAAAA,GAAQC,0BAAgBD,GAAAA,EAAKJ,WAAAA,CAAAA,CAAAA;AAC7D,CAAA;AAEA,MAAMM,aAAAA,GAAgB;AACpBC,IAAAA,MAAAA,EAAQ,EAAC;AACTC,IAAAA,MAAAA,EAAQ,EAAE;AACVC,IAAAA,WAAAA,EAAa,EAAC;AACdC,IAAAA,QAAAA,EAAU,EAAC;AACXC,IAAAA,YAAAA,EAAc,EAAC;AACfC,IAAAA,QAAAA,EAAU,EAAC;AACXC,IAAAA,WAAAA,EAAa;AACf,CAAA;AAEO,MAAMC,YAAAA,GAAe,CAC1Bd,SAAAA,EACAe,SAAAA,EACAC,MAAAA,GAAAA;IAEAf,kBAAAA,CAAEgB,QAAQ,CAACF,SAAAA,EAAWT,aAAAA,CAAAA;IAEtB,IAAI;QACFY,yBAAAA,CAAeH,SAAAA,CAAAA;AACjB,IAAA,CAAA,CAAE,OAAOI,CAAAA,EAAG;QACV,IAAIA,CAAAA,YAAaC,eAAAA,CAAIC,eAAe,EAAE;AACpC,YAAA,MAAM,IAAIC,KAAAA,CAAM,CAAC,iCAAiC,EAAEtB,SAAAA,CAAU,IAAI,EAAEmB,CAAAA,CAAEI,MAAM,CAACC,IAAI,CAAC,IAAA,CAAA,CAAA,CAAO,CAAA;AAC3F,QAAA;AACF,IAAA;AAEA,IAAA,MAAMC,SAA0B,EAAC;IACjC,OAAO;QACL,MAAMC,SAAAA,CAAAA,GAAAA;YACJ,IAAID,MAAAA,CAAOC,SAAS,EAAE;AACpB,gBA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AA,GAAc;AAChB,YAAA,MAAMA,cAAcG,MAAAA,CAAOc,GAAG,CAAC,aAAA,CAAA,CAAeS,MAAM,CAACvC,SAAAA,CAAAA;AACrD,YAAA,OAAOF,qBAAqBe,WAAAA,EAAab,SAAAA,CAAAA;AAC3C,QAAA,CAAA;AACA8C,QAAAA,UAAAA,CAAAA,CAAWC,cAA8B,EAAA;YACvC,OAAO/B,MAAAA,CAAOc,GAAG,CAAC,aAAA,CAAA,CAAeA,GAAG,CAAC,CAAA,EAAG9B,SAAAA,CAAU,CAAC,EAAE+C,cAAAA,CAAAA,CAAgB,CAAA;AACvE,QAAA,CAAA;AACA,QAAA,IAAItC,WAAAA,CAAAA,GAAc;AAChB,YAAA,MAAMA,cAAcO,MAAAA,CAAOc,GAAG,CAAC,aAAA,CAAA,CAAeS,MAAM,CAACvC,SAAAA,CAAAA;AACrD,YAAA,OAAOF,qBAAqBW,WAAAA,EAAaT,SAAAA,CAAAA;AAC3C,QAAA;AACF,KAAA;AACF;;;;"}
|
package/dist/ee/license.js
CHANGED
|
@@ -5,6 +5,11 @@ var path = require('path');
|
|
|
5
5
|
var crypto = require('crypto');
|
|
6
6
|
var strapiUtils = require('@strapi/utils');
|
|
7
7
|
|
|
8
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
9
|
+
|
|
10
|
+
var fs__default = /*#__PURE__*/_interopDefault(fs);
|
|
11
|
+
var crypto__default = /*#__PURE__*/_interopDefault(crypto);
|
|
12
|
+
|
|
8
13
|
const DEFAULT_FEATURES = {
|
|
9
14
|
bronze: [],
|
|
10
15
|
silver: [],
|
|
@@ -38,7 +43,7 @@ const DEFAULT_FEATURES = {
|
|
|
38
43
|
]
|
|
39
44
|
};
|
|
40
45
|
const LICENSE_REGISTRY_URI = 'https://license.strapi.io';
|
|
41
|
-
const publicKey =
|
|
46
|
+
const publicKey = fs__default.default.readFileSync(path.resolve(__dirname, '../../resources/key.pub'));
|
|
42
47
|
class LicenseCheckError extends Error {
|
|
43
48
|
constructor(message, shouldFallback = false){
|
|
44
49
|
super(message), this.shouldFallback = false;
|
|
@@ -48,7 +53,7 @@ class LicenseCheckError extends Error {
|
|
|
48
53
|
const readLicense = (directory)=>{
|
|
49
54
|
try {
|
|
50
55
|
const path$1 = path.join(directory, 'license.txt');
|
|
51
|
-
return
|
|
56
|
+
return fs__default.default.readFileSync(path$1).toString();
|
|
52
57
|
} catch (error) {
|
|
53
58
|
if (typeof error === 'object' && error !== null && 'code' in error && error.code !== 'ENOENT') {
|
|
54
59
|
throw Error('License file not readable, review its format and access rules.');
|
|
@@ -61,7 +66,7 @@ const verifyLicense = (license)=>{
|
|
|
61
66
|
throw new Error('Invalid license.');
|
|
62
67
|
}
|
|
63
68
|
const stringifiedContent = Buffer.from(base64Content, 'base64').toString();
|
|
64
|
-
const verify =
|
|
69
|
+
const verify = crypto__default.default.createVerify('RSA-SHA256');
|
|
65
70
|
verify.update(stringifiedContent);
|
|
66
71
|
verify.end();
|
|
67
72
|
const verified = verify.verify(publicKey, signature, 'base64');
|
package/dist/ee/license.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"license.js","sources":["../../src/ee/license.ts"],"sourcesContent":["import fs from 'fs';\nimport { join, resolve } from 'path';\nimport crypto from 'crypto';\nimport type { Core } from '@strapi/types';\n\nimport { generateInstallId } from '@strapi/utils';\n\ninterface LicenseInfo {\n type: 'bronze' | 'silver' | 'gold';\n isTrial: boolean;\n expireAt?: string;\n seats?: number;\n features?: Array<{ name: string; options?: Record<string, unknown> }>;\n subscriptionId?: string;\n planPriceId?: string;\n}\n\nconst DEFAULT_FEATURES = {\n bronze: [],\n silver: [],\n gold: [\n { name: 'sso' },\n // Set a null retention duration to allow the user to override it\n // The default of 90 days is set in the audit logs service\n { name: 'audit-logs', options: { retentionDays: null } },\n { name: 'review-workflows' },\n { name: 'cms-content-releases' },\n { name: 'cms-content-history', options: { retentionDays: 99999 } },\n { name: 'cms-advanced-preview' },\n ],\n};\n\nconst LICENSE_REGISTRY_URI = 'https://license.strapi.io';\n\nconst publicKey = fs.readFileSync(resolve(__dirname, '../../resources/key.pub'));\n\nclass LicenseCheckError extends Error {\n shouldFallback = false;\n\n constructor(message: string, shouldFallback = false) {\n super(message);\n\n this.shouldFallback = shouldFallback;\n }\n}\n\nconst readLicense = (directory: string) => {\n try {\n const path = join(directory, 'license.txt');\n return fs.readFileSync(path).toString();\n } catch (error) {\n if (typeof error === 'object' && error !== null && 'code' in error && error.code !== 'ENOENT') {\n throw Error('License file not readable, review its format and access rules.');\n }\n }\n};\n\nconst verifyLicense = (license: string) => {\n const [signature, base64Content] = Buffer.from(license, 'base64').toString().split('\\n');\n\n if (!signature || !base64Content) {\n throw new Error('Invalid license.');\n }\n\n const stringifiedContent = Buffer.from(base64Content, 'base64').toString();\n\n const verify = crypto.createVerify('RSA-SHA256');\n verify.update(stringifiedContent);\n verify.end();\n\n const verified = verify.verify(publicKey, signature, 'base64');\n\n if (!verified) {\n throw new Error('Invalid license.');\n }\n\n const licenseInfo: LicenseInfo = JSON.parse(stringifiedContent);\n\n if (!licenseInfo.features) {\n licenseInfo.features = DEFAULT_FEATURES[licenseInfo.type];\n }\n\n if (!licenseInfo.isTrial) {\n licenseInfo.isTrial = false;\n }\n\n Object.freeze(licenseInfo.features);\n return licenseInfo;\n};\n\nconst throwError = () => {\n throw new LicenseCheckError('Could not proceed to the online validation of your license.', true);\n};\n\nconst fetchLicense = async (\n { strapi }: { strapi: Core.Strapi },\n key: string,\n projectId: string\n) => {\n const { installId: installIdFromPackageJson } = strapi.config;\n\n const response = await strapi\n .fetch(`${LICENSE_REGISTRY_URI}/api/licenses/validate`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n key,\n projectId,\n deviceId: generateInstallId(projectId, installIdFromPackageJson),\n }), // NOTE: Doing nothing on the LR with the installId\n })\n .catch(throwError);\n\n const contentType = response.headers.get('Content-Type');\n\n if (contentType?.includes('application/json')) {\n const { data, error } = await response.json();\n\n switch (response.status) {\n case 200:\n return data.license;\n case 400:\n throw new LicenseCheckError(error.message);\n case 404:\n throw new LicenseCheckError('The license used does not exists.');\n default:\n throwError();\n }\n } else {\n throwError();\n }\n};\n\nexport { readLicense, verifyLicense, fetchLicense, LicenseCheckError, LICENSE_REGISTRY_URI };\n"],"names":["DEFAULT_FEATURES","bronze","silver","gold","name","options","retentionDays","LICENSE_REGISTRY_URI","publicKey","fs","readFileSync","resolve","__dirname","LicenseCheckError","Error","message","shouldFallback","readLicense","directory","path","join","toString","error","code","verifyLicense","license","signature","base64Content","Buffer","from","split","stringifiedContent","verify","crypto","createVerify","update","end","verified","licenseInfo","JSON","parse","features","type","isTrial","Object","freeze","throwError","fetchLicense","strapi","key","projectId","installId","installIdFromPackageJson","config","response","fetch","method","headers","body","stringify","deviceId","generateInstallId","catch","contentType","get","includes","data","json","status"],"mappings":"
|
|
1
|
+
{"version":3,"file":"license.js","sources":["../../src/ee/license.ts"],"sourcesContent":["import fs from 'fs';\nimport { join, resolve } from 'path';\nimport crypto from 'crypto';\nimport type { Core } from '@strapi/types';\n\nimport { generateInstallId } from '@strapi/utils';\n\ninterface LicenseInfo {\n type: 'bronze' | 'silver' | 'gold';\n isTrial: boolean;\n expireAt?: string;\n seats?: number;\n features?: Array<{ name: string; options?: Record<string, unknown> }>;\n subscriptionId?: string;\n planPriceId?: string;\n}\n\nconst DEFAULT_FEATURES = {\n bronze: [],\n silver: [],\n gold: [\n { name: 'sso' },\n // Set a null retention duration to allow the user to override it\n // The default of 90 days is set in the audit logs service\n { name: 'audit-logs', options: { retentionDays: null } },\n { name: 'review-workflows' },\n { name: 'cms-content-releases' },\n { name: 'cms-content-history', options: { retentionDays: 99999 } },\n { name: 'cms-advanced-preview' },\n ],\n};\n\nconst LICENSE_REGISTRY_URI = 'https://license.strapi.io';\n\nconst publicKey = fs.readFileSync(resolve(__dirname, '../../resources/key.pub'));\n\nclass LicenseCheckError extends Error {\n shouldFallback = false;\n\n constructor(message: string, shouldFallback = false) {\n super(message);\n\n this.shouldFallback = shouldFallback;\n }\n}\n\nconst readLicense = (directory: string) => {\n try {\n const path = join(directory, 'license.txt');\n return fs.readFileSync(path).toString();\n } catch (error) {\n if (typeof error === 'object' && error !== null && 'code' in error && error.code !== 'ENOENT') {\n throw Error('License file not readable, review its format and access rules.');\n }\n }\n};\n\nconst verifyLicense = (license: string) => {\n const [signature, base64Content] = Buffer.from(license, 'base64').toString().split('\\n');\n\n if (!signature || !base64Content) {\n throw new Error('Invalid license.');\n }\n\n const stringifiedContent = Buffer.from(base64Content, 'base64').toString();\n\n const verify = crypto.createVerify('RSA-SHA256');\n verify.update(stringifiedContent);\n verify.end();\n\n const verified = verify.verify(publicKey, signature, 'base64');\n\n if (!verified) {\n throw new Error('Invalid license.');\n }\n\n const licenseInfo: LicenseInfo = JSON.parse(stringifiedContent);\n\n if (!licenseInfo.features) {\n licenseInfo.features = DEFAULT_FEATURES[licenseInfo.type];\n }\n\n if (!licenseInfo.isTrial) {\n licenseInfo.isTrial = false;\n }\n\n Object.freeze(licenseInfo.features);\n return licenseInfo;\n};\n\nconst throwError = () => {\n throw new LicenseCheckError('Could not proceed to the online validation of your license.', true);\n};\n\nconst fetchLicense = async (\n { strapi }: { strapi: Core.Strapi },\n key: string,\n projectId: string\n) => {\n const { installId: installIdFromPackageJson } = strapi.config;\n\n const response = await strapi\n .fetch(`${LICENSE_REGISTRY_URI}/api/licenses/validate`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n key,\n projectId,\n deviceId: generateInstallId(projectId, installIdFromPackageJson),\n }), // NOTE: Doing nothing on the LR with the installId\n })\n .catch(throwError);\n\n const contentType = response.headers.get('Content-Type');\n\n if (contentType?.includes('application/json')) {\n const { data, error } = await response.json();\n\n switch (response.status) {\n case 200:\n return data.license;\n case 400:\n throw new LicenseCheckError(error.message);\n case 404:\n throw new LicenseCheckError('The license used does not exists.');\n default:\n throwError();\n }\n } else {\n throwError();\n }\n};\n\nexport { readLicense, verifyLicense, fetchLicense, LicenseCheckError, LICENSE_REGISTRY_URI };\n"],"names":["DEFAULT_FEATURES","bronze","silver","gold","name","options","retentionDays","LICENSE_REGISTRY_URI","publicKey","fs","readFileSync","resolve","__dirname","LicenseCheckError","Error","message","shouldFallback","readLicense","directory","path","join","toString","error","code","verifyLicense","license","signature","base64Content","Buffer","from","split","stringifiedContent","verify","crypto","createVerify","update","end","verified","licenseInfo","JSON","parse","features","type","isTrial","Object","freeze","throwError","fetchLicense","strapi","key","projectId","installId","installIdFromPackageJson","config","response","fetch","method","headers","body","stringify","deviceId","generateInstallId","catch","contentType","get","includes","data","json","status"],"mappings":";;;;;;;;;;;;AAiBA,MAAMA,gBAAAA,GAAmB;AACvBC,IAAAA,MAAAA,EAAQ,EAAE;AACVC,IAAAA,MAAAA,EAAQ,EAAE;IACVC,IAAAA,EAAM;AACJ,QAAA;YAAEC,IAAAA,EAAM;AAAM,SAAA;;;AAGd,QAAA;YAAEA,IAAAA,EAAM,YAAA;YAAcC,OAAAA,EAAS;gBAAEC,aAAAA,EAAe;AAAK;AAAE,SAAA;AACvD,QAAA;YAAEF,IAAAA,EAAM;AAAmB,SAAA;AAC3B,QAAA;YAAEA,IAAAA,EAAM;AAAuB,SAAA;AAC/B,QAAA;YAAEA,IAAAA,EAAM,qBAAA;YAAuBC,OAAAA,EAAS;gBAAEC,aAAAA,EAAe;AAAM;AAAE,SAAA;AACjE,QAAA;YAAEF,IAAAA,EAAM;AAAuB;AAChC;AACH,CAAA;AAEA,MAAMG,oBAAAA,GAAuB;AAE7B,MAAMC,SAAAA,GAAYC,mBAAAA,CAAGC,YAAY,CAACC,aAAQC,SAAAA,EAAW,yBAAA,CAAA,CAAA;AAErD,MAAMC,iBAAAA,SAA0BC,KAAAA,CAAAA;AAG9B,IAAA,WAAA,CAAYC,OAAe,EAAEC,cAAAA,GAAiB,KAAK,CAAE;QACnD,KAAK,CAACD,eAHRC,cAAAA,GAAiB,K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SAAS,kBAAA,CAAA,EAAqB;QAC7C,MAAM,EAAEC,IAAI,EAAE5C,KAAK,EAAE,GAAG,MAAMgC,SAASa,IAAI,EAAA;AAE3C,QAAA,OAAQb,SAASc,MAAM;YACrB,KAAK,GAAA;AACH,gBAAA,OAAOF,KAAKzC,OAAO;YACrB,KAAK,GAAA;gBACH,MAAM,IAAIZ,iBAAAA,CAAkBS,KAAAA,CAAMP,OAAO,CAAA;YAC3C,KAAK,GAAA;AACH,gBAAA,MAAM,IAAIF,iBAAAA,CAAkB,mCAAA,CAAA;AAC9B,YAAA;AACEiC,gBAAAA,UAAAA,EAAAA;AACJ;IACF,CAAA,MAAO;AACLA,QAAAA,UAAAA,EAAAA;AACF,IAAA;AACF;;;;;;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { Core } from '@strapi/types';
|
|
|
3
3
|
import Strapi, { type StrapiOptions } from './Strapi';
|
|
4
4
|
export { default as compileStrapi } from './compile';
|
|
5
5
|
export * as factories from './factories';
|
|
6
|
+
export * as ai from './ai';
|
|
6
7
|
export declare const createStrapi: (options?: Partial<StrapiOptions>) => Core.Strapi;
|
|
7
8
|
declare module 'koa' {
|
|
8
9
|
type ParsedQuery = ReturnType<typeof qs.parse>;
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAE1C,OAAO,MAAM,EAAE,EAAE,KAAK,aAAa,EAAE,MAAM,UAAU,CAAC;AAGtD,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,WAAW,CAAC;AACrD,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAE1C,OAAO,MAAM,EAAE,EAAE,KAAK,aAAa,EAAE,MAAM,UAAU,CAAC;AAGtD,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,WAAW,CAAC;AACrD,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,EAAE,MAAM,MAAM,CAAC;AAE3B,eAAO,MAAM,YAAY,aAAa,QAAQ,aAAa,CAAC,KAAQ,WAanE,CAAC;AAIF,OAAO,QAAQ,KAAK,CAAC;IACnB,KAAK,WAAW,GAAG,UAAU,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC;IAE/C,UAAiB,WAAW;QAC1B,WAAW,CAAC,EAAE,WAAW,CAAC;QAE1B,IAAI,KAAK,IAAI,WAAW,CAAC;QACzB,IAAI,KAAK,CAAC,GAAG,EAAE,GAAG,EAAE;KACrB;IAED,UAAiB,WAAW;QAC1B,WAAW,CAAC,EAAE,WAAW,CAAC;QAE1B,IAAI,KAAK,IAAI,WAAW,CAAC;QACzB,IAAI,KAAK,CAAC,GAAG,EAAE,GAAG,EAAE;KACrB;CACF"}
|
package/dist/index.js
CHANGED
|
@@ -15,6 +15,7 @@ var signals = require('./utils/signals.js');
|
|
|
15
15
|
var resolveWorkingDirs = require('./utils/resolve-working-dirs.js');
|
|
16
16
|
var compile = require('./compile.js');
|
|
17
17
|
var factories = require('./factories.js');
|
|
18
|
+
var ai = require('./ai.js');
|
|
18
19
|
|
|
19
20
|
const createStrapi = (options = {})=>{
|
|
20
21
|
const strapi = new Strapi({
|
|
@@ -30,5 +31,6 @@ const createStrapi = (options = {})=>{
|
|
|
30
31
|
|
|
31
32
|
exports.compileStrapi = compile;
|
|
32
33
|
exports.factories = factories;
|
|
34
|
+
exports.ai = ai;
|
|
33
35
|
exports.createStrapi = createStrapi;
|
|
34
36
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import * as qs from 'qs';\nimport type { Core } from '@strapi/types';\n\nimport Strapi, { type StrapiOptions } from './Strapi';\nimport { destroyOnSignal, resolveWorkingDirectories, createUpdateNotifier } from './utils';\n\nexport { default as compileStrapi } from './compile';\nexport * as factories from './factories';\n\nexport const createStrapi = (options: Partial<StrapiOptions> = {}): Core.Strapi => {\n const strapi = new Strapi({\n ...options,\n ...resolveWorkingDirectories(options),\n });\n\n destroyOnSignal(strapi);\n createUpdateNotifier(strapi);\n\n // TODO: deprecate and remove in next major\n global.strapi = strapi;\n\n return strapi;\n};\n\n// Augment Koa query type based on Strapi query middleware\n\ndeclare module 'koa' {\n type ParsedQuery = ReturnType<typeof qs.parse>;\n\n export interface BaseRequest {\n _querycache?: ParsedQuery;\n\n get query(): ParsedQuery;\n set query(obj: any);\n }\n\n export interface BaseContext {\n _querycache?: ParsedQuery;\n\n get query(): ParsedQuery;\n set query(obj: any);\n }\n}\n"],"names":["createStrapi","options","strapi","Strapi","resolveWorkingDirectories","destroyOnSignal","createUpdateNotifier","global"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import * as qs from 'qs';\nimport type { Core } from '@strapi/types';\n\nimport Strapi, { type StrapiOptions } from './Strapi';\nimport { destroyOnSignal, resolveWorkingDirectories, createUpdateNotifier } from './utils';\n\nexport { default as compileStrapi } from './compile';\nexport * as factories from './factories';\nexport * as ai from './ai';\n\nexport const createStrapi = (options: Partial<StrapiOptions> = {}): Core.Strapi => {\n const strapi = new Strapi({\n ...options,\n ...resolveWorkingDirectories(options),\n });\n\n destroyOnSignal(strapi);\n createUpdateNotifier(strapi);\n\n // TODO: deprecate and remove in next major\n global.strapi = strapi;\n\n return strapi;\n};\n\n// Augment Koa query type based on Strapi query middleware\n\ndeclare module 'koa' {\n type ParsedQuery = ReturnType<typeof qs.parse>;\n\n export interface BaseRequest {\n _querycache?: ParsedQuery;\n\n get query(): ParsedQuery;\n set query(obj: any);\n }\n\n export interface BaseContext {\n _querycache?: ParsedQuery;\n\n get query(): ParsedQuery;\n set query(obj: any);\n }\n}\n"],"names":["createStrapi","options","strapi","Strapi","resolveWorkingDirectories","destroyOnSignal","createUpdateNotifier","global"],"mappings":";;;;;;;;;;;;;;;;;;;AAUO,MAAMA,YAAAA,GAAe,CAACC,OAAAA,GAAkC,EAAE,GAAA;IAC/D,MAAMC,MAAAA,GAAS,IAAIC,MAAAA,CAAO;AACxB,QAAA,GAAGF,OAAO;AACV,QAAA,GAAGG,6CAA0BH,OAAAA;AAC/B,KAAA,CAAA;IAEAI,uBAAAA,CAAgBH,MAAAA,CAAAA;IAChBI,0BAAAA,CAAqBJ,MAAAA,CAAAA;;AAGrBK,IAAAA,MAAAA,CAAOL,MAAM,GAAGA,MAAAA;IAEhB,OAAOA,MAAAA;AACT;;;;;;;"}
|
package/dist/index.mjs
CHANGED
|
@@ -14,6 +14,8 @@ import { resolveWorkingDirectories } from './utils/resolve-working-dirs.mjs';
|
|
|
14
14
|
export { default as compileStrapi } from './compile.mjs';
|
|
15
15
|
import * as factories from './factories.mjs';
|
|
16
16
|
export { factories };
|
|
17
|
+
import * as ai from './ai.mjs';
|
|
18
|
+
export { ai };
|
|
17
19
|
|
|
18
20
|
const createStrapi = (options = {})=>{
|
|
19
21
|
const strapi = new Strapi({
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../src/index.ts"],"sourcesContent":["import * as qs from 'qs';\nimport type { Core } from '@strapi/types';\n\nimport Strapi, { type StrapiOptions } from './Strapi';\nimport { destroyOnSignal, resolveWorkingDirectories, createUpdateNotifier } from './utils';\n\nexport { default as compileStrapi } from './compile';\nexport * as factories from './factories';\n\nexport const createStrapi = (options: Partial<StrapiOptions> = {}): Core.Strapi => {\n const strapi = new Strapi({\n ...options,\n ...resolveWorkingDirectories(options),\n });\n\n destroyOnSignal(strapi);\n createUpdateNotifier(strapi);\n\n // TODO: deprecate and remove in next major\n global.strapi = strapi;\n\n return strapi;\n};\n\n// Augment Koa query type based on Strapi query middleware\n\ndeclare module 'koa' {\n type ParsedQuery = ReturnType<typeof qs.parse>;\n\n export interface BaseRequest {\n _querycache?: ParsedQuery;\n\n get query(): ParsedQuery;\n set query(obj: any);\n }\n\n export interface BaseContext {\n _querycache?: ParsedQuery;\n\n get query(): ParsedQuery;\n set query(obj: any);\n }\n}\n"],"names":["createStrapi","options","strapi","Strapi","resolveWorkingDirectories","destroyOnSignal","createUpdateNotifier","global"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../src/index.ts"],"sourcesContent":["import * as qs from 'qs';\nimport type { Core } from '@strapi/types';\n\nimport Strapi, { type StrapiOptions } from './Strapi';\nimport { destroyOnSignal, resolveWorkingDirectories, createUpdateNotifier } from './utils';\n\nexport { default as compileStrapi } from './compile';\nexport * as factories from './factories';\nexport * as ai from './ai';\n\nexport const createStrapi = (options: Partial<StrapiOptions> = {}): Core.Strapi => {\n const strapi = new Strapi({\n ...options,\n ...resolveWorkingDirectories(options),\n });\n\n destroyOnSignal(strapi);\n createUpdateNotifier(strapi);\n\n // TODO: deprecate and remove in next major\n global.strapi = strapi;\n\n return strapi;\n};\n\n// Augment Koa query type based on Strapi query middleware\n\ndeclare module 'koa' {\n type ParsedQuery = ReturnType<typeof qs.parse>;\n\n export interface BaseRequest {\n _querycache?: ParsedQuery;\n\n get query(): ParsedQuery;\n set query(obj: any);\n }\n\n export interface BaseContext {\n _querycache?: ParsedQuery;\n\n get query(): ParsedQuery;\n set query(obj: any);\n }\n}\n"],"names":["createStrapi","options","strapi","Strapi","resolveWorkingDirectories","destroyOnSignal","createUpdateNotifier","global"],"mappings":";;;;;;;;;;;;;;;;;;;AAUO,MAAMA,YAAAA,GAAe,CAACC,OAAAA,GAAkC,EAAE,GAAA;IAC/D,MAAMC,MAAAA,GAAS,IAAIC,MAAAA,CAAO;AACxB,QAAA,GAAGF,OAAO;AACV,QAAA,GAAGG,0BAA0BH,OAAAA;AAC/B,KAAA,CAAA;IAEAI,eAAAA,CAAgBH,MAAAA,CAAAA;IAChBI,oBAAAA,CAAqBJ,MAAAA,CAAAA;;AAGrBK,IAAAA,MAAAA,CAAOL,MAAM,GAAGA,MAAAA;IAEhB,OAAOA,MAAAA;AACT;;;;"}
|
package/dist/loaders/admin.js
CHANGED
|
@@ -3,6 +3,10 @@
|
|
|
3
3
|
var _ = require('lodash');
|
|
4
4
|
var index = require('../domain/content-type/index.js');
|
|
5
5
|
|
|
6
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
7
|
+
|
|
8
|
+
var ___default = /*#__PURE__*/_interopDefault(_);
|
|
9
|
+
|
|
6
10
|
async function loadAdmin(strapi) {
|
|
7
11
|
strapi.get('services').add(`admin::`, strapi.admin?.services);
|
|
8
12
|
strapi.get('controllers').add(`admin::`, strapi.admin?.controllers);
|
|
@@ -10,7 +14,7 @@ async function loadAdmin(strapi) {
|
|
|
10
14
|
strapi.get('policies').add(`admin::`, strapi.admin?.policies);
|
|
11
15
|
strapi.get('middlewares').add(`admin::`, strapi.admin?.middlewares);
|
|
12
16
|
const userAdminConfig = strapi.config.get('admin');
|
|
13
|
-
strapi.get('config').set('admin',
|
|
17
|
+
strapi.get('config').set('admin', ___default.default.merge(strapi.admin?.config, userAdminConfig));
|
|
14
18
|
}
|
|
15
19
|
const formatContentTypes = (contentTypes)=>{
|
|
16
20
|
Object.values(contentTypes).forEach((definition)=>{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admin.js","sources":["../../src/loaders/admin.ts"],"sourcesContent":["import _ from 'lodash';\nimport type { Core, Struct } from '@strapi/types';\nimport { getGlobalId } from '../domain/content-type';\n\nexport default async function loadAdmin(strapi: Core.Strapi) {\n strapi.get('services').add(`admin::`, strapi.admin?.services);\n strapi.get('controllers').add(`admin::`, strapi.admin?.controllers);\n strapi.get('content-types').add(`admin::`, formatContentTypes(strapi.admin?.contentTypes ?? {}));\n strapi.get('policies').add(`admin::`, strapi.admin?.policies);\n strapi.get('middlewares').add(`admin::`, strapi.admin?.middlewares);\n\n const userAdminConfig = strapi.config.get('admin');\n strapi.get('config').set('admin', _.merge(strapi.admin?.config, userAdminConfig));\n}\n\nconst formatContentTypes = (contentTypes: Record<string, { schema: Struct.ContentTypeSchema }>) => {\n Object.values(contentTypes).forEach((definition) => {\n const { schema } = definition;\n\n Object.assign(schema, {\n plugin: 'admin',\n globalId: getGlobalId(schema, 'admin'),\n });\n });\n\n return contentTypes;\n};\n"],"names":["loadAdmin","strapi","get","add","admin","services","controllers","formatContentTypes","contentTypes","policies","middlewares","userAdminConfig","config","set","_","merge","Object","values","forEach","definition","schema","assign","plugin","globalId","getGlobalId"],"mappings":"
|
|
1
|
+
{"version":3,"file":"admin.js","sources":["../../src/loaders/admin.ts"],"sourcesContent":["import _ from 'lodash';\nimport type { Core, Struct } from '@strapi/types';\nimport { getGlobalId } from '../domain/content-type';\n\nexport default async function loadAdmin(strapi: Core.Strapi) {\n strapi.get('services').add(`admin::`, strapi.admin?.services);\n strapi.get('controllers').add(`admin::`, strapi.admin?.controllers);\n strapi.get('content-types').add(`admin::`, formatContentTypes(strapi.admin?.contentTypes ?? {}));\n strapi.get('policies').add(`admin::`, strapi.admin?.policies);\n strapi.get('middlewares').add(`admin::`, strapi.admin?.middlewares);\n\n const userAdminConfig = strapi.config.get('admin');\n strapi.get('config').set('admin', _.merge(strapi.admin?.config, userAdminConfig));\n}\n\nconst formatContentTypes = (contentTypes: Record<string, { schema: Struct.ContentTypeSchema }>) => {\n Object.values(contentTypes).forEach((definition) => {\n const { schema } = definition;\n\n Object.assign(schema, {\n plugin: 'admin',\n globalId: getGlobalId(schema, 'admin'),\n });\n });\n\n return contentTypes;\n};\n"],"names":["loadAdmin","strapi","get","add","admin","services","controllers","formatContentTypes","contentTypes","policies","middlewares","userAdminConfig","config","set","_","merge","Object","values","forEach","definition","schema","assign","plugin","globalId","getGlobalId"],"mappings":";;;;;;;;;AAIe,eAAeA,UAAUC,MAAmB,EAAA;IACzDA,MAAAA,CAAOC,GAAG,CAAC,UAAA,CAAA,CAAYC,GAAG,CAAC,CAAC,OAAO,CAAC,EAAEF,MAAAA,CAAOG,KAAK,EAAEC,QAAAA,CAAAA;IACpDJ,MAAAA,CAAOC,GAAG,CAAC,aAAA,CAAA,CAAeC,GAAG,CAAC,CAAC,OAAO,CAAC,EAAEF,MAAAA,CAAOG,KAAK,EAAEE,WAAAA,CAAAA;AACvDL,IAAAA,MAAAA,CAAOC,GAAG,CAAC,eAAA,CAAA,CAAiBC,GAAG,CAAC,CAAC,OAAO,CAAC,EAAEI,kBAAAA,CAAmBN,MAAAA,CAAOG,KAAK,EAAEI,gBAAgB,EAAC,CAAA,CAAA;IAC7FP,MAAAA,CAAOC,GAAG,CAAC,UAAA,CAAA,CAAYC,GAAG,CAAC,CAAC,OAAO,CAAC,EAAEF,MAAAA,CAAOG,KAAK,EAAEK,QAAAA,CAAAA;IACpDR,MAAAA,CAAOC,GAAG,CAAC,aAAA,CAAA,CAAeC,GAAG,CAAC,CAAC,OAAO,CAAC,EAAEF,MAAAA,CAAOG,KAAK,EAAEM,WAAAA,CAAAA;AAEvD,IAAA,MAAMC,eAAAA,GAAkBV,MAAAA,CAAOW,MAAM,CAACV,GAAG,CAAC,OAAA,CAAA;AAC1CD,IAAAA,MAAAA,CAAOC,GAAG,CAAC,QAAA,CAAA,CAAUW,GAAG,CAAC,OAAA,EAASC,kBAAAA,CAAEC,KAAK,CAACd,MAAAA,CAAOG,KAAK,EAAEQ,MAAAA,EAAQD,eAAAA,CAAAA,CAAAA;AAClE;AAEA,MAAMJ,qBAAqB,CAACC,YAAAA,GAAAA;AAC1BQ,IAAAA,MAAAA,CAAOC,MAAM,CAACT,YAAAA,CAAAA,CAAcU,OAAO,CAAC,CAACC,UAAAA,GAAAA;QACnC,MAAM,EAAEC,MAAM,EAAE,GAAGD,UAAAA;QAEnBH,MAAAA,CAAOK,MAAM,CAACD,MAAAA,EAAQ;YACpBE,MAAAA,EAAQ,OAAA;AACRC,YAAAA,QAAAA,EAAUC,kBAAYJ,MAAAA,EAAQ,OAAA;AAChC,SAAA,CAAA;AACF,IAAA,CAAA,CAAA;IAEA,OAAOZ,YAAAA;AACT,CAAA;;;;"}
|
package/dist/loaders/apis.js
CHANGED
|
@@ -7,22 +7,27 @@ var strapiUtils = require('@strapi/utils');
|
|
|
7
7
|
var fp = require('lodash/fp');
|
|
8
8
|
var index = require('../domain/content-type/index.js');
|
|
9
9
|
|
|
10
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
11
|
+
|
|
12
|
+
var fse__default = /*#__PURE__*/_interopDefault(fse);
|
|
13
|
+
var ___default = /*#__PURE__*/_interopDefault(_);
|
|
14
|
+
|
|
10
15
|
const DEFAULT_CONTENT_TYPE = {
|
|
11
16
|
schema: {},
|
|
12
17
|
actions: {},
|
|
13
18
|
lifecycles: {}
|
|
14
19
|
};
|
|
15
20
|
// to handle names with numbers in it we first check if it is already in kebabCase
|
|
16
|
-
const normalizeName = (name)=>strapiUtils.strings.isKebabCase(name) ? name :
|
|
21
|
+
const normalizeName = (name)=>strapiUtils.strings.isKebabCase(name) ? name : ___default.default.kebabCase(name);
|
|
17
22
|
const isDirectory = (fd)=>fd.isDirectory();
|
|
18
23
|
const isDotFile = (fd)=>fd.name.startsWith('.');
|
|
19
24
|
async function loadAPIs(strapi) {
|
|
20
25
|
if (!fse.existsSync(strapi.dirs.dist.api)) {
|
|
21
26
|
return;
|
|
22
27
|
}
|
|
23
|
-
const apisFDs = await (await
|
|
28
|
+
const apisFDs = await (await fse__default.default.readdir(strapi.dirs.dist.api, {
|
|
24
29
|
withFileTypes: true
|
|
25
|
-
})).filter(isDirectory).filter(
|
|
30
|
+
})).filter(isDirectory).filter(___default.default.negate(isDotFile));
|
|
26
31
|
const apis = {};
|
|
27
32
|
// only load folders
|
|
28
33
|
for (const apiFD of apisFDs){
|
|
@@ -41,14 +46,14 @@ const validateContentTypesUnicity = (apis)=>{
|
|
|
41
46
|
const names = [];
|
|
42
47
|
allApisSchemas.forEach(({ schema })=>{
|
|
43
48
|
if (schema.info.singularName) {
|
|
44
|
-
const singularName =
|
|
49
|
+
const singularName = ___default.default.kebabCase(schema.info.singularName);
|
|
45
50
|
if (names.includes(singularName)) {
|
|
46
51
|
throw new Error(`The singular name "${schema.info.singularName}" should be unique`);
|
|
47
52
|
}
|
|
48
53
|
names.push(singularName);
|
|
49
54
|
}
|
|
50
55
|
if (schema.info.pluralName) {
|
|
51
|
-
const pluralName =
|
|
56
|
+
const pluralName = ___default.default.kebabCase(schema.info.pluralName);
|
|
52
57
|
if (names.includes(pluralName)) {
|
|
53
58
|
throw new Error(`The plural name "${schema.info.pluralName}" should be unique`);
|
|
54
59
|
}
|
|
@@ -79,16 +84,16 @@ const loadAPI = async (apiName, dir)=>{
|
|
|
79
84
|
};
|
|
80
85
|
};
|
|
81
86
|
const loadIndex = async (dir)=>{
|
|
82
|
-
if (await
|
|
87
|
+
if (await fse__default.default.pathExists(path.join(dir, 'index.js'))) {
|
|
83
88
|
return loadFile(path.join(dir, 'index.js'));
|
|
84
89
|
}
|
|
85
90
|
};
|
|
86
91
|
// because this is async and its contents are dynamic, we must return it within an object to avoid a property called `then` being interpreted as a Promise
|
|
87
92
|
const loadContentTypes = async (apiName, dir)=>{
|
|
88
|
-
if (!await
|
|
93
|
+
if (!await fse__default.default.pathExists(dir)) {
|
|
89
94
|
return;
|
|
90
95
|
}
|
|
91
|
-
const fds = await
|
|
96
|
+
const fds = await fse__default.default.readdir(dir, {
|
|
92
97
|
withFileTypes: true
|
|
93
98
|
});
|
|
94
99
|
const contentTypes = {};
|
|
@@ -119,10 +124,10 @@ const loadContentTypes = async (apiName, dir)=>{
|
|
|
119
124
|
};
|
|
120
125
|
// because this is async and its contents are dynamic, we must return it within an object to avoid a property called `then` being interpreted as a Promise
|
|
121
126
|
const loadDir = async (dir)=>{
|
|
122
|
-
if (!await
|
|
127
|
+
if (!await fse__default.default.pathExists(dir)) {
|
|
123
128
|
return;
|
|
124
129
|
}
|
|
125
|
-
const fds = await
|
|
130
|
+
const fds = await fse__default.default.readdir(dir, {
|
|
126
131
|
withFileTypes: true
|
|
127
132
|
});
|
|
128
133
|
const root = {};
|
|
@@ -147,7 +152,7 @@ const loadFile = async (file)=>{
|
|
|
147
152
|
};
|
|
148
153
|
case '.json':
|
|
149
154
|
return {
|
|
150
|
-
result: await
|
|
155
|
+
result: await fse__default.default.readJSON(file)
|
|
151
156
|
};
|
|
152
157
|
default:
|
|
153
158
|
return {
|
package/dist/loaders/apis.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apis.js","sources":["../../src/loaders/apis.ts"],"sourcesContent":["import { join, extname, basename } from 'path';\nimport fse, { existsSync } from 'fs-extra';\nimport _ from 'lodash';\nimport { strings, importDefault } from '@strapi/utils';\nimport { isEmpty } from 'lodash/fp';\nimport type { Core, Struct } from '@strapi/types';\nimport { getGlobalId, type ContentTypeDefinition } from '../domain/content-type';\n\ninterface API {\n bootstrap: () => void | Promise<void>;\n destroy: () => void | Promise<void>;\n register: () => void | Promise<void>;\n config: Record<string, unknown>;\n routes: Record<string, Core.Router>;\n controllers: Record<string, Core.Controller>;\n services: Record<string, Core.Service>;\n policies: Record<string, Core.Policy>;\n middlewares: Record<string, Core.Middleware>;\n contentTypes: Record<string, { schema: Struct.ContentTypeSchema }>;\n}\n\ninterface APIs {\n [key: string]: API;\n}\n\nconst DEFAULT_CONTENT_TYPE = {\n schema: {},\n actions: {},\n lifecycles: {},\n};\n\n// to handle names with numbers in it we first check if it is already in kebabCase\nconst normalizeName = (name: string) => (strings.isKebabCase(name) ? name : _.kebabCase(name));\n\nconst isDirectory = (fd: fse.Dirent) => fd.isDirectory();\nconst isDotFile = (fd: fse.Dirent) => fd.name.startsWith('.');\n\nexport default async function loadAPIs(strapi: Core.Strapi) {\n if (!existsSync(strapi.dirs.dist.api)) {\n return;\n }\n\n const apisFDs = await (await fse.readdir(strapi.dirs.dist.api, { withFileTypes: true }))\n .filter(isDirectory)\n .filter(_.negate(isDotFile));\n\n const apis: APIs = {};\n\n // only load folders\n for (const apiFD of apisFDs) {\n const apiName = normalizeName(apiFD.name);\n const api = await loadAPI(apiName, join(strapi.dirs.dist.api, apiFD.name));\n\n // @ts-expect-error TODO verify that it's a valid api, not missing bootstrap, register, and destroy\n apis[apiName] = api;\n }\n\n validateContentTypesUnicity(apis);\n\n for (const apiName of Object.keys(apis)) {\n strapi.get('apis').add(apiName, apis[apiName]);\n }\n}\n\nconst validateContentTypesUnicity = (apis: APIs) => {\n const allApisSchemas = Object.values(apis).flatMap((api) => Object.values(api.contentTypes));\n\n const names: string[] = [];\n allApisSchemas.forEach(({ schema }) => {\n if (schema.info.singularName) {\n const singularName = _.kebabCase(schema.info.singularName);\n if (names.includes(singularName)) {\n throw new Error(`The singular name \"${schema.info.singularName}\" should be unique`);\n }\n names.push(singularName);\n }\n\n if (schema.info.pluralName) {\n const pluralName = _.kebabCase(schema.info.pluralName);\n if (names.includes(pluralName)) {\n throw new Error(`The plural name \"${schema.info.pluralName}\" should be unique`);\n }\n names.push(pluralName);\n }\n });\n};\n\nconst loadAPI = async (apiName: string, dir: string) => {\n const [index, config, routes, controllers, services, policies, middlewares, contentTypes] = (\n await Promise.all([\n loadIndex(dir),\n loadDir(join(dir, 'config')),\n loadDir(join(dir, 'routes')),\n loadDir(join(dir, 'controllers')),\n loadDir(join(dir, 'services')),\n loadDir(join(dir, 'policies')),\n loadDir(join(dir, 'middlewares')),\n loadContentTypes(apiName, join(dir, 'content-types')),\n ])\n ).map((result) => result?.result);\n\n return {\n ...(index || {}),\n config: config || {},\n routes: routes || [],\n controllers: controllers || {},\n services: services || {},\n policies: policies || {},\n middlewares: middlewares || {},\n contentTypes: contentTypes || {},\n };\n};\n\nconst loadIndex = async (dir: string) => {\n if (await fse.pathExists(join(dir, 'index.js'))) {\n return loadFile(join(dir, 'index.js'));\n }\n};\n\n// because this is async and its contents are dynamic, we must return it within an object to avoid a property called `then` being interpreted as a Promise\nconst loadContentTypes = async (apiName: string, dir: string) => {\n if (!(await fse.pathExists(dir))) {\n return;\n }\n\n const fds = await fse.readdir(dir, { withFileTypes: true });\n const contentTypes: API['contentTypes'] = {};\n\n // only load folders\n for (const fd of fds) {\n if (fd.isFile()) {\n continue;\n }\n\n const contentTypeName = normalizeName(fd.name);\n const loadedContentType = (await loadDir(join(dir, fd.name)))?.result;\n\n if (isEmpty(loadedContentType) || isEmpty(loadedContentType.schema)) {\n throw new Error(`Could not load content type found at ${dir}`);\n }\n\n const contentType = {\n ...DEFAULT_CONTENT_TYPE,\n ...loadedContentType,\n } as ContentTypeDefinition;\n\n Object.assign(contentType.schema, {\n apiName,\n collectionName: contentType.schema.collectionName || contentType.schema.info.singularName,\n globalId: getGlobalId(contentType.schema),\n });\n\n contentTypes[normalizeName(contentTypeName)] = contentType;\n }\n\n return { result: contentTypes };\n};\n\n// because this is async and its contents are dynamic, we must return it within an object to avoid a property called `then` being interpreted as a Promise\nconst loadDir = async (dir: string) => {\n if (!(await fse.pathExists(dir))) {\n return;\n }\n\n const fds = await fse.readdir(dir, { withFileTypes: true });\n\n const root: Record<string, unknown> = {};\n for (const fd of fds) {\n if (!fd.isFile() || extname(fd.name) === '.map') {\n continue;\n }\n\n const key = basename(fd.name, extname(fd.name));\n\n root[normalizeName(key)] = (await loadFile(join(dir, fd.name))).result;\n }\n\n return { result: root };\n};\n\n// because this is async and its contents are dynamic, we must return it as an array to avoid a property called `then` being interpreted as a Promise\nconst loadFile = async (file: string): Promise<{ result: unknown }> => {\n const ext = extname(file);\n\n switch (ext) {\n case '.js':\n return { result: importDefault(file) };\n case '.json':\n return { result: await fse.readJSON(file) };\n default:\n return { result: {} };\n }\n};\n"],"names":["DEFAULT_CONTENT_TYPE","schema","actions","lifecycles","normalizeName","name","strings","isKebabCase","_","kebabCase","isDirectory","fd","isDotFile","startsWith","loadAPIs","strapi","existsSync","dirs","dist","api","apisFDs","fse","readdir","withFileTypes","filter","negate","apis","apiFD","apiName","loadAPI","join","validateContentTypesUnicity","Object","keys","get","add","allApisSchemas","values","flatMap","contentTypes","names","forEach","info","singularName","includes","Error","push","pluralName","dir","index","config","routes","controllers","services","policies","middlewares","Promise","all","loadIndex","loadDir","loadContentTypes","map","result","pathExists","loadFile","fds","isFile","contentTypeName","loadedContentType","isEmpty","contentType","assign","collectionName","globalId","getGlobalId","root","extname","key","basename","file","ext","importDefault","readJSON"],"mappings":";;;;;;;;;AAyBA,MAAMA,oBAAAA,GAAuB;AAC3BC,IAAAA,MAAAA,EAAQ,EAAC;AACTC,IAAAA,OAAAA,EAAS,EAAC;AACVC,IAAAA,UAAAA,EAAY;AACd,CAAA;AAEA;AACA,MAAMC,aAAAA,GAAgB,CAACC,IAAAA,GAAkBC,mBAAAA,CAAQC,WAAW,CAACF,IAAAA,CAAAA,GAAQA,IAAAA,GAAOG,CAAAA,CAAEC,SAAS,CAACJ,IAAAA,CAAAA;AAExF,MAAMK,WAAAA,GAAc,CAACC,EAAAA,GAAmBA,EAAAA,CAAGD,WAAW,EAAA;AACtD,MAAME,YAAY,CAACD,EAAAA,GAAmBA,GAAGN,IAAI,CAACQ,UAAU,CAAC,GAAA,CAAA;AAE1C,eAAeC,SAASC,MAAmB,EAAA;IACxD,IAAI,CAACC,eAAWD,MAAAA,CAAOE,IAAI,CAACC,IAAI,CAACC,GAAG,CAAA,EAAG;AACrC,QAAA;AACF,IAAA;AAEA,IAAA,MAAMC,OAAAA,GAAU,MAAM,CAAC,MAAMC,GAAAA,CAAIC,OAAO,CAACP,MAAAA,CAAOE,IAAI,CAACC,IAAI,CAACC,GAAG,EAAE;QAAEI,aAAAA,EAAe;KAAK,CAAC,EACnFC,MAAM,CAACd,WAAAA,C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B,aAAAA,EAAe;AAAK,KAAA,CAAA;AAEzD,IAAA,MAAMoD,OAAgC,EAAC;IACvC,KAAK,MAAMhE,MAAMsD,GAAAA,CAAK;QACpB,IAAI,CAACtD,GAAGuD,MAAM,EAAA,IAAMU,aAAQjE,EAAAA,CAAGN,IAAI,MAAM,MAAA,EAAQ;AAC/C,YAAA;AACF,QAAA;AAEA,QAAA,MAAMwE,MAAMC,aAAAA,CAASnE,EAAAA,CAAGN,IAAI,EAAEuE,YAAAA,CAAQjE,GAAGN,IAAI,CAAA,CAAA;AAE7CsE,QAAAA,IAAI,CAACvE,aAAAA,CAAcyE,GAAAA,CAAAA,CAAK,GAAG,CAAC,MAAMb,QAAAA,CAASlC,SAAAA,CAAKkB,GAAAA,EAAKrC,EAAAA,CAAGN,IAAI,CAAA,CAAC,EAAGyD,MAAM;AACxE,IAAA;IAEA,OAAO;QAAEA,MAAAA,EAAQa;AAAK,KAAA;AACxB,CAAA;AAEA;AACA,MAAMX,WAAW,OAAOe,IAAAA,GAAAA;AACtB,IAAA,MAAMC,MAAMJ,YAAAA,CAAQG,IAAAA,CAAAA;IAEpB,OAAQC,GAAAA;QACN,KAAK,KAAA;YACH,OAAO;AAAElB,gBAAAA,MAAAA,EAAQmB,yBAAAA,CAAcF,IAAAA;AAAM,aAAA;QACvC,KAAK,OAAA;YACH,OAAO;gBAAEjB,MAAAA,EAAQ,MAAMzC,GAAAA,CAAI6D,QAAQ,CAACH,IAAAA;AAAM,aAAA;AAC5C,QAAA;YACE,OAAO;AAAEjB,gBAAAA,MAAAA,EAAQ;AAAG,aAAA;AACxB;AACF,CAAA;;;;"}
|
|
1
|
+
{"version":3,"file":"apis.js","sources":["../../src/loaders/apis.ts"],"sourcesContent":["import { join, extname, basename } from 'path';\nimport fse, { existsSync } from 'fs-extra';\nimport _ from 'lodash';\nimport { strings, importDefault } from '@strapi/utils';\nimport { isEmpty } from 'lodash/fp';\nimport type { Core, Struct } from '@strapi/types';\nimport { getGlobalId, type ContentTypeDefinition } from '../domain/content-type';\n\ninterface API {\n bootstrap: () => void | Promise<void>;\n destroy: () => void | Promise<void>;\n register: () => void | Promise<void>;\n config: Record<string, unknown>;\n routes: Record<string, Core.Router>;\n controllers: Record<string, Core.Controller>;\n services: Record<string, Core.Service>;\n policies: Record<string, Core.Policy>;\n middlewares: Record<string, Core.Middleware>;\n contentTypes: Record<string, { schema: Struct.ContentTypeSchema }>;\n}\n\ninterface APIs {\n [key: string]: API;\n}\n\nconst DEFAULT_CONTENT_TYPE = {\n schema: {},\n actions: {},\n lifecycles: {},\n};\n\n// to handle names with numbers in it we first check if it is already in kebabCase\nconst normalizeName = (name: string) => (strings.isKebabCase(name) ? name : _.kebabCase(name));\n\nconst isDirectory = (fd: fse.Dirent) => fd.isDirectory();\nconst isDotFile = (fd: fse.Dirent) => fd.name.startsWith('.');\n\nexport default async function loadAPIs(strapi: Core.Strapi) {\n if (!existsSync(strapi.dirs.dist.api)) {\n return;\n }\n\n const apisFDs = await (await fse.readdir(strapi.dirs.dist.api, { withFileTypes: true }))\n .filter(isDirectory)\n .filter(_.negate(isDotFile));\n\n const apis: APIs = {};\n\n // only load folders\n for (const apiFD of apisFDs) {\n const apiName = normalizeName(apiFD.name);\n const api = await loadAPI(apiName, join(strapi.dirs.dist.api, apiFD.name));\n\n // @ts-expect-error TODO verify that it's a valid api, not missing bootstrap, register, and destroy\n apis[apiName] = api;\n }\n\n validateContentTypesUnicity(apis);\n\n for (const apiName of Object.keys(apis)) {\n strapi.get('apis').add(apiName, apis[apiName]);\n }\n}\n\nconst validateContentTypesUnicity = (apis: APIs) => {\n const allApisSchemas = Object.values(apis).flatMap((api) => Object.values(api.contentTypes));\n\n const names: string[] = [];\n allApisSchemas.forEach(({ schema }) => {\n if (schema.info.singularName) {\n const singularName = _.kebabCase(schema.info.singularName);\n if (names.includes(singularName)) {\n throw new Error(`The singular name \"${schema.info.singularName}\" should be unique`);\n }\n names.push(singularName);\n }\n\n if (schema.info.pluralName) {\n const pluralName = _.kebabCase(schema.info.pluralName);\n if (names.includes(pluralName)) {\n throw new Error(`The plural name \"${schema.info.pluralName}\" should be unique`);\n }\n names.push(pluralName);\n }\n });\n};\n\nconst loadAPI = async (apiName: string, dir: string) => {\n const [index, config, routes, controllers, services, policies, middlewares, contentTypes] = (\n await Promise.all([\n loadIndex(dir),\n loadDir(join(dir, 'config')),\n loadDir(join(dir, 'routes')),\n loadDir(join(dir, 'controllers')),\n loadDir(join(dir, 'services')),\n loadDir(join(dir, 'policies')),\n loadDir(join(dir, 'middlewares')),\n loadContentTypes(apiName, join(dir, 'content-types')),\n ])\n ).map((result) => result?.result);\n\n return {\n ...(index || {}),\n config: config || {},\n routes: routes || [],\n controllers: controllers || {},\n services: services || {},\n policies: policies || {},\n middlewares: middlewares || {},\n contentTypes: contentTypes || {},\n };\n};\n\nconst loadIndex = async (dir: string) => {\n if (await fse.pathExists(join(dir, 'index.js'))) {\n return loadFile(join(dir, 'index.js'));\n }\n};\n\n// because this is async and its contents are dynamic, we must return it within an object to avoid a property called `then` being interpreted as a Promise\nconst loadContentTypes = async (apiName: string, dir: string) => {\n if (!(await fse.pathExists(dir))) {\n return;\n }\n\n const fds = await fse.readdir(dir, { withFileTypes: true });\n const contentTypes: API['contentTypes'] = {};\n\n // only load folders\n for (const fd of fds) {\n if (fd.isFile()) {\n continue;\n }\n\n const contentTypeName = normalizeName(fd.name);\n const loadedContentType = (await loadDir(join(dir, fd.name)))?.result;\n\n if (isEmpty(loadedContentType) || isEmpty(loadedContentType.schema)) {\n throw new Error(`Could not load content type found at ${dir}`);\n }\n\n const contentType = {\n ...DEFAULT_CONTENT_TYPE,\n ...loadedContentType,\n } as ContentTypeDefinition;\n\n Object.assign(contentType.schema, {\n apiName,\n collectionName: contentType.schema.collectionName || contentType.schema.info.singularName,\n globalId: getGlobalId(contentType.schema),\n });\n\n contentTypes[normalizeName(contentTypeName)] = contentType;\n }\n\n return { result: contentTypes };\n};\n\n// because this is async and its contents are dynamic, we must return it within an object to avoid a property called `then` being interpreted as a Promise\nconst loadDir = async (dir: string) => {\n if (!(await fse.pathExists(dir))) {\n return;\n }\n\n const fds = await fse.readdir(dir, { withFileTypes: true });\n\n const root: Record<string, unknown> = {};\n for (const fd of fds) {\n if (!fd.isFile() || extname(fd.name) === '.map') {\n continue;\n }\n\n const key = basename(fd.name, extname(fd.name));\n\n root[normalizeName(key)] = (await loadFile(join(dir, fd.name))).result;\n }\n\n return { result: root };\n};\n\n// because this is async and its contents are dynamic, we must return it as an array to avoid a property called `then` being interpreted as a Promise\nconst loadFile = async (file: string): Promise<{ result: unknown }> => {\n const ext = extname(file);\n\n switch (ext) {\n case '.js':\n return { result: importDefault(file) };\n case '.json':\n return { result: await fse.readJSON(file) };\n default:\n return { result: {} };\n }\n};\n"],"names":["DEFAULT_CONTENT_TYPE","schema","actions","lifecycles","normalizeName","name","strings","isKebabCase","_","kebabCase","isDirectory","fd","isDotFile","startsWith","loadAPIs","strapi","existsSync","dirs","dist","api","apisFDs","fse","readdir","withFileTypes","filter","negate","apis","apiFD","apiName","loadAPI","join","validateContentTypesUnicity","Object","keys","get","add","allApisSchemas","values","flatMap","contentTypes","names","forEach","info","singularName","includes","Error","push","pluralName","dir","index","config","routes","controllers","services","policies","middlewares","Promise","all","loadIndex","loadDir","loadContentTypes","map","result","pathExists","loadFile","fds","isFile","contentTypeName","loadedContentType","isEmpty","contentType","assign","collectionName","globalId","getGlobalId","root","extname","key","basename","file","ext","importDefault","readJSON"],"mappings":";;;;;;;;;;;;;;AAyBA,MAAMA,oBAAAA,GAAuB;AAC3BC,IAAAA,MAAAA,EAAQ,EAAC;AACTC,IAAAA,OAAAA,EAAS,EAAC;AACVC,IAAAA,UAAAA,EAAY;AACd,CAAA;AAEA;AACA,MAAMC,aAAAA,GAAgB,CAACC,IAAAA,GAAkBC,mBAAAA,CAAQC,WAAW,CAACF,IAAAA,CAAAA,GAAQA,IAAAA,GAAOG,kBAAAA,CAAEC,SAAS,CAACJ,IAAAA,CAAAA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,OAAO;AAAElB,gBAAAA,MAAAA,EAAQmB,yBAAAA,CAAcF,IAAAA;AAAM,aAAA;QACvC,KAAK,OAAA;YACH,OAAO;gBAAEjB,MAAAA,EAAQ,MAAMzC,oBAAAA,CAAI6D,QAAQ,CAACH,IAAAA;AAAM,aAAA;AAC5C,QAAA;YACE,OAAO;AAAEjB,gBAAAA,MAAAA,EAAQ;AAAG,aAAA;AACxB;AACF,CAAA;;;;"}
|
|
@@ -5,6 +5,10 @@ var _ = require('lodash');
|
|
|
5
5
|
var fse = require('fs-extra');
|
|
6
6
|
var loadFiles = require('../utils/load-files.js');
|
|
7
7
|
|
|
8
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
9
|
+
|
|
10
|
+
var ___default = /*#__PURE__*/_interopDefault(_);
|
|
11
|
+
|
|
8
12
|
async function loadComponents(strapi) {
|
|
9
13
|
if (!await fse.pathExists(strapi.dirs.dist.components)) {
|
|
10
14
|
return {};
|
|
@@ -20,12 +24,12 @@ async function loadComponents(strapi) {
|
|
|
20
24
|
}
|
|
21
25
|
const uid = `${category}.${key}`;
|
|
22
26
|
acc[uid] = Object.assign(schema, {
|
|
23
|
-
__schema__:
|
|
27
|
+
__schema__: ___default.default.cloneDeep(schema),
|
|
24
28
|
uid,
|
|
25
29
|
category,
|
|
26
30
|
modelType: 'component',
|
|
27
31
|
modelName: key,
|
|
28
|
-
globalId: schema.globalId ||
|
|
32
|
+
globalId: schema.globalId || ___default.default.upperFirst(___default.default.camelCase(`component_${uid}`))
|
|
29
33
|
});
|
|
30
34
|
});
|
|
31
35
|
return acc;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"components.js","sources":["../../src/loaders/components.ts"],"sourcesContent":["import { join } from 'path';\nimport _ from 'lodash';\nimport { pathExists } from 'fs-extra';\nimport type { Core, Struct, UID } from '@strapi/types';\nimport { loadFiles } from '../utils/load-files';\n\ntype LoadedComponent = {\n collectionName: string;\n __filename__: string;\n __schema__: LoadedComponent;\n uid: string;\n category: string;\n modelName: string;\n globalId: string;\n info: any;\n attributes: any;\n};\n\ntype LoadedComponents = {\n [category: string]: {\n [key: string]: LoadedComponent;\n };\n};\n\ntype ComponentMap = {\n [uid in UID.Component]: Struct.ComponentSchema;\n};\n\nexport default async function loadComponents(strapi: Core.Strapi) {\n if (!(await pathExists(strapi.dirs.dist.components))) {\n return {};\n }\n\n const map = await loadFiles<LoadedComponents>(strapi.dirs.dist.components, '*/*.*(js|json)');\n\n const components = Object.keys(map).reduce((acc, category) => {\n Object.keys(map[category]).forEach((key) => {\n const schema = map[category][key];\n\n if (!schema.collectionName) {\n // NOTE: We're using the filepath from the app directory instead of the dist for information purpose\n const filePath = join(strapi.dirs.app.components, category, schema.__filename__);\n\n return strapi.stopWithError(\n `Component ${key} is missing a \"collectionName\" property.\\nVerify file ${filePath}.`\n );\n }\n\n const uid: UID.Component = `${category}.${key}`;\n\n acc[uid] = Object.assign(schema, {\n __schema__: _.cloneDeep(schema),\n uid,\n category,\n modelType: 'component' as const,\n modelName: key,\n globalId: schema.globalId || _.upperFirst(_.camelCase(`component_${uid}`)),\n });\n });\n\n return acc;\n }, {} as ComponentMap);\n\n strapi.get('components').add(components);\n}\n"],"names":["loadComponents","strapi","pathExists","dirs","dist","components","map","loadFiles","Object","keys","reduce","acc","category","forEach","key","schema","collectionName","filePath","join","app","__filename__","stopWithError","uid","assign","__schema__","_","cloneDeep","modelType","modelName","globalId","upperFirst","camelCase","get","add"],"mappings":"
|
|
1
|
+
{"version":3,"file":"components.js","sources":["../../src/loaders/components.ts"],"sourcesContent":["import { join } from 'path';\nimport _ from 'lodash';\nimport { pathExists } from 'fs-extra';\nimport type { Core, Struct, UID } from '@strapi/types';\nimport { loadFiles } from '../utils/load-files';\n\ntype LoadedComponent = {\n collectionName: string;\n __filename__: string;\n __schema__: LoadedComponent;\n uid: string;\n category: string;\n modelName: string;\n globalId: string;\n info: any;\n attributes: any;\n};\n\ntype LoadedComponents = {\n [category: string]: {\n [key: string]: LoadedComponent;\n };\n};\n\ntype ComponentMap = {\n [uid in UID.Component]: Struct.ComponentSchema;\n};\n\nexport default async function loadComponents(strapi: Core.Strapi) {\n if (!(await pathExists(strapi.dirs.dist.components))) {\n return {};\n }\n\n const map = await loadFiles<LoadedComponents>(strapi.dirs.dist.components, '*/*.*(js|json)');\n\n const components = Object.keys(map).reduce((acc, category) => {\n Object.keys(map[category]).forEach((key) => {\n const schema = map[category][key];\n\n if (!schema.collectionName) {\n // NOTE: We're using the filepath from the app directory instead of the dist for information purpose\n const filePath = join(strapi.dirs.app.components, category, schema.__filename__);\n\n return strapi.stopWithError(\n `Component ${key} is missing a \"collectionName\" property.\\nVerify file ${filePath}.`\n );\n }\n\n const uid: UID.Component = `${category}.${key}`;\n\n acc[uid] = Object.assign(schema, {\n __schema__: _.cloneDeep(schema),\n uid,\n category,\n modelType: 'component' as const,\n modelName: key,\n globalId: schema.globalId || _.upperFirst(_.camelCase(`component_${uid}`)),\n });\n });\n\n return acc;\n }, {} as ComponentMap);\n\n strapi.get('components').add(components);\n}\n"],"names":["loadComponents","strapi","pathExists","dirs","dist","components","map","loadFiles","Object","keys","reduce","acc","category","forEach","key","schema","collectionName","filePath","join","app","__filename__","stopWithError","uid","assign","__schema__","_","cloneDeep","modelType","modelName","globalId","upperFirst","camelCase","get","add"],"mappings":";;;;;;;;;;;AA4Be,eAAeA,eAAeC,MAAmB,EAAA;IAC9D,IAAI,CAAE,MAAMC,cAAAA,CAAWD,MAAAA,CAAOE,IAAI,CAACC,IAAI,CAACC,UAAU,CAAA,EAAI;AACpD,QAAA,OAAO,EAAC;AACV,IAAA;IAEA,MAAMC,GAAAA,GAAM,MAAMC,mBAAAA,CAA4BN,MAAAA,CAAOE,IAAI,CAACC,IAAI,CAACC,UAAU,EAAE,gBAAA,CAAA;IAE3E,MAAMA,UAAAA,GAAaG,OAAOC,IAAI,CAACH,KAAKI,MAAM,CAAC,CAACC,GAAAA,EAAKC,QAAAA,GAAAA;QAC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