@strapi/core 5.59.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 (83) hide show
  1. package/dist/core-api/routes/index.js +10 -45
  2. package/dist/core-api/routes/index.js.map +1 -1
  3. package/dist/core-api/routes/index.mjs +10 -25
  4. package/dist/core-api/routes/index.mjs.map +1 -1
  5. package/dist/core-api/routes/response.d.ts +28 -0
  6. package/dist/core-api/routes/response.d.ts.map +1 -0
  7. package/dist/core-api/routes/response.js +63 -0
  8. package/dist/core-api/routes/response.js.map +1 -0
  9. package/dist/core-api/routes/response.mjs +40 -0
  10. package/dist/core-api/routes/response.mjs.map +1 -0
  11. package/dist/package.json.js +14 -14
  12. package/dist/package.json.mjs +14 -14
  13. package/dist/providers/admin.d.ts.map +1 -1
  14. package/dist/providers/admin.js +8 -0
  15. package/dist/providers/admin.js.map +1 -1
  16. package/dist/providers/admin.mjs +8 -0
  17. package/dist/providers/admin.mjs.map +1 -1
  18. package/dist/services/config.js +1 -1
  19. package/dist/services/config.js.map +1 -1
  20. package/dist/services/config.mjs +2 -2
  21. package/dist/services/config.mjs.map +1 -1
  22. package/dist/services/document-service/components.d.ts +14 -1
  23. package/dist/services/document-service/components.d.ts.map +1 -1
  24. package/dist/services/document-service/components.js +413 -18
  25. package/dist/services/document-service/components.js.map +1 -1
  26. package/dist/services/document-service/components.mjs +414 -20
  27. package/dist/services/document-service/components.mjs.map +1 -1
  28. package/dist/services/document-service/events.d.ts.map +1 -1
  29. package/dist/services/document-service/events.js +6 -1
  30. package/dist/services/document-service/events.js.map +1 -1
  31. package/dist/services/document-service/events.mjs +6 -1
  32. package/dist/services/document-service/events.mjs.map +1 -1
  33. package/dist/services/document-service/middlewares/middleware-manager.d.ts +1 -1
  34. package/dist/services/document-service/middlewares/middleware-manager.d.ts.map +1 -1
  35. package/dist/services/document-service/middlewares/middleware-manager.js +6 -1
  36. package/dist/services/document-service/middlewares/middleware-manager.js.map +1 -1
  37. package/dist/services/document-service/middlewares/middleware-manager.mjs +6 -1
  38. package/dist/services/document-service/middlewares/middleware-manager.mjs.map +1 -1
  39. package/dist/services/entity-validator/index.d.ts.map +1 -1
  40. package/dist/services/entity-validator/index.js +6 -2
  41. package/dist/services/entity-validator/index.js.map +1 -1
  42. package/dist/services/entity-validator/index.mjs +7 -3
  43. package/dist/services/entity-validator/index.mjs.map +1 -1
  44. package/dist/services/event-hub.d.ts +1 -0
  45. package/dist/services/event-hub.d.ts.map +1 -1
  46. package/dist/services/event-hub.js +7 -0
  47. package/dist/services/event-hub.js.map +1 -1
  48. package/dist/services/event-hub.mjs +7 -0
  49. package/dist/services/event-hub.mjs.map +1 -1
  50. package/dist/services/mcp/handlers/handlePost.d.ts.map +1 -1
  51. package/dist/services/mcp/handlers/handlePost.js +4 -2
  52. package/dist/services/mcp/handlers/handlePost.js.map +1 -1
  53. package/dist/services/mcp/handlers/handlePost.mjs +4 -2
  54. package/dist/services/mcp/handlers/handlePost.mjs.map +1 -1
  55. package/dist/services/mcp/internal/McpServerFactory.d.ts +4 -1
  56. package/dist/services/mcp/internal/McpServerFactory.d.ts.map +1 -1
  57. package/dist/services/mcp/internal/McpServerFactory.js +8 -2
  58. package/dist/services/mcp/internal/McpServerFactory.js.map +1 -1
  59. package/dist/services/mcp/internal/McpServerFactory.mjs +9 -3
  60. package/dist/services/mcp/internal/McpServerFactory.mjs.map +1 -1
  61. package/dist/services/mcp/internal/resolveToolSchemaScope.d.ts +16 -0
  62. package/dist/services/mcp/internal/resolveToolSchemaScope.d.ts.map +1 -0
  63. package/dist/services/mcp/internal/resolveToolSchemaScope.js +40 -0
  64. package/dist/services/mcp/internal/resolveToolSchemaScope.js.map +1 -0
  65. package/dist/services/mcp/internal/resolveToolSchemaScope.mjs +38 -0
  66. package/dist/services/mcp/internal/resolveToolSchemaScope.mjs.map +1 -0
  67. package/dist/services/mcp/tool-registry.d.ts +5 -0
  68. package/dist/services/mcp/tool-registry.d.ts.map +1 -1
  69. package/dist/services/mcp/tool-registry.js +30 -1
  70. package/dist/services/mcp/tool-registry.js.map +1 -1
  71. package/dist/services/mcp/tool-registry.mjs +30 -1
  72. package/dist/services/mcp/tool-registry.mjs.map +1 -1
  73. package/dist/services/webhook-runner.d.ts.map +1 -1
  74. package/dist/services/webhook-runner.js +23 -3
  75. package/dist/services/webhook-runner.js.map +1 -1
  76. package/dist/services/webhook-runner.mjs +23 -3
  77. package/dist/services/webhook-runner.mjs.map +1 -1
  78. package/dist/services/webhook-store.d.ts.map +1 -1
  79. package/dist/services/webhook-store.js +21 -2
  80. package/dist/services/webhook-store.js.map +1 -1
  81. package/dist/services/webhook-store.mjs +21 -2
  82. package/dist/services/webhook-store.mjs.map +1 -1
  83. package/package.json +14 -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;
477
+ };
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;
208
530
  };
209
- const deleteComponents = async (uid, entityToDelete, { loadComponents = true } = {})=>{
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);
@@ -442,6 +836,7 @@ exports.deleteComponents = deleteComponents;
442
836
  exports.findComponentParent = findComponentParent;
443
837
  exports.getComponents = getComponents;
444
838
  exports.getParentSchemasForComponent = getParentSchemasForComponent;
839
+ exports.isComponentUnchanged = isComponentUnchanged;
445
840
  exports.omitComponentData = omitComponentData;
446
841
  exports.updateComponents = updateComponents;
447
842
  //# sourceMappingURL=components.js.map