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