strapi-plugin-bulk-updater 1.6.5 → 1.6.7

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.
@@ -339,6 +339,137 @@ const contentTypes = {
339
339
  schema: auditLog
340
340
  }
341
341
  };
342
+ const CRASH_GUARD_SYMBOL = Symbol.for("strapi-plugin-bulk-updater.undiciCrashGuardInstalled");
343
+ let activeBulkOperations = 0;
344
+ function getActiveBulkOperationCount() {
345
+ return activeBulkOperations;
346
+ }
347
+ async function trackActiveBulkOperation(fn) {
348
+ activeBulkOperations++;
349
+ try {
350
+ return await fn();
351
+ } finally {
352
+ activeBulkOperations = Math.max(0, activeBulkOperations - 1);
353
+ }
354
+ }
355
+ function getBatchConcurrency(strapi) {
356
+ const DEFAULT_CONCURRENCY = 5;
357
+ const MIN_CONCURRENCY = 1;
358
+ const MAX_CONCURRENCY = 10;
359
+ try {
360
+ const configured = strapi?.config?.get?.("plugin::bulk-updater.batchConcurrency");
361
+ if (configured !== void 0 && configured !== null && configured !== "") {
362
+ const parsed = Number(configured);
363
+ if (Number.isFinite(parsed) && parsed >= MIN_CONCURRENCY) {
364
+ return Math.min(MAX_CONCURRENCY, Math.floor(parsed));
365
+ }
366
+ }
367
+ } catch {
368
+ }
369
+ return DEFAULT_CONCURRENCY;
370
+ }
371
+ function sanitizeSensitiveErrorText(text) {
372
+ if (!text || typeof text !== "string") return "";
373
+ return text.replace(/Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi, "Bearer [REDACTED]").replace(/Basic\s+[A-Za-z0-9+/=]+/gi, "Basic [REDACTED]").replace(/(authorization|api[_-]?key|token|secret|password)\s*[:=]\s*[^\s,;'"}\]]+/gi, "$1=[REDACTED]").replace(/([?&](?:token|key|api_key|apikey|secret|password|auth)=)[^&\s]+/gi, "$1[REDACTED]");
374
+ }
375
+ function isFetchFailedError(err) {
376
+ if (!err) return false;
377
+ const visited = /* @__PURE__ */ new Set();
378
+ let current = err;
379
+ while (current && typeof current === "object" && !visited.has(current)) {
380
+ visited.add(current);
381
+ const msg = typeof current.message === "string" ? current.message : "";
382
+ const code = typeof current.code === "string" ? current.code : "";
383
+ const stack = typeof current.stack === "string" ? current.stack : "";
384
+ if (/fetch failed/i.test(msg) || code.startsWith("UND_ERR_") || stack.includes("node:internal/deps/undici")) {
385
+ return true;
386
+ }
387
+ if (Array.isArray(current.errors)) {
388
+ for (const sub of current.errors) {
389
+ if (isFetchFailedError(sub)) return true;
390
+ }
391
+ }
392
+ current = current.cause;
393
+ }
394
+ return false;
395
+ }
396
+ function formatErrorWithCause(err, fallback = "Unknown error") {
397
+ if (!err) return fallback;
398
+ if (typeof err === "string") return sanitizeSensitiveErrorText(err) || fallback;
399
+ const primaryMsg = typeof err.message === "string" && err.message.trim() && err.message !== "[object Object]" ? err.message.trim() : fallback;
400
+ const causeParts = [];
401
+ const visited = /* @__PURE__ */ new Set([err]);
402
+ let current = err.cause;
403
+ while (current && !visited.has(current) && causeParts.length < 4) {
404
+ visited.add(current);
405
+ if (typeof current === "string") {
406
+ if (current.trim()) causeParts.push(current.trim());
407
+ break;
408
+ }
409
+ if (typeof current === "object") {
410
+ const code = typeof current.code === "string" ? current.code.trim() : "";
411
+ const msg = typeof current.message === "string" ? current.message.trim() : "";
412
+ const addr = typeof current.address === "string" ? current.address.trim() : "";
413
+ const port = current.port !== void 0 && current.port !== null ? String(current.port) : "";
414
+ const endpoint = addr ? port ? `${addr}:${port}` : addr : "";
415
+ const pieces = [];
416
+ if (code) pieces.push(code);
417
+ if (msg && msg !== code) pieces.push(msg);
418
+ if (endpoint && !msg.includes(endpoint)) pieces.push(endpoint);
419
+ if (pieces.length > 0) {
420
+ causeParts.push(pieces.join(" - "));
421
+ } else if (Array.isArray(current.errors) && current.errors.length > 0) {
422
+ const subMsgs = current.errors.slice(0, 2).map((e) => {
423
+ const subCode = e?.code ? `${e.code}: ` : "";
424
+ return `${subCode}${e?.message || ""}`.trim();
425
+ }).filter(Boolean);
426
+ if (subMsgs.length > 0) {
427
+ causeParts.push(subMsgs.join("; "));
428
+ }
429
+ }
430
+ current = current.cause;
431
+ } else {
432
+ break;
433
+ }
434
+ }
435
+ let formatted = primaryMsg;
436
+ if (causeParts.length > 0) {
437
+ formatted = `${primaryMsg} (${causeParts.join(" -> ")})`;
438
+ }
439
+ if (isFetchFailedError(err) && !formatted.toLowerCase().includes("webhook")) {
440
+ formatted += " — downstream webhook or lifecycle HTTP request failed";
441
+ }
442
+ return sanitizeSensitiveErrorText(formatted);
443
+ }
444
+ function installUndiciCrashGuard(strapi) {
445
+ const globalObj = globalThis;
446
+ if (globalObj[CRASH_GUARD_SYMBOL]) {
447
+ return globalObj[CRASH_GUARD_SYMBOL];
448
+ }
449
+ const handler = (reason) => {
450
+ if (!isFetchFailedError(reason)) {
451
+ return;
452
+ }
453
+ const formatted = formatErrorWithCause(reason, "fetch failed");
454
+ const inBulk = activeBulkOperations > 0;
455
+ const contextNote = inBulk ? `during active bulk/CSV operation (${activeBulkOperations} active)` : "outside active bulk operation";
456
+ const logMsg = `[bulk-updater] Prevented server crash from unhandled undici fetch rejection ${contextNote}: ${formatted}. Check Strapi Settings > Webhooks or custom lifecycle hooks for unreachable/slow endpoints.`;
457
+ if (strapi?.log?.error) {
458
+ strapi.log.error(logMsg);
459
+ } else {
460
+ console.error(logMsg);
461
+ }
462
+ };
463
+ process.on("unhandledRejection", handler);
464
+ const uninstall = () => {
465
+ process.removeListener("unhandledRejection", handler);
466
+ if (globalObj[CRASH_GUARD_SYMBOL] === uninstall) {
467
+ delete globalObj[CRASH_GUARD_SYMBOL];
468
+ }
469
+ };
470
+ globalObj[CRASH_GUARD_SYMBOL] = uninstall;
471
+ return uninstall;
472
+ }
342
473
  const bulkUpdaterController = ({ strapi }) => ({
343
474
  async getModels(ctx) {
344
475
  try {
@@ -414,8 +545,10 @@ const bulkUpdaterController = ({ strapi }) => ({
414
545
  const result = await service.batchUpdate(ctx.request.body || {}, currentUser);
415
546
  ctx.body = result;
416
547
  } catch (err) {
417
- ctx.status = 400;
418
- ctx.body = { success: false, error: err.message };
548
+ const formatted = formatErrorWithCause(err, "Batch update failed");
549
+ strapi.log?.error?.(`[bulk-updater] POST /batch-update error: ${formatted}`);
550
+ ctx.status = isFetchFailedError(err) ? 502 : 400;
551
+ ctx.body = { success: false, error: formatted };
419
552
  }
420
553
  },
421
554
  async batchPublish(ctx) {
@@ -425,8 +558,10 @@ const bulkUpdaterController = ({ strapi }) => ({
425
558
  const result = await service.batchPublish(ctx.request.body || {}, currentUser);
426
559
  ctx.body = result;
427
560
  } catch (err) {
428
- ctx.status = 400;
429
- ctx.body = { success: false, error: err.message };
561
+ const formatted = formatErrorWithCause(err, "Batch publish failed");
562
+ strapi.log?.error?.(`[bulk-updater] POST /batch-publish error: ${formatted}`);
563
+ ctx.status = isFetchFailedError(err) ? 502 : 400;
564
+ ctx.body = { success: false, error: formatted };
430
565
  }
431
566
  },
432
567
  async previewBatch(ctx) {
@@ -458,8 +593,10 @@ const bulkUpdaterController = ({ strapi }) => ({
458
593
  const result = await service.approveBatch(batchId, currentUser, { executeImmediately });
459
594
  ctx.body = result;
460
595
  } catch (err) {
461
- ctx.status = 400;
462
- ctx.body = { success: false, error: err.message };
596
+ const formatted = formatErrorWithCause(err, "Batch approval failed");
597
+ strapi.log?.error?.(`[bulk-updater] POST /batches/${ctx.params?.batchId}/approve error: ${formatted}`);
598
+ ctx.status = isFetchFailedError(err) ? 502 : 400;
599
+ ctx.body = { success: false, error: formatted };
463
600
  }
464
601
  },
465
602
  async rejectBatch(ctx) {
@@ -483,8 +620,10 @@ const bulkUpdaterController = ({ strapi }) => ({
483
620
  const result = await service.executeNow(batchId, currentUser);
484
621
  ctx.body = result;
485
622
  } catch (err) {
486
- ctx.status = 400;
487
- ctx.body = { success: false, error: err.message };
623
+ const formatted = formatErrorWithCause(err, "Batch execution failed");
624
+ strapi.log?.error?.(`[bulk-updater] POST /batches/${ctx.params?.batchId}/execute-now error: ${formatted}`);
625
+ ctx.status = isFetchFailedError(err) ? 502 : 400;
626
+ ctx.body = { success: false, error: formatted };
488
627
  }
489
628
  },
490
629
  async getBatchStatus(ctx) {
@@ -770,8 +909,10 @@ const csvController = ({ strapi }) => ({
770
909
  });
771
910
  ctx.body = result;
772
911
  } catch (err) {
773
- ctx.status = 500;
774
- ctx.body = { success: false, error: err.message };
912
+ const formatted = formatErrorWithCause(err, "CSV import failed");
913
+ strapi.log?.error?.(`[bulk-updater] POST /csv/import error: ${formatted}`);
914
+ ctx.status = isFetchFailedError(err) ? 502 : 500;
915
+ ctx.body = { success: false, error: formatted };
775
916
  }
776
917
  },
777
918
  async importChunk(ctx) {
@@ -802,8 +943,10 @@ const csvController = ({ strapi }) => ({
802
943
  });
803
944
  ctx.body = result;
804
945
  } catch (err) {
805
- ctx.status = 500;
806
- ctx.body = { success: false, error: err.message };
946
+ const formatted = formatErrorWithCause(err, "CSV chunk import failed");
947
+ strapi.log?.error?.(`[bulk-updater] POST /csv/import-chunk error: ${formatted}`);
948
+ ctx.status = isFetchFailedError(err) ? 502 : 500;
949
+ ctx.body = { success: false, error: formatted };
807
950
  }
808
951
  },
809
952
  async validatePreflight(ctx) {
@@ -856,8 +999,10 @@ const csvController = ({ strapi }) => ({
856
999
  });
857
1000
  ctx.body = result;
858
1001
  } catch (err) {
859
- ctx.status = 500;
860
- ctx.body = { success: false, error: err.message };
1002
+ const formatted = formatErrorWithCause(err, "CSV batch submission failed");
1003
+ strapi.log?.error?.(`[bulk-updater] POST /csv/submit-batch error: ${formatted}`);
1004
+ ctx.status = isFetchFailedError(err) ? 502 : 500;
1005
+ ctx.body = { success: false, error: formatted };
861
1006
  }
862
1007
  }
863
1008
  });
@@ -5493,7 +5638,7 @@ async function resolveAndMaybePublishTarget({
5493
5638
  }
5494
5639
  }
5495
5640
  const inspectionTarget = target.status || target.publishedAt ? { ...currentEntry, status: target.status, publishedAt: target.publishedAt } : currentEntry;
5496
- const { hadPublishedVersion } = resolveRecordPublicationStatus(inspectionTarget, pubRecord, isDraftAndPublish);
5641
+ const { hadPublishedVersion, status: preStatus } = resolveRecordPublicationStatus(inspectionTarget, pubRecord, isDraftAndPublish);
5497
5642
  const isEditing = isRowInEditingStage$1(inspectionTarget) || isRowInEditingStage$1(target);
5498
5643
  const shouldPublish = evaluateShouldPublish({
5499
5644
  isDraftAndPublish,
@@ -5507,6 +5652,7 @@ async function resolveAndMaybePublishTarget({
5507
5652
  candLocale: isLocalized ? candLocale : void 0,
5508
5653
  isDraftAndPublish,
5509
5654
  hadPublishedVersion,
5655
+ previousStatus: preStatus,
5510
5656
  shouldPublish,
5511
5657
  async postUpdate(relatedTargetUid) {
5512
5658
  if (shouldPublish) {
@@ -5515,7 +5661,9 @@ async function resolveAndMaybePublishTarget({
5515
5661
  if (isLocalized) pubArgs.locale = candLocale;
5516
5662
  await strapi.documents(target.uid).publish(pubArgs);
5517
5663
  } catch (publishErr) {
5518
- strapi.log.warn(`[bulk-updater] Failed to auto-publish ${target.uid}/${target.documentId}:`, publishErr);
5664
+ strapi.log.warn(
5665
+ `[bulk-updater] Failed to auto-publish ${target.uid}/${target.documentId}: ${formatErrorWithCause(publishErr)}`
5666
+ );
5519
5667
  }
5520
5668
  }
5521
5669
  invalidateCollectionCache(target.uid);
@@ -5668,6 +5816,9 @@ async function executeGridTargetUpdate({
5668
5816
  oldValue: oldSummaryVal,
5669
5817
  newValue: newSummaryVal,
5670
5818
  status: "updated",
5819
+ previousStatus: lifecycle.previousStatus,
5820
+ hadPublishedVersion: lifecycle.hadPublishedVersion,
5821
+ isDraftAndPublish: lifecycle.isDraftAndPublish,
5671
5822
  message: isMultiOcc ? `Successfully updated ${changedDiffs.length} grid occurrence(s) in ${attribute}` : `Successfully updated ${attribute}`,
5672
5823
  dynamicZoneDiffs: isComponentNested ? changedDiffs : void 0,
5673
5824
  gridGroupDiffs: changedDiffs.length > 1 || isComponentNested ? changedDiffs : void 0
@@ -5746,562 +5897,610 @@ async function executeBatchInternal(strapi, {
5746
5897
  results: []
5747
5898
  };
5748
5899
  batchJobsMap.set(batchId, jobState);
5749
- let regexObj = null;
5750
- if (effectiveEditMode !== "grid" && isRegex && regexPattern) {
5751
- regexObj = new RegExp(regexPattern, "g");
5752
- }
5753
- const CHUNK_SIZE = 25;
5754
- const publishedCounterparts = /* @__PURE__ */ new Map();
5755
- const uidsWithDraftAndPublish = /* @__PURE__ */ new Set();
5756
- const docIdsByUid = /* @__PURE__ */ new Map();
5757
- for (const target of targets) {
5758
- if (target.uid && target.documentId) {
5759
- const ct = strapi.contentTypes[target.uid];
5760
- if (ct?.options?.draftAndPublish) {
5761
- uidsWithDraftAndPublish.add(target.uid);
5762
- if (!docIdsByUid.has(target.uid)) {
5763
- docIdsByUid.set(target.uid, []);
5900
+ return await trackActiveBulkOperation(async () => {
5901
+ try {
5902
+ let regexObj = null;
5903
+ if (effectiveEditMode !== "grid" && isRegex && regexPattern) {
5904
+ regexObj = new RegExp(regexPattern, "g");
5905
+ }
5906
+ const CHUNK_SIZE = getBatchConcurrency(strapi);
5907
+ const publishedCounterparts = /* @__PURE__ */ new Map();
5908
+ const uidsWithDraftAndPublish = /* @__PURE__ */ new Set();
5909
+ const docIdsByUid = /* @__PURE__ */ new Map();
5910
+ for (const target of targets) {
5911
+ if (target.uid && target.documentId) {
5912
+ const ct = strapi.contentTypes[target.uid];
5913
+ if (ct?.options?.draftAndPublish) {
5914
+ uidsWithDraftAndPublish.add(target.uid);
5915
+ if (!docIdsByUid.has(target.uid)) {
5916
+ docIdsByUid.set(target.uid, []);
5917
+ }
5918
+ docIdsByUid.get(target.uid).push(target.documentId);
5919
+ }
5764
5920
  }
5765
- docIdsByUid.get(target.uid).push(target.documentId);
5766
5921
  }
5767
- }
5768
- }
5769
- for (const colUid of uidsWithDraftAndPublish) {
5770
- const docIds = docIdsByUid.get(colUid) || [];
5771
- if (docIds.length > 0) {
5772
- try {
5773
- const pubDocs = await strapi.documents(colUid).findMany({
5774
- status: "published",
5775
- filters: { documentId: { $in: docIds } },
5776
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
5777
- limit: Math.max(docIds.length, 100)
5778
- });
5779
- for (const pub of pubDocs || []) {
5780
- if (pub?.documentId) {
5781
- publishedCounterparts.set(`${colUid}@@@${pub.documentId}`, pub);
5782
- if (pub.locale) {
5783
- publishedCounterparts.set(`${colUid}@@@${pub.documentId}@@@${pub.locale}`, pub);
5922
+ for (const colUid of uidsWithDraftAndPublish) {
5923
+ const docIds = docIdsByUid.get(colUid) || [];
5924
+ if (docIds.length > 0) {
5925
+ try {
5926
+ const pubDocs = await strapi.documents(colUid).findMany({
5927
+ status: "published",
5928
+ filters: { documentId: { $in: docIds } },
5929
+ fields: ["documentId", "updatedAt", "publishedAt", "locale"],
5930
+ limit: Math.max(docIds.length, 100)
5931
+ });
5932
+ for (const pub of pubDocs || []) {
5933
+ if (pub?.documentId) {
5934
+ publishedCounterparts.set(`${colUid}@@@${pub.documentId}`, pub);
5935
+ if (pub.locale) {
5936
+ publishedCounterparts.set(`${colUid}@@@${pub.documentId}@@@${pub.locale}`, pub);
5937
+ }
5938
+ }
5784
5939
  }
5940
+ } catch {
5785
5941
  }
5786
5942
  }
5787
- } catch {
5788
5943
  }
5789
- }
5790
- }
5791
- const documentLoader = /* @__PURE__ */ new Map();
5792
- const getDocumentDeduplicated = (uid, documentId) => {
5793
- const loaderKey = `${uid}@@@${documentId}`;
5794
- if (!documentLoader.has(loaderKey)) {
5795
- const ct = strapi.contentTypes[uid];
5796
- const populateDef = ct?.attributes ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
5797
- documentLoader.set(
5798
- loaderKey,
5799
- strapi.documents(uid).findOne({
5800
- documentId,
5801
- ...populateDef ? { populate: populateDef } : { populate: "*" }
5802
- })
5803
- );
5804
- }
5805
- return documentLoader.get(loaderKey);
5806
- };
5807
- for (let i = 0; i < targets.length; i += CHUNK_SIZE) {
5808
- const chunk = targets.slice(i, i + CHUNK_SIZE);
5809
- const chunkPromises = chunk.map(async (target) => {
5810
- const contentType = strapi.contentTypes[target.uid];
5811
- const displayName = contentType?.info?.displayName || target.uid;
5812
- try {
5813
- if (effectiveEditMode === "grid") {
5814
- return await executeGridTargetUpdate({
5815
- strapi,
5816
- target,
5817
- attribute,
5818
- contentType,
5819
- displayName,
5820
- publishedCounterparts,
5821
- publishOnApproval: Boolean(publishOnApproval),
5822
- publishStrategy,
5823
- unreviewedConsent: Boolean(unreviewedConsent),
5824
- currentUser
5825
- });
5944
+ const documentLoader = /* @__PURE__ */ new Map();
5945
+ const getDocumentDeduplicated = (uid, documentId) => {
5946
+ const loaderKey = `${uid}@@@${documentId}`;
5947
+ if (!documentLoader.has(loaderKey)) {
5948
+ const ct = strapi.contentTypes[uid];
5949
+ const populateDef = ct?.attributes ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
5950
+ documentLoader.set(
5951
+ loaderKey,
5952
+ strapi.documents(uid).findOne({
5953
+ documentId,
5954
+ ...populateDef ? { populate: populateDef } : { populate: "*" }
5955
+ })
5956
+ );
5826
5957
  }
5827
- const currentEntry = await getDocumentDeduplicated(target.uid, target.documentId);
5828
- const entryLabel = currentEntry?.name || currentEntry?.title || currentEntry?.email || `Entry #${target.documentId}`;
5829
- const parsed = parseDynamicZonePath(attribute);
5830
- const isNested = attribute.includes(".") || attribute.includes("[");
5831
- const isComponentNested = isNested && isDeepComponentField(contentType, strapi.components, attribute);
5832
- const parts = isNested ? parsed.cleanPath.split(".") : [];
5833
- const rootKey = parsed.rootKey;
5834
- const targetComponentUid = target.targetComponentUid || parsed.targetComponentUid;
5835
- const targetIndexes = target.dynamicZoneIndexes;
5836
- const attrDef = contentType?.attributes?.[attribute];
5837
- const hasAttribute = Boolean(attrDef) || isComponentNested;
5838
- if (hasAttribute) {
5839
- if (isComponentNested) {
5840
- const populateOption = buildDeepPopulate(contentType.attributes, strapi.components);
5841
- const findOneArgs = { documentId: target.documentId };
5842
- if (populateOption) {
5843
- findOneArgs.populate = populateOption;
5958
+ return documentLoader.get(loaderKey);
5959
+ };
5960
+ for (let i = 0; i < targets.length; i += CHUNK_SIZE) {
5961
+ const chunk = targets.slice(i, i + CHUNK_SIZE);
5962
+ const chunkPromises = chunk.map(async (target) => {
5963
+ const contentType = strapi.contentTypes[target.uid];
5964
+ const displayName = contentType?.info?.displayName || target.uid;
5965
+ try {
5966
+ if (effectiveEditMode === "grid") {
5967
+ return await executeGridTargetUpdate({
5968
+ strapi,
5969
+ target,
5970
+ attribute,
5971
+ contentType,
5972
+ displayName,
5973
+ publishedCounterparts,
5974
+ publishOnApproval: Boolean(publishOnApproval),
5975
+ publishStrategy,
5976
+ unreviewedConsent: Boolean(unreviewedConsent),
5977
+ currentUser
5978
+ });
5844
5979
  }
5845
- const currentEntryWithPopulate = await strapi.documents(target.uid).findOne(findOneArgs);
5846
- const isRootDz = contentType?.attributes?.[rootKey]?.type === "dynamiczone";
5847
- const existingRoot = currentEntryWithPopulate?.[rootKey] || (isRootDz ? [] : {});
5848
- let affectedMatches = [];
5849
- if (isRootDz && Array.isArray(existingRoot)) {
5850
- affectedMatches = getAllNestedValues({ [rootKey]: existingRoot }, attribute);
5851
- if (targetIndexes && targetIndexes.length > 0) {
5852
- affectedMatches = affectedMatches.filter((m) => targetIndexes.includes(m.index));
5853
- }
5854
- if (targetComponentUid) {
5855
- affectedMatches = affectedMatches.filter((m) => m.componentUid === targetComponentUid);
5980
+ const currentEntry = await getDocumentDeduplicated(target.uid, target.documentId);
5981
+ const entryLabel = currentEntry?.name || currentEntry?.title || currentEntry?.email || `Entry #${target.documentId}`;
5982
+ const parsed = parseDynamicZonePath(attribute);
5983
+ const isNested = attribute.includes(".") || attribute.includes("[");
5984
+ const isComponentNested = isNested && isDeepComponentField(contentType, strapi.components, attribute);
5985
+ const parts = isNested ? parsed.cleanPath.split(".") : [];
5986
+ const rootKey = parsed.rootKey;
5987
+ const targetComponentUid = target.targetComponentUid || parsed.targetComponentUid;
5988
+ const targetIndexes = target.dynamicZoneIndexes;
5989
+ const attrDef = contentType?.attributes?.[attribute];
5990
+ const hasAttribute = Boolean(attrDef) || isComponentNested;
5991
+ if (hasAttribute) {
5992
+ if (isComponentNested) {
5993
+ const populateOption = buildDeepPopulate(contentType.attributes, strapi.components);
5994
+ const findOneArgs = { documentId: target.documentId };
5995
+ if (populateOption) {
5996
+ findOneArgs.populate = populateOption;
5997
+ }
5998
+ const currentEntryWithPopulate = await strapi.documents(target.uid).findOne(findOneArgs);
5999
+ const isRootDz = contentType?.attributes?.[rootKey]?.type === "dynamiczone";
6000
+ const existingRoot = currentEntryWithPopulate?.[rootKey] || (isRootDz ? [] : {});
6001
+ let affectedMatches = [];
6002
+ if (isRootDz && Array.isArray(existingRoot)) {
6003
+ affectedMatches = getAllNestedValues({ [rootKey]: existingRoot }, attribute);
6004
+ if (targetIndexes && targetIndexes.length > 0) {
6005
+ affectedMatches = affectedMatches.filter((m) => targetIndexes.includes(m.index));
6006
+ }
6007
+ if (targetComponentUid) {
6008
+ affectedMatches = affectedMatches.filter((m) => m.componentUid === targetComponentUid);
6009
+ }
6010
+ }
6011
+ const currentVal2 = isRootDz ? affectedMatches.length > 0 ? affectedMatches.map((m) => m.value).join(", ") : getDeepProperty(existingRoot, parts.slice(1).join(".")) : getDeepProperty(existingRoot, parts.slice(1).join("."));
6012
+ let newValue2 = value;
6013
+ if (regexObj && typeof currentVal2 === "string") {
6014
+ newValue2 = currentVal2.replace(regexObj, value);
6015
+ }
6016
+ const updatedRoot = setDeepProperty(existingRoot, parts.slice(1), newValue2, {
6017
+ targetIndexes,
6018
+ targetComponentUid
6019
+ });
6020
+ const isDraftAndPublishComp = Boolean(contentType?.options?.draftAndPublish);
6021
+ const candLocaleComp = target.locale || currentEntry?.locale;
6022
+ let pubRecordComp = candLocaleComp && publishedCounterparts.get(`${target.uid}@@@${target.documentId}@@@${candLocaleComp}`) || publishedCounterparts.get(`${target.uid}@@@${target.documentId}`);
6023
+ if (!pubRecordComp && isDraftAndPublishComp && target.documentId) {
6024
+ try {
6025
+ const singlePub = await strapi.documents(target.uid).findMany({
6026
+ status: "published",
6027
+ filters: { documentId: target.documentId },
6028
+ fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6029
+ limit: 1
6030
+ });
6031
+ if (singlePub && singlePub.length > 0) {
6032
+ pubRecordComp = singlePub[0];
6033
+ publishedCounterparts.set(`${target.uid}@@@${target.documentId}`, pubRecordComp);
6034
+ }
6035
+ } catch {
6036
+ }
6037
+ }
6038
+ const inspectionTargetComp = target.status || target.publishedAt ? { ...currentEntry, status: target.status, publishedAt: target.publishedAt } : currentEntry;
6039
+ const { hadPublishedVersion: hadPubComp, status: preStatusComp } = resolveRecordPublicationStatus(
6040
+ inspectionTargetComp,
6041
+ pubRecordComp,
6042
+ isDraftAndPublishComp
6043
+ );
6044
+ const isEditingComp = isRowInEditingStage$1(inspectionTargetComp) || isRowInEditingStage$1(target);
6045
+ const shouldPublishComp = evaluateShouldPublish({
6046
+ isDraftAndPublish: isDraftAndPublishComp,
6047
+ hadPublishedVersion: hadPubComp,
6048
+ isEditing: isEditingComp,
6049
+ publishOnApproval: Boolean(publishOnApproval),
6050
+ publishStrategy,
6051
+ unreviewedConsent
6052
+ });
6053
+ const proposedEntityComp = deepMergeEntities(currentEntryWithPopulate || currentEntry, { [rootKey]: updatedRoot });
6054
+ const valResultComp = await validateEntityQuotas(strapi, target.uid, proposedEntityComp);
6055
+ if (!valResultComp.isValid) {
6056
+ return {
6057
+ uid: target.uid,
6058
+ collectionName: displayName,
6059
+ documentId: target.documentId,
6060
+ label: entryLabel,
6061
+ attribute,
6062
+ oldValue: currentVal2 ?? null,
6063
+ newValue: newValue2,
6064
+ status: "error",
6065
+ message: valResultComp.errorMessage
6066
+ };
6067
+ }
6068
+ const updateArgsComp = {
6069
+ documentId: target.documentId,
6070
+ data: {
6071
+ [rootKey]: updatedRoot
6072
+ }
6073
+ };
6074
+ if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleComp && candLocaleComp !== "null" && candLocaleComp !== "undefined") {
6075
+ updateArgsComp.locale = candLocaleComp;
6076
+ }
6077
+ await strapi.documents(target.uid).update(updateArgsComp);
6078
+ if (shouldPublishComp) {
6079
+ try {
6080
+ const pubArgs = {
6081
+ documentId: target.documentId
6082
+ };
6083
+ if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleComp && candLocaleComp !== "null" && candLocaleComp !== "undefined") {
6084
+ pubArgs.locale = candLocaleComp;
6085
+ }
6086
+ await strapi.documents(target.uid).publish(pubArgs);
6087
+ } catch (publishErr) {
6088
+ strapi.log.warn(
6089
+ `[bulk-updater] Failed to auto-publish ${target.uid}/${target.documentId}: ${formatErrorWithCause(publishErr)}`
6090
+ );
6091
+ }
6092
+ }
6093
+ invalidateCollectionCache(target.uid);
6094
+ await recordContentHistoryVersion(strapi, {
6095
+ uid: target.uid,
6096
+ documentId: target.documentId,
6097
+ userId: currentUser?.id,
6098
+ statusOverride: shouldPublishComp ? "published" : isDraftAndPublishComp ? hadPubComp ? "modified" : "draft" : void 0
6099
+ });
6100
+ const dzDiffs = isRootDz && affectedMatches.length > 0 ? affectedMatches.map((m) => ({
6101
+ index: m.index,
6102
+ componentUid: m.componentUid,
6103
+ componentName: m.componentName,
6104
+ attribute: `${rootKey}[#${m.index} ${m.componentName}].${parts.slice(1).join(".")}`,
6105
+ oldValue: m.value,
6106
+ newValue: regexObj && typeof m.value === "string" ? m.value.replace(regexObj, value) : value
6107
+ })) : [];
6108
+ return {
6109
+ uid: target.uid,
6110
+ collectionName: displayName,
6111
+ documentId: target.documentId,
6112
+ locale: candLocaleComp,
6113
+ label: entryLabel,
6114
+ attribute,
6115
+ oldValue: currentVal2 ?? null,
6116
+ newValue: newValue2,
6117
+ status: "updated",
6118
+ previousStatus: preStatusComp,
6119
+ hadPublishedVersion: hadPubComp,
6120
+ isDraftAndPublish: isDraftAndPublishComp,
6121
+ message: isRootDz ? `Successfully updated ${affectedMatches.length} dynamic zone item(s) in ${attribute}` : `Successfully updated nested field ${attribute}`,
6122
+ dynamicZoneDiffs: dzDiffs
6123
+ };
5856
6124
  }
5857
- }
5858
- const currentVal2 = isRootDz ? affectedMatches.length > 0 ? affectedMatches.map((m) => m.value).join(", ") : getDeepProperty(existingRoot, parts.slice(1).join(".")) : getDeepProperty(existingRoot, parts.slice(1).join("."));
5859
- let newValue2 = value;
5860
- if (regexObj && typeof currentVal2 === "string") {
5861
- newValue2 = currentVal2.replace(regexObj, value);
5862
- }
5863
- const updatedRoot = setDeepProperty(existingRoot, parts.slice(1), newValue2, {
5864
- targetIndexes,
5865
- targetComponentUid
5866
- });
5867
- const isDraftAndPublishComp = Boolean(contentType?.options?.draftAndPublish);
5868
- const candLocaleComp = target.locale || currentEntry?.locale;
5869
- let pubRecordComp = candLocaleComp && publishedCounterparts.get(`${target.uid}@@@${target.documentId}@@@${candLocaleComp}`) || publishedCounterparts.get(`${target.uid}@@@${target.documentId}`);
5870
- if (!pubRecordComp && isDraftAndPublishComp && target.documentId) {
5871
- try {
5872
- const singlePub = await strapi.documents(target.uid).findMany({
5873
- status: "published",
5874
- filters: { documentId: target.documentId },
5875
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
5876
- limit: 1
6125
+ if (attrDef.type === "relation") {
6126
+ const isMulti = attrDef.relation === "oneToMany" || attrDef.relation === "manyToMany";
6127
+ const currentEntryWithPopulate = await strapi.documents(target.uid).findOne({
6128
+ documentId: target.documentId,
6129
+ populate: [attribute]
5877
6130
  });
5878
- if (singlePub && singlePub.length > 0) {
5879
- pubRecordComp = singlePub[0];
5880
- publishedCounterparts.set(`${target.uid}@@@${target.documentId}`, pubRecordComp);
6131
+ const currentRel = currentEntryWithPopulate?.[attribute];
6132
+ let oldDocIds = [];
6133
+ let oldDisplay = "";
6134
+ if (isMulti && Array.isArray(currentRel)) {
6135
+ oldDocIds = currentRel.map((r) => r.documentId).filter(Boolean);
6136
+ oldDisplay = currentRel.map((r) => r.name || r.title || r.email || r.documentId).join(", ") || "(empty)";
6137
+ } else if (currentRel) {
6138
+ oldDocIds = currentRel.documentId ? [currentRel.documentId] : [];
6139
+ oldDisplay = currentRel.name || currentRel.title || currentRel.email || currentRel.documentId || "(empty)";
6140
+ } else {
6141
+ oldDisplay = "(unlinked / none)";
5881
6142
  }
5882
- } catch {
6143
+ let mode = "set";
6144
+ let targetDocIds = [];
6145
+ let newDisplay = "";
6146
+ if (value === "__clear__" || value === "") {
6147
+ mode = "clear";
6148
+ newDisplay = "(cleared / unlinked)";
6149
+ } else {
6150
+ try {
6151
+ const parsed2 = JSON.parse(value);
6152
+ if (parsed2 && typeof parsed2 === "object" && parsed2.mode) {
6153
+ mode = parsed2.mode;
6154
+ targetDocIds = Array.isArray(parsed2.documentIds) ? parsed2.documentIds : parsed2.documentId ? [parsed2.documentId] : [];
6155
+ newDisplay = parsed2.label || targetDocIds.join(", ") || `[${mode}]`;
6156
+ } else if (Array.isArray(parsed2)) {
6157
+ targetDocIds = parsed2;
6158
+ newDisplay = targetDocIds.join(", ");
6159
+ } else {
6160
+ targetDocIds = [value];
6161
+ newDisplay = value;
6162
+ }
6163
+ } catch {
6164
+ targetDocIds = [value];
6165
+ newDisplay = value;
6166
+ }
6167
+ }
6168
+ let relationPayload;
6169
+ if (mode === "clear") {
6170
+ relationPayload = isMulti ? { set: [] } : null;
6171
+ } else if (mode === "set") {
6172
+ relationPayload = isMulti ? { set: targetDocIds } : targetDocIds[0] || null;
6173
+ } else if (mode === "connect") {
6174
+ relationPayload = { connect: targetDocIds };
6175
+ } else if (mode === "disconnect") {
6176
+ relationPayload = { disconnect: targetDocIds };
6177
+ }
6178
+ const isDraftAndPublishRel = Boolean(contentType?.options?.draftAndPublish);
6179
+ const candLocaleRel = target.locale || currentEntry?.locale;
6180
+ let pubRecordRel = candLocaleRel && publishedCounterparts.get(`${target.uid}@@@${target.documentId}@@@${candLocaleRel}`) || publishedCounterparts.get(`${target.uid}@@@${target.documentId}`);
6181
+ if (!pubRecordRel && isDraftAndPublishRel && target.documentId) {
6182
+ try {
6183
+ const singlePub = await strapi.documents(target.uid).findMany({
6184
+ status: "published",
6185
+ filters: { documentId: target.documentId },
6186
+ fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6187
+ limit: 1
6188
+ });
6189
+ if (singlePub && singlePub.length > 0) {
6190
+ pubRecordRel = singlePub[0];
6191
+ publishedCounterparts.set(`${target.uid}@@@${target.documentId}`, pubRecordRel);
6192
+ }
6193
+ } catch {
6194
+ }
6195
+ }
6196
+ const inspectionTargetRel = target.status || target.publishedAt ? { ...currentEntry, status: target.status, publishedAt: target.publishedAt } : currentEntry;
6197
+ const { hadPublishedVersion: hadPubRel, status: preStatusRel } = resolveRecordPublicationStatus(
6198
+ inspectionTargetRel,
6199
+ pubRecordRel,
6200
+ isDraftAndPublishRel
6201
+ );
6202
+ const isEditingRel = isRowInEditingStage$1(inspectionTargetRel) || isRowInEditingStage$1(target);
6203
+ const shouldPublishRel = evaluateShouldPublish({
6204
+ isDraftAndPublish: isDraftAndPublishRel,
6205
+ hadPublishedVersion: hadPubRel,
6206
+ isEditing: isEditingRel,
6207
+ publishOnApproval: Boolean(publishOnApproval),
6208
+ publishStrategy,
6209
+ unreviewedConsent
6210
+ });
6211
+ const proposedEntityRel = deepMergeEntities(currentEntry, { [attribute]: relationPayload });
6212
+ const valResultRel = await validateEntityQuotas(strapi, target.uid, proposedEntityRel);
6213
+ if (!valResultRel.isValid) {
6214
+ return {
6215
+ uid: target.uid,
6216
+ collectionName: displayName,
6217
+ documentId: target.documentId,
6218
+ label: entryLabel,
6219
+ attribute,
6220
+ oldValue: { isRelation: true, documentIds: oldDocIds, display: oldDisplay },
6221
+ newValue: { isRelation: true, mode, documentIds: targetDocIds, display: newDisplay },
6222
+ status: "error",
6223
+ message: valResultRel.errorMessage
6224
+ };
6225
+ }
6226
+ const updateArgsRel = {
6227
+ documentId: target.documentId,
6228
+ data: {
6229
+ [attribute]: relationPayload
6230
+ }
6231
+ };
6232
+ if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleRel && candLocaleRel !== "null" && candLocaleRel !== "undefined") {
6233
+ updateArgsRel.locale = candLocaleRel;
6234
+ }
6235
+ await strapi.documents(target.uid).update(updateArgsRel);
6236
+ if (shouldPublishRel) {
6237
+ try {
6238
+ const pubArgs = {
6239
+ documentId: target.documentId
6240
+ };
6241
+ if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleRel && candLocaleRel !== "null" && candLocaleRel !== "undefined") {
6242
+ pubArgs.locale = candLocaleRel;
6243
+ }
6244
+ await strapi.documents(target.uid).publish(pubArgs);
6245
+ } catch (publishErr) {
6246
+ strapi.log.warn(
6247
+ `[bulk-updater] Failed to auto-publish ${target.uid}/${target.documentId}: ${formatErrorWithCause(publishErr)}`
6248
+ );
6249
+ }
6250
+ }
6251
+ invalidateCollectionCache(target.uid);
6252
+ if (attrDef.target) {
6253
+ invalidateCollectionCache(attrDef.target);
6254
+ }
6255
+ await recordContentHistoryVersion(strapi, {
6256
+ uid: target.uid,
6257
+ documentId: target.documentId,
6258
+ userId: currentUser?.id,
6259
+ statusOverride: shouldPublishRel ? "published" : isDraftAndPublishRel ? hadPubRel ? "modified" : "draft" : void 0
6260
+ });
6261
+ return {
6262
+ uid: target.uid,
6263
+ collectionName: displayName,
6264
+ documentId: target.documentId,
6265
+ locale: candLocaleRel,
6266
+ label: entryLabel,
6267
+ attribute,
6268
+ oldValue: { isRelation: true, documentIds: oldDocIds, display: oldDisplay },
6269
+ newValue: { isRelation: true, mode, documentIds: targetDocIds, display: newDisplay },
6270
+ status: "updated",
6271
+ previousStatus: preStatusRel,
6272
+ hadPublishedVersion: hadPubRel,
6273
+ isDraftAndPublish: isDraftAndPublishRel,
6274
+ message: `Successfully updated relation "${attribute}"`
6275
+ };
5883
6276
  }
5884
- }
5885
- const inspectionTargetComp = target.status || target.publishedAt ? { ...currentEntry, status: target.status, publishedAt: target.publishedAt } : currentEntry;
5886
- const { hadPublishedVersion: hadPubComp } = resolveRecordPublicationStatus(
5887
- inspectionTargetComp,
5888
- pubRecordComp,
5889
- isDraftAndPublishComp
5890
- );
5891
- const isEditingComp = isRowInEditingStage$1(inspectionTargetComp) || isRowInEditingStage$1(target);
5892
- const shouldPublishComp = evaluateShouldPublish({
5893
- isDraftAndPublish: isDraftAndPublishComp,
5894
- hadPublishedVersion: hadPubComp,
5895
- isEditing: isEditingComp,
5896
- publishOnApproval: Boolean(publishOnApproval),
5897
- publishStrategy,
5898
- unreviewedConsent
5899
- });
5900
- const proposedEntityComp = deepMergeEntities(currentEntryWithPopulate || currentEntry, { [rootKey]: updatedRoot });
5901
- const valResultComp = await validateEntityQuotas(strapi, target.uid, proposedEntityComp);
5902
- if (!valResultComp.isValid) {
6277
+ let newValue = value;
6278
+ const currentVal = currentEntry?.[attribute];
6279
+ if (regexObj && typeof currentVal === "string") {
6280
+ newValue = currentVal.replace(regexObj, value);
6281
+ }
6282
+ const isDraftAndPublishScalar = Boolean(contentType?.options?.draftAndPublish);
6283
+ const candLocaleScalar = target.locale || currentEntry?.locale;
6284
+ let pubRecordScalar = candLocaleScalar && publishedCounterparts.get(`${target.uid}@@@${target.documentId}@@@${candLocaleScalar}`) || publishedCounterparts.get(`${target.uid}@@@${target.documentId}`);
6285
+ if (!pubRecordScalar && isDraftAndPublishScalar && target.documentId) {
6286
+ try {
6287
+ const singlePub = await strapi.documents(target.uid).findMany({
6288
+ status: "published",
6289
+ filters: { documentId: target.documentId },
6290
+ fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6291
+ limit: 1
6292
+ });
6293
+ if (singlePub && singlePub.length > 0) {
6294
+ pubRecordScalar = singlePub[0];
6295
+ publishedCounterparts.set(`${target.uid}@@@${target.documentId}`, pubRecordScalar);
6296
+ }
6297
+ } catch {
6298
+ }
6299
+ }
6300
+ const inspectionTargetScalar = target.status || target.publishedAt ? { ...currentEntry, status: target.status, publishedAt: target.publishedAt } : currentEntry;
6301
+ const { hadPublishedVersion: hadPubScalar, status: preStatusScalar } = resolveRecordPublicationStatus(
6302
+ inspectionTargetScalar,
6303
+ pubRecordScalar,
6304
+ isDraftAndPublishScalar
6305
+ );
6306
+ const isEditingScalar = isRowInEditingStage$1(inspectionTargetScalar) || isRowInEditingStage$1(target);
6307
+ const shouldPublishScalar = evaluateShouldPublish({
6308
+ isDraftAndPublish: isDraftAndPublishScalar,
6309
+ hadPublishedVersion: hadPubScalar,
6310
+ isEditing: isEditingScalar,
6311
+ publishOnApproval: Boolean(publishOnApproval),
6312
+ publishStrategy,
6313
+ unreviewedConsent
6314
+ });
6315
+ const proposedEntityScalar = deepMergeEntities(currentEntry, { [attribute]: newValue });
6316
+ const valResultScalar = await validateEntityQuotas(strapi, target.uid, proposedEntityScalar);
6317
+ if (!valResultScalar.isValid) {
6318
+ return {
6319
+ uid: target.uid,
6320
+ collectionName: displayName,
6321
+ documentId: target.documentId,
6322
+ label: entryLabel,
6323
+ attribute,
6324
+ oldValue: currentVal ?? null,
6325
+ newValue,
6326
+ status: "error",
6327
+ message: valResultScalar.errorMessage
6328
+ };
6329
+ }
6330
+ const updateArgsScalar = {
6331
+ documentId: target.documentId,
6332
+ data: {
6333
+ [attribute]: newValue
6334
+ }
6335
+ };
6336
+ if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleScalar && candLocaleScalar !== "null" && candLocaleScalar !== "undefined") {
6337
+ updateArgsScalar.locale = candLocaleScalar;
6338
+ }
6339
+ await strapi.documents(target.uid).update(updateArgsScalar);
6340
+ if (shouldPublishScalar) {
6341
+ try {
6342
+ const pubArgs = {
6343
+ documentId: target.documentId
6344
+ };
6345
+ if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleScalar && candLocaleScalar !== "null" && candLocaleScalar !== "undefined") {
6346
+ pubArgs.locale = candLocaleScalar;
6347
+ }
6348
+ await strapi.documents(target.uid).publish(pubArgs);
6349
+ } catch (publishErr) {
6350
+ strapi.log.warn(
6351
+ `[bulk-updater] Failed to auto-publish ${target.uid}/${target.documentId}: ${formatErrorWithCause(publishErr)}`
6352
+ );
6353
+ }
6354
+ }
6355
+ await recordContentHistoryVersion(strapi, {
6356
+ uid: target.uid,
6357
+ documentId: target.documentId,
6358
+ userId: currentUser?.id,
6359
+ statusOverride: shouldPublishScalar ? "published" : isDraftAndPublishScalar ? hadPubScalar ? "modified" : "draft" : void 0
6360
+ });
5903
6361
  return {
5904
6362
  uid: target.uid,
5905
6363
  collectionName: displayName,
5906
6364
  documentId: target.documentId,
6365
+ locale: candLocaleScalar,
5907
6366
  label: entryLabel,
5908
6367
  attribute,
5909
- oldValue: currentVal2 ?? null,
5910
- newValue: newValue2,
5911
- status: "error",
5912
- message: valResultComp.errorMessage
6368
+ oldValue: currentVal ?? null,
6369
+ newValue,
6370
+ status: "updated",
6371
+ previousStatus: preStatusScalar,
6372
+ hadPublishedVersion: hadPubScalar,
6373
+ isDraftAndPublish: isDraftAndPublishScalar,
6374
+ message: `Successfully updated ${attribute}`
6375
+ };
6376
+ } else {
6377
+ return {
6378
+ uid: target.uid,
6379
+ collectionName: displayName,
6380
+ documentId: target.documentId,
6381
+ label: entryLabel,
6382
+ attribute,
6383
+ status: "skipped",
6384
+ message: `Skipped: Attribute "${attribute}" does not exist in schema for ${displayName}`
5913
6385
  };
5914
6386
  }
5915
- const updateArgsComp = {
5916
- documentId: target.documentId,
5917
- data: {
5918
- [rootKey]: updatedRoot
5919
- }
5920
- };
5921
- if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleComp && candLocaleComp !== "null" && candLocaleComp !== "undefined") {
5922
- updateArgsComp.locale = candLocaleComp;
5923
- }
5924
- await strapi.documents(target.uid).update(updateArgsComp);
5925
- if (shouldPublishComp) {
5926
- try {
5927
- const pubArgs = {
5928
- documentId: target.documentId
5929
- };
5930
- if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleComp && candLocaleComp !== "null" && candLocaleComp !== "undefined") {
5931
- pubArgs.locale = candLocaleComp;
5932
- }
5933
- await strapi.documents(target.uid).publish(pubArgs);
5934
- } catch (publishErr) {
5935
- strapi.log.warn(`[bulk-updater] Failed to auto-publish ${target.uid}/${target.documentId}:`, publishErr);
5936
- }
6387
+ } catch (updateErr) {
6388
+ const formattedErr = formatErrorWithCause(updateErr, "Failed to update record");
6389
+ if (isFetchFailedError(updateErr)) {
6390
+ strapi.log?.error?.(
6391
+ `[bulk-updater] Network/webhook fetch error during batch ${batchId} update of ${target.uid}/${target.documentId}: ${formattedErr}`
6392
+ );
5937
6393
  }
5938
- invalidateCollectionCache(target.uid);
5939
- await recordContentHistoryVersion(strapi, {
5940
- uid: target.uid,
5941
- documentId: target.documentId,
5942
- userId: currentUser?.id,
5943
- statusOverride: shouldPublishComp ? "published" : isDraftAndPublishComp ? hadPubComp ? "modified" : "draft" : void 0
5944
- });
5945
- const dzDiffs = isRootDz && affectedMatches.length > 0 ? affectedMatches.map((m) => ({
5946
- index: m.index,
5947
- componentUid: m.componentUid,
5948
- componentName: m.componentName,
5949
- attribute: `${rootKey}[#${m.index} ${m.componentName}].${parts.slice(1).join(".")}`,
5950
- oldValue: m.value,
5951
- newValue: regexObj && typeof m.value === "string" ? m.value.replace(regexObj, value) : value
5952
- })) : [];
5953
6394
  return {
5954
6395
  uid: target.uid,
5955
6396
  collectionName: displayName,
5956
6397
  documentId: target.documentId,
5957
- label: entryLabel,
6398
+ label: `Entry #${target.documentId}`,
5958
6399
  attribute,
5959
- oldValue: currentVal2 ?? null,
5960
- newValue: newValue2,
5961
- status: "updated",
5962
- message: isRootDz ? `Successfully updated ${affectedMatches.length} dynamic zone item(s) in ${attribute}` : `Successfully updated nested field ${attribute}`,
5963
- dynamicZoneDiffs: dzDiffs
6400
+ status: "error",
6401
+ message: formattedErr
5964
6402
  };
5965
6403
  }
5966
- if (attrDef.type === "relation") {
5967
- const isMulti = attrDef.relation === "oneToMany" || attrDef.relation === "manyToMany";
5968
- const currentEntryWithPopulate = await strapi.documents(target.uid).findOne({
5969
- documentId: target.documentId,
5970
- populate: [attribute]
6404
+ });
6405
+ const chunkResults = await Promise.all(chunkPromises);
6406
+ for (const res of chunkResults) {
6407
+ if (res.status === "updated") updatedCount++;
6408
+ else if (res.status === "skipped") skippedCount++;
6409
+ results.push(res);
6410
+ }
6411
+ jobState.processedCount = results.length;
6412
+ jobState.updatedCount = updatedCount;
6413
+ jobState.skippedCount = skippedCount;
6414
+ jobState.failedCount = results.filter((r) => r.status === "error").length;
6415
+ if (i + CHUNK_SIZE < targets.length) {
6416
+ await new Promise((resolve) => setImmediate(resolve));
6417
+ }
6418
+ }
6419
+ const affectedUids = new Set(targets.map((t) => t.uid));
6420
+ affectedUids.forEach((uid) => {
6421
+ invalidateCollectionCache(uid);
6422
+ });
6423
+ const failedCount = results.filter((r) => r.status === "error").length;
6424
+ jobState.failedCount = failedCount;
6425
+ jobState.completedAt = (/* @__PURE__ */ new Date()).toISOString();
6426
+ jobState.isLive = updatedCount > 0;
6427
+ jobState.status = failedCount === 0 && updatedCount > 0 ? "successful" : failedCount > 0 && updatedCount > 0 ? "partial_failure" : failedCount > 0 ? "failed" : "successful";
6428
+ jobState.results = results.map((r) => ({
6429
+ ...r,
6430
+ isLive: r.status === "updated"
6431
+ }));
6432
+ const flattenedDiffs = [];
6433
+ for (const r of results) {
6434
+ if (effectiveEditMode === "grid") {
6435
+ flattenedDiffs.push(r);
6436
+ } else if (r.dynamicZoneDiffs && r.dynamicZoneDiffs.length > 0) {
6437
+ for (const dz of r.dynamicZoneDiffs) {
6438
+ flattenedDiffs.push({
6439
+ uid: r.uid,
6440
+ collectionName: r.collectionName,
6441
+ documentId: r.documentId,
6442
+ locale: r.locale,
6443
+ label: `${r.label} [Block #${dz.index} (${dz.componentName})]`,
6444
+ attribute: dz.attribute,
6445
+ oldValue: dz.oldValue,
6446
+ newValue: dz.newValue,
6447
+ status: "updated",
6448
+ previousStatus: r.previousStatus,
6449
+ hadPublishedVersion: r.hadPublishedVersion,
6450
+ isDraftAndPublish: r.isDraftAndPublish,
6451
+ message: `Updated ${dz.attribute}`
5971
6452
  });
5972
- const currentRel = currentEntryWithPopulate?.[attribute];
5973
- let oldDocIds = [];
5974
- let oldDisplay = "";
5975
- if (isMulti && Array.isArray(currentRel)) {
5976
- oldDocIds = currentRel.map((r) => r.documentId).filter(Boolean);
5977
- oldDisplay = currentRel.map((r) => r.name || r.title || r.email || r.documentId).join(", ") || "(empty)";
5978
- } else if (currentRel) {
5979
- oldDocIds = currentRel.documentId ? [currentRel.documentId] : [];
5980
- oldDisplay = currentRel.name || currentRel.title || currentRel.email || currentRel.documentId || "(empty)";
5981
- } else {
5982
- oldDisplay = "(unlinked / none)";
5983
- }
5984
- let mode = "set";
5985
- let targetDocIds = [];
5986
- let newDisplay = "";
5987
- if (value === "__clear__" || value === "") {
5988
- mode = "clear";
5989
- newDisplay = "(cleared / unlinked)";
5990
- } else {
5991
- try {
5992
- const parsed2 = JSON.parse(value);
5993
- if (parsed2 && typeof parsed2 === "object" && parsed2.mode) {
5994
- mode = parsed2.mode;
5995
- targetDocIds = Array.isArray(parsed2.documentIds) ? parsed2.documentIds : parsed2.documentId ? [parsed2.documentId] : [];
5996
- newDisplay = parsed2.label || targetDocIds.join(", ") || `[${mode}]`;
5997
- } else if (Array.isArray(parsed2)) {
5998
- targetDocIds = parsed2;
5999
- newDisplay = targetDocIds.join(", ");
6000
- } else {
6001
- targetDocIds = [value];
6002
- newDisplay = value;
6003
- }
6004
- } catch {
6005
- targetDocIds = [value];
6006
- newDisplay = value;
6007
- }
6008
- }
6009
- let relationPayload;
6010
- if (mode === "clear") {
6011
- relationPayload = isMulti ? { set: [] } : null;
6012
- } else if (mode === "set") {
6013
- relationPayload = isMulti ? { set: targetDocIds } : targetDocIds[0] || null;
6014
- } else if (mode === "connect") {
6015
- relationPayload = { connect: targetDocIds };
6016
- } else if (mode === "disconnect") {
6017
- relationPayload = { disconnect: targetDocIds };
6018
- }
6019
- const isDraftAndPublishRel = Boolean(contentType?.options?.draftAndPublish);
6020
- const candLocaleRel = target.locale || currentEntry?.locale;
6021
- let pubRecordRel = candLocaleRel && publishedCounterparts.get(`${target.uid}@@@${target.documentId}@@@${candLocaleRel}`) || publishedCounterparts.get(`${target.uid}@@@${target.documentId}`);
6022
- if (!pubRecordRel && isDraftAndPublishRel && target.documentId) {
6023
- try {
6024
- const singlePub = await strapi.documents(target.uid).findMany({
6025
- status: "published",
6026
- filters: { documentId: target.documentId },
6027
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6028
- limit: 1
6029
- });
6030
- if (singlePub && singlePub.length > 0) {
6031
- pubRecordRel = singlePub[0];
6032
- publishedCounterparts.set(`${target.uid}@@@${target.documentId}`, pubRecordRel);
6033
- }
6034
- } catch {
6035
- }
6036
- }
6037
- const inspectionTargetRel = target.status || target.publishedAt ? { ...currentEntry, status: target.status, publishedAt: target.publishedAt } : currentEntry;
6038
- const { hadPublishedVersion: hadPubRel } = resolveRecordPublicationStatus(
6039
- inspectionTargetRel,
6040
- pubRecordRel,
6041
- isDraftAndPublishRel
6042
- );
6043
- const isEditingRel = isRowInEditingStage$1(inspectionTargetRel) || isRowInEditingStage$1(target);
6044
- const shouldPublishRel = evaluateShouldPublish({
6045
- isDraftAndPublish: isDraftAndPublishRel,
6046
- hadPublishedVersion: hadPubRel,
6047
- isEditing: isEditingRel,
6048
- publishOnApproval: Boolean(publishOnApproval),
6049
- publishStrategy,
6050
- unreviewedConsent
6051
- });
6052
- const proposedEntityRel = deepMergeEntities(currentEntry, { [attribute]: relationPayload });
6053
- const valResultRel = await validateEntityQuotas(strapi, target.uid, proposedEntityRel);
6054
- if (!valResultRel.isValid) {
6055
- return {
6056
- uid: target.uid,
6057
- collectionName: displayName,
6058
- documentId: target.documentId,
6059
- label: entryLabel,
6060
- attribute,
6061
- oldValue: { isRelation: true, documentIds: oldDocIds, display: oldDisplay },
6062
- newValue: { isRelation: true, mode, documentIds: targetDocIds, display: newDisplay },
6063
- status: "error",
6064
- message: valResultRel.errorMessage
6065
- };
6066
- }
6067
- const updateArgsRel = {
6068
- documentId: target.documentId,
6069
- data: {
6070
- [attribute]: relationPayload
6071
- }
6072
- };
6073
- if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleRel && candLocaleRel !== "null" && candLocaleRel !== "undefined") {
6074
- updateArgsRel.locale = candLocaleRel;
6075
- }
6076
- await strapi.documents(target.uid).update(updateArgsRel);
6077
- if (shouldPublishRel) {
6078
- try {
6079
- const pubArgs = {
6080
- documentId: target.documentId
6081
- };
6082
- if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleRel && candLocaleRel !== "null" && candLocaleRel !== "undefined") {
6083
- pubArgs.locale = candLocaleRel;
6084
- }
6085
- await strapi.documents(target.uid).publish(pubArgs);
6086
- } catch (publishErr) {
6087
- strapi.log.warn(`[bulk-updater] Failed to auto-publish ${target.uid}/${target.documentId}:`, publishErr);
6088
- }
6089
- }
6090
- invalidateCollectionCache(target.uid);
6091
- if (attrDef.target) {
6092
- invalidateCollectionCache(attrDef.target);
6093
- }
6094
- await recordContentHistoryVersion(strapi, {
6095
- uid: target.uid,
6096
- documentId: target.documentId,
6097
- userId: currentUser?.id,
6098
- statusOverride: shouldPublishRel ? "published" : isDraftAndPublishRel ? hadPubRel ? "modified" : "draft" : void 0
6099
- });
6100
- return {
6101
- uid: target.uid,
6102
- collectionName: displayName,
6103
- documentId: target.documentId,
6104
- label: entryLabel,
6105
- attribute,
6106
- oldValue: { isRelation: true, documentIds: oldDocIds, display: oldDisplay },
6107
- newValue: { isRelation: true, mode, documentIds: targetDocIds, display: newDisplay },
6108
- status: "updated",
6109
- message: `Successfully updated relation "${attribute}"`
6110
- };
6111
- }
6112
- let newValue = value;
6113
- const currentVal = currentEntry?.[attribute];
6114
- if (regexObj && typeof currentVal === "string") {
6115
- newValue = currentVal.replace(regexObj, value);
6116
- }
6117
- const isDraftAndPublishScalar = Boolean(contentType?.options?.draftAndPublish);
6118
- const candLocaleScalar = target.locale || currentEntry?.locale;
6119
- let pubRecordScalar = candLocaleScalar && publishedCounterparts.get(`${target.uid}@@@${target.documentId}@@@${candLocaleScalar}`) || publishedCounterparts.get(`${target.uid}@@@${target.documentId}`);
6120
- if (!pubRecordScalar && isDraftAndPublishScalar && target.documentId) {
6121
- try {
6122
- const singlePub = await strapi.documents(target.uid).findMany({
6123
- status: "published",
6124
- filters: { documentId: target.documentId },
6125
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6126
- limit: 1
6127
- });
6128
- if (singlePub && singlePub.length > 0) {
6129
- pubRecordScalar = singlePub[0];
6130
- publishedCounterparts.set(`${target.uid}@@@${target.documentId}`, pubRecordScalar);
6131
- }
6132
- } catch {
6133
- }
6134
- }
6135
- const inspectionTargetScalar = target.status || target.publishedAt ? { ...currentEntry, status: target.status, publishedAt: target.publishedAt } : currentEntry;
6136
- const { hadPublishedVersion: hadPubScalar } = resolveRecordPublicationStatus(
6137
- inspectionTargetScalar,
6138
- pubRecordScalar,
6139
- isDraftAndPublishScalar
6140
- );
6141
- const isEditingScalar = isRowInEditingStage$1(inspectionTargetScalar) || isRowInEditingStage$1(target);
6142
- const shouldPublishScalar = evaluateShouldPublish({
6143
- isDraftAndPublish: isDraftAndPublishScalar,
6144
- hadPublishedVersion: hadPubScalar,
6145
- isEditing: isEditingScalar,
6146
- publishOnApproval: Boolean(publishOnApproval),
6147
- publishStrategy,
6148
- unreviewedConsent
6149
- });
6150
- const proposedEntityScalar = deepMergeEntities(currentEntry, { [attribute]: newValue });
6151
- const valResultScalar = await validateEntityQuotas(strapi, target.uid, proposedEntityScalar);
6152
- if (!valResultScalar.isValid) {
6153
- return {
6154
- uid: target.uid,
6155
- collectionName: displayName,
6156
- documentId: target.documentId,
6157
- label: entryLabel,
6158
- attribute,
6159
- oldValue: currentVal ?? null,
6160
- newValue,
6161
- status: "error",
6162
- message: valResultScalar.errorMessage
6163
- };
6164
6453
  }
6165
- const updateArgsScalar = {
6166
- documentId: target.documentId,
6167
- data: {
6168
- [attribute]: newValue
6169
- }
6170
- };
6171
- if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleScalar && candLocaleScalar !== "null" && candLocaleScalar !== "undefined") {
6172
- updateArgsScalar.locale = candLocaleScalar;
6173
- }
6174
- await strapi.documents(target.uid).update(updateArgsScalar);
6175
- if (shouldPublishScalar) {
6176
- try {
6177
- const pubArgs = {
6178
- documentId: target.documentId
6179
- };
6180
- if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleScalar && candLocaleScalar !== "null" && candLocaleScalar !== "undefined") {
6181
- pubArgs.locale = candLocaleScalar;
6182
- }
6183
- await strapi.documents(target.uid).publish(pubArgs);
6184
- } catch (publishErr) {
6185
- strapi.log.warn(`[bulk-updater] Failed to auto-publish ${target.uid}/${target.documentId}:`, publishErr);
6186
- }
6187
- }
6188
- await recordContentHistoryVersion(strapi, {
6189
- uid: target.uid,
6190
- documentId: target.documentId,
6191
- userId: currentUser?.id,
6192
- statusOverride: shouldPublishScalar ? "published" : isDraftAndPublishScalar ? hadPubScalar ? "modified" : "draft" : void 0
6193
- });
6194
- return {
6195
- uid: target.uid,
6196
- collectionName: displayName,
6197
- documentId: target.documentId,
6198
- label: entryLabel,
6199
- attribute,
6200
- oldValue: currentVal ?? null,
6201
- newValue,
6202
- status: "updated",
6203
- message: `Successfully updated ${attribute}`
6204
- };
6205
6454
  } else {
6206
- return {
6207
- uid: target.uid,
6208
- collectionName: displayName,
6209
- documentId: target.documentId,
6210
- label: entryLabel,
6211
- attribute,
6212
- status: "skipped",
6213
- message: `Skipped: Attribute "${attribute}" does not exist in schema for ${displayName}`
6214
- };
6455
+ flattenedDiffs.push(r);
6215
6456
  }
6216
- } catch (updateErr) {
6217
- return {
6218
- uid: target.uid,
6219
- collectionName: displayName,
6220
- documentId: target.documentId,
6221
- label: `Entry #${target.documentId}`,
6222
- attribute,
6223
- status: "error",
6224
- message: updateErr.message
6225
- };
6226
6457
  }
6227
- });
6228
- const chunkResults = await Promise.all(chunkPromises);
6229
- for (const res of chunkResults) {
6230
- if (res.status === "updated") updatedCount++;
6231
- else if (res.status === "skipped") skippedCount++;
6232
- results.push(res);
6233
- }
6234
- jobState.processedCount = results.length;
6235
- jobState.updatedCount = updatedCount;
6236
- jobState.skippedCount = skippedCount;
6237
- jobState.failedCount = results.filter((r) => r.status === "error").length;
6238
- }
6239
- const affectedUids = new Set(targets.map((t) => t.uid));
6240
- affectedUids.forEach((uid) => {
6241
- invalidateCollectionCache(uid);
6242
- });
6243
- const failedCount = results.filter((r) => r.status === "error").length;
6244
- jobState.failedCount = failedCount;
6245
- jobState.completedAt = (/* @__PURE__ */ new Date()).toISOString();
6246
- jobState.isLive = updatedCount > 0;
6247
- jobState.status = failedCount === 0 && updatedCount > 0 ? "successful" : failedCount > 0 && updatedCount > 0 ? "partial_failure" : failedCount > 0 ? "failed" : "successful";
6248
- jobState.results = results.map((r) => ({
6249
- ...r,
6250
- isLive: r.status === "updated"
6251
- }));
6252
- const flattenedDiffs = [];
6253
- for (const r of results) {
6254
- if (effectiveEditMode === "grid") {
6255
- flattenedDiffs.push(r);
6256
- } else if (r.dynamicZoneDiffs && r.dynamicZoneDiffs.length > 0) {
6257
- for (const dz of r.dynamicZoneDiffs) {
6258
- flattenedDiffs.push({
6259
- uid: r.uid,
6260
- collectionName: r.collectionName,
6261
- documentId: r.documentId,
6262
- label: `${r.label} [Block #${dz.index} (${dz.componentName})]`,
6263
- attribute: dz.attribute,
6264
- oldValue: dz.oldValue,
6265
- newValue: dz.newValue,
6266
- status: "updated",
6267
- message: `Updated ${dz.attribute}`
6268
- });
6458
+ const batchSummary = {
6459
+ batchId,
6460
+ attribute,
6461
+ value: effectiveSummaryVal,
6462
+ editMode: effectiveEditMode,
6463
+ updatedCount,
6464
+ skippedCount,
6465
+ totalTargets: targets.length,
6466
+ publishOnApproval,
6467
+ publishStrategy,
6468
+ unreviewedConsent
6469
+ };
6470
+ try {
6471
+ await strapi.plugin("bulk-updater").service("audit").recordBatch(
6472
+ batchSummary,
6473
+ flattenedDiffs,
6474
+ currentUser
6475
+ );
6476
+ } catch (auditErr) {
6477
+ strapi.log?.warn?.(
6478
+ `[bulk-updater] Non-fatal audit logging failure for batch ${batchId}: ${formatErrorWithCause(auditErr)}`
6479
+ );
6269
6480
  }
6270
- } else {
6271
- flattenedDiffs.push(r);
6481
+ return {
6482
+ success: true,
6483
+ batchId,
6484
+ attribute,
6485
+ value: effectiveSummaryVal,
6486
+ editMode: effectiveEditMode,
6487
+ updatedCount,
6488
+ skippedCount,
6489
+ failedCount,
6490
+ totalTargets: targets.length,
6491
+ isLive: jobState.isLive,
6492
+ status: jobState.status,
6493
+ results
6494
+ };
6495
+ } catch (fatalErr) {
6496
+ const formattedFatal = formatErrorWithCause(fatalErr, "Batch execution failed");
6497
+ jobState.status = "failed";
6498
+ jobState.error = formattedFatal;
6499
+ jobState.completedAt = (/* @__PURE__ */ new Date()).toISOString();
6500
+ strapi.log?.error?.(`[bulk-updater] Batch ${batchId} aborted with error: ${formattedFatal}`);
6501
+ throw fatalErr;
6272
6502
  }
6273
- }
6274
- const batchSummary = {
6275
- batchId,
6276
- attribute,
6277
- value: effectiveSummaryVal,
6278
- editMode: effectiveEditMode,
6279
- updatedCount,
6280
- skippedCount,
6281
- totalTargets: targets.length,
6282
- publishOnApproval,
6283
- publishStrategy,
6284
- unreviewedConsent
6285
- };
6286
- await strapi.plugin("bulk-updater").service("audit").recordBatch(
6287
- batchSummary,
6288
- flattenedDiffs,
6289
- currentUser
6290
- );
6291
- return {
6292
- success: true,
6293
- batchId,
6294
- attribute,
6295
- value: effectiveSummaryVal,
6296
- editMode: effectiveEditMode,
6297
- updatedCount,
6298
- skippedCount,
6299
- failedCount,
6300
- totalTargets: targets.length,
6301
- isLive: jobState.isLive,
6302
- status: jobState.status,
6303
- results
6304
- };
6503
+ });
6305
6504
  }
6306
6505
  async function executePublishBatchInternal(strapi, {
6307
6506
  selectedEntries = [],
@@ -6355,120 +6554,146 @@ async function executePublishBatchInternal(strapi, {
6355
6554
  results: []
6356
6555
  };
6357
6556
  batchJobsMap.set(batchId, jobState);
6358
- const targets = Array.from(targetsMap.values());
6359
- const CHUNK_SIZE = 25;
6360
- for (let i = 0; i < targets.length; i += CHUNK_SIZE) {
6361
- const chunk = targets.slice(i, i + CHUNK_SIZE);
6362
- const chunkPromises = chunk.map(async (target) => {
6363
- try {
6364
- const contentType = strapi.contentTypes[target.uid];
6365
- const displayName = contentType?.info?.displayName || target.uid;
6366
- const isDraftAndPublish = Boolean(contentType?.options?.draftAndPublish);
6367
- let existingDoc = null;
6368
- try {
6369
- existingDoc = await strapi.documents(target.uid).findOne({
6370
- documentId: target.documentId
6371
- });
6372
- } catch {
6373
- existingDoc = null;
6374
- }
6375
- const entryLabel = existingDoc?.name || existingDoc?.title || existingDoc?.label || existingDoc?.documentId || `Entry #${target.documentId}`;
6376
- if (!isDraftAndPublish) {
6377
- return {
6378
- uid: target.uid,
6379
- collectionName: displayName,
6380
- documentId: target.documentId,
6381
- label: entryLabel,
6382
- attribute: "(publish)",
6383
- status: "skipped",
6384
- message: `Skipped: Draft & Publish is disabled for collection ${displayName}`
6385
- };
6386
- }
6387
- const isAlreadyPublished = Boolean(existingDoc?.publishedAt);
6388
- await strapi.documents(target.uid).publish({
6389
- documentId: target.documentId
6390
- });
6391
- invalidateCollectionCache(target.uid);
6392
- await recordContentHistoryVersion(strapi, {
6393
- uid: target.uid,
6394
- documentId: target.documentId,
6395
- userId: currentUser?.id,
6396
- statusOverride: "published"
6557
+ return await trackActiveBulkOperation(async () => {
6558
+ try {
6559
+ const targets = Array.from(targetsMap.values());
6560
+ const CHUNK_SIZE = getBatchConcurrency(strapi);
6561
+ for (let i = 0; i < targets.length; i += CHUNK_SIZE) {
6562
+ const chunk = targets.slice(i, i + CHUNK_SIZE);
6563
+ const chunkPromises = chunk.map(async (target) => {
6564
+ try {
6565
+ const contentType = strapi.contentTypes[target.uid];
6566
+ const displayName = contentType?.info?.displayName || target.uid;
6567
+ const isDraftAndPublish = Boolean(contentType?.options?.draftAndPublish);
6568
+ let existingDoc = null;
6569
+ try {
6570
+ existingDoc = await strapi.documents(target.uid).findOne({
6571
+ documentId: target.documentId
6572
+ });
6573
+ } catch {
6574
+ existingDoc = null;
6575
+ }
6576
+ const entryLabel = existingDoc?.name || existingDoc?.title || existingDoc?.label || existingDoc?.documentId || `Entry #${target.documentId}`;
6577
+ if (!isDraftAndPublish) {
6578
+ return {
6579
+ uid: target.uid,
6580
+ collectionName: displayName,
6581
+ documentId: target.documentId,
6582
+ label: entryLabel,
6583
+ attribute: "(publish)",
6584
+ status: "skipped",
6585
+ message: `Skipped: Draft & Publish is disabled for collection ${displayName}`
6586
+ };
6587
+ }
6588
+ const isAlreadyPublished = Boolean(existingDoc?.publishedAt);
6589
+ await strapi.documents(target.uid).publish({
6590
+ documentId: target.documentId
6591
+ });
6592
+ invalidateCollectionCache(target.uid);
6593
+ await recordContentHistoryVersion(strapi, {
6594
+ uid: target.uid,
6595
+ documentId: target.documentId,
6596
+ userId: currentUser?.id,
6597
+ statusOverride: "published"
6598
+ });
6599
+ return {
6600
+ uid: target.uid,
6601
+ collectionName: displayName,
6602
+ documentId: target.documentId,
6603
+ label: entryLabel,
6604
+ attribute: "(publish)",
6605
+ oldValue: isAlreadyPublished ? "published" : "draft",
6606
+ newValue: "published",
6607
+ status: "updated",
6608
+ message: isAlreadyPublished ? "Re-published latest version live" : "Successfully published to live"
6609
+ };
6610
+ } catch (pubErr) {
6611
+ const formattedPubErr = formatErrorWithCause(pubErr, "Failed to publish entry");
6612
+ if (isFetchFailedError(pubErr)) {
6613
+ strapi.log?.error?.(
6614
+ `[bulk-updater] Network/webhook fetch error during batch publish ${batchId} of ${target.uid}/${target.documentId}: ${formattedPubErr}`
6615
+ );
6616
+ }
6617
+ return {
6618
+ uid: target.uid,
6619
+ collectionName: strapi.contentTypes[target.uid]?.info?.displayName || target.uid,
6620
+ documentId: target.documentId,
6621
+ label: `Entry #${target.documentId}`,
6622
+ attribute: "(publish)",
6623
+ status: "error",
6624
+ message: formattedPubErr
6625
+ };
6626
+ }
6397
6627
  });
6398
- return {
6399
- uid: target.uid,
6400
- collectionName: displayName,
6401
- documentId: target.documentId,
6402
- label: entryLabel,
6403
- attribute: "(publish)",
6404
- oldValue: isAlreadyPublished ? "published" : "draft",
6405
- newValue: "published",
6406
- status: "updated",
6407
- message: isAlreadyPublished ? "Re-published latest version live" : "Successfully published to live"
6408
- };
6409
- } catch (pubErr) {
6410
- return {
6411
- uid: target.uid,
6412
- collectionName: strapi.contentTypes[target.uid]?.info?.displayName || target.uid,
6413
- documentId: target.documentId,
6414
- label: `Entry #${target.documentId}`,
6415
- attribute: "(publish)",
6416
- status: "error",
6417
- message: pubErr.message || "Failed to publish entry"
6418
- };
6628
+ const chunkResults = await Promise.all(chunkPromises);
6629
+ for (const res of chunkResults) {
6630
+ if (res.status === "updated") publishedCount++;
6631
+ else if (res.status === "skipped") skippedCount++;
6632
+ results.push(res);
6633
+ }
6634
+ jobState.processedCount = results.length;
6635
+ jobState.updatedCount = publishedCount;
6636
+ jobState.skippedCount = skippedCount;
6637
+ jobState.failedCount = results.filter((r) => r.status === "error").length;
6638
+ if (i + CHUNK_SIZE < targets.length) {
6639
+ await new Promise((resolve) => setImmediate(resolve));
6640
+ }
6641
+ }
6642
+ const affectedUids = new Set(targets.map((t) => t.uid));
6643
+ affectedUids.forEach((uid) => {
6644
+ invalidateCollectionCache(uid);
6645
+ });
6646
+ const failedCount = results.filter((r) => r.status === "error").length;
6647
+ jobState.failedCount = failedCount;
6648
+ jobState.completedAt = (/* @__PURE__ */ new Date()).toISOString();
6649
+ jobState.isLive = publishedCount > 0;
6650
+ jobState.status = failedCount === 0 && publishedCount > 0 ? "successful" : failedCount > 0 && publishedCount > 0 ? "partial_failure" : failedCount > 0 ? "failed" : "successful";
6651
+ jobState.results = results.map((r) => ({
6652
+ ...r,
6653
+ isLive: r.status === "updated"
6654
+ }));
6655
+ const batchSummary = {
6656
+ batchId,
6657
+ attribute: "(publish)",
6658
+ value: "published",
6659
+ updatedCount: publishedCount,
6660
+ skippedCount,
6661
+ totalTargets: targetsMap.size,
6662
+ publishOnApproval: true,
6663
+ unreviewedConsent
6664
+ };
6665
+ try {
6666
+ await strapi.plugin("bulk-updater").service("audit").recordBatch(
6667
+ batchSummary,
6668
+ results,
6669
+ currentUser
6670
+ );
6671
+ } catch (auditErr) {
6672
+ strapi.log?.warn?.(
6673
+ `[bulk-updater] Non-fatal audit logging failure for publish batch ${batchId}: ${formatErrorWithCause(auditErr)}`
6674
+ );
6419
6675
  }
6420
- });
6421
- const chunkResults = await Promise.all(chunkPromises);
6422
- for (const res of chunkResults) {
6423
- if (res.status === "updated") publishedCount++;
6424
- else if (res.status === "skipped") skippedCount++;
6425
- results.push(res);
6426
- }
6427
- jobState.processedCount = results.length;
6428
- jobState.updatedCount = publishedCount;
6429
- jobState.skippedCount = skippedCount;
6430
- jobState.failedCount = results.filter((r) => r.status === "error").length;
6431
- }
6432
- const affectedUids = new Set(targets.map((t) => t.uid));
6433
- affectedUids.forEach((uid) => {
6434
- invalidateCollectionCache(uid);
6676
+ return {
6677
+ success: true,
6678
+ batchId,
6679
+ publishedCount,
6680
+ updatedCount: publishedCount,
6681
+ skippedCount,
6682
+ failedCount,
6683
+ totalTargets: targetsMap.size,
6684
+ isLive: publishedCount > 0,
6685
+ status: jobState.status,
6686
+ results
6687
+ };
6688
+ } catch (fatalErr) {
6689
+ const formattedFatal = formatErrorWithCause(fatalErr, "Batch publish failed");
6690
+ jobState.status = "failed";
6691
+ jobState.error = formattedFatal;
6692
+ jobState.completedAt = (/* @__PURE__ */ new Date()).toISOString();
6693
+ strapi.log?.error?.(`[bulk-updater] Publish batch ${batchId} aborted with error: ${formattedFatal}`);
6694
+ throw fatalErr;
6695
+ }
6435
6696
  });
6436
- const failedCount = results.filter((r) => r.status === "error").length;
6437
- jobState.failedCount = failedCount;
6438
- jobState.completedAt = (/* @__PURE__ */ new Date()).toISOString();
6439
- jobState.isLive = publishedCount > 0;
6440
- jobState.status = failedCount === 0 && publishedCount > 0 ? "successful" : failedCount > 0 && publishedCount > 0 ? "partial_failure" : failedCount > 0 ? "failed" : "successful";
6441
- jobState.results = results.map((r) => ({
6442
- ...r,
6443
- isLive: r.status === "updated"
6444
- }));
6445
- const batchSummary = {
6446
- batchId,
6447
- attribute: "(publish)",
6448
- value: "published",
6449
- updatedCount: publishedCount,
6450
- skippedCount,
6451
- totalTargets: targetsMap.size,
6452
- publishOnApproval: true,
6453
- unreviewedConsent
6454
- };
6455
- await strapi.plugin("bulk-updater").service("audit").recordBatch(
6456
- batchSummary,
6457
- results,
6458
- currentUser
6459
- );
6460
- return {
6461
- success: true,
6462
- batchId,
6463
- publishedCount,
6464
- updatedCount: publishedCount,
6465
- skippedCount,
6466
- failedCount,
6467
- totalTargets: targetsMap.size,
6468
- isLive: publishedCount > 0,
6469
- status: jobState.status,
6470
- results
6471
- };
6472
6697
  }
6473
6698
  async function executeBatchByPayload(strapi, batch, currentUser) {
6474
6699
  if (batch.payload?.action === "csv_import") {
@@ -8845,21 +9070,20 @@ const auditService = ({ strapi }) => ({
8845
9070
  const isDynamicZone = rootAttrDef?.type === "dynamiczone";
8846
9071
  const isNested = item.attribute.includes(".") || item.attribute.includes("[") || isComponent || isDynamicZone || isDeepComponentField(ct, strapi.components, item.attribute);
8847
9072
  const isLocalized = Boolean(ct?.pluginOptions?.i18n?.localized) && item.locale && item.locale !== "null" && item.locale !== "undefined";
8848
- let wasPublished = false;
9073
+ const isDraftAndPublish = Boolean(ct?.options?.draftAndPublish ?? item.isDraftAndPublish);
9074
+ const populateOption = isNested ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
9075
+ const findOneArgs = { documentId: item.documentId };
9076
+ if (populateOption) {
9077
+ findOneArgs.populate = populateOption;
9078
+ }
9079
+ if (isLocalized) {
9080
+ findOneArgs.locale = item.locale;
9081
+ }
9082
+ const currentDoc = await strapi.documents(item.uid).findOne(findOneArgs);
9083
+ if (!currentDoc) {
9084
+ throw new Error(`Document "${item.documentId}" not found in collection "${item.uid}".`);
9085
+ }
8849
9086
  if (isNested && (isComponent || isDynamicZone || rootAttrDef)) {
8850
- const populateOption = buildDeepPopulate(ct.attributes, strapi.components);
8851
- const findOneArgs = { documentId: item.documentId };
8852
- if (populateOption) {
8853
- findOneArgs.populate = populateOption;
8854
- }
8855
- if (isLocalized) {
8856
- findOneArgs.locale = item.locale;
8857
- }
8858
- const currentDoc = await strapi.documents(item.uid).findOne(findOneArgs);
8859
- if (!currentDoc) {
8860
- throw new Error(`Document "${item.documentId}" not found in collection "${item.uid}".`);
8861
- }
8862
- wasPublished = Boolean(currentDoc?.publishedAt);
8863
9087
  const isRootDz = isDynamicZone;
8864
9088
  const existingRoot = currentDoc?.[rootKey] || (isRootDz ? [] : {});
8865
9089
  let restoredRoot;
@@ -8925,11 +9149,6 @@ const auditService = ({ strapi }) => ({
8925
9149
  }
8926
9150
  });
8927
9151
  } else {
8928
- const currentDoc = await strapi.documents(item.uid).findOne({
8929
- documentId: item.documentId,
8930
- ...isLocalized ? { locale: item.locale } : {}
8931
- });
8932
- wasPublished = Boolean(currentDoc?.publishedAt);
8933
9152
  await strapi.documents(item.uid).update({
8934
9153
  documentId: item.documentId,
8935
9154
  ...isLocalized ? { locale: item.locale } : {},
@@ -8938,14 +9157,85 @@ const auditService = ({ strapi }) => ({
8938
9157
  }
8939
9158
  });
8940
9159
  }
8941
- if (ct?.options?.draftAndPublish && wasPublished) {
9160
+ let targetStatus = void 0;
9161
+ if (item.previousStatus === "published" || item.previousStatus === "modified" || item.previousStatus === "draft") {
9162
+ targetStatus = item.previousStatus;
9163
+ } else if (item.hadPublishedVersion === false) {
9164
+ targetStatus = "draft";
9165
+ } else if (item.hadPublishedVersion === true) {
9166
+ targetStatus = "published";
9167
+ }
9168
+ if (isDraftAndPublish && !targetStatus) {
9169
+ let publishedCounterpart = null;
8942
9170
  try {
8943
- await strapi.documents(item.uid).publish({
8944
- documentId: item.documentId,
8945
- ...isLocalized ? { locale: item.locale } : {}
8946
- });
8947
- } catch (publishErr) {
8948
- strapi.log.warn(`[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`, publishErr?.message);
9171
+ const docSvc = strapi.documents(item.uid);
9172
+ if (typeof docSvc.findMany === "function") {
9173
+ const pubs = await docSvc.findMany({
9174
+ status: "published",
9175
+ filters: { documentId: item.documentId },
9176
+ fields: ["documentId", "publishedAt"],
9177
+ limit: 1,
9178
+ ...isLocalized ? { locale: item.locale } : {}
9179
+ });
9180
+ if (pubs && pubs.length > 0) {
9181
+ publishedCounterpart = pubs[0];
9182
+ }
9183
+ }
9184
+ } catch {
9185
+ }
9186
+ if (publishedCounterpart?.publishedAt || currentDoc?.publishedAt) {
9187
+ targetStatus = "published";
9188
+ } else {
9189
+ targetStatus = "draft";
9190
+ }
9191
+ }
9192
+ if (isDraftAndPublish) {
9193
+ const docSvc = strapi.documents(item.uid);
9194
+ if (targetStatus === "published") {
9195
+ try {
9196
+ if (typeof docSvc.publish === "function") {
9197
+ await docSvc.publish({
9198
+ documentId: item.documentId,
9199
+ ...isLocalized ? { locale: item.locale } : {}
9200
+ });
9201
+ }
9202
+ } catch (publishErr) {
9203
+ strapi.log.warn(
9204
+ `[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`,
9205
+ publishErr?.message
9206
+ );
9207
+ }
9208
+ } else if (targetStatus === "draft") {
9209
+ try {
9210
+ if (typeof docSvc.unpublish === "function") {
9211
+ let hasPublished = false;
9212
+ if (typeof docSvc.findMany === "function") {
9213
+ const pubs = await docSvc.findMany({
9214
+ status: "published",
9215
+ filters: { documentId: item.documentId },
9216
+ fields: ["documentId", "publishedAt"],
9217
+ limit: 1,
9218
+ ...isLocalized ? { locale: item.locale } : {}
9219
+ });
9220
+ if (pubs && pubs.length > 0) {
9221
+ hasPublished = true;
9222
+ }
9223
+ } else if (currentDoc?.publishedAt) {
9224
+ hasPublished = true;
9225
+ }
9226
+ if (hasPublished) {
9227
+ await docSvc.unpublish({
9228
+ documentId: item.documentId,
9229
+ ...isLocalized ? { locale: item.locale } : {}
9230
+ });
9231
+ }
9232
+ }
9233
+ } catch (unpubErr) {
9234
+ strapi.log.warn(
9235
+ `[bulk-updater] Failed to unpublish rollback for ${item.uid}/${item.documentId}:`,
9236
+ unpubErr?.message
9237
+ );
9238
+ }
8949
9239
  }
8950
9240
  }
8951
9241
  try {
@@ -8953,7 +9243,7 @@ const auditService = ({ strapi }) => ({
8953
9243
  uid: item.uid,
8954
9244
  documentId: item.documentId,
8955
9245
  userId,
8956
- statusOverride: ct?.options?.draftAndPublish ? wasPublished ? "published" : "draft" : void 0
9246
+ statusOverride: isDraftAndPublish ? targetStatus : "published"
8957
9247
  });
8958
9248
  } catch {
8959
9249
  }
@@ -8971,7 +9261,8 @@ const auditService = ({ strapi }) => ({
8971
9261
  label: item.label,
8972
9262
  attribute: item.attribute,
8973
9263
  revertedTo: item.oldValue,
8974
- status: "reverted"
9264
+ status: "reverted",
9265
+ restoredLifecycleStatus: isDraftAndPublish ? targetStatus : "published"
8975
9266
  });
8976
9267
  } catch (err) {
8977
9268
  rollbackDetails.push({
@@ -9686,6 +9977,9 @@ function extractDetailedErrorMessage(err) {
9686
9977
  if (err.details?.message) {
9687
9978
  return err.details.message;
9688
9979
  }
9980
+ if (isFetchFailedError(err) || err.cause) {
9981
+ return formatErrorWithCause(err, "Error processing row");
9982
+ }
9689
9983
  if (err.message && err.message !== "[object Object]") {
9690
9984
  return err.message;
9691
9985
  }
@@ -9915,7 +10209,7 @@ async function executeUpdateMutation(strapi, ct, uid, existing, row, rowNumber,
9915
10209
  ...rowStatus ? { status: rowStatus } : {},
9916
10210
  ...rowPubAt ? { publishedAt: rowPubAt } : {}
9917
10211
  } : existing;
9918
- const { hadPublishedVersion } = resolveRecordPublicationStatus(
10212
+ const { hadPublishedVersion, status: preStatus } = resolveRecordPublicationStatus(
9919
10213
  inspectionExisting,
9920
10214
  pubRecord,
9921
10215
  isDraftAndPublish
@@ -9966,7 +10260,9 @@ async function executeUpdateMutation(strapi, ct, uid, existing, row, rowNumber,
9966
10260
  if (effectiveLocale) pubArgs.locale = effectiveLocale;
9967
10261
  await strapi.documents(uid).publish(pubArgs);
9968
10262
  } catch (pubErr) {
9969
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${resolvedDocId}:`, pubErr);
10263
+ strapi.log.warn(
10264
+ `[bulk-updater] Auto-publish failed for ${uid}/${resolvedDocId}: ${formatErrorWithCause(pubErr)}`
10265
+ );
9970
10266
  }
9971
10267
  }
9972
10268
  try {
@@ -10000,11 +10296,15 @@ async function executeUpdateMutation(strapi, ct, uid, existing, row, rowNumber,
10000
10296
  uid,
10001
10297
  collectionName: ct.info?.displayName || uid,
10002
10298
  documentId: resolvedDocId,
10299
+ locale: effectiveLocale,
10003
10300
  label: existing.title || existing.name || `Entry #${resolvedDocId}`,
10004
10301
  attribute: attrKey,
10005
10302
  oldValue: oldVal,
10006
10303
  newValue: newVal,
10007
10304
  status: "updated",
10305
+ previousStatus: preStatus,
10306
+ hadPublishedVersion,
10307
+ isDraftAndPublish,
10008
10308
  message: `${actionLabel} "${attrKey}" via CSV import (row ${rowNumber})`
10009
10309
  });
10010
10310
  }
@@ -10084,7 +10384,9 @@ async function executeCreateMutation(strapi, ct, uid, docId, row, rowNumber, opt
10084
10384
  if (effectiveLocale) pubArgs.locale = effectiveLocale;
10085
10385
  await strapi.documents(uid).publish(pubArgs);
10086
10386
  } catch (pubErr) {
10087
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${newDocId}:`, pubErr);
10387
+ strapi.log.warn(
10388
+ `[bulk-updater] Auto-publish failed for ${uid}/${newDocId}: ${formatErrorWithCause(pubErr)}`
10389
+ );
10088
10390
  }
10089
10391
  }
10090
10392
  try {
@@ -10115,177 +10417,121 @@ async function executeCreateMutation(strapi, ct, uid, docId, row, rowNumber, opt
10115
10417
  }
10116
10418
  }
10117
10419
  async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
10118
- ct.attributes || {};
10119
- const { mode = "auto", publish = true, publishStrategy = "safe", user, originalHeaders } = options;
10120
- const isDraftAndPublish = Boolean(ct.options?.draftAndPublish);
10121
- const docIdsInChunk = rows.map((r) => extractDocId(r)).filter(Boolean);
10122
- const publishedCounterparts = /* @__PURE__ */ new Map();
10123
- if (isDraftAndPublish && docIdsInChunk.length > 0) {
10124
- try {
10125
- const pubDocs = await strapi.documents(uid).findMany({
10126
- status: "published",
10127
- filters: { documentId: { $in: docIdsInChunk } },
10128
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
10129
- limit: Math.max(docIdsInChunk.length, 100)
10130
- });
10131
- for (const pub of pubDocs || []) {
10132
- if (pub?.documentId) {
10133
- publishedCounterparts.set(String(pub.documentId), pub);
10134
- if (pub.locale) {
10135
- publishedCounterparts.set(`${pub.documentId}@@@${pub.locale}`, pub);
10420
+ return await trackActiveBulkOperation(async () => {
10421
+ const attrs = ct.attributes || {};
10422
+ const { mode = "auto", publish = true, publishStrategy = "safe", user, originalHeaders } = options;
10423
+ const isDraftAndPublish = Boolean(ct.options?.draftAndPublish);
10424
+ const docIdsInChunk = rows.map((r) => extractDocId(r)).filter(Boolean);
10425
+ const publishedCounterparts = /* @__PURE__ */ new Map();
10426
+ if (isDraftAndPublish && docIdsInChunk.length > 0) {
10427
+ try {
10428
+ const pubDocs = await strapi.documents(uid).findMany({
10429
+ status: "published",
10430
+ filters: { documentId: { $in: docIdsInChunk } },
10431
+ fields: ["documentId", "updatedAt", "publishedAt", "locale"],
10432
+ limit: Math.max(docIdsInChunk.length, 100)
10433
+ });
10434
+ for (const pub of pubDocs || []) {
10435
+ if (pub?.documentId) {
10436
+ publishedCounterparts.set(String(pub.documentId), pub);
10437
+ if (pub.locale) {
10438
+ publishedCounterparts.set(`${pub.documentId}@@@${pub.locale}`, pub);
10439
+ }
10136
10440
  }
10137
10441
  }
10442
+ } catch {
10138
10443
  }
10139
- } catch {
10140
10444
  }
10141
- }
10142
- const stats = {
10143
- total: rows.length,
10144
- created: 0,
10145
- updated: 0,
10146
- skipped: 0,
10147
- failed: 0,
10148
- newWithoutDocId: 0,
10149
- errors: [],
10150
- failedRows: [],
10151
- diffs: []
10152
- };
10153
- const batchModeInfo = detectCsvBatchExportMode(rows);
10154
- if (batchModeInfo.error) {
10445
+ const stats = {
10446
+ total: rows.length,
10447
+ created: 0,
10448
+ updated: 0,
10449
+ skipped: 0,
10450
+ failed: 0,
10451
+ newWithoutDocId: 0,
10452
+ errors: [],
10453
+ failedRows: [],
10454
+ diffs: []
10455
+ };
10456
+ const batchModeInfo = detectCsvBatchExportMode(rows);
10457
+ if (batchModeInfo.error) {
10458
+ for (let i = 0; i < rows.length; i++) {
10459
+ const rowNumber = startRowNumber + i;
10460
+ const row = rows[i];
10461
+ const docId = extractDocId(row);
10462
+ stats.skipped++;
10463
+ if (stats.failed !== void 0) stats.failed++;
10464
+ recordFailedCsvRow(
10465
+ stats,
10466
+ rowNumber,
10467
+ row,
10468
+ batchModeInfo.error,
10469
+ docId || void 0,
10470
+ originalHeaders
10471
+ );
10472
+ stats.diffs.push({
10473
+ uid,
10474
+ collectionName: ct.info?.displayName || uid,
10475
+ documentId: docId || `(Row #${rowNumber})`,
10476
+ label: `Row #${rowNumber}`,
10477
+ attribute: "__bulk_updater_metadata",
10478
+ oldValue: null,
10479
+ newValue: null,
10480
+ status: "error",
10481
+ message: batchModeInfo.error
10482
+ });
10483
+ }
10484
+ return stats;
10485
+ }
10486
+ const rowOptions = {
10487
+ ...options,
10488
+ expectedExportMode: batchModeInfo.mode
10489
+ };
10155
10490
  for (let i = 0; i < rows.length; i++) {
10156
10491
  const rowNumber = startRowNumber + i;
10157
10492
  const row = rows[i];
10158
- const docId = extractDocId(row);
10159
- stats.skipped++;
10160
- if (stats.failed !== void 0) stats.failed++;
10161
- recordFailedCsvRow(
10162
- stats,
10163
- rowNumber,
10164
- row,
10165
- batchModeInfo.error,
10166
- docId || void 0,
10167
- originalHeaders
10168
- );
10169
- stats.diffs.push({
10170
- uid,
10171
- collectionName: ct.info?.displayName || uid,
10172
- documentId: docId || `(Row #${rowNumber})`,
10173
- label: `Row #${rowNumber}`,
10174
- attribute: "__bulk_updater_metadata",
10175
- oldValue: null,
10176
- newValue: null,
10177
- status: "error",
10178
- message: batchModeInfo.error
10179
- });
10180
- }
10181
- return stats;
10182
- }
10183
- const rowOptions = {
10184
- ...options,
10185
- expectedExportMode: batchModeInfo.mode
10186
- };
10187
- for (let i = 0; i < rows.length; i++) {
10188
- const rowNumber = startRowNumber + i;
10189
- const row = rows[i];
10190
- let docId = extractDocId(row);
10191
- const rowLocale = extractLocale(row);
10192
- const effectiveLocale = getEffectiveLocale(ct, rowLocale);
10193
- const isEditing = isRowInEditingStage(row);
10194
- if (ct.kind === "singleType" && !docId) {
10195
- try {
10196
- const findSingleArgs = {};
10197
- if (effectiveLocale) findSingleArgs.locale = effectiveLocale;
10198
- const singleDoc = await strapi.documents(uid).findFirst(findSingleArgs);
10199
- if (singleDoc?.documentId) {
10200
- docId = singleDoc.documentId;
10493
+ let docId = extractDocId(row);
10494
+ const rowLocale = extractLocale(row);
10495
+ const effectiveLocale = getEffectiveLocale(ct, rowLocale);
10496
+ const isEditing = isRowInEditingStage(row);
10497
+ if (ct.kind === "singleType" && !docId) {
10498
+ try {
10499
+ const findSingleArgs = {};
10500
+ if (effectiveLocale) findSingleArgs.locale = effectiveLocale;
10501
+ const singleDoc = await strapi.documents(uid).findFirst(findSingleArgs);
10502
+ if (singleDoc?.documentId) {
10503
+ docId = singleDoc.documentId;
10504
+ }
10505
+ } catch {
10201
10506
  }
10202
- } catch {
10203
10507
  }
10204
- }
10205
- try {
10206
- if (mode === "update") {
10207
- if (!docId) {
10208
- stats.skipped++;
10209
- recordFailedCsvRow(
10210
- stats,
10211
- rowNumber,
10212
- row,
10213
- "Missing or invalid documentId for Update mode. (Tip: Use Smart Auto-Detect mode to auto-add entries without document IDs).",
10214
- void 0,
10215
- originalHeaders
10216
- );
10217
- continue;
10218
- }
10219
- const existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
10220
- if (!existing) {
10221
- stats.skipped++;
10222
- recordFailedCsvRow(
10223
- stats,
10224
- rowNumber,
10225
- row,
10226
- `Document with ID "${docId}" not found in database.`,
10227
- docId,
10228
- originalHeaders
10229
- );
10230
- continue;
10231
- }
10232
- await executeUpdateMutation(
10233
- strapi,
10234
- ct,
10235
- uid,
10236
- existing,
10237
- row,
10238
- rowNumber,
10239
- rowOptions,
10240
- effectiveLocale,
10241
- isEditing,
10242
- isDraftAndPublish,
10243
- publishedCounterparts,
10244
- stats,
10245
- "Updated"
10246
- );
10247
- } else if (mode === "create_or_override") {
10248
- let existing = null;
10249
- if (docId) {
10250
- existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
10251
- }
10252
- if (existing) {
10253
- await executeUpdateMutation(
10254
- strapi,
10255
- ct,
10256
- uid,
10257
- existing,
10258
- row,
10259
- rowNumber,
10260
- rowOptions,
10261
- effectiveLocale,
10262
- isEditing,
10263
- isDraftAndPublish,
10264
- publishedCounterparts,
10265
- stats,
10266
- "Overridden"
10267
- );
10268
- } else {
10269
- await executeCreateMutation(
10270
- strapi,
10271
- ct,
10272
- uid,
10273
- docId,
10274
- row,
10275
- rowNumber,
10276
- rowOptions,
10277
- effectiveLocale,
10278
- isEditing,
10279
- isDraftAndPublish,
10280
- stats
10281
- );
10282
- }
10283
- } else {
10284
- let existing = null;
10285
- if (docId) {
10286
- existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
10287
- }
10288
- if (existing) {
10508
+ try {
10509
+ if (mode === "update") {
10510
+ if (!docId) {
10511
+ stats.skipped++;
10512
+ recordFailedCsvRow(
10513
+ stats,
10514
+ rowNumber,
10515
+ row,
10516
+ "Missing or invalid documentId for Update mode. (Tip: Use Smart Auto-Detect mode to auto-add entries without document IDs).",
10517
+ void 0,
10518
+ originalHeaders
10519
+ );
10520
+ continue;
10521
+ }
10522
+ const existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
10523
+ if (!existing) {
10524
+ stats.skipped++;
10525
+ recordFailedCsvRow(
10526
+ stats,
10527
+ rowNumber,
10528
+ row,
10529
+ `Document with ID "${docId}" not found in database.`,
10530
+ docId,
10531
+ originalHeaders
10532
+ );
10533
+ continue;
10534
+ }
10289
10535
  await executeUpdateMutation(
10290
10536
  strapi,
10291
10537
  ct,
@@ -10301,48 +10547,114 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
10301
10547
  stats,
10302
10548
  "Updated"
10303
10549
  );
10550
+ } else if (mode === "create_or_override") {
10551
+ let existing = null;
10552
+ if (docId) {
10553
+ existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
10554
+ }
10555
+ if (existing) {
10556
+ await executeUpdateMutation(
10557
+ strapi,
10558
+ ct,
10559
+ uid,
10560
+ existing,
10561
+ row,
10562
+ rowNumber,
10563
+ rowOptions,
10564
+ effectiveLocale,
10565
+ isEditing,
10566
+ isDraftAndPublish,
10567
+ publishedCounterparts,
10568
+ stats,
10569
+ "Overridden"
10570
+ );
10571
+ } else {
10572
+ await executeCreateMutation(
10573
+ strapi,
10574
+ ct,
10575
+ uid,
10576
+ docId,
10577
+ row,
10578
+ rowNumber,
10579
+ rowOptions,
10580
+ effectiveLocale,
10581
+ isEditing,
10582
+ isDraftAndPublish,
10583
+ stats
10584
+ );
10585
+ }
10304
10586
  } else {
10305
- await executeCreateMutation(
10306
- strapi,
10307
- ct,
10308
- uid,
10309
- docId,
10310
- row,
10311
- rowNumber,
10312
- rowOptions,
10313
- effectiveLocale,
10314
- isEditing,
10315
- isDraftAndPublish,
10316
- stats
10587
+ let existing = null;
10588
+ if (docId) {
10589
+ existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
10590
+ }
10591
+ if (existing) {
10592
+ await executeUpdateMutation(
10593
+ strapi,
10594
+ ct,
10595
+ uid,
10596
+ existing,
10597
+ row,
10598
+ rowNumber,
10599
+ rowOptions,
10600
+ effectiveLocale,
10601
+ isEditing,
10602
+ isDraftAndPublish,
10603
+ publishedCounterparts,
10604
+ stats,
10605
+ "Updated"
10606
+ );
10607
+ } else {
10608
+ await executeCreateMutation(
10609
+ strapi,
10610
+ ct,
10611
+ uid,
10612
+ docId,
10613
+ row,
10614
+ rowNumber,
10615
+ rowOptions,
10616
+ effectiveLocale,
10617
+ isEditing,
10618
+ isDraftAndPublish,
10619
+ stats
10620
+ );
10621
+ }
10622
+ }
10623
+ } catch (err) {
10624
+ stats.skipped++;
10625
+ if (stats.failed !== void 0) stats.failed++;
10626
+ const errMsg = sanitizeUserErrorMessage(extractDetailedErrorMessage(err));
10627
+ if (isFetchFailedError(err)) {
10628
+ strapi.log?.error?.(
10629
+ `[bulk-updater] Network/webhook fetch error during CSV import row ${rowNumber} (${uid}/${docId || "new"}): ${errMsg}`
10317
10630
  );
10318
10631
  }
10632
+ recordFailedCsvRow(
10633
+ stats,
10634
+ rowNumber,
10635
+ row,
10636
+ errMsg,
10637
+ docId || void 0,
10638
+ originalHeaders
10639
+ );
10640
+ stats.diffs.push({
10641
+ uid,
10642
+ collectionName: ct.info?.displayName || uid,
10643
+ documentId: docId || `(Row #${rowNumber})`,
10644
+ label: `Row #${rowNumber}`,
10645
+ attribute: "(record)",
10646
+ oldValue: null,
10647
+ newValue: null,
10648
+ status: "error",
10649
+ message: `Failed to process row ${rowNumber}: ${errMsg}`
10650
+ });
10651
+ }
10652
+ if (i > 0 && i % 10 === 0) {
10653
+ await new Promise((resolve) => setImmediate(resolve));
10319
10654
  }
10320
- } catch (err) {
10321
- stats.skipped++;
10322
- if (stats.failed !== void 0) stats.failed++;
10323
- const errMsg = sanitizeUserErrorMessage(extractDetailedErrorMessage(err));
10324
- recordFailedCsvRow(
10325
- stats,
10326
- rowNumber,
10327
- row,
10328
- errMsg,
10329
- docId || void 0,
10330
- originalHeaders
10331
- );
10332
- stats.diffs.push({
10333
- uid,
10334
- collectionName: ct.info?.displayName || uid,
10335
- documentId: docId || `(Row #${rowNumber})`,
10336
- label: `Row #${rowNumber}`,
10337
- attribute: "(record)",
10338
- oldValue: null,
10339
- newValue: null,
10340
- status: "error",
10341
- message: `Failed to process row ${rowNumber}: ${errMsg}`
10342
- });
10343
10655
  }
10344
- }
10345
- return stats;
10656
+ return stats;
10657
+ });
10346
10658
  }
10347
10659
  async function recordCsvAuditLog(strapi, ct, uid, batchId, stats, user, publishOnApproval, publishStrategy, unreviewedConsent) {
10348
10660
  if (stats.updated === 0 && stats.created === 0) return;
@@ -11792,6 +12104,7 @@ const index = {
11792
12104
  });
11793
12105
  },
11794
12106
  bootstrap({ strapi }) {
12107
+ installUndiciCrashGuard(strapi);
11795
12108
  strapi.server.use(async (ctx, next) => {
11796
12109
  try {
11797
12110
  await next();
@@ -11814,6 +12127,9 @@ const index = {
11814
12127
  }
11815
12128
  });
11816
12129
  strapi.documents.use(async (context, next) => {
12130
+ if (typeof context.uid === "string" && context.uid.startsWith("plugin::bulk-updater.")) {
12131
+ return await next();
12132
+ }
11817
12133
  const params = context.params;
11818
12134
  if (["create", "update"].includes(context.action)) {
11819
12135
  const data = params?.data;
@@ -11996,9 +12312,14 @@ exports.extractHeadingsFromRichText = extractHeadingsFromRichText;
11996
12312
  exports.extractMetadataFromRow = extractMetadataFromRow;
11997
12313
  exports.extractRowFlattenedMetadata = extractRowFlattenedMetadata;
11998
12314
  exports.formatErrorCsvFilename = formatErrorCsvFilename;
12315
+ exports.formatErrorWithCause = formatErrorWithCause;
12316
+ exports.getActiveBulkOperationCount = getActiveBulkOperationCount;
11999
12317
  exports.getAllNestedValues = getAllNestedValues;
12318
+ exports.getBatchConcurrency = getBatchConcurrency;
12000
12319
  exports.getDeepProp = getDeepProp;
12001
12320
  exports.inspectRowMetadataMode = inspectRowMetadataMode;
12321
+ exports.installUndiciCrashGuard = installUndiciCrashGuard;
12322
+ exports.isFetchFailedError = isFetchFailedError;
12002
12323
  exports.isPlainObject = isPlainObject;
12003
12324
  exports.isValidDocumentId = isValidDocumentId;
12004
12325
  exports.normalizeExportMode = normalizeExportMode;
@@ -12016,12 +12337,14 @@ exports.resolveErrorColumnName = resolveErrorColumnName;
12016
12337
  exports.resolveMediaIds = resolveMediaIds;
12017
12338
  exports.resolveRelationPayload = resolveRelationPayload;
12018
12339
  exports.resolveTargetObjectField = resolveTargetObjectField;
12340
+ exports.sanitizeSensitiveErrorText = sanitizeSensitiveErrorText;
12019
12341
  exports.sanitizeUserErrorMessage = sanitizeUserErrorMessage;
12020
12342
  exports.serializeDocumentsToCsv = serializeDocumentsToCsv;
12021
12343
  exports.serializeFieldValue = serializeFieldValue;
12022
12344
  exports.serializePlannedCell = serializePlannedCell;
12023
12345
  exports.setDeepProp = setDeepProp;
12024
12346
  exports.sortAuditRecordsDesc = sortAuditRecordsDesc;
12347
+ exports.trackActiveBulkOperation = trackActiveBulkOperation;
12025
12348
  exports.validateEntityQuotas = validateEntityQuotas;
12026
12349
  exports.validateRecordSchemaConstraints = validateRecordSchemaConstraints;
12027
12350
  exports.verifyDocumentIntegrity = verifyDocumentIntegrity;