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
@@ -16,6 +16,10 @@ const PERMISSIONS = {
16
16
  // CSV Management
17
17
  csvExport: `plugin::${PLUGIN_ID}.csv.export`,
18
18
  csvImport: `plugin::${PLUGIN_ID}.csv.import`,
19
+ csvSubmitForChecker: `plugin::${PLUGIN_ID}.csv.submit-for-checker`,
20
+ csvForceRunNow: `plugin::${PLUGIN_ID}.csv.force-run-now`,
21
+ csvQueueForOffPeak: `plugin::${PLUGIN_ID}.csv.queue-for-off-peak`,
22
+ csvPreFlightDryRun: `plugin::${PLUGIN_ID}.csv.pre-flight-dry-run`,
19
23
  // Audit Trail
20
24
  auditView: `plugin::${PLUGIN_ID}.audit.view`,
21
25
  auditDetails: `plugin::${PLUGIN_ID}.audit.details`,
@@ -102,6 +106,34 @@ const BULK_UPDATER_PERMISSION_ACTIONS = [
102
106
  pluginName: PLUGIN_ID,
103
107
  subCategory: "CSV Management"
104
108
  },
109
+ {
110
+ section: "plugins",
111
+ displayName: "CSV Submit For Checker",
112
+ uid: "csv.submit-for-checker",
113
+ pluginName: PLUGIN_ID,
114
+ subCategory: "CSV Management"
115
+ },
116
+ {
117
+ section: "plugins",
118
+ displayName: "CSV Force Run Now",
119
+ uid: "csv.force-run-now",
120
+ pluginName: PLUGIN_ID,
121
+ subCategory: "CSV Management"
122
+ },
123
+ {
124
+ section: "plugins",
125
+ displayName: "CSV Queue For Off-Peak",
126
+ uid: "csv.queue-for-off-peak",
127
+ pluginName: PLUGIN_ID,
128
+ subCategory: "CSV Management"
129
+ },
130
+ {
131
+ section: "plugins",
132
+ displayName: "CSV Run Pre-Flight Dry Run",
133
+ uid: "csv.pre-flight-dry-run",
134
+ pluginName: PLUGIN_ID,
135
+ subCategory: "CSV Management"
136
+ },
105
137
  {
106
138
  section: "plugins",
107
139
  displayName: "View Audit History",
@@ -184,7 +216,27 @@ const BATCH_UPDATE_POLICY_CONFIG = {
184
216
  mode: "any",
185
217
  enforceBatchUpdateExecutionMode: true
186
218
  };
187
- function resolveBatchUpdateRequiredPermissions(body) {
219
+ const CSV_SUBMIT_BATCH_POLICY_CONFIG = {
220
+ actions: [
221
+ PERMISSIONS.csvImport,
222
+ PERMISSIONS.csvSubmitForChecker,
223
+ PERMISSIONS.csvForceRunNow,
224
+ PERMISSIONS.csvQueueForOffPeak
225
+ ],
226
+ mode: "any",
227
+ enforceCsvSubmitExecutionMode: true
228
+ };
229
+ const WORKSPACE_MODE_PERMISSIONS = {
230
+ maker_checker: PERMISSIONS.workspaceSubmitForChecker,
231
+ queue_offpeak: PERMISSIONS.workspaceQueueForOffPeak,
232
+ immediate: PERMISSIONS.workspaceForceRunNow
233
+ };
234
+ const CSV_MODE_PERMISSIONS = {
235
+ maker_checker: PERMISSIONS.csvSubmitForChecker,
236
+ queue_offpeak: PERMISSIONS.csvQueueForOffPeak,
237
+ immediate: PERMISSIONS.csvForceRunNow
238
+ };
239
+ function resolveExecutionModeRequiredPermissions(body, modePermissionMap, checkPreviewOrigin) {
188
240
  const rawMode = body?.executionMode;
189
241
  const effectiveMode = rawMode === void 0 ? "immediate" : rawMode;
190
242
  if (typeof effectiveMode !== "string" || !["maker_checker", "queue_offpeak", "immediate"].includes(effectiveMode)) {
@@ -194,20 +246,23 @@ function resolveBatchUpdateRequiredPermissions(body) {
194
246
  reason: `Unsupported or unauthorized execution mode "${String(rawMode)}".`
195
247
  };
196
248
  }
197
- const required = [];
198
- if (effectiveMode === "maker_checker") {
199
- required.push(PERMISSIONS.workspaceSubmitForChecker);
200
- } else if (effectiveMode === "queue_offpeak") {
201
- required.push(PERMISSIONS.workspaceQueueForOffPeak);
202
- } else {
203
- required.push(PERMISSIONS.workspaceForceRunNow);
204
- }
205
- const isPreviewInitiated = body?.initiatedFromPreview === true || body?.initiatedFromPreview === "true" || body?.source === "preview" || body?.executionSource === "preview";
206
- if (isPreviewInitiated) {
207
- required.push(PERMISSIONS.workspaceProceedToExecute);
249
+ const required = [
250
+ modePermissionMap[effectiveMode]
251
+ ];
252
+ if (checkPreviewOrigin) {
253
+ const isPreviewInitiated = body?.initiatedFromPreview === true || body?.initiatedFromPreview === "true" || body?.source === "preview" || body?.executionSource === "preview";
254
+ if (isPreviewInitiated) {
255
+ required.push(PERMISSIONS.workspaceProceedToExecute);
256
+ }
208
257
  }
209
258
  return { valid: true, actions: required };
210
259
  }
260
+ function resolveBatchUpdateRequiredPermissions(body) {
261
+ return resolveExecutionModeRequiredPermissions(body, WORKSPACE_MODE_PERMISSIONS, true);
262
+ }
263
+ function resolveCsvSubmitRequiredPermissions(body) {
264
+ return resolveExecutionModeRequiredPermissions(body, CSV_MODE_PERMISSIONS, false);
265
+ }
211
266
  function setForbiddenResponse(ctx, message = "You do not have permission to perform this action.") {
212
267
  if (ctx) {
213
268
  ctx.status = 403;
@@ -226,6 +281,7 @@ const hasPermissionsPolicy = (policyContext, config, { strapi } = {}) => {
226
281
  let actions = [];
227
282
  let mode = "all";
228
283
  let enforceBatchMode = false;
284
+ let enforceCsvMode = false;
229
285
  if (Array.isArray(config)) {
230
286
  actions = config;
231
287
  } else if (config && typeof config === "object") {
@@ -234,6 +290,7 @@ const hasPermissionsPolicy = (policyContext, config, { strapi } = {}) => {
234
290
  mode = "any";
235
291
  }
236
292
  enforceBatchMode = Boolean(config.enforceBatchUpdateExecutionMode);
293
+ enforceCsvMode = Boolean(config.enforceCsvSubmitExecutionMode);
237
294
  } else if (typeof config === "string") {
238
295
  actions = [config];
239
296
  }
@@ -246,8 +303,8 @@ const hasPermissionsPolicy = (policyContext, config, { strapi } = {}) => {
246
303
  return true;
247
304
  }
248
305
  let batchModeActions = null;
249
- if (enforceBatchMode) {
250
- const resolved = resolveBatchUpdateRequiredPermissions(ctx?.request?.body);
306
+ if (enforceBatchMode || enforceCsvMode) {
307
+ const resolved = enforceCsvMode ? resolveCsvSubmitRequiredPermissions(ctx?.request?.body) : resolveBatchUpdateRequiredPermissions(ctx?.request?.body);
251
308
  if (!resolved.valid) {
252
309
  setForbiddenResponse(ctx, resolved.reason || "You do not have permission to perform this action.");
253
310
  return false;
@@ -285,6 +342,14 @@ const hasPermissionsPolicy = (policyContext, config, { strapi } = {}) => {
285
342
  }
286
343
  return true;
287
344
  };
345
+ const CSV_READ_PERMISSIONS = [
346
+ PERMISSIONS.csvExport,
347
+ PERMISSIONS.csvImport,
348
+ PERMISSIONS.csvSubmitForChecker,
349
+ PERMISSIONS.csvForceRunNow,
350
+ PERMISSIONS.csvQueueForOffPeak,
351
+ PERMISSIONS.csvPreFlightDryRun
352
+ ];
288
353
  function requirePermissions(actions, mode = "all") {
289
354
  return [
290
355
  {
@@ -308,8 +373,7 @@ const routes = {
308
373
  policies: requirePermissions(
309
374
  [
310
375
  PERMISSIONS.workspaceView,
311
- PERMISSIONS.csvExport,
312
- PERMISSIONS.csvImport,
376
+ ...CSV_READ_PERMISSIONS,
313
377
  PERMISSIONS.validationView
314
378
  ],
315
379
  "any"
@@ -322,7 +386,7 @@ const routes = {
322
386
  handler: "bulkUpdater.getCollectionEntries",
323
387
  config: {
324
388
  policies: requirePermissions(
325
- [PERMISSIONS.workspaceView, PERMISSIONS.csvExport, PERMISSIONS.csvImport],
389
+ [PERMISSIONS.workspaceView, ...CSV_READ_PERMISSIONS],
326
390
  "any"
327
391
  )
328
392
  }
@@ -333,7 +397,7 @@ const routes = {
333
397
  handler: "bulkUpdater.getRelationOptions",
334
398
  config: {
335
399
  policies: requirePermissions(
336
- [PERMISSIONS.workspaceView, PERMISSIONS.csvExport, PERMISSIONS.csvImport],
400
+ [PERMISSIONS.workspaceView, ...CSV_READ_PERMISSIONS],
337
401
  "any"
338
402
  )
339
403
  }
@@ -344,7 +408,7 @@ const routes = {
344
408
  handler: "bulkUpdater.getMediaOptions",
345
409
  config: {
346
410
  policies: requirePermissions(
347
- [PERMISSIONS.workspaceView, PERMISSIONS.csvExport, PERMISSIONS.csvImport],
411
+ [PERMISSIONS.workspaceView, ...CSV_READ_PERMISSIONS],
348
412
  "any"
349
413
  )
350
414
  }
@@ -431,6 +495,9 @@ const routes = {
431
495
  PERMISSIONS.workspaceView,
432
496
  PERMISSIONS.workspaceExecute,
433
497
  PERMISSIONS.csvImport,
498
+ PERMISSIONS.csvSubmitForChecker,
499
+ PERMISSIONS.csvForceRunNow,
500
+ PERMISSIONS.csvQueueForOffPeak,
434
501
  PERMISSIONS.auditView,
435
502
  PERMISSIONS.approvalView
436
503
  ],
@@ -523,7 +590,7 @@ const routes = {
523
590
  path: "/csv/template/:uid",
524
591
  handler: "csv.getTemplate",
525
592
  config: {
526
- policies: requirePermissions([PERMISSIONS.csvExport, PERMISSIONS.csvImport], "any")
593
+ policies: requirePermissions(CSV_READ_PERMISSIONS, "any")
527
594
  }
528
595
  },
529
596
  {
@@ -563,7 +630,7 @@ const routes = {
563
630
  path: "/csv/import",
564
631
  handler: "csv.importCsv",
565
632
  config: {
566
- policies: requirePermissions(PERMISSIONS.csvImport)
633
+ policies: requirePermissions(PERMISSIONS.csvForceRunNow)
567
634
  }
568
635
  },
569
636
  {
@@ -571,7 +638,7 @@ const routes = {
571
638
  path: "/csv/import-chunk",
572
639
  handler: "csv.importChunk",
573
640
  config: {
574
- policies: requirePermissions(PERMISSIONS.csvImport)
641
+ policies: requirePermissions(PERMISSIONS.csvForceRunNow)
575
642
  }
576
643
  },
577
644
  {
@@ -579,7 +646,7 @@ const routes = {
579
646
  path: "/csv/validate-preflight",
580
647
  handler: "csv.validatePreflight",
581
648
  config: {
582
- policies: requirePermissions(PERMISSIONS.csvImport)
649
+ policies: requirePermissions(PERMISSIONS.csvPreFlightDryRun)
583
650
  }
584
651
  },
585
652
  {
@@ -587,7 +654,12 @@ const routes = {
587
654
  path: "/csv/submit-batch",
588
655
  handler: "csv.submitBatch",
589
656
  config: {
590
- policies: requirePermissions(PERMISSIONS.csvImport)
657
+ policies: [
658
+ {
659
+ name: "plugin::bulk-updater.hasPermissions",
660
+ config: CSV_SUBMIT_BATCH_POLICY_CONFIG
661
+ }
662
+ ]
591
663
  }
592
664
  }
593
665
  ]
@@ -668,7 +740,15 @@ const contentTypes = {
668
740
  schema: auditLog
669
741
  }
670
742
  };
743
+ const { AsyncLocalStorage } = require("async_hooks");
671
744
  const CRASH_GUARD_SYMBOL = Symbol.for("strapi-plugin-bulk-updater.undiciCrashGuardInstalled");
745
+ const rollbackContextStorage = new AsyncLocalStorage();
746
+ function runInRollbackContext(fn) {
747
+ return rollbackContextStorage.run(true, fn);
748
+ }
749
+ function isRollbackContext() {
750
+ return rollbackContextStorage.getStore() === true;
751
+ }
672
752
  let activeBulkOperations = 0;
673
753
  function getActiveBulkOperationCount() {
674
754
  return activeBulkOperations;
@@ -1115,6 +1195,13 @@ const validationRulesController = ({ strapi }) => ({
1115
1195
  }
1116
1196
  }
1117
1197
  });
1198
+ function ensureCsvAuthorized(ctx, policyConfig, strapi) {
1199
+ const hasAuthContext = Boolean(
1200
+ ctx?.state?.userAbility || Array.isArray(ctx?.state?.permissions) || Array.isArray(ctx?.state?.user?.permissions) || ctx?.state?.user?.isSuperAdmin !== void 0
1201
+ );
1202
+ if (!hasAuthContext) return true;
1203
+ return hasPermissionsPolicy(ctx, policyConfig, { strapi });
1204
+ }
1118
1205
  const csvController = ({ strapi }) => ({
1119
1206
  async getTemplate(ctx) {
1120
1207
  try {
@@ -1223,6 +1310,9 @@ const csvController = ({ strapi }) => ({
1223
1310
  },
1224
1311
  async importCsv(ctx) {
1225
1312
  try {
1313
+ if (!ensureCsvAuthorized(ctx, { actions: [PERMISSIONS.csvForceRunNow] }, strapi)) {
1314
+ return;
1315
+ }
1226
1316
  const { uid, csvText, mode, publish, publishStrategy, unreviewedConsent } = ctx.request.body;
1227
1317
  if (!uid) {
1228
1318
  ctx.status = 400;
@@ -1252,6 +1342,9 @@ const csvController = ({ strapi }) => ({
1252
1342
  },
1253
1343
  async importChunk(ctx) {
1254
1344
  try {
1345
+ if (!ensureCsvAuthorized(ctx, { actions: [PERMISSIONS.csvForceRunNow] }, strapi)) {
1346
+ return;
1347
+ }
1255
1348
  const { uid, rows, batchId, isFirstChunk, isLastChunk, startRowNumber, mode, publish, publishStrategy, unreviewedConsent, originalHeaders } = ctx.request.body;
1256
1349
  if (!uid) {
1257
1350
  ctx.status = 400;
@@ -1286,6 +1379,9 @@ const csvController = ({ strapi }) => ({
1286
1379
  },
1287
1380
  async validatePreflight(ctx) {
1288
1381
  try {
1382
+ if (!ensureCsvAuthorized(ctx, { actions: [PERMISSIONS.csvPreFlightDryRun] }, strapi)) {
1383
+ return;
1384
+ }
1289
1385
  const { uid, rows, mode } = ctx.request.body;
1290
1386
  if (!uid) {
1291
1387
  ctx.status = 400;
@@ -1309,6 +1405,9 @@ const csvController = ({ strapi }) => ({
1309
1405
  },
1310
1406
  async submitBatch(ctx) {
1311
1407
  try {
1408
+ if (!ensureCsvAuthorized(ctx, CSV_SUBMIT_BATCH_POLICY_CONFIG, strapi)) {
1409
+ return;
1410
+ }
1312
1411
  const { uid, rows, executionMode, makerNotes, forceImmediate, mode, publish, publishStrategy, unreviewedConsent, unreviewedCount } = ctx.request.body;
1313
1412
  if (!uid) {
1314
1413
  ctx.status = 400;
@@ -9552,236 +9651,239 @@ const auditService = ({ strapi }) => ({
9552
9651
  * Helper to revert diff items back to original values
9553
9652
  */
9554
9653
  async revertDiffItems(diffs, userId) {
9555
- let revertedCount = 0;
9556
- const rollbackDetails = [];
9557
- for (const item of diffs) {
9558
- if (item.status === "updated" && item.uid && item.documentId && item.attribute) {
9559
- try {
9560
- const ct = strapi.contentTypes[item.uid];
9561
- if (!ct) {
9562
- throw new Error(`Content type "${item.uid}" does not exist in schema.`);
9563
- }
9564
- const isRel = item.oldValue && typeof item.oldValue === "object" && item.oldValue.isRelation;
9565
- let rollbackPayload;
9566
- if (isRel) {
9567
- const oldDocIds = Array.isArray(item.oldValue.documentIds) ? item.oldValue.documentIds : [];
9568
- rollbackPayload = { set: oldDocIds };
9569
- } else {
9570
- rollbackPayload = item.oldValue ?? null;
9571
- }
9572
- const parsed = parseDynamicZonePath(item.attribute);
9573
- const rootKey = parsed.rootKey;
9574
- const rootAttrDef = ct.attributes?.[rootKey];
9575
- const isComponent = rootAttrDef?.type === "component";
9576
- const isDynamicZone = rootAttrDef?.type === "dynamiczone";
9577
- const isNested = item.attribute.includes(".") || item.attribute.includes("[") || isComponent || isDynamicZone || isDeepComponentField(ct, strapi.components, item.attribute);
9578
- const isLocalized = Boolean(ct?.pluginOptions?.i18n?.localized) && item.locale && item.locale !== "null" && item.locale !== "undefined";
9579
- const isDraftAndPublish = Boolean(ct?.options?.draftAndPublish ?? item.isDraftAndPublish);
9580
- const populateOption = isNested ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
9581
- const findOneArgs = { documentId: item.documentId };
9582
- if (populateOption) {
9583
- findOneArgs.populate = populateOption;
9584
- }
9585
- if (isLocalized) {
9586
- findOneArgs.locale = item.locale;
9587
- }
9588
- const currentDoc = await strapi.documents(item.uid).findOne(findOneArgs);
9589
- if (!currentDoc) {
9590
- throw new Error(`Document "${item.documentId}" not found in collection "${item.uid}".`);
9591
- }
9592
- if (isNested && (isComponent || isDynamicZone || rootAttrDef)) {
9593
- const isRootDz = isDynamicZone;
9594
- const existingRoot = currentDoc?.[rootKey] || (isRootDz ? [] : {});
9595
- let restoredRoot;
9596
- if (Array.isArray(item.dynamicZoneDiffs) && item.dynamicZoneDiffs.length > 0) {
9597
- const hasStructuredSegments = item.dynamicZoneDiffs.some(
9598
- (dz) => Array.isArray(dz?.segments) && dz.segments.length > 0
9599
- );
9600
- if (hasStructuredSegments) {
9601
- const occUpdates = item.dynamicZoneDiffs.map((dzDiff) => {
9602
- const isRelDiff = dzDiff.oldValue && typeof dzDiff.oldValue === "object" && dzDiff.oldValue.isRelation;
9603
- const val = isRelDiff ? { mode: "set", documentIds: Array.isArray(dzDiff.oldValue.documentIds) ? dzDiff.oldValue.documentIds : [] } : dzDiff.oldValue ?? null;
9604
- return {
9605
- occurrenceKey: dzDiff.occurrenceKey,
9606
- segments: dzDiff.segments,
9607
- dynamicZoneIndex: dzDiff.index,
9608
- componentId: dzDiff.componentId,
9609
- componentUid: dzDiff.componentUid,
9610
- value: val
9611
- };
9612
- });
9613
- const reverted = await applyOccurrenceUpdatesToDocument({
9614
- strapi,
9615
- contentType: ct,
9616
- allComponents: strapi.components,
9617
- currentDoc,
9618
- attribute: item.attribute,
9619
- updates: occUpdates
9620
- });
9621
- if (reverted.errors.length > 0) {
9622
- throw new Error(reverted.errors.join("; "));
9623
- }
9624
- restoredRoot = reverted.updateData[rootKey];
9625
- } else {
9626
- let workingRoot = existingRoot;
9627
- for (const dzDiff of item.dynamicZoneDiffs) {
9628
- const parsedDz = parseDynamicZonePath(dzDiff.attribute || item.attribute);
9629
- const dzParts = parsedDz.cleanPath.split(".").slice(1);
9630
- const targetIndexes = dzDiff.index !== void 0 ? [dzDiff.index] : parsedDz.targetIndex !== void 0 ? [parsedDz.targetIndex] : void 0;
9631
- workingRoot = setDeepProperty(workingRoot, dzParts, dzDiff.oldValue ?? null, {
9632
- targetIndexes,
9633
- targetComponentUid: dzDiff.componentUid || parsedDz.targetComponentUid,
9634
- strapi
9654
+ return runInRollbackContext(async () => {
9655
+ const revertedEntryKeys = /* @__PURE__ */ new Set();
9656
+ const rollbackDetails = [];
9657
+ for (const item of diffs) {
9658
+ if (item.status === "updated" && item.uid && item.documentId && item.attribute) {
9659
+ try {
9660
+ const ct = strapi.contentTypes[item.uid];
9661
+ if (!ct) {
9662
+ throw new Error(`Content type "${item.uid}" does not exist in schema.`);
9663
+ }
9664
+ const isRel = item.oldValue && typeof item.oldValue === "object" && item.oldValue.isRelation;
9665
+ let rollbackPayload;
9666
+ if (isRel) {
9667
+ const oldDocIds = Array.isArray(item.oldValue.documentIds) ? item.oldValue.documentIds : [];
9668
+ rollbackPayload = { set: oldDocIds };
9669
+ } else {
9670
+ rollbackPayload = item.oldValue ?? null;
9671
+ }
9672
+ const parsed = parseDynamicZonePath(item.attribute);
9673
+ const rootKey = parsed.rootKey;
9674
+ const rootAttrDef = ct.attributes?.[rootKey];
9675
+ const isComponent = rootAttrDef?.type === "component";
9676
+ const isDynamicZone = rootAttrDef?.type === "dynamiczone";
9677
+ const isNested = item.attribute.includes(".") || item.attribute.includes("[") || isComponent || isDynamicZone || isDeepComponentField(ct, strapi.components, item.attribute);
9678
+ const isLocalized = Boolean(ct?.pluginOptions?.i18n?.localized) && item.locale && item.locale !== "null" && item.locale !== "undefined";
9679
+ const isDraftAndPublish = Boolean(ct?.options?.draftAndPublish ?? item.isDraftAndPublish);
9680
+ const populateOption = isNested ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
9681
+ const findOneArgs = { documentId: item.documentId };
9682
+ if (populateOption) {
9683
+ findOneArgs.populate = populateOption;
9684
+ }
9685
+ if (isLocalized) {
9686
+ findOneArgs.locale = item.locale;
9687
+ }
9688
+ const currentDoc = await strapi.documents(item.uid).findOne(findOneArgs);
9689
+ if (!currentDoc) {
9690
+ throw new Error(`Document "${item.documentId}" not found in collection "${item.uid}".`);
9691
+ }
9692
+ if (isNested && (isComponent || isDynamicZone || rootAttrDef)) {
9693
+ const isRootDz = isDynamicZone;
9694
+ const existingRoot = currentDoc?.[rootKey] || (isRootDz ? [] : {});
9695
+ let restoredRoot;
9696
+ if (Array.isArray(item.dynamicZoneDiffs) && item.dynamicZoneDiffs.length > 0) {
9697
+ const hasStructuredSegments = item.dynamicZoneDiffs.some(
9698
+ (dz) => Array.isArray(dz?.segments) && dz.segments.length > 0
9699
+ );
9700
+ if (hasStructuredSegments) {
9701
+ const occUpdates = item.dynamicZoneDiffs.map((dzDiff) => {
9702
+ const isRelDiff = dzDiff.oldValue && typeof dzDiff.oldValue === "object" && dzDiff.oldValue.isRelation;
9703
+ const val = isRelDiff ? { mode: "set", documentIds: Array.isArray(dzDiff.oldValue.documentIds) ? dzDiff.oldValue.documentIds : [] } : dzDiff.oldValue ?? null;
9704
+ return {
9705
+ occurrenceKey: dzDiff.occurrenceKey,
9706
+ segments: dzDiff.segments,
9707
+ dynamicZoneIndex: dzDiff.index,
9708
+ componentId: dzDiff.componentId,
9709
+ componentUid: dzDiff.componentUid,
9710
+ value: val
9711
+ };
9635
9712
  });
9713
+ const reverted = await applyOccurrenceUpdatesToDocument({
9714
+ strapi,
9715
+ contentType: ct,
9716
+ allComponents: strapi.components,
9717
+ currentDoc,
9718
+ attribute: item.attribute,
9719
+ updates: occUpdates
9720
+ });
9721
+ if (reverted.errors.length > 0) {
9722
+ throw new Error(reverted.errors.join("; "));
9723
+ }
9724
+ restoredRoot = reverted.updateData[rootKey];
9725
+ } else {
9726
+ let workingRoot = existingRoot;
9727
+ for (const dzDiff of item.dynamicZoneDiffs) {
9728
+ const parsedDz = parseDynamicZonePath(dzDiff.attribute || item.attribute);
9729
+ const dzParts = parsedDz.cleanPath.split(".").slice(1);
9730
+ const targetIndexes = dzDiff.index !== void 0 ? [dzDiff.index] : parsedDz.targetIndex !== void 0 ? [parsedDz.targetIndex] : void 0;
9731
+ workingRoot = setDeepProperty(workingRoot, dzParts, dzDiff.oldValue ?? null, {
9732
+ targetIndexes,
9733
+ targetComponentUid: dzDiff.componentUid || parsedDz.targetComponentUid,
9734
+ strapi
9735
+ });
9736
+ }
9737
+ restoredRoot = workingRoot;
9636
9738
  }
9637
- restoredRoot = workingRoot;
9739
+ } else {
9740
+ const parts = parsed.cleanPath.split(".");
9741
+ const pathParts = parts.slice(1);
9742
+ const targetIndexes = parsed.targetIndex !== void 0 ? [parsed.targetIndex] : void 0;
9743
+ const targetComponentUid = parsed.targetComponentUid;
9744
+ restoredRoot = setDeepProperty(existingRoot, pathParts, rollbackPayload, {
9745
+ targetIndexes,
9746
+ targetComponentUid,
9747
+ strapi
9748
+ });
9638
9749
  }
9639
- } else {
9640
- const parts = parsed.cleanPath.split(".");
9641
- const pathParts = parts.slice(1);
9642
- const targetIndexes = parsed.targetIndex !== void 0 ? [parsed.targetIndex] : void 0;
9643
- const targetComponentUid = parsed.targetComponentUid;
9644
- restoredRoot = setDeepProperty(existingRoot, pathParts, rollbackPayload, {
9645
- targetIndexes,
9646
- targetComponentUid,
9647
- strapi
9750
+ await strapi.documents(item.uid).update({
9751
+ documentId: item.documentId,
9752
+ ...isLocalized ? { locale: item.locale } : {},
9753
+ data: {
9754
+ [rootKey]: restoredRoot
9755
+ }
9648
9756
  });
9649
- }
9650
- await strapi.documents(item.uid).update({
9651
- documentId: item.documentId,
9652
- ...isLocalized ? { locale: item.locale } : {},
9653
- data: {
9654
- [rootKey]: restoredRoot
9655
- }
9656
- });
9657
- } else {
9658
- await strapi.documents(item.uid).update({
9659
- documentId: item.documentId,
9660
- ...isLocalized ? { locale: item.locale } : {},
9661
- data: {
9662
- [item.attribute]: rollbackPayload
9663
- }
9664
- });
9665
- }
9666
- let targetStatus = void 0;
9667
- if (item.previousStatus === "published" || item.previousStatus === "modified" || item.previousStatus === "draft") {
9668
- targetStatus = item.previousStatus;
9669
- } else if (item.hadPublishedVersion === false) {
9670
- targetStatus = "draft";
9671
- } else if (item.hadPublishedVersion === true) {
9672
- targetStatus = "published";
9673
- }
9674
- if (isDraftAndPublish && !targetStatus) {
9675
- let publishedCounterpart = null;
9676
- try {
9677
- const docSvc = strapi.documents(item.uid);
9678
- if (typeof docSvc.findMany === "function") {
9679
- const pubs = await docSvc.findMany({
9680
- status: "published",
9681
- filters: { documentId: item.documentId },
9682
- fields: ["documentId", "publishedAt"],
9683
- limit: 1,
9684
- ...isLocalized ? { locale: item.locale } : {}
9685
- });
9686
- if (pubs && pubs.length > 0) {
9687
- publishedCounterpart = pubs[0];
9757
+ } else {
9758
+ await strapi.documents(item.uid).update({
9759
+ documentId: item.documentId,
9760
+ ...isLocalized ? { locale: item.locale } : {},
9761
+ data: {
9762
+ [item.attribute]: rollbackPayload
9688
9763
  }
9689
- }
9690
- } catch {
9764
+ });
9691
9765
  }
9692
- if (publishedCounterpart?.publishedAt || currentDoc?.publishedAt) {
9693
- targetStatus = "published";
9694
- } else {
9766
+ let targetStatus = void 0;
9767
+ if (item.previousStatus === "published" || item.previousStatus === "modified" || item.previousStatus === "draft") {
9768
+ targetStatus = item.previousStatus;
9769
+ } else if (item.hadPublishedVersion === false) {
9695
9770
  targetStatus = "draft";
9771
+ } else if (item.hadPublishedVersion === true) {
9772
+ targetStatus = "published";
9696
9773
  }
9697
- }
9698
- if (isDraftAndPublish) {
9699
- const docSvc = strapi.documents(item.uid);
9700
- if (targetStatus === "published") {
9774
+ if (isDraftAndPublish && !targetStatus) {
9775
+ let publishedCounterpart = null;
9701
9776
  try {
9702
- if (typeof docSvc.publish === "function") {
9703
- await docSvc.publish({
9704
- documentId: item.documentId,
9777
+ const docSvc = strapi.documents(item.uid);
9778
+ if (typeof docSvc.findMany === "function") {
9779
+ const pubs = await docSvc.findMany({
9780
+ status: "published",
9781
+ filters: { documentId: item.documentId },
9782
+ fields: ["documentId", "publishedAt"],
9783
+ limit: 1,
9705
9784
  ...isLocalized ? { locale: item.locale } : {}
9706
9785
  });
9786
+ if (pubs && pubs.length > 0) {
9787
+ publishedCounterpart = pubs[0];
9788
+ }
9707
9789
  }
9708
- } catch (publishErr) {
9709
- strapi.log.warn(
9710
- `[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`,
9711
- publishErr?.message
9712
- );
9790
+ } catch {
9713
9791
  }
9714
- } else if (targetStatus === "draft") {
9715
- try {
9716
- if (typeof docSvc.unpublish === "function") {
9717
- let hasPublished = false;
9718
- if (typeof docSvc.findMany === "function") {
9719
- const pubs = await docSvc.findMany({
9720
- status: "published",
9721
- filters: { documentId: item.documentId },
9722
- fields: ["documentId", "publishedAt"],
9723
- limit: 1,
9792
+ if (publishedCounterpart?.publishedAt || currentDoc?.publishedAt) {
9793
+ targetStatus = "published";
9794
+ } else {
9795
+ targetStatus = "draft";
9796
+ }
9797
+ }
9798
+ if (isDraftAndPublish) {
9799
+ const docSvc = strapi.documents(item.uid);
9800
+ if (targetStatus === "published") {
9801
+ try {
9802
+ if (typeof docSvc.publish === "function") {
9803
+ await docSvc.publish({
9804
+ documentId: item.documentId,
9724
9805
  ...isLocalized ? { locale: item.locale } : {}
9725
9806
  });
9726
- if (pubs && pubs.length > 0) {
9807
+ }
9808
+ } catch (publishErr) {
9809
+ strapi.log.warn(
9810
+ `[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`,
9811
+ publishErr?.message
9812
+ );
9813
+ }
9814
+ } else if (targetStatus === "draft") {
9815
+ try {
9816
+ if (typeof docSvc.unpublish === "function") {
9817
+ let hasPublished = false;
9818
+ if (typeof docSvc.findMany === "function") {
9819
+ const pubs = await docSvc.findMany({
9820
+ status: "published",
9821
+ filters: { documentId: item.documentId },
9822
+ fields: ["documentId", "publishedAt"],
9823
+ limit: 1,
9824
+ ...isLocalized ? { locale: item.locale } : {}
9825
+ });
9826
+ if (pubs && pubs.length > 0) {
9827
+ hasPublished = true;
9828
+ }
9829
+ } else if (currentDoc?.publishedAt) {
9727
9830
  hasPublished = true;
9728
9831
  }
9729
- } else if (currentDoc?.publishedAt) {
9730
- hasPublished = true;
9731
- }
9732
- if (hasPublished) {
9733
- await docSvc.unpublish({
9734
- documentId: item.documentId,
9735
- ...isLocalized ? { locale: item.locale } : {}
9736
- });
9832
+ if (hasPublished) {
9833
+ await docSvc.unpublish({
9834
+ documentId: item.documentId,
9835
+ ...isLocalized ? { locale: item.locale } : {}
9836
+ });
9837
+ }
9737
9838
  }
9839
+ } catch (unpubErr) {
9840
+ strapi.log.warn(
9841
+ `[bulk-updater] Failed to unpublish rollback for ${item.uid}/${item.documentId}:`,
9842
+ unpubErr?.message
9843
+ );
9738
9844
  }
9739
- } catch (unpubErr) {
9740
- strapi.log.warn(
9741
- `[bulk-updater] Failed to unpublish rollback for ${item.uid}/${item.documentId}:`,
9742
- unpubErr?.message
9743
- );
9744
9845
  }
9745
9846
  }
9746
- }
9747
- try {
9748
- await recordContentHistoryVersion(strapi, {
9847
+ try {
9848
+ await recordContentHistoryVersion(strapi, {
9849
+ uid: item.uid,
9850
+ documentId: item.documentId,
9851
+ userId,
9852
+ statusOverride: isDraftAndPublish ? targetStatus : "published"
9853
+ });
9854
+ } catch {
9855
+ }
9856
+ try {
9857
+ const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
9858
+ if (bulkService?.invalidateCache) {
9859
+ bulkService.invalidateCache(item.uid);
9860
+ }
9861
+ } catch {
9862
+ }
9863
+ const entryKey = `${item.uid}@@@${item.documentId}@@@${isLocalized ? item.locale : ""}`;
9864
+ revertedEntryKeys.add(entryKey);
9865
+ rollbackDetails.push({
9749
9866
  uid: item.uid,
9750
9867
  documentId: item.documentId,
9751
- userId,
9752
- statusOverride: isDraftAndPublish ? targetStatus : "published"
9868
+ label: item.label,
9869
+ attribute: item.attribute,
9870
+ revertedTo: item.oldValue,
9871
+ status: "reverted",
9872
+ restoredLifecycleStatus: isDraftAndPublish ? targetStatus : "published"
9873
+ });
9874
+ } catch (err) {
9875
+ rollbackDetails.push({
9876
+ uid: item.uid,
9877
+ documentId: item.documentId,
9878
+ label: item.label,
9879
+ status: "error",
9880
+ message: err.message
9753
9881
  });
9754
- } catch {
9755
- }
9756
- try {
9757
- const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
9758
- if (bulkService?.invalidateCache) {
9759
- bulkService.invalidateCache(item.uid);
9760
- }
9761
- } catch {
9762
9882
  }
9763
- revertedCount++;
9764
- rollbackDetails.push({
9765
- uid: item.uid,
9766
- documentId: item.documentId,
9767
- label: item.label,
9768
- attribute: item.attribute,
9769
- revertedTo: item.oldValue,
9770
- status: "reverted",
9771
- restoredLifecycleStatus: isDraftAndPublish ? targetStatus : "published"
9772
- });
9773
- } catch (err) {
9774
- rollbackDetails.push({
9775
- uid: item.uid,
9776
- documentId: item.documentId,
9777
- label: item.label,
9778
- status: "error",
9779
- message: err.message
9780
- });
9781
9883
  }
9782
9884
  }
9783
- }
9784
- return { revertedCount, rollbackDetails };
9885
+ return { revertedCount: revertedEntryKeys.size, rollbackDetails };
9886
+ });
9785
9887
  },
9786
9888
  /**
9787
9889
  * Performs deterministic rollback of a batch.
@@ -12657,6 +12759,9 @@ const index = {
12657
12759
  }
12658
12760
  });
12659
12761
  strapi.documents.use(async (context, next) => {
12762
+ if (isRollbackContext()) {
12763
+ return await next();
12764
+ }
12660
12765
  if (typeof context.uid === "string" && context.uid.startsWith("plugin::bulk-updater.")) {
12661
12766
  return await next();
12662
12767
  }