@strapi/core 5.58.0 → 5.60.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.
Files changed (158) hide show
  1. package/dist/Strapi.d.ts.map +1 -1
  2. package/dist/Strapi.js +1 -0
  3. package/dist/Strapi.js.map +1 -1
  4. package/dist/Strapi.mjs +1 -0
  5. package/dist/Strapi.mjs.map +1 -1
  6. package/dist/core-api/routes/index.js +10 -45
  7. package/dist/core-api/routes/index.js.map +1 -1
  8. package/dist/core-api/routes/index.mjs +10 -25
  9. package/dist/core-api/routes/index.mjs.map +1 -1
  10. package/dist/core-api/routes/response.d.ts +28 -0
  11. package/dist/core-api/routes/response.d.ts.map +1 -0
  12. package/dist/core-api/routes/response.js +63 -0
  13. package/dist/core-api/routes/response.js.map +1 -0
  14. package/dist/core-api/routes/response.mjs +40 -0
  15. package/dist/core-api/routes/response.mjs.map +1 -0
  16. package/dist/ee/entitlements.d.ts.map +1 -1
  17. package/dist/ee/entitlements.js.map +1 -1
  18. package/dist/ee/entitlements.mjs.map +1 -1
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +1 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/index.mjs +1 -1
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/loaders/apis.d.ts.map +1 -1
  25. package/dist/loaders/apis.js.map +1 -1
  26. package/dist/loaders/apis.mjs.map +1 -1
  27. package/dist/loaders/plugins/get-enabled-plugins.js +2 -2
  28. package/dist/loaders/plugins/get-enabled-plugins.js.map +1 -1
  29. package/dist/loaders/plugins/get-enabled-plugins.mjs +2 -2
  30. package/dist/loaders/plugins/get-enabled-plugins.mjs.map +1 -1
  31. package/dist/middlewares/cors.d.ts.map +1 -1
  32. package/dist/middlewares/cors.js.map +1 -1
  33. package/dist/middlewares/cors.mjs.map +1 -1
  34. package/dist/migrations/database/5.0.0-discard-drafts.js +1 -1
  35. package/dist/migrations/database/5.0.0-discard-drafts.js.map +1 -1
  36. package/dist/migrations/database/5.0.0-discard-drafts.mjs +1 -1
  37. package/dist/migrations/database/5.0.0-discard-drafts.mjs.map +1 -1
  38. package/dist/migrations/first-published-at.js +1 -1
  39. package/dist/migrations/first-published-at.js.map +1 -1
  40. package/dist/migrations/first-published-at.mjs +1 -1
  41. package/dist/migrations/first-published-at.mjs.map +1 -1
  42. package/dist/package.json.js +15 -14
  43. package/dist/package.json.js.map +1 -1
  44. package/dist/package.json.mjs +15 -14
  45. package/dist/package.json.mjs.map +1 -1
  46. package/dist/providers/admin.d.ts.map +1 -1
  47. package/dist/providers/admin.js +8 -0
  48. package/dist/providers/admin.js.map +1 -1
  49. package/dist/providers/admin.mjs +8 -0
  50. package/dist/providers/admin.mjs.map +1 -1
  51. package/dist/registries/controllers.d.ts.map +1 -1
  52. package/dist/registries/controllers.js.map +1 -1
  53. package/dist/registries/controllers.mjs.map +1 -1
  54. package/dist/services/config.js +1 -1
  55. package/dist/services/config.js.map +1 -1
  56. package/dist/services/config.mjs +2 -2
  57. package/dist/services/config.mjs.map +1 -1
  58. package/dist/services/content-source-maps.js +6 -6
  59. package/dist/services/content-source-maps.js.map +1 -1
  60. package/dist/services/content-source-maps.mjs +6 -6
  61. package/dist/services/content-source-maps.mjs.map +1 -1
  62. package/dist/services/document-service/components.d.ts +27 -12
  63. package/dist/services/document-service/components.d.ts.map +1 -1
  64. package/dist/services/document-service/components.js +530 -86
  65. package/dist/services/document-service/components.js.map +1 -1
  66. package/dist/services/document-service/components.mjs +532 -89
  67. package/dist/services/document-service/components.mjs.map +1 -1
  68. package/dist/services/document-service/events.d.ts.map +1 -1
  69. package/dist/services/document-service/events.js +11 -2
  70. package/dist/services/document-service/events.js.map +1 -1
  71. package/dist/services/document-service/events.mjs +11 -2
  72. package/dist/services/document-service/events.mjs.map +1 -1
  73. package/dist/services/document-service/middlewares/middleware-manager.d.ts +1 -1
  74. package/dist/services/document-service/middlewares/middleware-manager.d.ts.map +1 -1
  75. package/dist/services/document-service/middlewares/middleware-manager.js +6 -1
  76. package/dist/services/document-service/middlewares/middleware-manager.js.map +1 -1
  77. package/dist/services/document-service/middlewares/middleware-manager.mjs +6 -1
  78. package/dist/services/document-service/middlewares/middleware-manager.mjs.map +1 -1
  79. package/dist/services/document-service/repository.d.ts.map +1 -1
  80. package/dist/services/document-service/repository.js +26 -7
  81. package/dist/services/document-service/repository.js.map +1 -1
  82. package/dist/services/document-service/repository.mjs +27 -8
  83. package/dist/services/document-service/repository.mjs.map +1 -1
  84. package/dist/services/document-service/transform/data.d.ts.map +1 -1
  85. package/dist/services/document-service/transform/data.js.map +1 -1
  86. package/dist/services/document-service/transform/data.mjs.map +1 -1
  87. package/dist/services/document-service/transform/relations/transform/default-locale.d.ts +4 -1
  88. package/dist/services/document-service/transform/relations/transform/default-locale.d.ts.map +1 -1
  89. package/dist/services/document-service/transform/relations/transform/default-locale.js +12 -9
  90. package/dist/services/document-service/transform/relations/transform/default-locale.js.map +1 -1
  91. package/dist/services/document-service/transform/relations/transform/default-locale.mjs +12 -10
  92. package/dist/services/document-service/transform/relations/transform/default-locale.mjs.map +1 -1
  93. package/dist/services/document-service/utils/clone-relations.d.ts +21 -4
  94. package/dist/services/document-service/utils/clone-relations.d.ts.map +1 -1
  95. package/dist/services/document-service/utils/clone-relations.js +619 -34
  96. package/dist/services/document-service/utils/clone-relations.js.map +1 -1
  97. package/dist/services/document-service/utils/clone-relations.mjs +619 -36
  98. package/dist/services/document-service/utils/clone-relations.mjs.map +1 -1
  99. package/dist/services/document-service/utils/unidirectional-relations.d.ts +4 -2
  100. package/dist/services/document-service/utils/unidirectional-relations.d.ts.map +1 -1
  101. package/dist/services/document-service/utils/unidirectional-relations.js +1 -10
  102. package/dist/services/document-service/utils/unidirectional-relations.js.map +1 -1
  103. package/dist/services/document-service/utils/unidirectional-relations.mjs +1 -10
  104. package/dist/services/document-service/utils/unidirectional-relations.mjs.map +1 -1
  105. package/dist/services/entity-validator/index.d.ts.map +1 -1
  106. package/dist/services/entity-validator/index.js +6 -2
  107. package/dist/services/entity-validator/index.js.map +1 -1
  108. package/dist/services/entity-validator/index.mjs +7 -3
  109. package/dist/services/entity-validator/index.mjs.map +1 -1
  110. package/dist/services/event-hub.d.ts +1 -0
  111. package/dist/services/event-hub.d.ts.map +1 -1
  112. package/dist/services/event-hub.js +30 -5
  113. package/dist/services/event-hub.js.map +1 -1
  114. package/dist/services/event-hub.mjs +30 -5
  115. package/dist/services/event-hub.mjs.map +1 -1
  116. package/dist/services/mcp/handlers/handlePost.d.ts.map +1 -1
  117. package/dist/services/mcp/handlers/handlePost.js +4 -2
  118. package/dist/services/mcp/handlers/handlePost.js.map +1 -1
  119. package/dist/services/mcp/handlers/handlePost.mjs +4 -2
  120. package/dist/services/mcp/handlers/handlePost.mjs.map +1 -1
  121. package/dist/services/mcp/internal/McpServerFactory.d.ts +4 -1
  122. package/dist/services/mcp/internal/McpServerFactory.d.ts.map +1 -1
  123. package/dist/services/mcp/internal/McpServerFactory.js +8 -2
  124. package/dist/services/mcp/internal/McpServerFactory.js.map +1 -1
  125. package/dist/services/mcp/internal/McpServerFactory.mjs +9 -3
  126. package/dist/services/mcp/internal/McpServerFactory.mjs.map +1 -1
  127. package/dist/services/mcp/internal/resolveToolSchemaScope.d.ts +16 -0
  128. package/dist/services/mcp/internal/resolveToolSchemaScope.d.ts.map +1 -0
  129. package/dist/services/mcp/internal/resolveToolSchemaScope.js +40 -0
  130. package/dist/services/mcp/internal/resolveToolSchemaScope.js.map +1 -0
  131. package/dist/services/mcp/internal/resolveToolSchemaScope.mjs +38 -0
  132. package/dist/services/mcp/internal/resolveToolSchemaScope.mjs.map +1 -0
  133. package/dist/services/mcp/tool-registry.d.ts +5 -0
  134. package/dist/services/mcp/tool-registry.d.ts.map +1 -1
  135. package/dist/services/mcp/tool-registry.js +30 -1
  136. package/dist/services/mcp/tool-registry.js.map +1 -1
  137. package/dist/services/mcp/tool-registry.mjs +30 -1
  138. package/dist/services/mcp/tool-registry.mjs.map +1 -1
  139. package/dist/services/webhook-runner.d.ts.map +1 -1
  140. package/dist/services/webhook-runner.js +23 -3
  141. package/dist/services/webhook-runner.js.map +1 -1
  142. package/dist/services/webhook-runner.mjs +23 -3
  143. package/dist/services/webhook-runner.mjs.map +1 -1
  144. package/dist/services/webhook-store.d.ts.map +1 -1
  145. package/dist/services/webhook-store.js +23 -4
  146. package/dist/services/webhook-store.js.map +1 -1
  147. package/dist/services/webhook-store.mjs +23 -4
  148. package/dist/services/webhook-store.mjs.map +1 -1
  149. package/dist/utils/fetch.d.ts.map +1 -1
  150. package/dist/utils/fetch.js +44 -8
  151. package/dist/utils/fetch.js.map +1 -1
  152. package/dist/utils/fetch.mjs +37 -8
  153. package/dist/utils/fetch.mjs.map +1 -1
  154. package/dist/utils/transform-content-types-to-models.js +5 -5
  155. package/dist/utils/transform-content-types-to-models.js.map +1 -1
  156. package/dist/utils/transform-content-types-to-models.mjs +5 -5
  157. package/dist/utils/transform-content-types-to-models.mjs.map +1 -1
  158. package/package.json +15 -14
