@strapi/core 0.0.0-next.1ebd3c267c132c3c5c3d3e1a6a947f61180ce341 → 0.0.0-next.20c174685c9e5863b57503950b4359362bc6ebac
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.
Potentially problematic release.
This version of @strapi/core might be problematic. Click here for more details.
- package/dist/Strapi.d.ts.map +1 -1
- package/dist/Strapi.js +2 -0
- package/dist/Strapi.js.map +1 -1
- package/dist/Strapi.mjs +2 -0
- package/dist/Strapi.mjs.map +1 -1
- package/dist/configuration/index.d.ts +1 -0
- package/dist/configuration/index.d.ts.map +1 -1
- package/dist/configuration/index.js +1 -0
- package/dist/configuration/index.js.map +1 -1
- package/dist/configuration/index.mjs +1 -0
- package/dist/configuration/index.mjs.map +1 -1
- package/dist/core-api/routes/index.d.ts +4 -22
- package/dist/core-api/routes/index.d.ts.map +1 -1
- package/dist/core-api/routes/index.js +150 -8
- package/dist/core-api/routes/index.js.map +1 -1
- package/dist/core-api/routes/index.mjs +131 -8
- package/dist/core-api/routes/index.mjs.map +1 -1
- package/dist/core-api/routes/validation/attributes.d.ts +244 -0
- package/dist/core-api/routes/validation/attributes.d.ts.map +1 -0
- package/dist/core-api/routes/validation/attributes.js +560 -0
- package/dist/core-api/routes/validation/attributes.js.map +1 -0
- package/dist/core-api/routes/validation/attributes.mjs +521 -0
- package/dist/core-api/routes/validation/attributes.mjs.map +1 -0
- package/dist/core-api/routes/validation/common.d.ts +105 -0
- package/dist/core-api/routes/validation/common.d.ts.map +1 -0
- package/dist/core-api/routes/validation/common.js +116 -0
- package/dist/core-api/routes/validation/common.js.map +1 -0
- package/dist/core-api/routes/validation/common.mjs +95 -0
- package/dist/core-api/routes/validation/common.mjs.map +1 -0
- package/dist/core-api/routes/validation/component.d.ts +34 -0
- package/dist/core-api/routes/validation/component.d.ts.map +1 -0
- package/dist/core-api/routes/validation/component.js +45 -0
- package/dist/core-api/routes/validation/component.js.map +1 -0
- package/dist/core-api/routes/validation/component.mjs +43 -0
- package/dist/core-api/routes/validation/component.mjs.map +1 -0
- package/dist/core-api/routes/validation/constants.d.ts +8 -0
- package/dist/core-api/routes/validation/constants.d.ts.map +1 -0
- package/dist/core-api/routes/validation/constants.js +18 -0
- package/dist/core-api/routes/validation/constants.js.map +1 -0
- package/dist/core-api/routes/validation/constants.mjs +16 -0
- package/dist/core-api/routes/validation/constants.mjs.map +1 -0
- package/dist/core-api/routes/validation/content-type.d.ts +128 -0
- package/dist/core-api/routes/validation/content-type.d.ts.map +1 -0
- package/dist/core-api/routes/validation/content-type.js +201 -0
- package/dist/core-api/routes/validation/content-type.js.map +1 -0
- package/dist/core-api/routes/validation/content-type.mjs +180 -0
- package/dist/core-api/routes/validation/content-type.mjs.map +1 -0
- package/dist/core-api/routes/validation/index.d.ts +5 -0
- package/dist/core-api/routes/validation/index.d.ts.map +1 -0
- package/dist/core-api/routes/validation/mappers.d.ts +105 -0
- package/dist/core-api/routes/validation/mappers.d.ts.map +1 -0
- package/dist/core-api/routes/validation/mappers.js +238 -0
- package/dist/core-api/routes/validation/mappers.js.map +1 -0
- package/dist/core-api/routes/validation/mappers.mjs +214 -0
- package/dist/core-api/routes/validation/mappers.mjs.map +1 -0
- package/dist/core-api/routes/validation/utils.d.ts +47 -0
- package/dist/core-api/routes/validation/utils.d.ts.map +1 -0
- package/dist/core-api/routes/validation/utils.js +112 -0
- package/dist/core-api/routes/validation/utils.js.map +1 -0
- package/dist/core-api/routes/validation/utils.mjs +90 -0
- package/dist/core-api/routes/validation/utils.mjs.map +1 -0
- package/dist/domain/module/index.d.ts.map +1 -1
- package/dist/domain/module/index.js +3 -0
- package/dist/domain/module/index.js.map +1 -1
- package/dist/domain/module/index.mjs +3 -0
- package/dist/domain/module/index.mjs.map +1 -1
- package/dist/ee/index.d.ts +6 -0
- package/dist/ee/index.d.ts.map +1 -1
- package/dist/ee/index.js +29 -3
- package/dist/ee/index.js.map +1 -1
- package/dist/ee/index.mjs +30 -4
- package/dist/ee/index.mjs.map +1 -1
- package/dist/ee/license.d.ts +3 -1
- package/dist/ee/license.d.ts.map +1 -1
- package/dist/ee/license.js +8 -2
- package/dist/ee/license.js.map +1 -1
- package/dist/ee/license.mjs +9 -4
- package/dist/ee/license.mjs.map +1 -1
- package/dist/factories.d.ts +3 -1
- package/dist/factories.d.ts.map +1 -1
- package/dist/factories.js +10 -2
- package/dist/factories.js.map +1 -1
- package/dist/factories.mjs +10 -3
- package/dist/factories.mjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/middlewares/cors.d.ts +9 -1
- package/dist/middlewares/cors.d.ts.map +1 -1
- package/dist/middlewares/cors.js +39 -17
- package/dist/middlewares/cors.js.map +1 -1
- package/dist/middlewares/cors.mjs +39 -18
- package/dist/middlewares/cors.mjs.map +1 -1
- package/dist/package.json.js +17 -14
- package/dist/package.json.js.map +1 -1
- package/dist/package.json.mjs +17 -14
- package/dist/package.json.mjs.map +1 -1
- package/dist/services/core-store.d.ts +2 -2
- package/dist/services/core-store.d.ts.map +1 -1
- package/dist/services/core-store.js.map +1 -1
- package/dist/services/core-store.mjs.map +1 -1
- package/dist/services/document-service/entries.d.ts.map +1 -1
- package/dist/services/document-service/entries.js +42 -0
- package/dist/services/document-service/entries.js.map +1 -1
- package/dist/services/document-service/entries.mjs +43 -1
- package/dist/services/document-service/entries.mjs.map +1 -1
- package/dist/services/document-service/internationalization.d.ts +6 -1
- package/dist/services/document-service/internationalization.d.ts.map +1 -1
- package/dist/services/document-service/internationalization.js +32 -0
- package/dist/services/document-service/internationalization.js.map +1 -1
- package/dist/services/document-service/internationalization.mjs +32 -1
- package/dist/services/document-service/internationalization.mjs.map +1 -1
- package/dist/services/document-service/repository.d.ts.map +1 -1
- package/dist/services/document-service/repository.js +5 -4
- package/dist/services/document-service/repository.js.map +1 -1
- package/dist/services/document-service/repository.mjs +6 -5
- package/dist/services/document-service/repository.mjs.map +1 -1
- package/dist/services/entity-validator/index.d.ts.map +1 -1
- package/dist/services/entity-validator/index.js +9 -0
- package/dist/services/entity-validator/index.js.map +1 -1
- package/dist/services/entity-validator/index.mjs +9 -0
- package/dist/services/entity-validator/index.mjs.map +1 -1
- package/dist/services/entity-validator/validators.d.ts +1 -0
- package/dist/services/entity-validator/validators.d.ts.map +1 -1
- package/dist/services/entity-validator/validators.js +3 -0
- package/dist/services/entity-validator/validators.js.map +1 -1
- package/dist/services/entity-validator/validators.mjs +3 -0
- package/dist/services/entity-validator/validators.mjs.map +1 -1
- package/dist/services/metrics/admin-user-hash.d.ts.map +1 -1
- package/dist/services/metrics/admin-user-hash.js.map +1 -1
- package/dist/services/metrics/admin-user-hash.mjs.map +1 -1
- package/dist/services/metrics/index.d.ts +1 -1
- package/dist/services/metrics/index.d.ts.map +1 -1
- package/dist/services/metrics/index.js +9 -8
- package/dist/services/metrics/index.js.map +1 -1
- package/dist/services/metrics/index.mjs +9 -8
- package/dist/services/metrics/index.mjs.map +1 -1
- package/dist/services/metrics/sender.d.ts.map +1 -1
- package/dist/services/metrics/sender.js +5 -5
- package/dist/services/metrics/sender.js.map +1 -1
- package/dist/services/metrics/sender.mjs +6 -6
- package/dist/services/metrics/sender.mjs.map +1 -1
- package/dist/services/server/register-routes.js +22 -2
- package/dist/services/server/register-routes.js.map +1 -1
- package/dist/services/server/register-routes.mjs +22 -2
- package/dist/services/server/register-routes.mjs.map +1 -1
- package/dist/services/server/routing.d.ts +10 -0
- package/dist/services/server/routing.d.ts.map +1 -1
- package/dist/services/server/routing.js +7 -1
- package/dist/services/server/routing.js.map +1 -1
- package/dist/services/server/routing.mjs +7 -1
- package/dist/services/server/routing.mjs.map +1 -1
- package/dist/services/utils/conditional-fields.d.ts +3 -0
- package/dist/services/utils/conditional-fields.d.ts.map +1 -0
- package/dist/services/utils/conditional-fields.js +22 -0
- package/dist/services/utils/conditional-fields.js.map +1 -0
- package/dist/services/utils/conditional-fields.mjs +20 -0
- package/dist/services/utils/conditional-fields.mjs.map +1 -0
- package/dist/utils/fetch.d.ts +5 -1
- package/dist/utils/fetch.d.ts.map +1 -1
- package/dist/utils/fetch.js +8 -4
- package/dist/utils/fetch.js.map +1 -1
- package/dist/utils/fetch.mjs +8 -4
- package/dist/utils/fetch.mjs.map +1 -1
- package/dist/utils/transform-content-types-to-models.d.ts +197 -0
- package/dist/utils/transform-content-types-to-models.d.ts.map +1 -1
- package/package.json +17 -14
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var strapiUtils = require('@strapi/utils');
|
|
4
|
+
var z = require('zod/v4');
|
|
5
|
+
|
|
6
|
+
function _interopNamespaceDefault(e) {
|
|
7
|
+
var n = Object.create(null);
|
|
8
|
+
if (e) {
|
|
9
|
+
Object.keys(e).forEach(function (k) {
|
|
10
|
+
if (k !== 'default') {
|
|
11
|
+
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
12
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
13
|
+
enumerable: true,
|
|
14
|
+
get: function () { return e[k]; }
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
n.default = e;
|
|
20
|
+
return Object.freeze(n);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
var z__namespace = /*#__PURE__*/_interopNamespaceDefault(z);
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Safely adds or updates a schema in Zod's global registry.
|
|
27
|
+
*
|
|
28
|
+
* If a schema with the given `id` already exists, it will be removed before adding the new one.
|
|
29
|
+
*
|
|
30
|
+
* This is useful for hot-reloading or preventing issues with cyclical dependencies.
|
|
31
|
+
*
|
|
32
|
+
* @param id - The unique identifier for the schema in the global registry.
|
|
33
|
+
* @param schema - The Zod schema to register.
|
|
34
|
+
* @example
|
|
35
|
+
* ```typescript
|
|
36
|
+
* safeGlobalRegistrySet("mySchema", z.object({ name: z.string() }));
|
|
37
|
+
* ```
|
|
38
|
+
*/ const safeGlobalRegistrySet = (id, schema)=>{
|
|
39
|
+
try {
|
|
40
|
+
const { _idmap: idMap } = z__namespace.globalRegistry;
|
|
41
|
+
const transformedId = strapiUtils.transformUidToValidOpenApiName(id);
|
|
42
|
+
if (idMap.has(transformedId)) {
|
|
43
|
+
// Remove existing schema to prevent conflicts
|
|
44
|
+
strapi.log.debug(`Removing existing schema ${transformedId} from registry`);
|
|
45
|
+
idMap.delete(transformedId);
|
|
46
|
+
}
|
|
47
|
+
// Register the new schema with the transformed ID
|
|
48
|
+
strapi.log.debug(`Registering schema ${transformedId} in global registry`);
|
|
49
|
+
z__namespace.globalRegistry.add(schema, {
|
|
50
|
+
id: transformedId
|
|
51
|
+
});
|
|
52
|
+
} catch (error) {
|
|
53
|
+
strapi.log.error(`Schema registration failed: Failed to register schema ${id} in global registry`);
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Safely creates and registers a Zod schema in the global registry, particularly useful for handling cyclical data structures.
|
|
59
|
+
*
|
|
60
|
+
* If a schema with the given `id` already exists in the global registry, it returns the existing schema.
|
|
61
|
+
*
|
|
62
|
+
* Otherwise, it registers a temporary `z.any()` schema, calls the provided `callback` to create the actual schema,
|
|
63
|
+
* and then replaces the temporary schema with the actual one in the registry.
|
|
64
|
+
*
|
|
65
|
+
* This prevents infinite loops in cases of cyclical dependencies.
|
|
66
|
+
*
|
|
67
|
+
* @param id - The unique identifier for the schema in the global registry.
|
|
68
|
+
* @param callback - A function that returns the Zod schema to be created and registered.
|
|
69
|
+
* @returns The created or retrieved Zod schema.
|
|
70
|
+
* @example
|
|
71
|
+
* ```typescript
|
|
72
|
+
* const CategorySchema = safeSchemaCreation("Category", () =>
|
|
73
|
+
* z.object({
|
|
74
|
+
* name: z.string(),
|
|
75
|
+
* products: z.array(safeSchemaCreation("Product", () =>
|
|
76
|
+
* z.object({
|
|
77
|
+
* name: z.string(),
|
|
78
|
+
* category: z.lazy(() => CategorySchema) // Cyclical reference
|
|
79
|
+
* })
|
|
80
|
+
* ))
|
|
81
|
+
* })
|
|
82
|
+
* );
|
|
83
|
+
* ```
|
|
84
|
+
*/ const safeSchemaCreation = (id, callback)=>{
|
|
85
|
+
try {
|
|
86
|
+
const { _idmap: idMap } = z__namespace.globalRegistry;
|
|
87
|
+
const transformedId = strapiUtils.transformUidToValidOpenApiName(id);
|
|
88
|
+
// Return existing schema if already registered
|
|
89
|
+
const mapItem = idMap.get(transformedId);
|
|
90
|
+
if (mapItem) {
|
|
91
|
+
strapi.log.debug(`Schema ${transformedId} found in registry, returning existing schema`);
|
|
92
|
+
return mapItem;
|
|
93
|
+
}
|
|
94
|
+
strapi.log.warn(`Schema ${transformedId} not found in global registry, creating an any placeholder`);
|
|
95
|
+
// Temporary any placeholder before replacing with the actual schema type
|
|
96
|
+
// Used to prevent infinite loops in cyclical data structures
|
|
97
|
+
safeGlobalRegistrySet(id, z__namespace.any());
|
|
98
|
+
// Generate the actual schema using the callback
|
|
99
|
+
const schema = callback();
|
|
100
|
+
// Replace the placeholder with the real schema
|
|
101
|
+
safeGlobalRegistrySet(id, schema);
|
|
102
|
+
strapi.log.debug(`Schema ${transformedId} successfully created and registered`);
|
|
103
|
+
return schema;
|
|
104
|
+
} catch (error) {
|
|
105
|
+
strapi.log.error(`Schema creation failed: Failed to create schema ${id}`);
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
exports.safeGlobalRegistrySet = safeGlobalRegistrySet;
|
|
111
|
+
exports.safeSchemaCreation = safeSchemaCreation;
|
|
112
|
+
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.js","sources":["../../../../src/core-api/routes/validation/utils.ts"],"sourcesContent":["import { transformUidToValidOpenApiName } from '@strapi/utils';\nimport type { Internal } from '@strapi/types';\nimport * as z from 'zod/v4';\n\n/**\n * Safely adds or updates a schema in Zod's global registry.\n *\n * If a schema with the given `id` already exists, it will be removed before adding the new one.\n *\n * This is useful for hot-reloading or preventing issues with cyclical dependencies.\n *\n * @param id - The unique identifier for the schema in the global registry.\n * @param schema - The Zod schema to register.\n * @example\n * ```typescript\n * safeGlobalRegistrySet(\"mySchema\", z.object({ name: z.string() }));\n * ```\n */\nexport const safeGlobalRegistrySet = (id: Internal.UID.Schema, schema: z.ZodType) => {\n try {\n const { _idmap: idMap } = z.globalRegistry;\n\n const transformedId = transformUidToValidOpenApiName(id);\n\n if (idMap.has(transformedId)) {\n // Remove existing schema to prevent conflicts\n strapi.log.debug(`Removing existing schema ${transformedId} from registry`);\n idMap.delete(transformedId);\n }\n\n // Register the new schema with the transformed ID\n strapi.log.debug(`Registering schema ${transformedId} in global registry`);\n z.globalRegistry.add(schema, { id: transformedId });\n } catch (error) {\n strapi.log.error(\n `Schema registration failed: Failed to register schema ${id} in global registry`\n );\n\n throw error;\n }\n};\n\n/**\n * Safely creates and registers a Zod schema in the global registry, particularly useful for handling cyclical data structures.\n *\n * If a schema with the given `id` already exists in the global registry, it returns the existing schema.\n *\n * Otherwise, it registers a temporary `z.any()` schema, calls the provided `callback` to create the actual schema,\n * and then replaces the temporary schema with the actual one in the registry.\n *\n * This prevents infinite loops in cases of cyclical dependencies.\n *\n * @param id - The unique identifier for the schema in the global registry.\n * @param callback - A function that returns the Zod schema to be created and registered.\n * @returns The created or retrieved Zod schema.\n * @example\n * ```typescript\n * const CategorySchema = safeSchemaCreation(\"Category\", () =>\n * z.object({\n * name: z.string(),\n * products: z.array(safeSchemaCreation(\"Product\", () =>\n * z.object({\n * name: z.string(),\n * category: z.lazy(() => CategorySchema) // Cyclical reference\n * })\n * ))\n * })\n * );\n * ```\n */\nexport const safeSchemaCreation = (id: Internal.UID.Schema, callback: () => z.ZodType) => {\n try {\n const { _idmap: idMap } = z.globalRegistry;\n\n const transformedId = transformUidToValidOpenApiName(id);\n\n // Return existing schema if already registered\n const mapItem = idMap.get(transformedId);\n if (mapItem) {\n strapi.log.debug(`Schema ${transformedId} found in registry, returning existing schema`);\n return mapItem;\n }\n\n strapi.log.warn(\n `Schema ${transformedId} not found in global registry, creating an any placeholder`\n );\n\n // Temporary any placeholder before replacing with the actual schema type\n // Used to prevent infinite loops in cyclical data structures\n safeGlobalRegistrySet(id, z.any());\n\n // Generate the actual schema using the callback\n const schema = callback();\n\n // Replace the placeholder with the real schema\n safeGlobalRegistrySet(id, schema);\n\n strapi.log.debug(`Schema ${transformedId} successfully created and registered`);\n\n return schema;\n } catch (error) {\n strapi.log.error(`Schema creation failed: Failed to create schema ${id}`);\n\n throw error;\n }\n};\n"],"names":["safeGlobalRegistrySet","id","schema","_idmap","idMap","z","globalRegistry","transformedId","transformUidToValidOpenApiName","has","strapi","log","debug","delete","add","error","safeSchemaCreation","callback","mapItem","get","warn","any"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;AAaC,IACM,MAAMA,qBAAwB,GAAA,CAACC,EAAyBC,EAAAA,MAAAA,GAAAA;IAC7D,IAAI;AACF,QAAA,MAAM,EAAEC,MAAQC,EAAAA,KAAK,EAAE,GAAGC,aAAEC,cAAc;AAE1C,QAAA,MAAMC,gBAAgBC,0CAA+BP,CAAAA,EAAAA,CAAAA;QAErD,IAAIG,KAAAA,CAAMK,GAAG,CAACF,aAAgB,CAAA,EAAA;;YAE5BG,MAAOC,CAAAA,GAAG,CAACC,KAAK,CAAC,CAAC,yBAAyB,EAAEL,aAAc,CAAA,cAAc,CAAC,CAAA;AAC1EH,YAAAA,KAAAA,CAAMS,MAAM,CAACN,aAAAA,CAAAA;AACf;;QAGAG,MAAOC,CAAAA,GAAG,CAACC,KAAK,CAAC,CAAC,mBAAmB,EAAEL,aAAc,CAAA,mBAAmB,CAAC,CAAA;AACzEF,QAAAA,YAAAA,CAAEC,cAAc,CAACQ,GAAG,CAACZ,MAAQ,EAAA;YAAED,EAAIM,EAAAA;AAAc,SAAA,CAAA;AACnD,KAAA,CAAE,OAAOQ,KAAO,EAA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api/utils';
|
|
2
|
+
import * as z from 'zod/v4';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Safely adds or updates a schema in Zod's global registry.
|
|
6
|
+
*
|
|
7
|
+
* If a schema with the given `id` already exists, it will be removed before adding the new one.
|
|
8
|
+
*
|
|
9
|
+
* This is useful for hot-reloading or preventing issues with cyclical dependencies.
|
|
10
|
+
*
|
|
11
|
+
* @param id - The unique identifier for the schema in the global registry.
|
|
12
|
+
* @param schema - The Zod schema to register.
|
|
13
|
+
* @example
|
|
14
|
+
* ```typescript
|
|
15
|
+
* safeGlobalRegistrySet("mySchema", z.object({ name: z.string() }));
|
|
16
|
+
* ```
|
|
17
|
+
*/ const safeGlobalRegistrySet = (id, schema)=>{
|
|
18
|
+
try {
|
|
19
|
+
const { _idmap: idMap } = z.globalRegistry;
|
|
20
|
+
const transformedId = transformUidToValidOpenApiName(id);
|
|
21
|
+
if (idMap.has(transformedId)) {
|
|
22
|
+
// Remove existing schema to prevent conflicts
|
|
23
|
+
strapi.log.debug(`Removing existing schema ${transformedId} from registry`);
|
|
24
|
+
idMap.delete(transformedId);
|
|
25
|
+
}
|
|
26
|
+
// Register the new schema with the transformed ID
|
|
27
|
+
strapi.log.debug(`Registering schema ${transformedId} in global registry`);
|
|
28
|
+
z.globalRegistry.add(schema, {
|
|
29
|
+
id: transformedId
|
|
30
|
+
});
|
|
31
|
+
} catch (error) {
|
|
32
|
+
strapi.log.error(`Schema registration failed: Failed to register schema ${id} in global registry`);
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Safely creates and registers a Zod schema in the global registry, particularly useful for handling cyclical data structures.
|
|
38
|
+
*
|
|
39
|
+
* If a schema with the given `id` already exists in the global registry, it returns the existing schema.
|
|
40
|
+
*
|
|
41
|
+
* Otherwise, it registers a temporary `z.any()` schema, calls the provided `callback` to create the actual schema,
|
|
42
|
+
* and then replaces the temporary schema with the actual one in the registry.
|
|
43
|
+
*
|
|
44
|
+
* This prevents infinite loops in cases of cyclical dependencies.
|
|
45
|
+
*
|
|
46
|
+
* @param id - The unique identifier for the schema in the global registry.
|
|
47
|
+
* @param callback - A function that returns the Zod schema to be created and registered.
|
|
48
|
+
* @returns The created or retrieved Zod schema.
|
|
49
|
+
* @example
|
|
50
|
+
* ```typescript
|
|
51
|
+
* const CategorySchema = safeSchemaCreation("Category", () =>
|
|
52
|
+
* z.object({
|
|
53
|
+
* name: z.string(),
|
|
54
|
+
* products: z.array(safeSchemaCreation("Product", () =>
|
|
55
|
+
* z.object({
|
|
56
|
+
* name: z.string(),
|
|
57
|
+
* category: z.lazy(() => CategorySchema) // Cyclical reference
|
|
58
|
+
* })
|
|
59
|
+
* ))
|
|
60
|
+
* })
|
|
61
|
+
* );
|
|
62
|
+
* ```
|
|
63
|
+
*/ const safeSchemaCreation = (id, callback)=>{
|
|
64
|
+
try {
|
|
65
|
+
const { _idmap: idMap } = z.globalRegistry;
|
|
66
|
+
const transformedId = transformUidToValidOpenApiName(id);
|
|
67
|
+
// Return existing schema if already registered
|
|
68
|
+
const mapItem = idMap.get(transformedId);
|
|
69
|
+
if (mapItem) {
|
|
70
|
+
strapi.log.debug(`Schema ${transformedId} found in registry, returning existing schema`);
|
|
71
|
+
return mapItem;
|
|
72
|
+
}
|
|
73
|
+
strapi.log.warn(`Schema ${transformedId} not found in global registry, creating an any placeholder`);
|
|
74
|
+
// Temporary any placeholder before replacing with the actual schema type
|
|
75
|
+
// Used to prevent infinite loops in cyclical data structures
|
|
76
|
+
safeGlobalRegistrySet(id, z.any());
|
|
77
|
+
// Generate the actual schema using the callback
|
|
78
|
+
const schema = callback();
|
|
79
|
+
// Replace the placeholder with the real schema
|
|
80
|
+
safeGlobalRegistrySet(id, schema);
|
|
81
|
+
strapi.log.debug(`Schema ${transformedId} successfully created and registered`);
|
|
82
|
+
return schema;
|
|
83
|
+
} catch (error) {
|
|
84
|
+
strapi.log.error(`Schema creation failed: Failed to create schema ${id}`);
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
export { safeGlobalRegistrySet, safeSchemaCreation };
|
|
90
|
+
//# sourceMappingURL=utils.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.mjs","sources":["../../../../src/core-api/routes/validation/utils.ts"],"sourcesContent":["import { transformUidToValidOpenApiName } from '@strapi/utils';\nimport type { Internal } from '@strapi/types';\nimport * as z from 'zod/v4';\n\n/**\n * Safely adds or updates a schema in Zod's global registry.\n *\n * If a schema with the given `id` already exists, it will be removed before adding the new one.\n *\n * This is useful for hot-reloading or preventing issues with cyclical dependencies.\n *\n * @param id - The unique identifier for the schema in the global registry.\n * @param schema - The Zod schema to register.\n * @example\n * ```typescript\n * safeGlobalRegistrySet(\"mySchema\", z.object({ name: z.string() }));\n * ```\n */\nexport const safeGlobalRegistrySet = (id: Internal.UID.Schema, schema: z.ZodType) => {\n try {\n const { _idmap: idMap } = z.globalRegistry;\n\n const transformedId = transformUidToValidOpenApiName(id);\n\n if (idMap.has(transformedId)) {\n // Remove existing schema to prevent conflicts\n strapi.log.debug(`Removing existing schema ${transformedId} from registry`);\n idMap.delete(transformedId);\n }\n\n // Register the new schema with the transformed ID\n strapi.log.debug(`Registering schema ${transformedId} in global registry`);\n z.globalRegistry.add(schema, { id: transformedId });\n } catch (error) {\n strapi.log.error(\n `Schema registration failed: Failed to register schema ${id} in global registry`\n );\n\n throw error;\n }\n};\n\n/**\n * Safely creates and registers a Zod schema in the global registry, particularly useful for handling cyclical data structures.\n *\n * If a schema with the given `id` already exists in the global registry, it returns the existing schema.\n *\n * Otherwise, it registers a temporary `z.any()` schema, calls the provided `callback` to create the actual schema,\n * and then replaces the temporary schema with the actual one in the registry.\n *\n * This prevents infinite loops in cases of cyclical dependencies.\n *\n * @param id - The unique identifier for the schema in the global registry.\n * @param callback - A function that returns the Zod schema to be created and registered.\n * @returns The created or retrieved Zod schema.\n * @example\n * ```typescript\n * const CategorySchema = safeSchemaCreation(\"Category\", () =>\n * z.object({\n * name: z.string(),\n * products: z.array(safeSchemaCreation(\"Product\", () =>\n * z.object({\n * name: z.string(),\n * category: z.lazy(() => CategorySchema) // Cyclical reference\n * })\n * ))\n * })\n * );\n * ```\n */\nexport const safeSchemaCreation = (id: Internal.UID.Schema, callback: () => z.ZodType) => {\n try {\n const { _idmap: idMap } = z.globalRegistry;\n\n const transformedId = transformUidToValidOpenApiName(id);\n\n // Return existing schema if already registered\n const mapItem = idMap.get(transformedId);\n if (mapItem) {\n strapi.log.debug(`Schema ${transformedId} found in registry, returning existing schema`);\n return mapItem;\n }\n\n strapi.log.warn(\n `Schema ${transformedId} not found in global registry, creating an any placeholder`\n );\n\n // Temporary any placeholder before replacing with the actual schema type\n // Used to prevent infinite loops in cyclical data structures\n safeGlobalRegistrySet(id, z.any());\n\n // Generate the actual schema using the callback\n const schema = callback();\n\n // Replace the placeholder with the real schema\n safeGlobalRegistrySet(id, schema);\n\n strapi.log.debug(`Schema ${transformedId} successfully created and registered`);\n\n return schema;\n } catch (error) {\n strapi.log.error(`Schema creation failed: Failed to create schema ${id}`);\n\n throw error;\n }\n};\n"],"names":["safeGlobalRegistrySet","id","schema","_idmap","idMap","z","globalRegistry","transformedId","transformUidToValidOpenApiName","has","strapi","log","debug","delete","add","error","safeSchemaCreation","callback","mapItem","get","warn","any"],"mappings":";;;AAIA;;;;;;;;;;;;;AAaC,IACM,MAAMA,qBAAwB,GAAA,CAACC,EAAyBC,EAAAA,MAAAA,GAAAA;IAC7D,IAAI;AACF,QAAA,MAAM,EAAEC,MAAQC,EAAAA,KAAK,EAAE,GAAGC,EAAEC,cAAc;AAE1C,QAAA,MAAMC,gBAAgBC,8BAA+BP,CAAAA,EAAAA,CAAAA;QAErD,IAAIG,KAAAA,CAAMK,GAAG,CAACF,aAAgB,CAAA,EAAA;;YAE5BG,MAAOC,CAAAA,GAAG,CAACC,KAAK,CAAC,CAAC,yBAAyB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,IAAI,CAAC,UAAU,CAAC,CAAC;CAC9C;AAiBD,eAAO,MAAM,YAAY,cACZ,MAAM,aACN,SAAS,UACZ,KAAK,MAAM,KAClB,MAwFF,CAAC"}
|
|
@@ -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 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,GAAQC,EAAAA,WAAAA,GAAAA;IACvE,OAAOC,CAAAA,CAAEC,OAAO,CAACH,GAAAA,EAAK,CAACI,KAAOC,EAAAA,GAAAA,GAAQC,0BAAgBD,GAAKJ,EAAAA,WAAAA,CAAAA,CAAAA;AAC7D,CAAA;AAEA,MAAMM,aAAgB,GAAA;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;AAEaC,MAAAA,YAAAA,GAAe,CAC1Bd,SAAAA,EACAe,SACAC,EAAAA,MAAAA,GAAAA;IAEAf,CAAEgB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,EAAAA,SAAAA,CAAAA;AACxC,SAAA;AACA4C,QAAAA,UAAAA,CAAAA,CAAWC,cAA8B,EAAA;AACvC,YAAA,OAAO7B,MAAOc,CAAAA,GAAG,CAAC,aAAA,CAAA,CAAeA,GAAG,CAAC,CAAC,EAAE9B,SAAU,CAAA,CAAC,EAAE6C,cAAAA,CAAe,CAAC,CAAA;AACvE,SAAA;AACA,QAAA,IAAIhC,WAAc,CAAA,GAAA;AAChB,YAAA,MAAMA,cAAcG,MAAOc,CAAAA,GAAG,CAAC,aAAA,CAAA,CAAeS,MAAM,CAACvC,SAAAA,CAAAA;AACrD,YAAA,OAAOF,qBAAqBe,WAAab,EAAAA,SAAAA,CAAAA;AAC3C,SAAA;AACA8C,QAAAA,UAAAA,CAAAA,CAAWC,cAA8B,EAAA;AACvC,YAAA,OAAO/B,MAAOc,CAAAA,GAAG,CAAC,aAAA,CAAA,CAAeA,GAAG,CAAC,CAAC,EAAE9B,SAAU,CAAA,CAAC,EAAE+C,cAAAA,CAAe,CAAC,CAAA;AACvE,SAAA;AACA,QAAA,IAAItC,WAAc,CAAA,GAAA;AAChB,YAAA,MAAMA,cAAcO,MAAOc,CAAAA,GAAG,CAAC,aAAA,CAAA,CAAeS,MAAM,CAACvC,SAAAA,CAAAA;AACrD,YAAA,OAAOF,qBAAqBW,WAAaT,EAAAA,SAAAA,CAAAA;AAC3C;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,GAAQC,EAAAA,WAAAA,GAAAA;IACvE,OAAOC,CAAAA,CAAEC,OAAO,CAACH,GAAAA,EAAK,CAACI,KAAOC,EAAAA,GAAAA,GAAQC,0BAAgBD,GAAKJ,EAAAA,WAAAA,CAAAA,CAAAA;AAC7D,CAAA;AAEA,MAAMM,aAAgB,GAAA;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;AAEaC,MAAAA,YAAAA,GAAe,CAC1Bd,SAAAA,EACAe,SACAC,EAAAA,MAAAA,GAAAA;IAEAf,CAAEgB,CAAAA,QAAQ,CAACF,SAAWT,EAAAA,aAAAA,CAAAA;IAEtB,IAAI;QACFY,yBAAeH,CAAAA,SAAAA,CAAAA;AACjB,KAAA,CAAE,OAAOI,CAAG,EAAA;QACV,IAAIA,CAAAA,YAAaC,eAAIC,CAAAA,eAAe,EAAE;AACpC,YAAA,MAAM,IAAIC,KAAAA,CAAM,CAAC,iCAAiC,EAAEtB,SAAU,CAAA,IAAI,EAAEmB,CAAAA,CAAEI,MAAM,CAACC,IAAI,CAAC,MAAM,CAAC,CAAA;AAC3F;AACF;AAEA,IAAA,MAAMC,SAA0B,EAAC;IACjC,OAAO;QACL,MAAMC,SAAAA,CAAAA,GAAAA;YACJ,IAAID,MAAAA,CAAOC,SAAS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M,CAACvC,SAAAA,CAAAA;AACrD,YAAA,OAAOF,qBAAqBe,WAAab,EAAAA,SAAAA,CAAAA;AAC3C,SAAA;AACA8C,QAAAA,UAAAA,CAAAA,CAAWC,cAA8B,EAAA;AACvC,YAAA,OAAO/B,MAAOc,CAAAA,GAAG,CAAC,aAAA,CAAA,CAAeA,GAAG,CAAC,CAAC,EAAE9B,SAAU,CAAA,CAAC,EAAE+C,cAAAA,CAAe,CAAC,CAAA;AACvE,SAAA;AACA,QAAA,IAAItC,WAAc,CAAA,GAAA;AAChB,YAAA,MAAMA,cAAcO,MAAOc,CAAAA,GAAG,CAAC,aAAA,CAAA,CAAeS,MAAM,CAACvC,SAAAA,CAAAA;AACrD,YAAA,OAAOF,qBAAqBW,WAAaT,EAAAA,SAAAA,CAAAA;AAC3C;AACF,KAAA;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","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 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,GAAQC,EAAAA,SAAAA,GAAAA;IACvE,OAAOC,CAAAA,CAAEC,OAAO,CAACH,GAAAA,EAAK,CAACI,KAAOC,EAAAA,GAAAA,GAAQC,gBAAgBD,GAAKJ,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AAA,CAAAA;AAC3C;AACF,KAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"index.mjs","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,GAAQC,EAAAA,SAAAA,GAAAA;IACvE,OAAOC,CAAAA,CAAEC,OAAO,CAACH,GAAAA,EAAK,CAACI,KAAOC,EAAAA,GAAAA,GAAQC,gBAAgBD,GAAKJ,EAAAA,SAAAA,CAAAA,CAAAA;AAC7D,CAAA;AAEA,MAAMM,aAAgB,GAAA;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;AAEaC,MAAAA,YAAAA,GAAe,CAC1Bd,SAAAA,EACAe,SACAC,EAAAA,MAAAA,GAAAA;IAEAf,CAAEgB,CAAAA,QAAQ,CAACF,SAAWT,EAAAA,aAAAA,CAAAA;IAEtB,IA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AA;AAC/C,YAAA,OAAOF,qBAAqBc,QAAUZ,EAAAA,SAAAA,CAAAA;AACxC,SAAA;AACA4C,QAAAA,UAAAA,CAAAA,CAAWC,cAA8B,EAAA;AACvC,YAAA,OAAO7B,MAAOc,CAAAA,GAAG,CAAC,aAAA,CAAA,CAAeA,GAAG,CAAC,CAAC,EAAE9B,SAAU,CAAA,CAAC,EAAE6C,cAAAA,CAAe,CAAC,CAAA;AACvE,SAAA;AACA,QAAA,IAAIhC,WAAc,CAAA,GAAA;AAChB,YAAA,MAAMA,cAAcG,MAAOc,CAAAA,GAAG,CAAC,aAAA,CAAA,CAAeS,MAAM,CAACvC,SAAAA,CAAAA;AACrD,YAAA,OAAOF,qBAAqBe,WAAab,EAAAA,SAAAA,CAAAA;AAC3C,SAAA;AACA8C,QAAAA,UAAAA,CAAAA,CAAWC,cAA8B,EAAA;AACvC,YAAA,OAAO/B,MAAOc,CAAAA,GAAG,CAAC,aAAA,CAAA,CAAeA,GAAG,CAAC,CAAC,EAAE9B,SAAU,CAAA,CAAC,EAAE+C,cAAAA,CAAe,CAAC,CAAA;AACvE,SAAA;AACA,QAAA,IAAItC,WAAc,CAAA,GAAA;AAChB,YAAA,MAAMA,cAAcO,MAAOc,CAAAA,GAAG,CAAC,aAAA,CAAA,CAAeS,MAAM,CAACvC,SAAAA,CAAAA;AACrD,YAAA,OAAOF,qBAAqBW,WAAaT,EAAAA,SAAAA,CAAAA;AAC3C;AACF,KAAA;AACF;;;;"}
|
package/dist/ee/index.d.ts
CHANGED
|
@@ -4,9 +4,15 @@ declare const _default: Readonly<{
|
|
|
4
4
|
checkLicense: ({ strapi }: {
|
|
5
5
|
strapi: Core.Strapi;
|
|
6
6
|
}) => Promise<void>;
|
|
7
|
+
getTrialEndDate: ({ strapi, }: {
|
|
8
|
+
strapi: Core.Strapi;
|
|
9
|
+
}) => Promise<{
|
|
10
|
+
trialEndsAt: string;
|
|
11
|
+
} | null>;
|
|
7
12
|
readonly isEE: boolean;
|
|
8
13
|
readonly seats: number | undefined;
|
|
9
14
|
readonly type: string | undefined;
|
|
15
|
+
readonly isTrial: boolean;
|
|
10
16
|
features: Readonly<{
|
|
11
17
|
list: () => {
|
|
12
18
|
[key: string]: any;
|
package/dist/ee/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/ee/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/ee/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;;;;;;;;;;;;;;;;;;;;;;;;iCAqSb,MAAM;;;AAxBnC,wBA0BG"}
|
package/dist/ee/index.js
CHANGED
|
@@ -1,20 +1,27 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var fp = require('lodash/fp');
|
|
4
|
+
var fetch = require('../utils/fetch.js');
|
|
4
5
|
var license = require('./license.js');
|
|
5
6
|
var cron = require('../utils/cron.js');
|
|
6
7
|
|
|
7
8
|
const ONE_MINUTE = 1000 * 60;
|
|
8
9
|
const ee = {
|
|
9
10
|
enabled: false,
|
|
10
|
-
licenseInfo: {
|
|
11
|
+
licenseInfo: {
|
|
12
|
+
isTrial: false
|
|
13
|
+
}
|
|
11
14
|
};
|
|
12
15
|
const disable = (message)=>{
|
|
13
16
|
// Prevent emitting ee.disable if it was already disabled
|
|
14
17
|
const shouldEmitEvent = ee.enabled !== false;
|
|
15
18
|
ee.logger?.warn(`${message} Switching to CE.`);
|
|
16
|
-
// Only keep the license key for potential re-enabling during a later check
|
|
17
|
-
ee.licenseInfo = fp.pick(
|
|
19
|
+
// Only keep the license key and isTrial for potential re-enabling during a later check
|
|
20
|
+
ee.licenseInfo = fp.pick([
|
|
21
|
+
'licenseKey',
|
|
22
|
+
'isTrial'
|
|
23
|
+
], ee.licenseInfo);
|
|
24
|
+
ee.licenseInfo.isTrial = false;
|
|
18
25
|
ee.enabled = false;
|
|
19
26
|
if (shouldEmitEvent) {
|
|
20
27
|
// Notify EE features that they should be disabled
|
|
@@ -163,6 +170,21 @@ const checkLicense = async ({ strapi: strapi1 })=>{
|
|
|
163
170
|
validateInfo();
|
|
164
171
|
}
|
|
165
172
|
};
|
|
173
|
+
const getTrialEndDate = async ({ strapi: strapi1 })=>{
|
|
174
|
+
const silentFetch = fetch.createStrapiFetch(strapi1, {
|
|
175
|
+
logs: false
|
|
176
|
+
});
|
|
177
|
+
const res = await silentFetch(`${license.LICENSE_REGISTRY_URI}/api/licenses/${ee.licenseInfo.licenseKey}/trial-countdown`, {
|
|
178
|
+
method: 'GET',
|
|
179
|
+
headers: {
|
|
180
|
+
'Content-Type': 'application/json'
|
|
181
|
+
}
|
|
182
|
+
}).catch(()=>{
|
|
183
|
+
throw new license.LicenseCheckError('Could not proceed to retrieve the trial time left for your license.', true);
|
|
184
|
+
});
|
|
185
|
+
const data = await res.json();
|
|
186
|
+
return data;
|
|
187
|
+
};
|
|
166
188
|
const list = ()=>{
|
|
167
189
|
return ee.licenseInfo.features?.map((feature)=>typeof feature === 'object' ? feature : {
|
|
168
190
|
name: feature
|
|
@@ -172,6 +194,7 @@ const get = (featureName)=>list().find((feature)=>feature.name === featureName);
|
|
|
172
194
|
var index = Object.freeze({
|
|
173
195
|
init,
|
|
174
196
|
checkLicense,
|
|
197
|
+
getTrialEndDate,
|
|
175
198
|
get isEE () {
|
|
176
199
|
return ee.enabled;
|
|
177
200
|
},
|
|
@@ -181,6 +204,9 @@ var index = Object.freeze({
|
|
|
181
204
|
get type () {
|
|
182
205
|
return ee.licenseInfo.type;
|
|
183
206
|
},
|
|
207
|
+
get isTrial () {
|
|
208
|
+
return ee.licenseInfo.isTrial;
|
|
209
|
+
},
|
|
184
210
|
features: Object.freeze({
|
|
185
211
|
list,
|
|
186
212
|
get,
|
package/dist/ee/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../src/ee/index.ts"],"sourcesContent":["import { pick, isEqual } from 'lodash/fp';\nimport type { Logger } from '@strapi/logger';\nimport type { Core } from '@strapi/types';\n\nimport { readLicense, verifyLicense, fetchLicense, LicenseCheckError } from './license';\nimport { shiftCronExpression } from '../utils/cron';\n\nconst ONE_MINUTE = 1000 * 60;\n\ninterface EE {\n enabled: boolean;\n licenseInfo: {\n licenseKey?: string;\n features?: Array<{ name: string; [key: string]: any } | string>;\n expireAt?: string;\n seats?: number;\n type?: string;\n };\n logger?: Logger;\n}\n\nconst ee: EE = {\n enabled: false,\n licenseInfo: {},\n};\n\nconst disable = (message: string) => {\n // Prevent emitting ee.disable if it was already disabled\n const shouldEmitEvent = ee.enabled !== false;\n\n ee.logger?.warn(`${message} Switching to CE.`);\n // Only keep the license key for potential re-enabling during a later check\n ee.licenseInfo = pick('licenseKey', ee.licenseInfo);\n\n ee.enabled = false;\n\n if (shouldEmitEvent) {\n // Notify EE features that they should be disabled\n strapi.eventHub.emit('ee.disable');\n }\n};\n\nconst enable = () => {\n // Prevent emitting ee.enable if it was already enabled\n const shouldEmitEvent = ee.enabled !== true;\n\n ee.enabled = true;\n\n if (shouldEmitEvent) {\n // Notify EE features that they should be disabled\n strapi.eventHub.emit('ee.enable');\n }\n};\n\nlet initialized = false;\n\n/**\n * Optimistically enable EE if the format of the license is valid, only run once.\n */\nconst init = (licenseDir: string, logger?: Logger) => {\n if (initialized) {\n return;\n }\n\n initialized = true;\n ee.logger = logger;\n\n if (process.env.STRAPI_DISABLE_EE?.toLowerCase() === 'true') {\n return;\n }\n\n try {\n const license = process.env.STRAPI_LICENSE || readLicense(licenseDir);\n\n if (license) {\n ee.licenseInfo = verifyLicense(license);\n enable();\n }\n } catch (error) {\n if (error instanceof Error) {\n disable(error.message);\n } else {\n disable('Invalid license.');\n }\n }\n};\n\n/**\n * Contact the license registry to update the license to its latest state.\n *\n * Store the result in database to avoid unecessary requests, and will fallback to that in case of a network failure.\n */\nconst onlineUpdate = async ({ strapi }: { strapi: Core.Strapi }) => {\n const { get, commit, rollback } = (await strapi.db?.transaction()) as any;\n const transaction = get();\n\n try {\n const storedInfo = await strapi.db\n ?.queryBuilder('strapi::core-store')\n .where({ key: 'ee_information' })\n .select('value')\n .first()\n .transacting(transaction)\n .forUpdate()\n .execute()\n .then((result: any) => (result ? JSON.parse(result.value) : result));\n\n const shouldContactRegistry = (storedInfo?.lastCheckAt ?? 0) < Date.now() - ONE_MINUTE;\n const result: {\n license?: string | null;\n error?: string;\n lastCheckAt?: number;\n } = { lastCheckAt: Date.now() };\n\n const fallback = (error: Error) => {\n if (error instanceof LicenseCheckError && error.shouldFallback && storedInfo?.license) {\n ee.logger?.warn(\n `${error.message} The last stored one will be used as a potential fallback.`\n );\n return storedInfo.license;\n }\n\n result.error = error.message;\n disable(error.message);\n };\n\n if (!ee?.licenseInfo?.licenseKey) {\n throw new Error('Missing license key.');\n }\n\n const license = shouldContactRegistry\n ? await fetchLicense({ strapi }, ee.licenseInfo.licenseKey, strapi.config.get('uuid')).catch(\n fallback\n )\n : storedInfo.license;\n\n if (license) {\n try {\n // Verify license and check if its info changed\n const newLicenseInfo = verifyLicense(license);\n const licenseInfoChanged =\n !isEqual(newLicenseInfo.features, ee.licenseInfo.features) ||\n newLicenseInfo.seats !== ee.licenseInfo.seats ||\n newLicenseInfo.type !== ee.licenseInfo.type;\n\n // Store the new license info\n ee.licenseInfo = newLicenseInfo;\n const wasEnabled = ee.enabled;\n validateInfo();\n\n // Notify EE features\n if (licenseInfoChanged && wasEnabled) {\n strapi.eventHub.emit('ee.update');\n }\n } catch (error) {\n if (error instanceof Error) {\n disable(error.message);\n } else {\n disable('Invalid license.');\n }\n }\n } else if (!shouldContactRegistry) {\n disable(storedInfo.error);\n }\n\n if (shouldContactRegistry) {\n result.license = license ?? null;\n const query = strapi.db.queryBuilder('strapi::core-store').transacting(transaction);\n\n if (!storedInfo) {\n query.insert({ key: 'ee_information', value: JSON.stringify(result) });\n } else {\n query.update({ value: JSON.stringify(result) }).where({ key: 'ee_information' });\n }\n\n await query.execute();\n }\n\n await commit();\n } catch (error) {\n // Example of errors: SQLite does not support FOR UPDATE\n await rollback();\n }\n};\n\nconst validateInfo = () => {\n if (typeof ee.licenseInfo.expireAt === 'undefined') {\n throw new Error('Missing license key.');\n }\n\n const expirationTime = new Date(ee.licenseInfo.expireAt).getTime();\n\n if (expirationTime < new Date().getTime()) {\n return disable('License expired.');\n }\n\n enable();\n};\n\nconst checkLicense = async ({ strapi }: { strapi: Core.Strapi }) => {\n const shouldStayOffline =\n ee.licenseInfo.type === 'gold' &&\n // This env variable support is temporarily used to ease the migration between online vs offline\n process.env.STRAPI_DISABLE_LICENSE_PING?.toLowerCase() === 'true';\n\n if (!shouldStayOffline) {\n await onlineUpdate({ strapi });\n\n strapi.cron.add({\n onlineUpdate: {\n task: () => onlineUpdate({ strapi }),\n options: shiftCronExpression('0 0 */12 * * *'),\n },\n });\n } else {\n if (!ee.licenseInfo.expireAt) {\n return disable('Your license does not have offline support.');\n }\n\n validateInfo();\n }\n};\n\nconst list = () => {\n return (\n ee.licenseInfo.features?.map((feature) =>\n typeof feature === 'object' ? feature : { name: feature }\n ) || []\n );\n};\n\nconst get = (featureName: string) => list().find((feature) => feature.name === featureName);\n\nexport default Object.freeze({\n init,\n checkLicense,\n\n get isEE() {\n return ee.enabled;\n },\n\n get seats() {\n return ee.licenseInfo.seats;\n },\n\n get type() {\n return ee.licenseInfo.type;\n },\n\n features: Object.freeze({\n list,\n get,\n isEnabled: (featureName: string) => get(featureName) !== undefined,\n }),\n});\n"],"names":["ONE_MINUTE","ee","enabled","licenseInfo","disable","message","shouldEmitEvent","logger","warn","pick","strapi","eventHub","emit","enable","initialized","init","licenseDir","process","env","STRAPI_DISABLE_EE","toLowerCase","license","STRAPI_LICENSE","readLicense","verifyLicense","error","Error","onlineUpdate","get","commit","rollback","db","transaction","storedInfo","queryBuilder","where","key","select","first","transacting","forUpdate","execute","then","result","JSON","parse","value","shouldContactRegistry","lastCheckAt","Date","now","fallback","LicenseCheckError","shouldFallback","licenseKey","fetchLicense","config","catch","newLicenseInfo","licenseInfoChanged","isEqual","features","seats","type","wasEnabled","validateInfo","query","insert","stringify","update","expireAt","expirationTime","getTime","checkLicense","shouldStayOffline","STRAPI_DISABLE_LICENSE_PING","cron","add","task","options","shiftCronExpression","list","map","feature","name","featureName","find","Object","freeze","isEE","isEnabled","undefined"],"mappings":";;;;;;AAOA,MAAMA,aAAa,IAAO,GAAA,EAAA;AAc1B,MAAMC,EAAS,GAAA;IACbC,OAAS,EAAA,KAAA;AACTC,IAAAA,WAAAA,EAAa;AACf,CAAA;AAEA,MAAMC,UAAU,CAACC,OAAAA,GAAAA;;IAEf,MAAMC,eAAAA,GAAkBL,EAAGC,CAAAA,OAAO,KAAK,KAAA;AAEvCD,IAAAA,EAAAA,CAAGM,MAAM,EAAEC,IAAAA,CAAK,CAAC,EAAEH,OAAAA,CAAQ,iBAAiB,CAAC,CAAA;;AAE7CJ,IAAAA,EAAAA,CAAGE,WAAW,GAAGM,OAAK,CAAA,YAAA,EAAcR,GAAGE,WAAW,CAAA;AAElDF,IAAAA,EAAAA,CAAGC,OAAO,GAAG,KAAA;AAEb,IAAA,IAAII,eAAiB,EAAA;;QAEnBI,MAAOC,CAAAA,QAAQ,CAACC,IAAI,CAAC,YAAA,CAAA;AACvB;AACF,CAAA;AAEA,MAAMC,MAAS,GAAA,IAAA;;IAEb,MAAMP,eAAAA,GAAkBL,EAAGC,CAAAA,OAAO,KAAK,IAAA;AAEvCD,IAAAA,EAAAA,CAAGC,OAAO,GAAG,IAAA;AAEb,IAAA,IAAII,eAAiB,EAAA;;QAEnBI,MAAOC,CAAAA,QAAQ,CAACC,IAAI,CAAC,WAAA,CAAA;AACvB;AACF,CAAA;AAEA,IAAIE,WAAc,GAAA,KAAA;AAElB;;IAGA,MAAMC,IAAO,GAAA,CAAC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
|
+
{"version":3,"file":"index.js","sources":["../../src/ee/index.ts"],"sourcesContent":["import { pick, isEqual } from 'lodash/fp';\nimport type { Logger } from '@strapi/logger';\nimport type { Core } from '@strapi/types';\nimport { createStrapiFetch } from '../utils/fetch';\nimport {\n readLicense,\n verifyLicense,\n fetchLicense,\n LicenseCheckError,\n LICENSE_REGISTRY_URI,\n} from './license';\nimport { shiftCronExpression } from '../utils/cron';\n\nconst ONE_MINUTE = 1000 * 60;\n\ninterface EE {\n enabled: boolean;\n licenseInfo: {\n licenseKey?: string;\n features?: Array<{ name: string; [key: string]: any } | string>;\n expireAt?: string;\n seats?: number;\n type?: string;\n isTrial: boolean;\n };\n logger?: Logger;\n}\n\nconst ee: EE = {\n enabled: false,\n licenseInfo: {\n isTrial: false,\n },\n};\n\nconst disable = (message: string) => {\n // Prevent emitting ee.disable if it was already disabled\n const shouldEmitEvent = ee.enabled !== false;\n\n ee.logger?.warn(`${message} Switching to CE.`);\n // Only keep the license key and isTrial for potential re-enabling during a later check\n ee.licenseInfo = pick(['licenseKey', 'isTrial'], ee.licenseInfo);\n\n ee.licenseInfo.isTrial = false;\n\n ee.enabled = false;\n\n if (shouldEmitEvent) {\n // Notify EE features that they should be disabled\n strapi.eventHub.emit('ee.disable');\n }\n};\n\nconst enable = () => {\n // Prevent emitting ee.enable if it was already enabled\n const shouldEmitEvent = ee.enabled !== true;\n\n ee.enabled = true;\n\n if (shouldEmitEvent) {\n // Notify EE features that they should be disabled\n strapi.eventHub.emit('ee.enable');\n }\n};\n\nlet initialized = false;\n\n/**\n * Optimistically enable EE if the format of the license is valid, only run once.\n */\nconst init = (licenseDir: string, logger?: Logger) => {\n if (initialized) {\n return;\n }\n\n initialized = true;\n ee.logger = logger;\n\n if (process.env.STRAPI_DISABLE_EE?.toLowerCase() === 'true') {\n return;\n }\n\n try {\n const license = process.env.STRAPI_LICENSE || readLicense(licenseDir);\n\n if (license) {\n ee.licenseInfo = verifyLicense(license);\n enable();\n }\n } catch (error) {\n if (error instanceof Error) {\n disable(error.message);\n } else {\n disable('Invalid license.');\n }\n }\n};\n\n/**\n * Contact the license registry to update the license to its latest state.\n *\n * Store the result in database to avoid unecessary requests, and will fallback to that in case of a network failure.\n */\nconst onlineUpdate = async ({ strapi }: { strapi: Core.Strapi }) => {\n const { get, commit, rollback } = (await strapi.db?.transaction()) as any;\n const transaction = get();\n\n try {\n const storedInfo = await strapi.db\n ?.queryBuilder('strapi::core-store')\n .where({ key: 'ee_information' })\n .select('value')\n .first()\n .transacting(transaction)\n .forUpdate()\n .execute()\n .then((result: any) => (result ? JSON.parse(result.value) : result));\n\n const shouldContactRegistry = (storedInfo?.lastCheckAt ?? 0) < Date.now() - ONE_MINUTE;\n const result: {\n license?: string | null;\n error?: string;\n lastCheckAt?: number;\n } = { lastCheckAt: Date.now() };\n\n const fallback = (error: Error) => {\n if (error instanceof LicenseCheckError && error.shouldFallback && storedInfo?.license) {\n ee.logger?.warn(\n `${error.message} The last stored one will be used as a potential fallback.`\n );\n return storedInfo.license;\n }\n\n result.error = error.message;\n disable(error.message);\n };\n\n if (!ee?.licenseInfo?.licenseKey) {\n throw new Error('Missing license key.');\n }\n\n const license = shouldContactRegistry\n ? await fetchLicense({ strapi }, ee.licenseInfo.licenseKey, strapi.config.get('uuid')).catch(\n fallback\n )\n : storedInfo.license;\n\n if (license) {\n try {\n // Verify license and check if its info changed\n const newLicenseInfo = verifyLicense(license);\n const licenseInfoChanged =\n !isEqual(newLicenseInfo.features, ee.licenseInfo.features) ||\n newLicenseInfo.seats !== ee.licenseInfo.seats ||\n newLicenseInfo.type !== ee.licenseInfo.type;\n\n // Store the new license info\n ee.licenseInfo = newLicenseInfo;\n const wasEnabled = ee.enabled;\n validateInfo();\n\n // Notify EE features\n if (licenseInfoChanged && wasEnabled) {\n strapi.eventHub.emit('ee.update');\n }\n } catch (error) {\n if (error instanceof Error) {\n disable(error.message);\n } else {\n disable('Invalid license.');\n }\n }\n } else if (!shouldContactRegistry) {\n disable(storedInfo.error);\n }\n\n if (shouldContactRegistry) {\n result.license = license ?? null;\n const query = strapi.db.queryBuilder('strapi::core-store').transacting(transaction);\n\n if (!storedInfo) {\n query.insert({ key: 'ee_information', value: JSON.stringify(result) });\n } else {\n query.update({ value: JSON.stringify(result) }).where({ key: 'ee_information' });\n }\n\n await query.execute();\n }\n\n await commit();\n } catch (error) {\n // Example of errors: SQLite does not support FOR UPDATE\n await rollback();\n }\n};\n\nconst validateInfo = () => {\n if (typeof ee.licenseInfo.expireAt === 'undefined') {\n throw new Error('Missing license key.');\n }\n\n const expirationTime = new Date(ee.licenseInfo.expireAt).getTime();\n\n if (expirationTime < new Date().getTime()) {\n return disable('License expired.');\n }\n\n enable();\n};\n\nconst checkLicense = async ({ strapi }: { strapi: Core.Strapi }) => {\n const shouldStayOffline =\n ee.licenseInfo.type === 'gold' &&\n // This env variable support is temporarily used to ease the migration between online vs offline\n process.env.STRAPI_DISABLE_LICENSE_PING?.toLowerCase() === 'true';\n\n if (!shouldStayOffline) {\n await onlineUpdate({ strapi });\n\n strapi.cron.add({\n onlineUpdate: {\n task: () => onlineUpdate({ strapi }),\n options: shiftCronExpression('0 0 */12 * * *'),\n },\n });\n } else {\n if (!ee.licenseInfo.expireAt) {\n return disable('Your license does not have offline support.');\n }\n\n validateInfo();\n }\n};\n\nconst getTrialEndDate = async ({\n strapi,\n}: {\n strapi: Core.Strapi;\n}): Promise<{ trialEndsAt: string } | null> => {\n const silentFetch = createStrapiFetch(strapi, {\n logs: false,\n });\n\n const res = await silentFetch(\n `${LICENSE_REGISTRY_URI}/api/licenses/${ee.licenseInfo.licenseKey}/trial-countdown`,\n {\n method: 'GET',\n headers: { 'Content-Type': 'application/json' },\n }\n ).catch(() => {\n throw new LicenseCheckError(\n 'Could not proceed to retrieve the trial time left for your license.',\n true\n );\n });\n\n const data = await res.json();\n\n return data;\n};\n\nconst list = () => {\n return (\n ee.licenseInfo.features?.map((feature) =>\n typeof feature === 'object' ? feature : { name: feature }\n ) || []\n );\n};\n\nconst get = (featureName: string) => list().find((feature) => feature.name === featureName);\n\nexport default Object.freeze({\n init,\n checkLicense,\n getTrialEndDate,\n\n get isEE() {\n return ee.enabled;\n },\n\n get seats() {\n return ee.licenseInfo.seats;\n },\n\n get type() {\n return ee.licenseInfo.type;\n },\n\n get isTrial() {\n return ee.licenseInfo.isTrial;\n },\n\n features: Object.freeze({\n list,\n get,\n isEnabled: (featureName: string) => get(featureName) !== undefined,\n }),\n});\n"],"names":["ONE_MINUTE","ee","enabled","licenseInfo","isTrial","disable","message","shouldEmitEvent","logger","warn","pick","strapi","eventHub","emit","enable","initialized","init","licenseDir","process","env","STRAPI_DISABLE_EE","toLowerCase","license","STRAPI_LICENSE","readLicense","verifyLicense","error","Error","onlineUpdate","get","commit","rollback","db","transaction","storedInfo","queryBuilder","where","key","select","first","transacting","forUpdate","execute","then","result","JSON","parse","value","shouldContactRegistry","lastCheckAt","Date","now","fallback","LicenseCheckError","shouldFallback","licenseKey","fetchLicense","config","catch","newLicenseInfo","licenseInfoChanged","isEqual","features","seats","type","wasEnabled","validateInfo","query","insert","stringify","update","expireAt","expirationTime","getTime","checkLicense","shouldStayOffline","STRAPI_DISABLE_LICENSE_PING","cron","add","task","options","shiftCronExpression","getTrialEndDate","silentFetch","createStrapiFetch","logs","res","LICENSE_REGISTRY_URI","method","headers","data","json","list","map","feature","name","featureName","find","Object","freeze","isEE","isEnabled","undefined"],"mappings":";;;;;;;AAaA,MAAMA,aAAa,IAAO,GAAA,EAAA;AAe1B,MAAMC,EAAS,GAAA;IACbC,OAAS,EAAA,KAAA;IACTC,WAAa,EAAA;QACXC,OAAS,EAAA;AACX;AACF,CAAA;AAEA,MAAMC,UAAU,CAACC,OAAAA,GAAAA;;IAEf,MAAMC,eAAAA,GAAkBN,EAAGC,CAAAA,OAAO,KAAK,KAAA;AAEvCD,IAAAA,EAAAA,CAAGO,MAAM,EAAEC,IAAAA,CAAK,CAAC,EAAEH,OAAAA,CAAQ,iBAAiB,CAAC,C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AA,GAAAA;QACAwE,SAAW,EAAA,CAACL,WAAwBnE,GAAAA,GAAAA,CAAImE,WAAiBM,CAAAA,KAAAA;AAC3D,KAAA;AACF,CAAG,CAAA;;;;"}
|
package/dist/ee/index.mjs
CHANGED
|
@@ -1,18 +1,25 @@
|
|
|
1
1
|
import { pick, isEqual } from 'lodash/fp';
|
|
2
|
-
import {
|
|
2
|
+
import { createStrapiFetch } from '../utils/fetch.mjs';
|
|
3
|
+
import { readLicense, verifyLicense, LICENSE_REGISTRY_URI, LicenseCheckError, fetchLicense } from './license.mjs';
|
|
3
4
|
import { shiftCronExpression } from '../utils/cron.mjs';
|
|
4
5
|
|
|
5
6
|
const ONE_MINUTE = 1000 * 60;
|
|
6
7
|
const ee = {
|
|
7
8
|
enabled: false,
|
|
8
|
-
licenseInfo: {
|
|
9
|
+
licenseInfo: {
|
|
10
|
+
isTrial: false
|
|
11
|
+
}
|
|
9
12
|
};
|
|
10
13
|
const disable = (message)=>{
|
|
11
14
|
// Prevent emitting ee.disable if it was already disabled
|
|
12
15
|
const shouldEmitEvent = ee.enabled !== false;
|
|
13
16
|
ee.logger?.warn(`${message} Switching to CE.`);
|
|
14
|
-
// Only keep the license key for potential re-enabling during a later check
|
|
15
|
-
ee.licenseInfo = pick(
|
|
17
|
+
// Only keep the license key and isTrial for potential re-enabling during a later check
|
|
18
|
+
ee.licenseInfo = pick([
|
|
19
|
+
'licenseKey',
|
|
20
|
+
'isTrial'
|
|
21
|
+
], ee.licenseInfo);
|
|
22
|
+
ee.licenseInfo.isTrial = false;
|
|
16
23
|
ee.enabled = false;
|
|
17
24
|
if (shouldEmitEvent) {
|
|
18
25
|
// Notify EE features that they should be disabled
|
|
@@ -161,6 +168,21 @@ const checkLicense = async ({ strapi: strapi1 })=>{
|
|
|
161
168
|
validateInfo();
|
|
162
169
|
}
|
|
163
170
|
};
|
|
171
|
+
const getTrialEndDate = async ({ strapi: strapi1 })=>{
|
|
172
|
+
const silentFetch = createStrapiFetch(strapi1, {
|
|
173
|
+
logs: false
|
|
174
|
+
});
|
|
175
|
+
const res = await silentFetch(`${LICENSE_REGISTRY_URI}/api/licenses/${ee.licenseInfo.licenseKey}/trial-countdown`, {
|
|
176
|
+
method: 'GET',
|
|
177
|
+
headers: {
|
|
178
|
+
'Content-Type': 'application/json'
|
|
179
|
+
}
|
|
180
|
+
}).catch(()=>{
|
|
181
|
+
throw new LicenseCheckError('Could not proceed to retrieve the trial time left for your license.', true);
|
|
182
|
+
});
|
|
183
|
+
const data = await res.json();
|
|
184
|
+
return data;
|
|
185
|
+
};
|
|
164
186
|
const list = ()=>{
|
|
165
187
|
return ee.licenseInfo.features?.map((feature)=>typeof feature === 'object' ? feature : {
|
|
166
188
|
name: feature
|
|
@@ -170,6 +192,7 @@ const get = (featureName)=>list().find((feature)=>feature.name === featureName);
|
|
|
170
192
|
var index = Object.freeze({
|
|
171
193
|
init,
|
|
172
194
|
checkLicense,
|
|
195
|
+
getTrialEndDate,
|
|
173
196
|
get isEE () {
|
|
174
197
|
return ee.enabled;
|
|
175
198
|
},
|
|
@@ -179,6 +202,9 @@ var index = Object.freeze({
|
|
|
179
202
|
get type () {
|
|
180
203
|
return ee.licenseInfo.type;
|
|
181
204
|
},
|
|
205
|
+
get isTrial () {
|
|
206
|
+
return ee.licenseInfo.isTrial;
|
|
207
|
+
},
|
|
182
208
|
features: Object.freeze({
|
|
183
209
|
list,
|
|
184
210
|
get,
|