strapi-plugin-bulk-updater 1.7.0 → 1.7.1

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 (29) hide show
  1. package/dist/_chunks/{BulkUpdater-CV49TvOV.mjs → BulkUpdater-BQnhVw0j.mjs} +31 -25
  2. package/dist/_chunks/BulkUpdater-BQnhVw0j.mjs.map +1 -0
  3. package/dist/_chunks/{BulkUpdater-Cnzgw4UH.js → BulkUpdater-BrBWtCjS.js} +31 -25
  4. package/dist/_chunks/BulkUpdater-BrBWtCjS.js.map +1 -0
  5. package/dist/_chunks/{SettingsPage-DXRWLRp_.mjs → SettingsPage-DYD6M988.mjs} +2 -2
  6. package/dist/_chunks/{SettingsPage-DXRWLRp_.mjs.map → SettingsPage-DYD6M988.mjs.map} +1 -1
  7. package/dist/_chunks/{SettingsPage-w_Lz-N0V.js → SettingsPage-DsKfbhNd.js} +2 -2
  8. package/dist/_chunks/{SettingsPage-w_Lz-N0V.js.map → SettingsPage-DsKfbhNd.js.map} +1 -1
  9. package/dist/_chunks/{ValidationRulesTab-eN_vH3TB.mjs → ValidationRulesTab-BzS4_gcN.mjs} +23 -3
  10. package/dist/_chunks/ValidationRulesTab-BzS4_gcN.mjs.map +1 -0
  11. package/dist/_chunks/{ValidationRulesTab-of8bIzre.js → ValidationRulesTab-DZw6CujQ.js} +23 -3
  12. package/dist/_chunks/ValidationRulesTab-DZw6CujQ.js.map +1 -0
  13. package/dist/_chunks/{index-C2HoRm23.js → index-BCOsNd1S.js} +12 -4
  14. package/dist/_chunks/index-BCOsNd1S.js.map +1 -0
  15. package/dist/_chunks/{index-2DodYa70.mjs → index-CjbxZZjb.mjs} +12 -4
  16. package/dist/_chunks/index-CjbxZZjb.mjs.map +1 -0
  17. package/dist/admin/index.js +1 -1
  18. package/dist/admin/index.mjs +1 -1
  19. package/dist/server/index.js +332 -227
  20. package/dist/server/index.js.map +1 -1
  21. package/dist/server/index.mjs +332 -227
  22. package/dist/server/index.mjs.map +1 -1
  23. package/package.json +1 -1
  24. package/dist/_chunks/BulkUpdater-CV49TvOV.mjs.map +0 -1
  25. package/dist/_chunks/BulkUpdater-Cnzgw4UH.js.map +0 -1
  26. package/dist/_chunks/ValidationRulesTab-eN_vH3TB.mjs.map +0 -1
  27. package/dist/_chunks/ValidationRulesTab-of8bIzre.js.map +0 -1
  28. package/dist/_chunks/index-2DodYa70.mjs.map +0 -1
  29. package/dist/_chunks/index-C2HoRm23.js.map +0 -1