@@ -2,6 +2,7 @@
2
2
 
3
3
  var _ = require('lodash');
4
4
  var strapiUtils = require('@strapi/utils');
5
+ var database = require('@strapi/database');
5
6
  var transformContentTypesToModels = require('../../utils/transform-content-types-to-models.js');
6
7
 
7
8
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -98,14 +99,26 @@ const getComponents = async (uid, entity)=>{
98
99
  if (attribute.type === 'component') {
99
100
  const { component: componentUID, repeatable = false } = attribute;
100
101
  const componentValue = data[attributeName];
101
- await deleteOldComponents(uid, componentUID, entityToUpdate, attributeName, componentValue);
102
+ const previousValue = await deleteOldComponents(uid, componentUID, entityToUpdate, attributeName, componentValue);
103
+ const previousComponents = ___default.default.castArray(previousValue ?? []).filter((component)=>!_.isNil(component));
104
+ const previousById = new Map(previousComponents.map((component)=>[
105
+ pickStringifiedId(component),
106
+ component
107
+ ]));
108
+ const getPrevious = (value)=>value && _.has(value, 'id') && !_.isNil(value.id) ? previousById.get(pickStringifiedId(value)) : undefined;
102
109
  if (repeatable === true) {
103
110
  if (!Array.isArray(componentValue)) {
104
111
  throw new Error('Expected an array to create repeatable component');
105
112
  }
106
113
  // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1
107
- const components = await strapiUtils.async.map(componentValue, (value)=>updateOrCreateComponent(componentUID, value));
108
- componentBody[attributeName] = components.filter(___default.default.negate(___default.default.isNil)).map(({ id })=>{
114
+ const results = await strapiUtils.async.map(componentValue, (value)=>updateOrCreateComponent(componentUID, value, getPrevious(value)));
115
+ const components = results.filter((result)=>!_.isNil(result));
116
+ // The join rows are already right when no component changed and the list kept its order
117
+ const sameList = _.isEqual(components.map(pickStringifiedId), previousComponents.map((component)=>pickStringifiedId(component)));
118
+ if (sameList && components.every((component)=>!component.changed)) {
119
+ continue;
120
+ }
121
+ componentBody[attributeName] = components.map(({ id })=>{
109
122
  return {
110
123
  id,
111
124
  __pivot: {
@@ -115,27 +128,50 @@ const getComponents = async (uid, entity)=>{
115
128
  };
116
129
  });
117
130
  } else {
118
- const component = await updateOrCreateComponent(componentUID, componentValue);
119
- componentBody[attributeName] = component && {
131
+ const component = await updateOrCreateComponent(componentUID, componentValue, getPrevious(componentValue));
132
+ const previousId = previousComponents[0] ? pickStringifiedId(previousComponents[0]) : null;
133
+ const currentId = component ? pickStringifiedId(component) : null;
134
+ if (previousId === currentId && (!component || !component.changed)) {
135
+ continue;
136
+ }
137
+ componentBody[attributeName] = component ? {
120
138
  id: component.id,
121
139
  __pivot: {
122
140
  field: attributeName,
123
141
  component_type: componentUID
124
142
  }
125
- };
143
+ } : null;
126
144
  }
127
145
  } else if (attribute.type === 'dynamiczone') {
128
146
  const dynamiczoneValues = data[attributeName];
129
- await deleteOldDZComponents(uid, entityToUpdate, attributeName, dynamiczoneValues);
147
+ const previousValue = await deleteOldDZComponents(uid, entityToUpdate, attributeName, dynamiczoneValues);
130
148
  if (!Array.isArray(dynamiczoneValues)) {
131
149
  throw new Error('Expected an array to create repeatable component');
132
150
  }
151
+ const toKey = (value)=>`${value.__component}:${pickStringifiedId(value)}`;
152
+ const previousComponents = ___default.default.castArray(previousValue ?? []).filter((component)=>!_.isNil(component));
153
+ const previousByKey = new Map(previousComponents.map((component)=>[
154
+ toKey(component),
155
+ component
156
+ ]));
133
157
  // MySQL/MariaDB can cause deadlocks here if concurrency higher than 1
134
- componentBody[attributeName] = await strapiUtils.async.map(dynamiczoneValues, async (value)=>{
135
- const { id } = await updateOrCreateComponent(value.__component, value);
158
+ const components = await strapiUtils.async.map(dynamiczoneValues, async (value)=>{
159
+ const previous = _.has(value, 'id') && !_.isNil(value.id) ? previousByKey.get(toKey(value)) : undefined;
160
+ const result = await updateOrCreateComponent(value.__component, value, previous);
161
+ return {
162
+ ...result,
163
+ __component: value.__component
164
+ };
165
+ });
166
+ // The join rows are already right when no component changed and the zone kept its order
167
+ const sameList = _.isEqual(components.map(toKey), previousComponents.map(toKey));
168
+ if (sameList && components.every((component)=>!component.changed)) {
169
+ continue;
170
+ }
171
+ componentBody[attributeName] = components.map(({ id, __component })=>{
136
172
  return {
137
173
  id,
138
- __component: value.__component,
174
+ __component,
139
175
  __pivot: {
140
176
  field: attributeName
141
177
  }
@@ -151,8 +187,207 @@ const pickStringifiedId = ({ id })=>{
151
187
  }
152
188
  return `${id}`;
153
189
  };
190
+ /**
191
+ * Populate of the media attributes of a component, ids only, so that a loaded component can be
192
+ * compared with the data sent for it (see isComponentUnchanged).
193
+ */ const getMediaPopulate = (componentUID)=>{
194
+ const { attributes = {} } = strapi.getModel(componentUID);
195
+ const populate = Object.entries(attributes).reduce((acc, [attributeName, attribute])=>{
196
+ if (attribute.type === 'media') {
197
+ acc[attributeName] = {
198
+ select: [
199
+ 'id'
200
+ ]
201
+ };
202
+ }
203
+ return acc;
204
+ }, {});
205
+ return _.isEmpty(populate) ? undefined : populate;
206
+ };
207
+ const getComponentLoadParams = (componentUID)=>{
208
+ const populate = getMediaPopulate(componentUID);
209
+ return populate ? {
210
+ populate
211
+ } : undefined;
212
+ };
213
+ /**
214
+ * Load params of a dynamic zone for the cleanup pass. The DB layer only returns the types listed
215
+ * in `on`, and a zone may still hold components of a type that was removed from it, so every
216
+ * registered component is listed, not only the ones the zone declares: those components have to
217
+ * be deleted too when they are no longer sent.
218
+ */ const getDynamicZoneLoadParams = ()=>{
219
+ const on = {};
220
+ let hasMedia = false;
221
+ for (const componentUID of Object.keys(strapi.components)){
222
+ const populate = getMediaPopulate(componentUID);
223
+ on[componentUID] = populate ? {
224
+ populate
225
+ } : {};
226
+ hasMedia = hasMedia || populate !== undefined;
227
+ }
228
+ return hasMedia ? {
229
+ on
230
+ } : undefined;
231
+ };
232
+ /**
233
+ * A relation or media sent as `{ connect: [], disconnect: [] }` leaves the stored value as it is.
234
+ */ const isRelationInputNoop = (value)=>{
235
+ if (!_.isPlainObject(value) || _.has(value, 'set')) {
236
+ return false;
237
+ }
238
+ const { connect, disconnect, ...rest } = value;
239
+ return _.isEmpty(connect) && _.isEmpty(disconnect) && Object.keys(rest).every((key)=>key === 'options');
240
+ };
241
+ /**
242
+ * Ids of a media value, as loaded (`{ id }`, `[{ id }]`) or as sent (ids, `{ id }` objects, a `set`).
243
+ * Returns null when they cannot be told.
244
+ */ const toMediaIds = (value)=>{
245
+ if (_.isNil(value)) {
246
+ return [];
247
+ }
248
+ if (typeof value === 'number' || typeof value === 'string') {
249
+ return [
250
+ String(value)
251
+ ];
252
+ }
253
+ if (Array.isArray(value)) {
254
+ const ids = value.map((item)=>_.isPlainObject(item) ? item.id : item);
255
+ return ids.every((id)=>typeof id === 'number' || typeof id === 'string') ? ids.map(String) : null;
256
+ }
257
+ if (_.isPlainObject(value)) {
258
+ if (_.has(value, 'set')) {
259
+ return toMediaIds(value.set);
260
+ }
261
+ if (_.has(value, 'id') && !_.has(value, 'connect') && !_.has(value, 'disconnect')) {
262
+ return toMediaIds([
263
+ value
264
+ ]);
265
+ }
266
+ }
267
+ return null;
268
+ };
269
+ const toComparableNumber = (value)=>{
270
+ if (typeof value === 'number') {
271
+ return Number.isFinite(value) ? value : null;
272
+ }
273
+ if (typeof value === 'string' && value.trim() !== '') {
274
+ const parsed = Number(value);
275
+ return Number.isFinite(parsed) ? parsed : null;
276
+ }
277
+ return null;
278
+ };
279
+ const toComparableBigInt = (value)=>{
280
+ try {
281
+ if (typeof value === 'bigint') {
282
+ return value.toString();
283
+ }
284
+ if (typeof value === 'number' && Number.isInteger(value)) {
285
+ return BigInt(value).toString();
286
+ }
287
+ if (typeof value === 'string' && value.trim() !== '') {
288
+ return BigInt(value.trim()).toString();
289
+ }
290
+ } catch {
291
+ // not a big integer
292
+ }
293
+ return null;
294
+ };
295
+ /**
296
+ * What the database layer would store for `value`, or null when it would reject it. Both sides of
297
+ * a comparison go through it so that the comparison matches the write it replaces: the database
298
+ * parsers read a date without a time in local time, format a Date as a local day and reject a
299
+ * time without seconds, and none of that is reproduced here.
300
+ */ const toStoredDateValue = (attribute, value)=>{
301
+ try {
302
+ const stored = database.createField({
303
+ type: attribute.type
304
+ }).toDB(value);
305
+ return stored instanceof Date ? stored.getTime() : String(stored);
306
+ } catch {
307
+ return null;
308
+ }
309
+ };
310
+ const toComparableJson = (value)=>{
311
+ if (typeof value === 'string') {
312
+ try {
313
+ return JSON.parse(value);
314
+ } catch {
315
+ return value;
316
+ }
317
+ }
318
+ return value;
319
+ };
320
+ const isScalarUnchanged = (attribute, stored, incoming)=>{
321
+ if (_.isNil(stored) || _.isNil(incoming)) {
322
+ return _.isNil(stored) && _.isNil(incoming);
323
+ }
324
+ switch(attribute.type){
325
+ case 'string':
326
+ case 'text':
327
+ case 'richtext':
328
+ case 'email':
329
+ case 'enumeration':
330
+ case 'uid':
331
+ return typeof incoming === 'string' && String(stored) === incoming;
332
+ case 'boolean':
333
+ return typeof incoming === 'boolean' && stored === incoming;
334
+ case 'integer':
335
+ case 'float':
336
+ case 'decimal':
337
+ {
338
+ const a = toComparableNumber(stored);
339
+ return a !== null && a === toComparableNumber(incoming);
340
+ }
341
+ case 'biginteger':
342
+ {
343
+ const a = toComparableBigInt(stored);
344
+ return a !== null && a === toComparableBigInt(incoming);
345
+ }
346
+ case 'date':
347
+ case 'time':
348
+ case 'datetime':
349
+ case 'timestamp':
350
+ {
351
+ const a = toStoredDateValue(attribute, stored);
352
+ return a !== null && a === toStoredDateValue(attribute, incoming);
353
+ }
354
+ case 'json':
355
+ case 'blocks':
356
+ return _.isEqual(toComparableJson(stored), toComparableJson(incoming));
357
+ default:
358
+ // passwords and unknown types: assume a change
359
+ return false;
360
+ }
361
+ };
362
+ /**
363
+ * Whether the data sent for a component leaves it as it is stored. Nested components and dynamic
364
+ * zones are not compared here: updateComponents only reports the ones that changed, and the caller
365
+ * checks that it reported none. Anything that cannot be compared with certainty counts as a change.
366
+ */ const isComponentUnchanged = (schema, stored, data)=>{
367
+ return Object.entries(schema.attributes).every(([attributeName, attribute])=>{
368
+ if (!_.has(data, attributeName) || strapiUtils.contentTypes.isComponentAttribute(attribute)) {
369
+ return true;
370
+ }
371
+ const incoming = data[attributeName];
372
+ if (attribute.type === 'relation') {
373
+ return isRelationInputNoop(incoming);
374
+ }
375
+ if (!_.has(stored, attributeName)) {
376
+ return false;
377
+ }
378
+ if (attribute.type === 'media') {
379
+ if (isRelationInputNoop(incoming)) {
380
+ return true;
381
+ }
382
+ const storedIds = toMediaIds(stored[attributeName]);
383
+ const incomingIds = toMediaIds(incoming);
384
+ return storedIds !== null && incomingIds !== null && _.isEqual(storedIds, incomingIds);
385
+ }
386
+ return isScalarUnchanged(attribute, stored[attributeName], incoming);
387
+ });
388
+ };
154
389
  const deleteOldComponents = async (uid, componentUID, entityToUpdate, attributeName, componentValue)=>{
155
- const previousValue = await strapi.db.query(uid).load(entityToUpdate, attributeName);
390
+ const previousValue = await strapi.db.query(uid).load(entityToUpdate, attributeName, getComponentLoadParams(componentUID));
156
391
  const idsToKeep = ___default.default.castArray(componentValue).filter((value)=>_.has(value, 'id')).map(pickStringifiedId);
157
392
  const allIds = ___default.default.castArray(previousValue).filter((value)=>_.has(value, 'id')).map(pickStringifiedId);
158
393
  idsToKeep.forEach((id)=>{
@@ -168,9 +403,10 @@ const deleteOldComponents = async (uid, componentUID, entityToUpdate, attributeN
168
403
  });
169
404
  }
170
405
  }
406
+ return previousValue;
171
407
  };
172
408
  const deleteOldDZComponents = async (uid, entityToUpdate, attributeName, dynamiczoneValues)=>{
173
- const previousValue = await strapi.db.query(uid).load(entityToUpdate, attributeName);
409
+ const previousValue = await strapi.db.query(uid).load(entityToUpdate, attributeName, getDynamicZoneLoadParams());
174
410
  const idsToKeep = ___default.default.castArray(dynamiczoneValues).filter((value)=>_.has(value, 'id')).map((v)=>({
175
411
  id: pickStringifiedId(v),
176
412
  __component: v.__component
@@ -205,8 +441,109 @@ const deleteOldDZComponents = async (uid, entityToUpdate, attributeName, dynamic
205
441
  });
206
442
  }
207
443
  }
444
+ return previousValue;
445
+ };
446
+ const addComponentIds = (groups, componentUID, ids)=>{
447
+ if (ids.length > 0) {
448
+ groups.set(componentUID, [
449
+ ...groups.get(componentUID) ?? [],
450
+ ...ids
451
+ ]);
452
+ }
453
+ };
454
+ /**
455
+ * Ids of the components held by the component and dynamic zone attributes of `values`, by component uid.
456
+ */ const groupComponentsByUid = (schema, values)=>{
457
+ const groups = new Map();
458
+ for (const [attributeName, attribute] of Object.entries(schema.attributes)){
459
+ const value = values[attributeName];
460
+ if (_.isNil(value)) {
461
+ continue;
462
+ }
463
+ const components = ___default.default.castArray(value).filter((component)=>_.isPlainObject(component) && !_.isNil(component.id));
464
+ if (attribute.type === 'component') {
465
+ addComponentIds(groups, attribute.component, components.map((component)=>component.id));
466
+ } else if (attribute.type === 'dynamiczone') {
467
+ for (const component of components){
468
+ if (component.__component) {
469
+ addComponentIds(groups, component.__component, [
470
+ component.id
471
+ ]);
472
+ }
473
+ }
474
+ }
475
+ }
476
+ return groups;
208
477
  };
209
- const deleteComponents = async (uid, entityToDelete, { loadComponents = true } = {})=>{
478
+ /**
479
+ * Ids of every component under an entry or a component, by component uid, down to the deepest
480
+ * level. Each level costs one query per component uid holding nested components, whatever the
481
+ * number of components.
482
+ */ const collectComponentTree = async (uid, entity, { loadComponents = true } = {})=>{
483
+ const tree = new Map();
484
+ const schema = strapi.getModel(uid);
485
+ const componentAttributes = strapiUtils.contentTypes.getComponentAttributes(schema);
486
+ if (componentAttributes.length === 0) {
487
+ return tree;
488
+ }
489
+ const values = loadComponents ? await strapi.db.query(uid).load(entity, componentAttributes) : entity;
490
+ let level = groupComponentsByUid(schema, values ?? {});
491
+ while(level.size > 0){
492
+ const nextLevel = new Map();
493
+ for (const [componentUID, ids] of level){
494
+ addComponentIds(tree, componentUID, ids);
495
+ const componentSchema = strapi.getModel(componentUID);
496
+ const nestedAttributes = strapiUtils.contentTypes.getComponentAttributes(componentSchema);
497
+ if (nestedAttributes.length === 0) {
498
+ continue;
499
+ }
500
+ // Read without lifecycles: the per-row path never ran `findMany` on a component type, so no
501
+ // subscriber should start receiving those events here
502
+ const rows = await strapi.db.queryBuilder(componentUID).init({
503
+ where: {
504
+ id: {
505
+ $in: ids
506
+ }
507
+ },
508
+ select: [
509
+ 'id'
510
+ ],
511
+ populate: Object.fromEntries(nestedAttributes.map((attributeName)=>[
512
+ attributeName,
513
+ // dynamic zone items need their __component, keep every column for them
514
+ componentSchema.attributes[attributeName].type === 'dynamiczone' ? true : {
515
+ select: [
516
+ 'id'
517
+ ]
518
+ }
519
+ ]))
520
+ }).execute();
521
+ for (const row of rows){
522
+ for (const [nestedUID, nestedIds] of groupComponentsByUid(componentSchema, row)){
523
+ addComponentIds(nextLevel, nestedUID, nestedIds);
524
+ }
525
+ }
526
+ }
527
+ level = nextLevel;
528
+ }
529
+ return tree;
530
+ };
531
+ const UPDATE_LIFECYCLES = [
532
+ 'beforeUpdate',
533
+ 'afterUpdate'
534
+ ];
535
+ const DELETE_LIFECYCLES = [
536
+ 'beforeDelete',
537
+ 'afterDelete',
538
+ 'beforeDeleteMany',
539
+ 'afterDeleteMany'
540
+ ];
541
+ /**
542
+ * Whether a database lifecycle subscriber would receive one of `actions` for the component type.
543
+ */ const hasLifecycleSubscribers = (componentUID, actions)=>actions.some((action)=>strapi.db.lifecycles.hasSubscribers(action, componentUID));
544
+ /**
545
+ * Deletes the components one by one, each with its own delete lifecycles.
546
+ */ const deleteComponentsOneByOne = async (uid, entityToDelete, { loadComponents = true } = {})=>{
210
547
  const { attributes = {} } = strapi.getModel(uid);
211
548
  const attributeNames = Object.keys(attributes);
212
549
  for (const attributeName of attributeNames){
@@ -231,6 +568,46 @@ const deleteComponents = async (uid, entityToDelete, { loadComponents = true } =
231
568
  }
232
569
  }
233
570
  };
571
+ // Keeps every statement under the parameter limits of the databases
572
+ const DELETE_BATCH_SIZE = 500;
573
+ /**
574
+ * Deletes every component under an entry or a component. The whole tree is removed level by level
575
+ * with one statement per component uid and per relation attribute. When a database lifecycle
576
+ * subscriber listens to any delete lifecycle of one of those component uids, the components are
577
+ * deleted one by one instead, so that each of them fires its events and no subscriber receives an
578
+ * event it did not receive before.
579
+ */ const deleteComponents = async (uid, entityToDelete, { loadComponents = true } = {})=>{
580
+ const tree = await collectComponentTree(uid, entityToDelete, {
581
+ loadComponents
582
+ });
583
+ if (tree.size === 0) {
584
+ return;
585
+ }
586
+ if ([
587
+ ...tree.keys()
588
+ ].some((componentUID)=>hasLifecycleSubscribers(componentUID, DELETE_LIFECYCLES))) {
589
+ await deleteComponentsOneByOne(uid, entityToDelete, {
590
+ loadComponents
591
+ });
592
+ return;
593
+ }
594
+ await strapi.db.transaction(async ({ trx })=>{
595
+ for (const [componentUID, ids] of tree){
596
+ for (const batch of ___default.default.chunk(ids, DELETE_BATCH_SIZE)){
597
+ await strapi.db.entityManager.deleteManyRelations(componentUID, batch, {
598
+ transaction: trx
599
+ });
600
+ await strapi.db.query(componentUID).deleteMany({
601
+ where: {
602
+ id: {
603
+ $in: batch
604
+ }
605
+ }
606
+ });
607
+ }
608
+ }
609
+ });
610
+ };
234
611
  /** *************************
235
612
  Component queries
236
613
  ************************** */ // components can have nested compos so this must be recursive
@@ -244,17 +621,30 @@ const createComponent = async (uid, data)=>{
244
621
  });
245
622
  };
246
623
  // components can have nested compos so this must be recursive
247
- const updateComponent = async (uid, componentToUpdate, data)=>{
624
+ const updateComponent = async (uid, componentToUpdate, data, previous)=>{
248
625
  const schema = strapi.getModel(uid);
249
626
  const componentData = await updateComponents(uid, componentToUpdate, data);
250
- return strapi.db.query(uid).update({
627
+ // Nothing to write when the component is stored as sent. updateComponents only reports the
628
+ // nested attributes that changed, so an empty componentData means none of them did. The write
629
+ // is kept when a lifecycle subscriber listens to it, so that it fires as before.
630
+ if (previous && _.isEmpty(componentData) && !hasLifecycleSubscribers(uid, UPDATE_LIFECYCLES) && isComponentUnchanged(schema, previous, data)) {
631
+ return {
632
+ id: componentToUpdate.id,
633
+ changed: false
634
+ };
635
+ }
636
+ const component = await strapi.db.query(uid).update({
251
637
  where: {
252
638
  id: componentToUpdate.id
253
639
  },
254
640
  data: assignComponentData(schema, componentData, data)
255
641
  });
642
+ return component ? {
643
+ id: component.id,
644
+ changed: true
645
+ } : null;
256
646
  };
257
- const updateOrCreateComponent = (componentUID, value)=>{
647
+ const updateOrCreateComponent = async (componentUID, value, previous)=>{
258
648
  if (value === null) {
259
649
  return null;
260
650
  }
@@ -263,10 +653,14 @@ const updateOrCreateComponent = (componentUID, value)=>{
263
653
  // TODO: verify the compo is associated with the entity
264
654
  return updateComponent(componentUID, {
265
655
  id: value.id
266
- }, value);
656
+ }, value, previous);
267
657
  }
268
658
  // create
269
- return createComponent(componentUID, value);
659
+ const component = await createComponent(componentUID, value);
660
+ return {
661
+ id: component.id,
662
+ changed: true
663
+ };
270
664
  };
271
665
  const deleteComponent = async (uid, componentToDelete)=>{
272
666
  await deleteComponents(uid, componentToDelete);
@@ -279,50 +673,75 @@ const deleteComponent = async (uid, componentToDelete)=>{
279
673
  const assignComponentData = _.curry((schema, componentData, data)=>{
280
674
  return _.assign({}, componentData, omitComponentData(schema, data));
281
675
  });
282
- /** *************************
283
- Component relation handling for document operations
284
- ************************** */ /**
285
- * Find the parent entry of a component instance.
676
+ // Component instance ids are bound as query parameters, so look them up in batches that stay
677
+ // well below the bind parameter limit of every supported database
678
+ const PARENT_LOOKUP_BATCH_SIZE = 500;
679
+ /**
680
+ * Find the parent entries of many instances of the same component.
286
681
  *
287
- * Given a component model, a specific component instance id, and the list of
288
- * possible parent content types (those that can embed this component),
289
- * this function checks each parent's *_cmps join table to see if the component
290
- * instance is linked to a parent entity.
682
+ * Given a component model, component instance ids, and the list of possible parent
683
+ * content types and components (those that can embed this component), this function
684
+ * checks each parent's *_cmps join table to see which instances it links to a parent.
685
+ * Parents are checked in order and the first one linking an instance is its parent.
291
686
  *
292
- * - Returns the parent uid, parent table name, and parent id if found.
293
- * - Returns null if no parent relationship exists.
294
- */ const findComponentParent = async (componentSchema, componentId, parentSchemasForComponent, opts)=>{
295
- if (!componentSchema?.uid) return null;
296
- const schemaBuilder = strapi.db.getSchemaConnection(opts?.trx);
687
+ * Each parent costs one query per batch of instances rather than one query per instance,
688
+ * and parents are no longer checked once every instance has been found.
689
+ *
690
+ * - Returns a map from component instance id (as a string) to its parent uid, parent table
691
+ * name and parent id.
692
+ * - Instances without a parent are not in the map.
693
+ */ const findComponentParents = async (componentSchema, componentIds, parentSchemasForComponent, opts)=>{
694
+ const parents = new Map();
695
+ if (!componentSchema?.uid) return parents;
297
696
  const withTrx = (qb)=>opts?.trx ? qb.transacting(opts.trx) : qb;
697
+ // Use the exact same functions that create the columns
698
+ const identifiers = strapi.db.metadata.identifiers;
699
+ const entityIdColumn = transformContentTypesToModels.getComponentJoinColumnEntityName(identifiers);
700
+ const componentIdColumn = transformContentTypesToModels.getComponentJoinColumnInverseName(identifiers);
701
+ const componentTypeColumn = transformContentTypesToModels.getComponentTypeColumn(identifiers);
702
+ let pendingIds = ___default.default.uniqBy(componentIds.filter((id)=>id !== undefined && id !== null), String);
298
703
  for (const parent of parentSchemasForComponent){
704
+ if (pendingIds.length === 0) break;
299
705
  if (!parent.collectionName) continue;
300
706
  // Use the exact same functions that create the tables
301
- const identifiers = strapi.db.metadata.identifiers;
302
707
  const joinTableName = transformContentTypesToModels.getComponentJoinTableName(parent.collectionName, identifiers);
303
- try {
304
- const tableExists = await schemaBuilder.hasTable(joinTableName);
305
- if (!tableExists) continue;
306
- // Use the exact same functions that create the columns
307
- const entityIdColumn = transformContentTypesToModels.getComponentJoinColumnEntityName(identifiers);
308
- const componentIdColumn = transformContentTypesToModels.getComponentJoinColumnInverseName(identifiers);
309
- const componentTypeColumn = transformContentTypesToModels.getComponentTypeColumn(identifiers);
310
- const parentRow = await withTrx(strapi.db.getConnection(joinTableName)).where({
311
- [componentIdColumn]: componentId,
312
- [componentTypeColumn]: componentSchema.uid
313
- }).first(entityIdColumn);
314
- if (parentRow) {
315
- return {
316
- uid: parent.uid,
317
- table: parent.collectionName,
318
- parentId: parentRow[entityIdColumn]
319
- };
708
+ // The join table is registered as a model of its own (see createCompoLinkModel) and schema
709
+ // sync creates every registered model, so the metadata knows whether it exists without
710
+ // querying the database schema
711
+ if (!strapi.db.metadata.has(joinTableName)) continue;
712
+ for (const batch of ___default.default.chunk(pendingIds, PARENT_LOOKUP_BATCH_SIZE)){
713
+ try {
714
+ const parentRows = await withTrx(strapi.db.getConnection(joinTableName)).select(entityIdColumn, componentIdColumn).where(componentTypeColumn, componentSchema.uid).whereIn(componentIdColumn, batch);
715
+ for (const parentRow of parentRows){
716
+ const componentId = String(parentRow[componentIdColumn]);
717
+ if (!parents.has(componentId)) {
718
+ parents.set(componentId, {
719
+ uid: parent.uid,
720
+ table: parent.collectionName,
721
+ parentId: parentRow[entityIdColumn]
722
+ });
723
+ }
724
+ }
725
+ } catch {
726
+ continue;
320
727
  }
321
- } catch {
322
- continue;
323
728
  }
729
+ pendingIds = pendingIds.filter((id)=>!parents.has(String(id)));
324
730
  }
325
- return null;
731
+ return parents;
732
+ };
733
+ /**
734
+ * Find the parent entry of a component instance.
735
+ *
736
+ * Single-instance form of `findComponentParents`.
737
+ *
738
+ * - Returns the parent uid, parent table name, and parent id if found.
739
+ * - Returns null if no parent relationship exists.
740
+ */ const findComponentParent = async (componentSchema, componentId, parentSchemasForComponent, opts)=>{
741
+ const parents = await findComponentParents(componentSchema, [
742
+ componentId
743
+ ], parentSchemasForComponent, opts);
744
+ return parents.get(String(componentId)) ?? null;
326
745
  };
327
746
  /**
328
747
  * Finds content types that contain the given component and have draft & publish enabled.
@@ -339,49 +758,73 @@ const assignComponentData = _.curry((schema, componentData, data)=>{
339
758
  });
340
759
  };
341
760
  /**
342
- * Determines if a component relation should be propagated to a new document version
343
- * when a document with draft and publish is updated.
344
- */ const shouldPropagateComponentRelationToNewVersion = async (componentRelation, componentSchema, parentSchemasForComponent, trx)=>{
345
- // Get the component ID column name using the actual component model name
346
- const componentIdColumn = strapi.db.metadata.identifiers.getJoinColumnAttributeIdName(___default.default.snakeCase(componentSchema.modelName));
347
- const componentId = componentRelation[componentIdColumn] ?? componentRelation.parentId;
348
- const parent = await findComponentParent(componentSchema, componentId, parentSchemasForComponent, {
761
+ * Finds which of the given component instances belong to an entry of a content type with
762
+ * draft and publish enabled, either directly or through parent components.
763
+ *
764
+ * Instances are resolved one nesting level at a time, so the number of queries depends on
765
+ * the schema rather than on the number of instances.
766
+ *
767
+ * - Returns the ids (as strings) of the instances owned by a draft and publish entry.
768
+ * - Instances without a parent, or owned by an entry without draft and publish, are not included.
769
+ */ const findInstancesOwnedByDraftAndPublishEntries = async (componentSchema, componentIds, trx)=>{
770
+ const ownedIds = new Set();
771
+ const parentSchemas = getParentSchemasForComponent(componentSchema);
772
+ if (parentSchemas.length === 0) {
773
+ return ownedIds;
774
+ }
775
+ const parents = await findComponentParents(componentSchema, componentIds, parentSchemas, {
349
776
  trx
350
777
  });
351
- // Keep relation if component has no parent entry
352
- if (!parent?.uid) {
353
- return true;
354
- }
355
- if (strapi.components[parent.uid]) {
356
- // If the parent is a component, we need to check its parents recursively
357
- const parentComponentSchema = strapi.components[parent.uid];
358
- const grandParentSchemas = getParentSchemasForComponent(parentComponentSchema);
359
- return shouldPropagateComponentRelationToNewVersion(parent, parentComponentSchema, grandParentSchemas, trx);
360
- }
361
- const parentContentType = strapi.contentTypes[parent.uid];
362
- // Keep relation if parent doesn't have draft & publish enabled
363
- if (!parentContentType?.options?.draftAndPublish) {
364
- return true;
365
- }
366
- // Discard relation if parent has draft & publish enabled
367
- return false;
778
+ // Instances nested in another component, grouped by that component and its instance id
779
+ const nestedInstances = new Map();
780
+ for (const [componentId, parent] of parents){
781
+ if (strapi.components[parent.uid]) {
782
+ const parentUid = parent.uid;
783
+ const parentKey = String(parent.parentId);
784
+ if (!nestedInstances.has(parentUid)) {
785
+ nestedInstances.set(parentUid, new Map());
786
+ }
787
+ const instancesByParent = nestedInstances.get(parentUid);
788
+ if (!instancesByParent.has(parentKey)) {
789
+ instancesByParent.set(parentKey, {
790
+ parentId: parent.parentId,
791
+ componentIds: []
792
+ });
793
+ }
794
+ instancesByParent.get(parentKey).componentIds.push(componentId);
795
+ continue;
796
+ }
797
+ if (strapi.contentTypes[parent.uid]?.options?.draftAndPublish) {
798
+ ownedIds.add(componentId);
799
+ }
800
+ }
801
+ // If the parent is a component, its own parents decide, so check them a level up
802
+ for (const [parentUid, instancesByParent] of nestedInstances){
803
+ const ownedParentIds = await findInstancesOwnedByDraftAndPublishEntries(strapi.components[parentUid], Array.from(instancesByParent.values(), ({ parentId })=>parentId), trx);
804
+ for (const parentKey of ownedParentIds){
805
+ instancesByParent.get(parentKey)?.componentIds.forEach((id)=>ownedIds.add(id));
806
+ }
807
+ }
808
+ return ownedIds;
368
809
  };
369
810
  /**
370
811
  * Creates a filter function for component relations that can be passed to the generic
371
- * unidirectional relations utility
812
+ * unidirectional relations utility.
813
+ *
814
+ * A relation of a component instance is propagated to the new document version unless the
815
+ * instance belongs to an entry with draft and publish enabled: that entry's new version gets
816
+ * its own copy of the component.
372
817
  */ const createComponentRelationFilter = ()=>{
373
- return async (relation, model, trx)=>{
818
+ return async (relations, model, trx)=>{
374
819
  // Only apply component-specific filtering for components
375
- if (model.modelType !== 'component') {
376
- return true;
820
+ if (model.modelType !== 'component' || relations.length === 0) {
821
+ return relations;
377
822
  }
378
823
  const componentSchema = model;
379
- const parentSchemas = getParentSchemasForComponent(componentSchema);
380
- // Exit if no draft & publish parent types exist
381
- if (parentSchemas.length === 0) {
382
- return true;
383
- }
384
- return shouldPropagateComponentRelationToNewVersion(relation, componentSchema, parentSchemas, trx);
824
+ // Get the component ID column name using the actual component model name
825
+ const componentIdColumn = strapi.db.metadata.identifiers.getJoinColumnAttributeIdName(___default.default.snakeCase(componentSchema.modelName));
826
+ const ownedIds = await findInstancesOwnedByDraftAndPublishEntries(componentSchema, relations.map((relation)=>relation[componentIdColumn]), trx);
827
+ return relations.filter((relation)=>!ownedIds.has(String(relation[componentIdColumn])));
385
828
  };
386
829
  };
387
830
 
@@ -393,6 +836,7 @@ exports.deleteComponents = deleteComponents;
393
836
  exports.findComponentParent = findComponentParent;
394
837
  exports.getComponents = getComponents;
395
838
  exports.getParentSchemasForComponent = getParentSchemasForComponent;
839
+ exports.isComponentUnchanged = isComponentUnchanged;
396
840
  exports.omitComponentData = omitComponentData;
397
841
  exports.updateComponents = updateComponents;
398
842
  //# sourceMappingURL=components.js.map