@@ -20,6 +20,10 @@ const PERMISSIONS = {
20
20
  // CSV Management
21
21
  csvExport: `plugin::${PLUGIN_ID}.csv.export`,
22
22
  csvImport: `plugin::${PLUGIN_ID}.csv.import`,
23
+ csvSubmitForChecker: `plugin::${PLUGIN_ID}.csv.submit-for-checker`,
24
+ csvForceRunNow: `plugin::${PLUGIN_ID}.csv.force-run-now`,
25
+ csvQueueForOffPeak: `plugin::${PLUGIN_ID}.csv.queue-for-off-peak`,
26
+ csvPreFlightDryRun: `plugin::${PLUGIN_ID}.csv.pre-flight-dry-run`,
23
27
  // Audit Trail
24
28
  auditView: `plugin::${PLUGIN_ID}.audit.view`,
25
29
  auditDetails: `plugin::${PLUGIN_ID}.audit.details`,
@@ -106,6 +110,34 @@ const BULK_UPDATER_PERMISSION_ACTIONS = [
106
110
  pluginName: PLUGIN_ID,
107
111
  subCategory: "CSV Management"
108
112
  },
113
+ {
114
+ section: "plugins",
115
+ displayName: "CSV Submit For Checker",
116
+ uid: "csv.submit-for-checker",
117
+ pluginName: PLUGIN_ID,
118
+ subCategory: "CSV Management"
119
+ },
120
+ {
121
+ section: "plugins",
122
+ displayName: "CSV Force Run Now",
123
+ uid: "csv.force-run-now",
124
+ pluginName: PLUGIN_ID,
125
+ subCategory: "CSV Management"
126
+ },
127
+ {
128
+ section: "plugins",
129
+ displayName: "CSV Queue For Off-Peak",
130
+ uid: "csv.queue-for-off-peak",
131
+ pluginName: PLUGIN_ID,
132
+ subCategory: "CSV Management"
133
+ },
134
+ {
135
+ section: "plugins",
136
+ displayName: "CSV Run Pre-Flight Dry Run",
137
+ uid: "csv.pre-flight-dry-run",
138
+ pluginName: PLUGIN_ID,
139
+ subCategory: "CSV Management"
140
+ },
109
141
  {
110
142
  section: "plugins",
111
143
  displayName: "View Audit History",
@@ -188,7 +220,27 @@ const BATCH_UPDATE_POLICY_CONFIG = {
188
220
  mode: "any",
189
221
  enforceBatchUpdateExecutionMode: true
190
222
  };
191
- function resolveBatchUpdateRequiredPermissions(body) {
223
+ const CSV_SUBMIT_BATCH_POLICY_CONFIG = {
224
+ actions: [
225
+ PERMISSIONS.csvImport,
226
+ PERMISSIONS.csvSubmitForChecker,
227
+ PERMISSIONS.csvForceRunNow,
228
+ PERMISSIONS.csvQueueForOffPeak
229
+ ],
230
+ mode: "any",
231
+ enforceCsvSubmitExecutionMode: true
232
+ };
233
+ const WORKSPACE_MODE_PERMISSIONS = {
234
+ maker_checker: PERMISSIONS.workspaceSubmitForChecker,
235
+ queue_offpeak: PERMISSIONS.workspaceQueueForOffPeak,
236
+ immediate: PERMISSIONS.workspaceForceRunNow
237
+ };
238
+ const CSV_MODE_PERMISSIONS = {
239
+ maker_checker: PERMISSIONS.csvSubmitForChecker,
240
+ queue_offpeak: PERMISSIONS.csvQueueForOffPeak,
241
+ immediate: PERMISSIONS.csvForceRunNow
242
+ };
243
+ function resolveExecutionModeRequiredPermissions(body, modePermissionMap, checkPreviewOrigin) {
192
244
  const rawMode = body?.executionMode;
193
245
  const effectiveMode = rawMode === void 0 ? "immediate" : rawMode;
194
246
  if (typeof effectiveMode !== "string" || !["maker_checker", "queue_offpeak", "immediate"].includes(effectiveMode)) {
@@ -198,20 +250,23 @@ function resolveBatchUpdateRequiredPermissions(body) {
198
250
  reason: `Unsupported or unauthorized execution mode "${String(rawMode)}".`
199
251
  };
200
252
  }
201
- const required = [];
202
- if (effectiveMode === "maker_checker") {
203
- required.push(PERMISSIONS.workspaceSubmitForChecker);
204
- } else if (effectiveMode === "queue_offpeak") {
205
- required.push(PERMISSIONS.workspaceQueueForOffPeak);
206
- } else {
207
- required.push(PERMISSIONS.workspaceForceRunNow);
208
- }
209
- const isPreviewInitiated = body?.initiatedFromPreview === true || body?.initiatedFromPreview === "true" || body?.source === "preview" || body?.executionSource === "preview";
210
- if (isPreviewInitiated) {
211
- required.push(PERMISSIONS.workspaceProceedToExecute);
253
+ const required = [
254
+ modePermissionMap[effectiveMode]
255
+ ];
256
+ if (checkPreviewOrigin) {
257
+ const isPreviewInitiated = body?.initiatedFromPreview === true || body?.initiatedFromPreview === "true" || body?.source === "preview" || body?.executionSource === "preview";
258
+ if (isPreviewInitiated) {
259
+ required.push(PERMISSIONS.workspaceProceedToExecute);
260
+ }
212
261
  }
213
262
  return { valid: true, actions: required };
214
263
  }
264
+ function resolveBatchUpdateRequiredPermissions(body) {
265
+ return resolveExecutionModeRequiredPermissions(body, WORKSPACE_MODE_PERMISSIONS, true);
266
+ }
267
+ function resolveCsvSubmitRequiredPermissions(body) {
268
+ return resolveExecutionModeRequiredPermissions(body, CSV_MODE_PERMISSIONS, false);
269
+ }
215
270
  function setForbiddenResponse(ctx, message = "You do not have permission to perform this action.") {
216
271
  if (ctx) {
217
272
  ctx.status = 403;
@@ -230,6 +285,7 @@ const hasPermissionsPolicy = (policyContext, config, { strapi } = {}) => {
230
285
  let actions = [];
231
286
  let mode = "all";
232
287
  let enforceBatchMode = false;
288
+ let enforceCsvMode = false;
233
289
  if (Array.isArray(config)) {
234
290
  actions = config;
235
291
  } else if (config && typeof config === "object") {
@@ -238,6 +294,7 @@ const hasPermissionsPolicy = (policyContext, config, { strapi } = {}) => {
238
294
  mode = "any";
239
295
  }
240
296
  enforceBatchMode = Boolean(config.enforceBatchUpdateExecutionMode);
297
+ enforceCsvMode = Boolean(config.enforceCsvSubmitExecutionMode);
241
298
  } else if (typeof config === "string") {
242
299
  actions = [config];
243
300
  }
@@ -250,8 +307,8 @@ const hasPermissionsPolicy = (policyContext, config, { strapi } = {}) => {
250
307
  return true;
251
308
  }
252
309
  let batchModeActions = null;
253
- if (enforceBatchMode) {
254
- const resolved = resolveBatchUpdateRequiredPermissions(ctx?.request?.body);
310
+ if (enforceBatchMode || enforceCsvMode) {
311
+ const resolved = enforceCsvMode ? resolveCsvSubmitRequiredPermissions(ctx?.request?.body) : resolveBatchUpdateRequiredPermissions(ctx?.request?.body);
255
312
  if (!resolved.valid) {
256
313
  setForbiddenResponse(ctx, resolved.reason || "You do not have permission to perform this action.");
257
314
  return false;
@@ -289,6 +346,14 @@ const hasPermissionsPolicy = (policyContext, config, { strapi } = {}) => {
289
346
  }
290
347
  return true;
291
348
  };
349
+ const CSV_READ_PERMISSIONS = [
350
+ PERMISSIONS.csvExport,
351
+ PERMISSIONS.csvImport,
352
+ PERMISSIONS.csvSubmitForChecker,
353
+ PERMISSIONS.csvForceRunNow,
354
+ PERMISSIONS.csvQueueForOffPeak,
355
+ PERMISSIONS.csvPreFlightDryRun
356
+ ];
292
357
  function requirePermissions(actions, mode = "all") {
293
358
  return [
294
359
  {
@@ -312,8 +377,7 @@ const routes = {
312
377
  policies: requirePermissions(
313
378
  [
314
379
  PERMISSIONS.workspaceView,
315
- PERMISSIONS.csvExport,
316
- PERMISSIONS.csvImport,
380
+ ...CSV_READ_PERMISSIONS,
317
381
  PERMISSIONS.validationView
318
382
  ],
319
383
  "any"
@@ -326,7 +390,7 @@ const routes = {
326
390
  handler: "bulkUpdater.getCollectionEntries",
327
391
  config: {
328
392
  policies: requirePermissions(
329
- [PERMISSIONS.workspaceView, PERMISSIONS.csvExport, PERMISSIONS.csvImport],
393
+ [PERMISSIONS.workspaceView, ...CSV_READ_PERMISSIONS],
330
394
  "any"
331
395
  )
332
396
  }
@@ -337,7 +401,7 @@ const routes = {
337
401
  handler: "bulkUpdater.getRelationOptions",
338
402
  config: {
339
403
  policies: requirePermissions(
340
- [PERMISSIONS.workspaceView, PERMISSIONS.csvExport, PERMISSIONS.csvImport],
404
+ [PERMISSIONS.workspaceView, ...CSV_READ_PERMISSIONS],
341
405
  "any"
342
406
  )
343
407
  }
@@ -348,7 +412,7 @@ const routes = {
348
412
  handler: "bulkUpdater.getMediaOptions",
349
413
  config: {
350
414
  policies: requirePermissions(
351
- [PERMISSIONS.workspaceView, PERMISSIONS.csvExport, PERMISSIONS.csvImport],
415
+ [PERMISSIONS.workspaceView, ...CSV_READ_PERMISSIONS],
352
416
  "any"
353
417
  )
354
418
  }
@@ -435,6 +499,9 @@ const routes = {
435
499
  PERMISSIONS.workspaceView,
436
500
  PERMISSIONS.workspaceExecute,
437
501
  PERMISSIONS.csvImport,
502
+ PERMISSIONS.csvSubmitForChecker,
503
+ PERMISSIONS.csvForceRunNow,
504
+ PERMISSIONS.csvQueueForOffPeak,
438
505
  PERMISSIONS.auditView,
439
506
  PERMISSIONS.approvalView
440
507
  ],
@@ -527,7 +594,7 @@ const routes = {
527
594
  path: "/csv/template/:uid",
528
595
  handler: "csv.getTemplate",
529
596
  config: {
530
- policies: requirePermissions([PERMISSIONS.csvExport, PERMISSIONS.csvImport], "any")
597
+ policies: requirePermissions(CSV_READ_PERMISSIONS, "any")
531
598
  }
532
599
  },
533
600
  {
@@ -567,7 +634,7 @@ const routes = {
567
634
  path: "/csv/import",
568
635
  handler: "csv.importCsv",
569
636
  config: {
570
- policies: requirePermissions(PERMISSIONS.csvImport)
637
+ policies: requirePermissions(PERMISSIONS.csvForceRunNow)
571
638
  }
572
639
  },
573
640
  {
@@ -575,7 +642,7 @@ const routes = {
575
642
  path: "/csv/import-chunk",
576
643
  handler: "csv.importChunk",
577
644
  config: {
578
- policies: requirePermissions(PERMISSIONS.csvImport)
645
+ policies: requirePermissions(PERMISSIONS.csvForceRunNow)
579
646
  }
580
647
  },
581
648
  {
@@ -583,7 +650,7 @@ const routes = {
583
650
  path: "/csv/validate-preflight",
584
651
  handler: "csv.validatePreflight",
585
652
  config: {
586
- policies: requirePermissions(PERMISSIONS.csvImport)
653
+ policies: requirePermissions(PERMISSIONS.csvPreFlightDryRun)
587
654
  }
588
655
  },
589
656
  {
@@ -591,7 +658,12 @@ const routes = {
591
658
  path: "/csv/submit-batch",
592
659
  handler: "csv.submitBatch",
593
660
  config: {
594
- policies: requirePermissions(PERMISSIONS.csvImport)
661
+ policies: [
662
+ {
663
+ name: "plugin::bulk-updater.hasPermissions",
664
+ config: CSV_SUBMIT_BATCH_POLICY_CONFIG
665
+ }
666
+ ]
595
667
  }
596
668
  }
597
669
  ]
@@ -672,7 +744,15 @@ const contentTypes = {
672
744
  schema: auditLog
673
745
  }
674
746
  };
747
+ const { AsyncLocalStorage } = require("async_hooks");
675
748
  const CRASH_GUARD_SYMBOL = Symbol.for("strapi-plugin-bulk-updater.undiciCrashGuardInstalled");
749
+ const rollbackContextStorage = new AsyncLocalStorage();
750
+ function runInRollbackContext(fn) {
751
+ return rollbackContextStorage.run(true, fn);
752
+ }
753
+ function isRollbackContext() {
754
+ return rollbackContextStorage.getStore() === true;
755
+ }
676
756
  let activeBulkOperations = 0;
677
757
  function getActiveBulkOperationCount() {
678
758
  return activeBulkOperations;
@@ -1119,6 +1199,13 @@ const validationRulesController = ({ strapi }) => ({
1119
1199
  }
1120
1200
  }
1121
1201
  });
1202
+ function ensureCsvAuthorized(ctx, policyConfig, strapi) {
1203
+ const hasAuthContext = Boolean(
1204
+ ctx?.state?.userAbility || Array.isArray(ctx?.state?.permissions) || Array.isArray(ctx?.state?.user?.permissions) || ctx?.state?.user?.isSuperAdmin !== void 0
1205
+ );
1206
+ if (!hasAuthContext) return true;
1207
+ return hasPermissionsPolicy(ctx, policyConfig, { strapi });
1208
+ }
1122
1209
  const csvController = ({ strapi }) => ({
1123
1210
  async getTemplate(ctx) {
1124
1211
  try {
@@ -1227,6 +1314,9 @@ const csvController = ({ strapi }) => ({
1227
1314
  },
1228
1315
  async importCsv(ctx) {
1229
1316
  try {
1317
+ if (!ensureCsvAuthorized(ctx, { actions: [PERMISSIONS.csvForceRunNow] }, strapi)) {
1318
+ return;
1319
+ }
1230
1320
  const { uid, csvText, mode, publish, publishStrategy, unreviewedConsent } = ctx.request.body;
1231
1321
  if (!uid) {
1232
1322
  ctx.status = 400;
@@ -1256,6 +1346,9 @@ const csvController = ({ strapi }) => ({
1256
1346
  },
1257
1347
  async importChunk(ctx) {
1258
1348
  try {
1349
+ if (!ensureCsvAuthorized(ctx, { actions: [PERMISSIONS.csvForceRunNow] }, strapi)) {
1350
+ return;
1351
+ }
1259
1352
  const { uid, rows, batchId, isFirstChunk, isLastChunk, startRowNumber, mode, publish, publishStrategy, unreviewedConsent, originalHeaders } = ctx.request.body;
1260
1353
  if (!uid) {
1261
1354
  ctx.status = 400;
@@ -1290,6 +1383,9 @@ const csvController = ({ strapi }) => ({
1290
1383
  },
1291
1384
  async validatePreflight(ctx) {
1292
1385
  try {
1386
+ if (!ensureCsvAuthorized(ctx, { actions: [PERMISSIONS.csvPreFlightDryRun] }, strapi)) {
1387
+ return;
1388
+ }
1293
1389
  const { uid, rows, mode } = ctx.request.body;
1294
1390
  if (!uid) {
1295
1391
  ctx.status = 400;
@@ -1313,6 +1409,9 @@ const csvController = ({ strapi }) => ({
1313
1409
  },
1314
1410
  async submitBatch(ctx) {
1315
1411
  try {
1412
+ if (!ensureCsvAuthorized(ctx, CSV_SUBMIT_BATCH_POLICY_CONFIG, strapi)) {
1413
+ return;
1414
+ }
1316
1415
  const { uid, rows, executionMode, makerNotes, forceImmediate, mode, publish, publishStrategy, unreviewedConsent, unreviewedCount } = ctx.request.body;
1317
1416
  if (!uid) {
1318
1417
  ctx.status = 400;
@@ -9556,236 +9655,239 @@ const auditService = ({ strapi }) => ({
9556
9655
  * Helper to revert diff items back to original values
9557
9656
  */
9558
9657
  async revertDiffItems(diffs, userId) {
9559
- let revertedCount = 0;
9560
- const rollbackDetails = [];
9561
- for (const item of diffs) {
9562
- if (item.status === "updated" && item.uid && item.documentId && item.attribute) {
9563
- try {
9564
- const ct = strapi.contentTypes[item.uid];
9565
- if (!ct) {
9566
- throw new Error(`Content type "${item.uid}" does not exist in schema.`);
9567
- }
9568
- const isRel = item.oldValue && typeof item.oldValue === "object" && item.oldValue.isRelation;
9569
- let rollbackPayload;
9570
- if (isRel) {
9571
- const oldDocIds = Array.isArray(item.oldValue.documentIds) ? item.oldValue.documentIds : [];
9572
- rollbackPayload = { set: oldDocIds };
9573
- } else {
9574
- rollbackPayload = item.oldValue ?? null;
9575
- }
9576
- const parsed = parseDynamicZonePath(item.attribute);
9577
- const rootKey = parsed.rootKey;
9578
- const rootAttrDef = ct.attributes?.[rootKey];
9579
- const isComponent = rootAttrDef?.type === "component";
9580
- const isDynamicZone = rootAttrDef?.type === "dynamiczone";
9581
- const isNested = item.attribute.includes(".") || item.attribute.includes("[") || isComponent || isDynamicZone || isDeepComponentField(ct, strapi.components, item.attribute);
9582
- const isLocalized = Boolean(ct?.pluginOptions?.i18n?.localized) && item.locale && item.locale !== "null" && item.locale !== "undefined";
9583
- const isDraftAndPublish = Boolean(ct?.options?.draftAndPublish ?? item.isDraftAndPublish);
9584
- const populateOption = isNested ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
9585
- const findOneArgs = { documentId: item.documentId };
9586
- if (populateOption) {
9587
- findOneArgs.populate = populateOption;
9588
- }
9589
- if (isLocalized) {
9590
- findOneArgs.locale = item.locale;
9591
- }
9592
- const currentDoc = await strapi.documents(item.uid).findOne(findOneArgs);
9593
- if (!currentDoc) {
9594
- throw new Error(`Document "${item.documentId}" not found in collection "${item.uid}".`);
9595
- }
9596
- if (isNested && (isComponent || isDynamicZone || rootAttrDef)) {
9597
- const isRootDz = isDynamicZone;
9598
- const existingRoot = currentDoc?.[rootKey] || (isRootDz ? [] : {});
9599
- let restoredRoot;
9600
- if (Array.isArray(item.dynamicZoneDiffs) && item.dynamicZoneDiffs.length > 0) {
9601
- const hasStructuredSegments = item.dynamicZoneDiffs.some(
9602
- (dz) => Array.isArray(dz?.segments) && dz.segments.length > 0
9603
- );
9604
- if (hasStructuredSegments) {
9605
- const occUpdates = item.dynamicZoneDiffs.map((dzDiff) => {
9606
- const isRelDiff = dzDiff.oldValue && typeof dzDiff.oldValue === "object" && dzDiff.oldValue.isRelation;
9607
- const val = isRelDiff ? { mode: "set", documentIds: Array.isArray(dzDiff.oldValue.documentIds) ? dzDiff.oldValue.documentIds : [] } : dzDiff.oldValue ?? null;
9608
- return {
9609
- occurrenceKey: dzDiff.occurrenceKey,
9610
- segments: dzDiff.segments,
9611
- dynamicZoneIndex: dzDiff.index,
9612
- componentId: dzDiff.componentId,
9613
- componentUid: dzDiff.componentUid,
9614
- value: val
9615
- };
9616
- });
9617
- const reverted = await applyOccurrenceUpdatesToDocument({
9618
- strapi,
9619
- contentType: ct,
9620
- allComponents: strapi.components,
9621
- currentDoc,
9622
- attribute: item.attribute,
9623
- updates: occUpdates
9624
- });
9625
- if (reverted.errors.length > 0) {
9626
- throw new Error(reverted.errors.join("; "));
9627
- }
9628
- restoredRoot = reverted.updateData[rootKey];
9629
- } else {
9630
- let workingRoot = existingRoot;
9631
- for (const dzDiff of item.dynamicZoneDiffs) {
9632
- const parsedDz = parseDynamicZonePath(dzDiff.attribute || item.attribute);
9633
- const dzParts = parsedDz.cleanPath.split(".").slice(1);
9634
- const targetIndexes = dzDiff.index !== void 0 ? [dzDiff.index] : parsedDz.targetIndex !== void 0 ? [parsedDz.targetIndex] : void 0;
9635
- workingRoot = setDeepProperty(workingRoot, dzParts, dzDiff.oldValue ?? null, {
9636
- targetIndexes,
9637
- targetComponentUid: dzDiff.componentUid || parsedDz.targetComponentUid,
9638
- strapi
9658
+ return runInRollbackContext(async () => {
9659
+ const revertedEntryKeys = /* @__PURE__ */ new Set();
9660
+ const rollbackDetails = [];
9661
+ for (const item of diffs) {
9662
+ if (item.status === "updated" && item.uid && item.documentId && item.attribute) {
9663
+ try {
9664
+ const ct = strapi.contentTypes[item.uid];
9665
+ if (!ct) {
9666
+ throw new Error(`Content type "${item.uid}" does not exist in schema.`);
9667
+ }
9668
+ const isRel = item.oldValue && typeof item.oldValue === "object" && item.oldValue.isRelation;
9669
+ let rollbackPayload;
9670
+ if (isRel) {
9671
+ const oldDocIds = Array.isArray(item.oldValue.documentIds) ? item.oldValue.documentIds : [];
9672
+ rollbackPayload = { set: oldDocIds };
9673
+ } else {
9674
+ rollbackPayload = item.oldValue ?? null;
9675
+ }
9676
+ const parsed = parseDynamicZonePath(item.attribute);
9677
+ const rootKey = parsed.rootKey;
9678
+ const rootAttrDef = ct.attributes?.[rootKey];
9679
+ const isComponent = rootAttrDef?.type === "component";
9680
+ const isDynamicZone = rootAttrDef?.type === "dynamiczone";
9681
+ const isNested = item.attribute.includes(".") || item.attribute.includes("[") || isComponent || isDynamicZone || isDeepComponentField(ct, strapi.components, item.attribute);
9682
+ const isLocalized = Boolean(ct?.pluginOptions?.i18n?.localized) && item.locale && item.locale !== "null" && item.locale !== "undefined";
9683
+ const isDraftAndPublish = Boolean(ct?.options?.draftAndPublish ?? item.isDraftAndPublish);
9684
+ const populateOption = isNested ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
9685
+ const findOneArgs = { documentId: item.documentId };
9686
+ if (populateOption) {
9687
+ findOneArgs.populate = populateOption;
9688
+ }
9689
+ if (isLocalized) {
9690
+ findOneArgs.locale = item.locale;
9691
+ }
9692
+ const currentDoc = await strapi.documents(item.uid).findOne(findOneArgs);
9693
+ if (!currentDoc) {
9694
+ throw new Error(`Document "${item.documentId}" not found in collection "${item.uid}".`);
9695
+ }
9696
+ if (isNested && (isComponent || isDynamicZone || rootAttrDef)) {
9697
+ const isRootDz = isDynamicZone;
9698
+ const existingRoot = currentDoc?.[rootKey] || (isRootDz ? [] : {});
9699
+ let restoredRoot;
9700
+ if (Array.isArray(item.dynamicZoneDiffs) && item.dynamicZoneDiffs.length > 0) {
9701
+ const hasStructuredSegments = item.dynamicZoneDiffs.some(
9702
+ (dz) => Array.isArray(dz?.segments) && dz.segments.length > 0
9703
+ );
9704
+ if (hasStructuredSegments) {
9705
+ const occUpdates = item.dynamicZoneDiffs.map((dzDiff) => {
9706
+ const isRelDiff = dzDiff.oldValue && typeof dzDiff.oldValue === "object" && dzDiff.oldValue.isRelation;
9707
+ const val = isRelDiff ? { mode: "set", documentIds: Array.isArray(dzDiff.oldValue.documentIds) ? dzDiff.oldValue.documentIds : [] } : dzDiff.oldValue ?? null;
9708
+ return {
9709
+ occurrenceKey: dzDiff.occurrenceKey,
9710
+ segments: dzDiff.segments,
9711
+ dynamicZoneIndex: dzDiff.index,
9712
+ componentId: dzDiff.componentId,
9713
+ componentUid: dzDiff.componentUid,
9714
+ value: val
9715
+ };
9639
9716
  });
9717
+ const reverted = await applyOccurrenceUpdatesToDocument({
9718
+ strapi,
9719
+ contentType: ct,
9720
+ allComponents: strapi.components,
9721
+ currentDoc,
9722
+ attribute: item.attribute,
9723
+ updates: occUpdates
9724
+ });
9725
+ if (reverted.errors.length > 0) {
9726
+ throw new Error(reverted.errors.join("; "));
9727
+ }
9728
+ restoredRoot = reverted.updateData[rootKey];
9729
+ } else {
9730
+ let workingRoot = existingRoot;
9731
+ for (const dzDiff of item.dynamicZoneDiffs) {
9732
+ const parsedDz = parseDynamicZonePath(dzDiff.attribute || item.attribute);
9733
+ const dzParts = parsedDz.cleanPath.split(".").slice(1);
9734
+ const targetIndexes = dzDiff.index !== void 0 ? [dzDiff.index] : parsedDz.targetIndex !== void 0 ? [parsedDz.targetIndex] : void 0;
9735
+ workingRoot = setDeepProperty(workingRoot, dzParts, dzDiff.oldValue ?? null, {
9736
+ targetIndexes,
9737
+ targetComponentUid: dzDiff.componentUid || parsedDz.targetComponentUid,
9738
+ strapi
9739
+ });
9740
+ }
9741
+ restoredRoot = workingRoot;
9640
9742
  }
9641
- restoredRoot = workingRoot;
9743
+ } else {
9744
+ const parts = parsed.cleanPath.split(".");
9745
+ const pathParts = parts.slice(1);
9746
+ const targetIndexes = parsed.targetIndex !== void 0 ? [parsed.targetIndex] : void 0;
9747
+ const targetComponentUid = parsed.targetComponentUid;
9748
+ restoredRoot = setDeepProperty(existingRoot, pathParts, rollbackPayload, {
9749
+ targetIndexes,
9750
+ targetComponentUid,
9751
+ strapi
9752
+ });
9642
9753
  }
9643
- } else {
9644
- const parts = parsed.cleanPath.split(".");
9645
- const pathParts = parts.slice(1);
9646
- const targetIndexes = parsed.targetIndex !== void 0 ? [parsed.targetIndex] : void 0;
9647
- const targetComponentUid = parsed.targetComponentUid;
9648
- restoredRoot = setDeepProperty(existingRoot, pathParts, rollbackPayload, {
9649
- targetIndexes,
9650
- targetComponentUid,
9651
- strapi
9754
+ await strapi.documents(item.uid).update({
9755
+ documentId: item.documentId,
9756
+ ...isLocalized ? { locale: item.locale } : {},
9757
+ data: {
9758
+ [rootKey]: restoredRoot
9759
+ }
9652
9760
  });
9653
- }
9654
- await strapi.documents(item.uid).update({
9655
- documentId: item.documentId,
9656
- ...isLocalized ? { locale: item.locale } : {},
9657
- data: {
9658
- [rootKey]: restoredRoot
9659
- }
9660
- });
9661
- } else {
9662
- await strapi.documents(item.uid).update({
9663
- documentId: item.documentId,
9664
- ...isLocalized ? { locale: item.locale } : {},
9665
- data: {
9666
- [item.attribute]: rollbackPayload
9667
- }
9668
- });
9669
- }
9670
- let targetStatus = void 0;
9671
- if (item.previousStatus === "published" || item.previousStatus === "modified" || item.previousStatus === "draft") {
9672
- targetStatus = item.previousStatus;
9673
- } else if (item.hadPublishedVersion === false) {
9674
- targetStatus = "draft";
9675
- } else if (item.hadPublishedVersion === true) {
9676
- targetStatus = "published";
9677
- }
9678
- if (isDraftAndPublish && !targetStatus) {
9679
- let publishedCounterpart = null;
9680
- try {
9681
- const docSvc = strapi.documents(item.uid);
9682
- if (typeof docSvc.findMany === "function") {
9683
- const pubs = await docSvc.findMany({
9684
- status: "published",
9685
- filters: { documentId: item.documentId },
9686
- fields: ["documentId", "publishedAt"],
9687
- limit: 1,
9688
- ...isLocalized ? { locale: item.locale } : {}
9689
- });
9690
- if (pubs && pubs.length > 0) {
9691
- publishedCounterpart = pubs[0];
9761
+ } else {
9762
+ await strapi.documents(item.uid).update({
9763
+ documentId: item.documentId,
9764
+ ...isLocalized ? { locale: item.locale } : {},
9765
+ data: {
9766
+ [item.attribute]: rollbackPayload
9692
9767
  }
9693
- }
9694
- } catch {
9768
+ });
9695
9769
  }
9696
- if (publishedCounterpart?.publishedAt || currentDoc?.publishedAt) {
9697
- targetStatus = "published";
9698
- } else {
9770
+ let targetStatus = void 0;
9771
+ if (item.previousStatus === "published" || item.previousStatus === "modified" || item.previousStatus === "draft") {
9772
+ targetStatus = item.previousStatus;
9773
+ } else if (item.hadPublishedVersion === false) {
9699
9774
  targetStatus = "draft";
9775
+ } else if (item.hadPublishedVersion === true) {
9776
+ targetStatus = "published";
9700
9777
  }
9701
- }
9702
- if (isDraftAndPublish) {
9703
- const docSvc = strapi.documents(item.uid);
9704
- if (targetStatus === "published") {
9778
+ if (isDraftAndPublish && !targetStatus) {
9779
+ let publishedCounterpart = null;
9705
9780
  try {
9706
- if (typeof docSvc.publish === "function") {
9707
- await docSvc.publish({
9708
- documentId: item.documentId,
9781
+ const docSvc = strapi.documents(item.uid);
9782
+ if (typeof docSvc.findMany === "function") {
9783
+ const pubs = await docSvc.findMany({
9784
+ status: "published",
9785
+ filters: { documentId: item.documentId },
9786
+ fields: ["documentId", "publishedAt"],
9787
+ limit: 1,
9709
9788
  ...isLocalized ? { locale: item.locale } : {}
9710
9789
  });
9790
+ if (pubs && pubs.length > 0) {
9791
+ publishedCounterpart = pubs[0];
9792
+ }
9711
9793
  }
9712
- } catch (publishErr) {
9713
- strapi.log.warn(
9714
- `[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`,
9715
- publishErr?.message
9716
- );
9794
+ } catch {
9717
9795
  }
9718
- } else if (targetStatus === "draft") {
9719
- try {
9720
- if (typeof docSvc.unpublish === "function") {
9721
- let hasPublished = false;
9722
- if (typeof docSvc.findMany === "function") {
9723
- const pubs = await docSvc.findMany({
9724
- status: "published",
9725
- filters: { documentId: item.documentId },
9726
- fields: ["documentId", "publishedAt"],
9727
- limit: 1,
9796
+ if (publishedCounterpart?.publishedAt || currentDoc?.publishedAt) {
9797
+ targetStatus = "published";
9798
+ } else {
9799
+ targetStatus = "draft";
9800
+ }
9801
+ }
9802
+ if (isDraftAndPublish) {
9803
+ const docSvc = strapi.documents(item.uid);
9804
+ if (targetStatus === "published") {
9805
+ try {
9806
+ if (typeof docSvc.publish === "function") {
9807
+ await docSvc.publish({
9808
+ documentId: item.documentId,
9728
9809
  ...isLocalized ? { locale: item.locale } : {}
9729
9810
  });
9730
- if (pubs && pubs.length > 0) {
9811
+ }
9812
+ } catch (publishErr) {
9813
+ strapi.log.warn(
9814
+ `[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`,
9815
+ publishErr?.message
9816
+ );
9817
+ }
9818
+ } else if (targetStatus === "draft") {
9819
+ try {
9820
+ if (typeof docSvc.unpublish === "function") {
9821
+ let hasPublished = false;
9822
+ if (typeof docSvc.findMany === "function") {
9823
+ const pubs = await docSvc.findMany({
9824
+ status: "published",
9825
+ filters: { documentId: item.documentId },
9826
+ fields: ["documentId", "publishedAt"],
9827
+ limit: 1,
9828
+ ...isLocalized ? { locale: item.locale } : {}
9829
+ });
9830
+ if (pubs && pubs.length > 0) {
9831
+ hasPublished = true;
9832
+ }
9833
+ } else if (currentDoc?.publishedAt) {
9731
9834
  hasPublished = true;
9732
9835
  }
9733
- } else if (currentDoc?.publishedAt) {
9734
- hasPublished = true;
9735
- }
9736
- if (hasPublished) {
9737
- await docSvc.unpublish({
9738
- documentId: item.documentId,
9739
- ...isLocalized ? { locale: item.locale } : {}
9740
- });
9836
+ if (hasPublished) {
9837
+ await docSvc.unpublish({
9838
+ documentId: item.documentId,
9839
+ ...isLocalized ? { locale: item.locale } : {}
9840
+ });
9841
+ }
9741
9842
  }
9843
+ } catch (unpubErr) {
9844
+ strapi.log.warn(
9845
+ `[bulk-updater] Failed to unpublish rollback for ${item.uid}/${item.documentId}:`,
9846
+ unpubErr?.message
9847
+ );
9742
9848
  }
9743
- } catch (unpubErr) {
9744
- strapi.log.warn(
9745
- `[bulk-updater] Failed to unpublish rollback for ${item.uid}/${item.documentId}:`,
9746
- unpubErr?.message
9747
- );
9748
9849
  }
9749
9850
  }
9750
- }
9751
- try {
9752
- await recordContentHistoryVersion(strapi, {
9851
+ try {
9852
+ await recordContentHistoryVersion(strapi, {
9853
+ uid: item.uid,
9854
+ documentId: item.documentId,
9855
+ userId,
9856
+ statusOverride: isDraftAndPublish ? targetStatus : "published"
9857
+ });
9858
+ } catch {
9859
+ }
9860
+ try {
9861
+ const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
9862
+ if (bulkService?.invalidateCache) {
9863
+ bulkService.invalidateCache(item.uid);
9864
+ }
9865
+ } catch {
9866
+ }
9867
+ const entryKey = `${item.uid}@@@${item.documentId}@@@${isLocalized ? item.locale : ""}`;
9868
+ revertedEntryKeys.add(entryKey);
9869
+ rollbackDetails.push({
9753
9870
  uid: item.uid,
9754
9871
  documentId: item.documentId,
9755
- userId,
9756
- statusOverride: isDraftAndPublish ? targetStatus : "published"
9872
+ label: item.label,
9873
+ attribute: item.attribute,
9874
+ revertedTo: item.oldValue,
9875
+ status: "reverted",
9876
+ restoredLifecycleStatus: isDraftAndPublish ? targetStatus : "published"
9877
+ });
9878
+ } catch (err) {
9879
+ rollbackDetails.push({
9880
+ uid: item.uid,
9881
+ documentId: item.documentId,
9882
+ label: item.label,
9883
+ status: "error",
9884
+ message: err.message
9757
9885
  });
9758
- } catch {
9759
- }
9760
- try {
9761
- const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
9762
- if (bulkService?.invalidateCache) {
9763
- bulkService.invalidateCache(item.uid);
9764
- }
9765
- } catch {
9766
9886
  }
9767
- revertedCount++;
9768
- rollbackDetails.push({
9769
- uid: item.uid,
9770
- documentId: item.documentId,
9771
- label: item.label,
9772
- attribute: item.attribute,
9773
- revertedTo: item.oldValue,
9774
- status: "reverted",
9775
- restoredLifecycleStatus: isDraftAndPublish ? targetStatus : "published"
9776
- });
9777
- } catch (err) {
9778
- rollbackDetails.push({
9779
- uid: item.uid,
9780
- documentId: item.documentId,
9781
- label: item.label,
9782
- status: "error",
9783
- message: err.message
9784
- });
9785
9887
  }
9786
9888
  }
9787
- }
9788
- return { revertedCount, rollbackDetails };
9889
+ return { revertedCount: revertedEntryKeys.size, rollbackDetails };
9890
+ });
9789
9891
  },
9790
9892
  /**
9791
9893
  * Performs deterministic rollback of a batch.
@@ -12661,6 +12763,9 @@ const index = {
12661
12763
  }
12662
12764
  });
12663
12765
  strapi.documents.use(async (context, next) => {
12766
+ if (isRollbackContext()) {
12767
+ return await next();
12768
+ }
12664
12769
  if (typeof context.uid === "string" && context.uid.startsWith("plugin::bulk-updater.")) {
12665
12770
  return await next();
12666
12771
  }