strapi-plugin-bulk-updater 1.5.13 → 1.5.14

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.
@@ -1836,14 +1836,14 @@ function resolveContentTypeField(contentType, field) {
1836
1836
  if (matched) return matched;
1837
1837
  return null;
1838
1838
  }
1839
- function buildDeepPopulate$1(attributes, allComponents, depth = 0) {
1839
+ function buildDeepPopulate(attributes, allComponents, depth = 0) {
1840
1840
  if (depth > 5) return void 0;
1841
1841
  const populate = {};
1842
1842
  for (const [key, def] of Object.entries(attributes || {})) {
1843
1843
  if (def.type === "component" && def.component) {
1844
1844
  const comp = allComponents[def.component];
1845
1845
  if (comp?.attributes) {
1846
- const subPopulate = buildDeepPopulate$1(comp.attributes, allComponents, depth + 1);
1846
+ const subPopulate = buildDeepPopulate(comp.attributes, allComponents, depth + 1);
1847
1847
  if (subPopulate && Object.keys(subPopulate).length > 0) {
1848
1848
  populate[key] = {
1849
1849
  populate: subPopulate
@@ -2377,7 +2377,7 @@ async function executeBatchInternal(strapi, {
2377
2377
  const loaderKey = `${uid}@@@${documentId}`;
2378
2378
  if (!documentLoader.has(loaderKey)) {
2379
2379
  const ct = strapi.contentTypes[uid];
2380
- const populateDef = ct?.attributes ? buildDeepPopulate$1(ct.attributes, strapi.components) : void 0;
2380
+ const populateDef = ct?.attributes ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
2381
2381
  documentLoader.set(
2382
2382
  loaderKey,
2383
2383
  strapi.documents(uid).findOne({
@@ -2407,7 +2407,7 @@ async function executeBatchInternal(strapi, {
2407
2407
  const hasAttribute = Boolean(attrDef) || isComponentNested;
2408
2408
  if (hasAttribute) {
2409
2409
  if (isComponentNested) {
2410
- const populateOption = buildDeepPopulate$1(contentType.attributes, strapi.components);
2410
+ const populateOption = buildDeepPopulate(contentType.attributes, strapi.components);
2411
2411
  const findOneArgs = { documentId: target.documentId };
2412
2412
  if (populateOption) {
2413
2413
  findOneArgs.populate = populateOption;
@@ -3251,7 +3251,7 @@ const bulkUpdaterService = ({ strapi }) => {
3251
3251
  let entries = [];
3252
3252
  let totalCount = 0;
3253
3253
  try {
3254
- const populateOption = buildDeepPopulate$1(allContentTypes[uid]?.attributes || {}, strapi.components);
3254
+ const populateOption = buildDeepPopulate(allContentTypes[uid]?.attributes || {}, strapi.components);
3255
3255
  if (meta.isSingleType) {
3256
3256
  const singleArgs = {};
3257
3257
  if (populateOption) {
@@ -3523,7 +3523,7 @@ const bulkUpdaterService = ({ strapi }) => {
3523
3523
  }
3524
3524
  }
3525
3525
  }
3526
- const populateOption = buildDeepPopulate$1(contentType.attributes, strapi.components);
3526
+ const populateOption = buildDeepPopulate(contentType.attributes, strapi.components);
3527
3527
  if (isSingleType) {
3528
3528
  let singleDoc = null;
3529
3529
  try {
@@ -3801,7 +3801,7 @@ const bulkUpdaterService = ({ strapi }) => {
3801
3801
  let currentEntry;
3802
3802
  if (isComponentNested) {
3803
3803
  const findOneArgs = { documentId: target.documentId };
3804
- const populateOption = buildDeepPopulate$1(contentType.attributes, strapi.components);
3804
+ const populateOption = buildDeepPopulate(contentType.attributes, strapi.components);
3805
3805
  if (populateOption) {
3806
3806
  findOneArgs.populate = populateOption;
3807
3807
  }
@@ -5013,6 +5013,39 @@ const DEFAULT_CANDIDATE_TYPES = [
5013
5013
  "api::audit.audit",
5014
5014
  "api::bulk-audit-log.bulk-audit-log"
5015
5015
  ];
5016
+ function sortAuditRecordsDesc(records) {
5017
+ return [...records].sort((a, b) => {
5018
+ const timeA = a.executedAt || a.createdAt ? new Date(a.executedAt || a.createdAt).getTime() : 0;
5019
+ const validTimeA = Number.isNaN(timeA) ? 0 : timeA;
5020
+ const timeB = b.executedAt || b.createdAt ? new Date(b.executedAt || b.createdAt).getTime() : 0;
5021
+ const validTimeB = Number.isNaN(timeB) ? 0 : timeB;
5022
+ if (validTimeB !== validTimeA) {
5023
+ return validTimeB - validTimeA;
5024
+ }
5025
+ if (typeof a.id === "number" && typeof b.id === "number") {
5026
+ return b.id - a.id;
5027
+ }
5028
+ const idA = String(a.id ?? a.batchId ?? "");
5029
+ const idB = String(b.id ?? b.batchId ?? "");
5030
+ return idB.localeCompare(idA);
5031
+ });
5032
+ }
5033
+ let rollbackLock = Promise.resolve();
5034
+ function withRollbackLock(fn) {
5035
+ const previousLock = rollbackLock;
5036
+ let release = () => {
5037
+ };
5038
+ rollbackLock = new Promise((resolve) => {
5039
+ release = resolve;
5040
+ });
5041
+ return previousLock.then(async () => {
5042
+ try {
5043
+ return await fn();
5044
+ } finally {
5045
+ release();
5046
+ }
5047
+ });
5048
+ }
5016
5049
  const auditService = ({ strapi }) => ({
5017
5050
  /**
5018
5051
  * Detects whether Strapi Enterprise Native Audit Log service is available.
@@ -5119,7 +5152,7 @@ const auditService = ({ strapi }) => ({
5119
5152
  /**
5120
5153
  * Optionally writes an audit event directly to Strapi Enterprise's native Audit Logs table.
5121
5154
  */
5122
- async recordToEnterpriseNative(action, payload2, user) {
5155
+ async recordToEnterpriseNative(action, payload, user) {
5123
5156
  try {
5124
5157
  const eeService = this.getEnterpriseAuditService();
5125
5158
  if (eeService && typeof eeService.save === "function") {
@@ -5127,7 +5160,7 @@ const auditService = ({ strapi }) => ({
5127
5160
  action,
5128
5161
  date: /* @__PURE__ */ new Date(),
5129
5162
  userId: user?.id,
5130
- payload: payload2
5163
+ payload
5131
5164
  });
5132
5165
  strapi.log.info(
5133
5166
  `[bulk-updater] Successfully dispatched event to Strapi Enterprise Audit Log: ${action}`
@@ -5241,7 +5274,15 @@ const auditService = ({ strapi }) => ({
5241
5274
  try {
5242
5275
  const store = strapi.store({ type: "plugin", name: "bulk-updater", key: "audit-history" });
5243
5276
  const stored = await store.get({}) || { history: [] };
5244
- const history = Array.isArray(stored.history) ? stored.history : [];
5277
+ const rawHistory = Array.isArray(stored.history) ? stored.history : [];
5278
+ const sortedHistory = sortAuditRecordsDesc(rawHistory);
5279
+ const latestRecord = sortedHistory.length > 0 ? sortedHistory[0] : null;
5280
+ const history = sortedHistory.map((rec) => ({
5281
+ ...rec,
5282
+ isLatestEligible: Boolean(
5283
+ latestRecord && rec.batchId === latestRecord.batchId && !latestRecord.isRolledBack
5284
+ )
5285
+ }));
5245
5286
  return {
5246
5287
  enabled: true,
5247
5288
  mode: "store",
@@ -5283,14 +5324,23 @@ const auditService = ({ strapi }) => ({
5283
5324
  isRolledBack: Boolean(r[f.isRolledBack]),
5284
5325
  rolledBackAt: r[f.rolledBackAt] || null,
5285
5326
  rolledBackBy: r[f.rolledBackBy] || null,
5286
- executedAt: r[f.executedAt] || r.createdAt
5327
+ executedAt: r[f.executedAt] || r.createdAt,
5328
+ createdAt: r.createdAt
5329
+ }));
5330
+ const sortedHistory = sortAuditRecordsDesc(normalized);
5331
+ const latestRecord = sortedHistory.length > 0 ? sortedHistory[0] : null;
5332
+ const history = sortedHistory.map((rec) => ({
5333
+ ...rec,
5334
+ isLatestEligible: Boolean(
5335
+ latestRecord && rec.batchId === latestRecord.batchId && !latestRecord.isRolledBack
5336
+ )
5287
5337
  }));
5288
5338
  return {
5289
5339
  enabled: true,
5290
5340
  mode: config.mode,
5291
5341
  contentType: config.contentType,
5292
5342
  isEnterpriseNativeAvailable: config.isEnterpriseNativeAvailable,
5293
- history: normalized
5343
+ history
5294
5344
  };
5295
5345
  } catch (err) {
5296
5346
  return {
@@ -5329,7 +5379,7 @@ const auditService = ({ strapi }) => ({
5329
5379
  const isNested = item.attribute.includes(".") || item.attribute.includes("[") || isComponent || isDynamicZone || isDeepComponentField(ct, strapi.components, item.attribute);
5330
5380
  let wasPublished = false;
5331
5381
  if (isNested && (isComponent || isDynamicZone || rootAttrDef)) {
5332
- const populateOption = buildDeepPopulate$1(ct.attributes, strapi.components);
5382
+ const populateOption = buildDeepPopulate(ct.attributes, strapi.components);
5333
5383
  const findOneArgs = { documentId: item.documentId };
5334
5384
  if (populateOption) {
5335
5385
  findOneArgs.populate = populateOption;
@@ -5432,34 +5482,151 @@ const auditService = ({ strapi }) => ({
5432
5482
  return { revertedCount, rollbackDetails };
5433
5483
  },
5434
5484
  /**
5435
- * Performs deterministic rollback of a batch
5485
+ * Performs deterministic rollback of a batch.
5486
+ * Strict invariant: ONLY the latest completed update is eligible for rollback.
5487
+ * Older completed updates, already rolled-back updates, and pending/failed/executing batches are strictly rejected.
5436
5488
  */
5437
5489
  async rollbackBatch(batchId, currentUser) {
5438
- const config = this.getAuditConfig();
5439
- if (!config.enabled) {
5440
- throw new Error("Audit trail is not configured or disabled.");
5441
- }
5442
- if (config.mode === "store") {
5443
- const store = strapi.store({ type: "plugin", name: "bulk-updater", key: "audit-history" });
5444
- const stored = await store.get({}) || { history: [] };
5445
- const history = Array.isArray(stored.history) ? stored.history : [];
5446
- const recordIndex = history.findIndex((r) => r.batchId === batchId);
5447
- if (recordIndex === -1) {
5490
+ return withRollbackLock(async () => {
5491
+ const config = this.getAuditConfig();
5492
+ if (!config.enabled) {
5493
+ throw new Error("Audit trail is not configured or disabled.");
5494
+ }
5495
+ if (!batchId) {
5496
+ throw new Error("A valid batchId is required to perform rollback.");
5497
+ }
5498
+ try {
5499
+ const bulkService = strapi.plugin("bulk-updater")?.service("bulkUpdater");
5500
+ if (bulkService && typeof bulkService.getBatchStatus === "function") {
5501
+ const statusRes = await bulkService.getBatchStatus(batchId);
5502
+ const batchJob = statusRes?.batch;
5503
+ if (batchJob) {
5504
+ if (batchJob.status === "pending_approval" || batchJob.status === "queued_offpeak") {
5505
+ throw new Error(`Batch "${batchId}" is currently pending and cannot be rolled back.`);
5506
+ }
5507
+ if (batchJob.status === "processing" || batchJob.status === "running" || batchJob.status === "executing") {
5508
+ throw new Error(`Batch "${batchId}" is currently executing and cannot be rolled back.`);
5509
+ }
5510
+ if (batchJob.status === "failed") {
5511
+ throw new Error(`Batch "${batchId}" failed during execution and cannot be rolled back.`);
5512
+ }
5513
+ }
5514
+ }
5515
+ } catch (checkErr) {
5516
+ if (checkErr.message?.startsWith('Batch "')) {
5517
+ throw checkErr;
5518
+ }
5519
+ }
5520
+ if (config.mode === "store") {
5521
+ const store = strapi.store({ type: "plugin", name: "bulk-updater", key: "audit-history" });
5522
+ const stored = await store.get({}) || { history: [] };
5523
+ const rawHistory = Array.isArray(stored.history) ? stored.history : [];
5524
+ if (rawHistory.length === 0) {
5525
+ throw new Error("No completed update records found in audit trail.");
5526
+ }
5527
+ const sortedHistory2 = sortAuditRecordsDesc(rawHistory);
5528
+ const targetRecord2 = sortedHistory2.find((r) => r.batchId === batchId);
5529
+ if (!targetRecord2) {
5530
+ throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
5531
+ }
5532
+ const latestRecord2 = sortedHistory2[0];
5533
+ if (latestRecord2.batchId !== batchId) {
5534
+ throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
5535
+ }
5536
+ if (targetRecord2.isRolledBack) {
5537
+ throw new Error(`Batch "${batchId}" has already been rolled back.`);
5538
+ }
5539
+ const diffs2 = Array.isArray(targetRecord2.diffs) ? targetRecord2.diffs : [];
5540
+ const { revertedCount: revertedCount2, rollbackDetails: rollbackDetails2 } = await this.revertDiffItems(diffs2, currentUser?.id);
5541
+ const recordIndex = rawHistory.findIndex((r) => r.batchId === batchId);
5542
+ if (recordIndex !== -1) {
5543
+ rawHistory[recordIndex] = {
5544
+ ...rawHistory[recordIndex],
5545
+ isRolledBack: true,
5546
+ rolledBackAt: (/* @__PURE__ */ new Date()).toISOString(),
5547
+ rolledBackBy: currentUser?.email || "Admin"
5548
+ };
5549
+ await store.set({ value: { history: rawHistory } });
5550
+ }
5551
+ try {
5552
+ const affectedUids = new Set(rollbackDetails2.map((d) => d.uid));
5553
+ const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
5554
+ affectedUids.forEach((uid) => {
5555
+ if (uid && bulkService?.invalidateCache) {
5556
+ bulkService.invalidateCache(uid);
5557
+ }
5558
+ });
5559
+ } catch {
5560
+ }
5561
+ await this.recordToEnterpriseNative(
5562
+ "bulk-updater.rollback",
5563
+ {
5564
+ batchId,
5565
+ revertedCount: revertedCount2
5566
+ },
5567
+ currentUser
5568
+ );
5569
+ return {
5570
+ success: true,
5571
+ batchId,
5572
+ revertedCount: revertedCount2,
5573
+ details: rollbackDetails2
5574
+ };
5575
+ }
5576
+ if (!config.contentType || !config.fields) {
5577
+ throw new Error("Audit trail is not configured or disabled.");
5578
+ }
5579
+ const f = config.fields;
5580
+ const allRecords = await strapi.documents(config.contentType).findMany({
5581
+ sort: { createdAt: "desc" }
5582
+ });
5583
+ if (!allRecords || allRecords.length === 0) {
5584
+ throw new Error("No completed update records found in audit trail.");
5585
+ }
5586
+ const normalizedHistory = allRecords.map((r) => ({
5587
+ id: r.id,
5588
+ documentId: r.documentId,
5589
+ batchId: r[f.batchId] || r.documentId,
5590
+ attribute: r[f.attribute],
5591
+ value: r[f.value],
5592
+ userEmail: r[f.userEmail] || "admin@strapi.io",
5593
+ userName: r[f.userName] || "Admin",
5594
+ updatedCount: r[f.updatedCount] || 0,
5595
+ skippedCount: r[f.skippedCount] || 0,
5596
+ totalTargets: r[f.totalTargets] || 0,
5597
+ diffs: typeof r[f.diffs] === "string" ? JSON.parse(r[f.diffs]) : r[f.diffs] || [],
5598
+ isRolledBack: Boolean(r[f.isRolledBack]),
5599
+ rolledBackAt: r[f.rolledBackAt] || null,
5600
+ rolledBackBy: r[f.rolledBackBy] || null,
5601
+ executedAt: r[f.executedAt] || r.createdAt,
5602
+ createdAt: r.createdAt
5603
+ }));
5604
+ const sortedHistory = sortAuditRecordsDesc(normalizedHistory);
5605
+ const targetRecord = sortedHistory.find((r) => r.batchId === batchId);
5606
+ if (!targetRecord) {
5448
5607
  throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
5449
5608
  }
5450
- const record2 = history[recordIndex];
5451
- if (record2.isRolledBack) {
5609
+ const latestRecord = sortedHistory[0];
5610
+ if (latestRecord.batchId !== batchId) {
5611
+ throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
5612
+ }
5613
+ if (targetRecord.isRolledBack) {
5452
5614
  throw new Error(`Batch "${batchId}" has already been rolled back.`);
5453
5615
  }
5454
- const diffs2 = Array.isArray(record2.diffs) ? record2.diffs : [];
5455
- const { revertedCount: revertedCount2, rollbackDetails: rollbackDetails2 } = await this.revertDiffItems(diffs2, currentUser?.id);
5456
- record2.isRolledBack = true;
5457
- record2.rolledBackAt = (/* @__PURE__ */ new Date()).toISOString();
5458
- record2.rolledBackBy = currentUser?.email || "Admin";
5459
- history[recordIndex] = record2;
5460
- await store.set({ value: { history } });
5616
+ const diffs = Array.isArray(targetRecord.diffs) ? targetRecord.diffs : [];
5617
+ const { revertedCount, rollbackDetails } = await this.revertDiffItems(diffs, currentUser?.id);
5618
+ const updateData = {};
5619
+ if (f.isRolledBack) updateData[f.isRolledBack] = true;
5620
+ if (f.rolledBackAt) updateData[f.rolledBackAt] = (/* @__PURE__ */ new Date()).toISOString();
5621
+ if (f.rolledBackBy) {
5622
+ updateData[f.rolledBackBy] = currentUser?.email || "Admin";
5623
+ }
5624
+ await strapi.documents(config.contentType).update({
5625
+ documentId: targetRecord.documentId,
5626
+ data: updateData
5627
+ });
5461
5628
  try {
5462
- const affectedUids = new Set(rollbackDetails2.map((d) => d.uid));
5629
+ const affectedUids = new Set(rollbackDetails.map((d) => d.uid));
5463
5630
  const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
5464
5631
  affectedUids.forEach((uid) => {
5465
5632
  if (uid && bulkService?.invalidateCache) {
@@ -5472,72 +5639,278 @@ const auditService = ({ strapi }) => ({
5472
5639
  "bulk-updater.rollback",
5473
5640
  {
5474
5641
  batchId,
5475
- revertedCount: revertedCount2
5642
+ revertedCount
5476
5643
  },
5477
5644
  currentUser
5478
5645
  );
5479
5646
  return {
5480
5647
  success: true,
5481
5648
  batchId,
5482
- revertedCount: revertedCount2,
5483
- details: rollbackDetails2
5649
+ revertedCount,
5650
+ details: rollbackDetails
5484
5651
  };
5652
+ });
5653
+ }
5654
+ });
5655
+ const SYSTEM_ATTRIBUTES = /* @__PURE__ */ new Set([
5656
+ "createdat",
5657
+ "updatedat",
5658
+ "publishedat",
5659
+ "createdby",
5660
+ "updatedby",
5661
+ "localizations",
5662
+ "locale",
5663
+ "documentid",
5664
+ "id",
5665
+ "strapistage",
5666
+ "strapi_stage",
5667
+ "strapiassignee",
5668
+ "strapi_assignee",
5669
+ "strapistatus",
5670
+ "strapi_status"
5671
+ ]);
5672
+ function classifyAttribute(attrName, attrDef) {
5673
+ const normKey = attrName.toLowerCase().replace(/[\s_-]/g, "");
5674
+ if (SYSTEM_ATTRIBUTES.has(normKey)) {
5675
+ return "system";
5676
+ }
5677
+ if (!attrDef || typeof attrDef !== "object") {
5678
+ return "scalar";
5679
+ }
5680
+ const type = String(attrDef.type || "").toLowerCase();
5681
+ if (type === "component") {
5682
+ return attrDef.repeatable ? "component_repeatable" : "component_single";
5683
+ }
5684
+ if (type === "dynamiczone") {
5685
+ return "dynamiczone";
5686
+ }
5687
+ if (type === "relation") {
5688
+ const rel = String(attrDef.relation || "").toLowerCase();
5689
+ const isMany = rel.endsWith("many") || rel === "onetomany" || rel === "manytomany" || rel === "morphone" || rel === "morphmany";
5690
+ return isMany ? "relation_to_many" : "relation_to_one";
5691
+ }
5692
+ if (type === "media") {
5693
+ return attrDef.multiple ? "media_to_many" : "media_single";
5694
+ }
5695
+ if (type === "blocks") {
5696
+ return "blocks";
5697
+ }
5698
+ if (type === "json") {
5699
+ return "json";
5700
+ }
5701
+ return "scalar";
5702
+ }
5703
+ function discoverComponentFields(strapi, compUid, visited = /* @__PURE__ */ new Set(), depth = 0, maxDepth = 6) {
5704
+ const result = {};
5705
+ if (depth >= maxDepth) return result;
5706
+ const comp = strapi.components?.[compUid];
5707
+ if (!comp?.attributes) return result;
5708
+ const nextVisited = new Set(visited);
5709
+ nextVisited.add(compUid);
5710
+ for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
5711
+ const normKey = attrName.toLowerCase().replace(/[\s_-]/g, "");
5712
+ if (SYSTEM_ATTRIBUTES.has(normKey)) continue;
5713
+ const category = classifyAttribute(attrName, attrDef);
5714
+ if (category === "system") continue;
5715
+ const field = {
5716
+ key: attrName,
5717
+ label: attrName,
5718
+ category,
5719
+ rawType: attrDef.type,
5720
+ repeatable: Boolean(attrDef.repeatable),
5721
+ componentUid: attrDef.component,
5722
+ dzComponents: Array.isArray(attrDef.components) ? attrDef.components : void 0,
5723
+ targetUid: attrDef.target,
5724
+ relationType: attrDef.relation,
5725
+ multiple: Boolean(attrDef.multiple),
5726
+ enumOptions: Array.isArray(attrDef.enum) ? attrDef.enum : void 0,
5727
+ required: Boolean(attrDef.required)
5728
+ };
5729
+ if (category === "component_single" && attrDef.component) {
5730
+ if (!visited.has(attrDef.component)) {
5731
+ field.subFields = discoverComponentFields(
5732
+ strapi,
5733
+ attrDef.component,
5734
+ nextVisited,
5735
+ depth + 1,
5736
+ maxDepth
5737
+ );
5738
+ }
5739
+ } else if (category === "component_repeatable" && attrDef.component) {
5740
+ if (!visited.has(attrDef.component)) {
5741
+ field.subFields = discoverComponentFields(
5742
+ strapi,
5743
+ attrDef.component,
5744
+ nextVisited,
5745
+ depth + 1,
5746
+ maxDepth
5747
+ );
5748
+ }
5485
5749
  }
5486
- if (!config.contentType || !config.fields) {
5487
- throw new Error("Audit trail is not configured or disabled.");
5750
+ result[attrName] = field;
5751
+ }
5752
+ return result;
5753
+ }
5754
+ function discoverSchema(strapi, uid) {
5755
+ const ct = strapi.contentTypes[uid];
5756
+ if (!ct) {
5757
+ throw new Error(`Content type "${uid}" not found in registered Strapi schema.`);
5758
+ }
5759
+ const fields = {};
5760
+ const allExportKeys = ["documentId"];
5761
+ const isLocalized = Boolean(ct.pluginOptions?.i18n?.localized);
5762
+ if (isLocalized) {
5763
+ allExportKeys.push("locale");
5764
+ }
5765
+ const isDraftAndPublish = Boolean(ct.options?.draftAndPublish);
5766
+ for (const [attrName, attrDef] of Object.entries(ct.attributes || {})) {
5767
+ const normKey = attrName.toLowerCase().replace(/[\s_-]/g, "");
5768
+ if (SYSTEM_ATTRIBUTES.has(normKey)) continue;
5769
+ if (attrDef?.target?.includes("review-workflow") || attrDef?.target === "admin::review-workflow-stage") {
5770
+ continue;
5488
5771
  }
5489
- const f = config.fields;
5490
- const records = await strapi.documents(config.contentType).findMany({
5491
- filters: {
5492
- [f.batchId]: { $eq: batchId }
5772
+ const category = classifyAttribute(attrName, attrDef);
5773
+ if (category === "system") continue;
5774
+ const field = {
5775
+ key: attrName,
5776
+ label: attrName,
5777
+ category,
5778
+ rawType: attrDef.type,
5779
+ repeatable: Boolean(attrDef.repeatable),
5780
+ componentUid: attrDef.component,
5781
+ dzComponents: Array.isArray(attrDef.components) ? attrDef.components : void 0,
5782
+ targetUid: attrDef.target,
5783
+ relationType: attrDef.relation,
5784
+ multiple: Boolean(attrDef.multiple),
5785
+ enumOptions: Array.isArray(attrDef.enum) ? attrDef.enum : void 0,
5786
+ required: Boolean(attrDef.required)
5787
+ };
5788
+ if ((category === "component_single" || category === "component_repeatable") && attrDef.component) {
5789
+ field.subFields = discoverComponentFields(strapi, attrDef.component, /* @__PURE__ */ new Set(), 0, 6);
5790
+ }
5791
+ fields[attrName] = field;
5792
+ allExportKeys.push(attrName);
5793
+ }
5794
+ return {
5795
+ uid,
5796
+ displayName: ct.info?.displayName || uid,
5797
+ singularName: ct.info?.singularName || uid,
5798
+ kind: ct.kind === "singleType" ? "singleType" : "collectionType",
5799
+ isDraftAndPublish,
5800
+ isLocalized,
5801
+ fields,
5802
+ allExportKeys
5803
+ };
5804
+ }
5805
+ function buildComponentPopulate(strapi, compUid, visited, depth, maxDepth) {
5806
+ if (depth >= maxDepth) return true;
5807
+ if (visited.has(compUid)) return true;
5808
+ const comp = strapi.components?.[compUid];
5809
+ if (!comp?.attributes) return true;
5810
+ const nextVisited = new Set(visited);
5811
+ nextVisited.add(compUid);
5812
+ const populate = {};
5813
+ for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
5814
+ const category = classifyAttribute(attrName, attrDef);
5815
+ if (category === "component_single" || category === "component_repeatable") {
5816
+ if (attrDef.component) {
5817
+ const subPop = buildComponentPopulate(
5818
+ strapi,
5819
+ attrDef.component,
5820
+ nextVisited,
5821
+ depth + 1,
5822
+ maxDepth
5823
+ );
5824
+ populate[attrName] = typeof subPop === "object" && Object.keys(subPop).length > 0 ? { populate: subPop } : true;
5825
+ } else {
5826
+ populate[attrName] = true;
5827
+ }
5828
+ } else if (category === "dynamiczone") {
5829
+ const dzComponents = Array.isArray(attrDef.components) ? attrDef.components : [];
5830
+ if (dzComponents.length > 0) {
5831
+ const onPopulate = {};
5832
+ for (const dzCompUid of dzComponents) {
5833
+ const dzCompPop = buildComponentPopulate(
5834
+ strapi,
5835
+ dzCompUid,
5836
+ nextVisited,
5837
+ depth + 1,
5838
+ maxDepth
5839
+ );
5840
+ onPopulate[dzCompUid] = typeof dzCompPop === "object" && Object.keys(dzCompPop).length > 0 ? { populate: dzCompPop } : true;
5841
+ }
5842
+ populate[attrName] = { on: onPopulate };
5843
+ } else {
5844
+ populate[attrName] = { populate: "*" };
5493
5845
  }
5494
- });
5495
- const record = records?.[0];
5496
- if (!record) {
5497
- throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
5498
- }
5499
- if (record[f.isRolledBack]) {
5500
- throw new Error(`Batch "${batchId}" has already been rolled back.`);
5501
- }
5502
- const diffs = typeof record[f.diffs] === "string" ? JSON.parse(record[f.diffs]) : record[f.diffs] || [];
5503
- const { revertedCount, rollbackDetails } = await this.revertDiffItems(diffs, currentUser?.id);
5504
- const updateData = {};
5505
- if (f.isRolledBack) updateData[f.isRolledBack] = true;
5506
- if (f.rolledBackAt) updateData[f.rolledBackAt] = (/* @__PURE__ */ new Date()).toISOString();
5507
- if (f.rolledBackBy) {
5508
- updateData[f.rolledBackBy] = currentUser?.email || "Admin";
5509
- }
5510
- await strapi.documents(config.contentType).update({
5511
- documentId: record.documentId,
5512
- data: updateData
5513
- });
5514
- try {
5515
- const affectedUids = new Set(rollbackDetails.map((d) => d.uid));
5516
- const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
5517
- affectedUids.forEach((uid) => {
5518
- if (uid && bulkService?.invalidateCache) {
5519
- bulkService.invalidateCache(uid);
5846
+ } else if (category === "relation_to_one" || category === "relation_to_many") {
5847
+ populate[attrName] = true;
5848
+ } else if (category === "media_single" || category === "media_to_many") {
5849
+ populate[attrName] = true;
5850
+ }
5851
+ }
5852
+ return Object.keys(populate).length > 0 ? populate : true;
5853
+ }
5854
+ function buildLosslessPopulate(strapi, uid, options = {}) {
5855
+ const maxDepth = options.maxDepth || 5;
5856
+ const schema = discoverSchema(strapi, uid);
5857
+ const populate = {};
5858
+ const visited = /* @__PURE__ */ new Set([uid]);
5859
+ for (const [fieldName, field] of Object.entries(schema.fields)) {
5860
+ switch (field.category) {
5861
+ case "component_single":
5862
+ case "component_repeatable": {
5863
+ if (field.componentUid) {
5864
+ const compPop = buildComponentPopulate(
5865
+ strapi,
5866
+ field.componentUid,
5867
+ visited,
5868
+ 0,
5869
+ maxDepth
5870
+ );
5871
+ populate[fieldName] = typeof compPop === "object" && Object.keys(compPop).length > 0 ? { populate: compPop } : true;
5872
+ } else {
5873
+ populate[fieldName] = true;
5520
5874
  }
5521
- });
5522
- } catch {
5875
+ break;
5876
+ }
5877
+ case "dynamiczone": {
5878
+ const dzComponents = field.dzComponents || [];
5879
+ if (dzComponents.length > 0) {
5880
+ const onPopulate = {};
5881
+ for (const compUid of dzComponents) {
5882
+ const compPop = buildComponentPopulate(
5883
+ strapi,
5884
+ compUid,
5885
+ visited,
5886
+ 0,
5887
+ maxDepth
5888
+ );
5889
+ onPopulate[compUid] = typeof compPop === "object" && Object.keys(compPop).length > 0 ? { populate: compPop } : true;
5890
+ }
5891
+ populate[fieldName] = { on: onPopulate };
5892
+ } else {
5893
+ populate[fieldName] = { populate: "*" };
5894
+ }
5895
+ break;
5896
+ }
5897
+ case "relation_to_one":
5898
+ case "relation_to_many": {
5899
+ populate[fieldName] = true;
5900
+ break;
5901
+ }
5902
+ case "media_single":
5903
+ case "media_to_many": {
5904
+ populate[fieldName] = true;
5905
+ break;
5906
+ }
5523
5907
  }
5524
- await this.recordToEnterpriseNative(
5525
- "bulk-updater.rollback",
5526
- {
5527
- batchId,
5528
- revertedCount
5529
- },
5530
- currentUser
5531
- );
5532
- return {
5533
- success: true,
5534
- batchId,
5535
- revertedCount,
5536
- details: rollbackDetails
5537
- };
5538
5908
  }
5539
- });
5540
- function escapeCsvValue(val) {
5909
+ return Object.keys(populate).length > 0 ? populate : void 0;
5910
+ }
5911
+ const METADATA_COLUMN_KEY = "__bulk_updater_metadata";
5912
+ const CURRENT_SCHEMA_VERSION = 1;
5913
+ function escapeCsvCell(val) {
5541
5914
  if (val === null || val === void 0) return "";
5542
5915
  let str = "";
5543
5916
  if (val instanceof Date) {
@@ -5548,15 +5921,15 @@ function escapeCsvValue(val) {
5548
5921
  str = String(val);
5549
5922
  }
5550
5923
  str = str.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
5551
- if (/^[=+@-]$/.test(str.charAt(0))) {
5924
+ if (/^[=+@-]/.test(str)) {
5552
5925
  str = `'${str}`;
5553
5926
  }
5554
- if (str.includes(",") || str.includes('"') || str.includes("\n")) {
5927
+ if (str.includes(",") || str.includes('"') || str.includes("\n") || str.includes("\r")) {
5555
5928
  return `"${str.replace(/"/g, '""')}"`;
5556
5929
  }
5557
5930
  return str;
5558
5931
  }
5559
- function parseCsvRows(csvText) {
5932
+ function parseCsvToMatrix(csvText) {
5560
5933
  if (!csvText) return [];
5561
5934
  let text = csvText;
5562
5935
  if (text.charCodeAt(0) === 65279) {
@@ -5624,13 +5997,13 @@ function parseCsvRows(csvText) {
5624
5997
  }
5625
5998
  return rows;
5626
5999
  }
5627
- function parseCsv(csvText) {
5628
- const rows = parseCsvRows(csvText);
5629
- if (rows.length < 2) return [];
5630
- const headers = rows[0].map((h) => h.trim());
6000
+ function parseCsvToRecords(csvText) {
6001
+ const matrix = parseCsvToMatrix(csvText);
6002
+ if (matrix.length < 2) return [];
6003
+ const headers = matrix[0].map((h) => h.trim());
5631
6004
  const records = [];
5632
- for (let i = 1; i < rows.length; i++) {
5633
- const row = rows[i];
6005
+ for (let i = 1; i < matrix.length; i++) {
6006
+ const row = matrix[i];
5634
6007
  const record = {};
5635
6008
  headers.forEach((h, idx) => {
5636
6009
  let val = row[idx] !== void 0 ? row[idx] : "";
@@ -5643,50 +6016,907 @@ function parseCsv(csvText) {
5643
6016
  }
5644
6017
  return records;
5645
6018
  }
5646
- const LIFECYCLE_STATUS_WORDS = /* @__PURE__ */ new Set([
5647
- "pending review",
5648
- "pending_review",
5649
- "pending approval",
5650
- "pending_approval",
5651
- "approved",
5652
- "rejected",
5653
- "draft",
5654
- "published",
5655
- "modified",
5656
- "supported",
5657
- "ignored",
5658
- "editing",
5659
- "in review",
5660
- "in_review",
5661
- "ready to publish",
5662
- "ready_to_publish",
5663
- "null",
5664
- "undefined"
5665
- ]);
5666
- function isValidDocId(val) {
6019
+ function serializeFieldValue(value, field) {
6020
+ if (value === null || value === void 0) {
6021
+ return "";
6022
+ }
6023
+ switch (field.category) {
6024
+ case "scalar": {
6025
+ if (value instanceof Date) {
6026
+ return value.toISOString();
6027
+ }
6028
+ return String(value);
6029
+ }
6030
+ case "blocks":
6031
+ case "json": {
6032
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
6033
+ }
6034
+ case "component_single": {
6035
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
6036
+ }
6037
+ case "component_repeatable": {
6038
+ if (Array.isArray(value)) {
6039
+ return JSON.stringify(value);
6040
+ }
6041
+ return typeof value === "object" ? JSON.stringify([value]) : "";
6042
+ }
6043
+ case "dynamiczone": {
6044
+ if (Array.isArray(value)) {
6045
+ const cleaned = value.map((block) => {
6046
+ if (block && typeof block === "object") {
6047
+ return { ...block };
6048
+ }
6049
+ return block;
6050
+ });
6051
+ return JSON.stringify(cleaned);
6052
+ }
6053
+ return "";
6054
+ }
6055
+ case "relation_to_one": {
6056
+ if (typeof value === "object" && value !== null) {
6057
+ const docId = value.documentId || value.id || "";
6058
+ return JSON.stringify({
6059
+ documentId: String(docId),
6060
+ title: value.title || value.name || value.slug || void 0
6061
+ });
6062
+ }
6063
+ return String(value);
6064
+ }
6065
+ case "relation_to_many": {
6066
+ if (Array.isArray(value)) {
6067
+ const list = value.map((item) => {
6068
+ if (typeof item === "object" && item !== null) {
6069
+ const docId = item.documentId || item.id || "";
6070
+ return {
6071
+ documentId: String(docId),
6072
+ title: item.title || item.name || item.slug || void 0
6073
+ };
6074
+ }
6075
+ return { documentId: String(item) };
6076
+ });
6077
+ return JSON.stringify(list);
6078
+ }
6079
+ return "";
6080
+ }
6081
+ case "media_single": {
6082
+ if (typeof value === "object" && value !== null) {
6083
+ return JSON.stringify({
6084
+ id: value.id,
6085
+ documentId: value.documentId,
6086
+ name: value.name,
6087
+ url: value.url,
6088
+ mime: value.mime
6089
+ });
6090
+ }
6091
+ return String(value);
6092
+ }
6093
+ case "media_to_many": {
6094
+ if (Array.isArray(value)) {
6095
+ const list = value.map((file) => {
6096
+ if (typeof file === "object" && file !== null) {
6097
+ return {
6098
+ id: file.id,
6099
+ documentId: file.documentId,
6100
+ name: file.name,
6101
+ url: file.url,
6102
+ mime: file.mime
6103
+ };
6104
+ }
6105
+ return file;
6106
+ });
6107
+ return JSON.stringify(list);
6108
+ }
6109
+ return "";
6110
+ }
6111
+ default:
6112
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
6113
+ }
6114
+ }
6115
+ function serializeDocumentsToCsv(strapi, uid, documents) {
6116
+ const schema = discoverSchema(strapi, uid);
6117
+ const headers = [METADATA_COLUMN_KEY, ...schema.allExportKeys];
6118
+ const lines = [];
6119
+ lines.push(headers.map(escapeCsvCell).join(","));
6120
+ const exportedAt = (/* @__PURE__ */ new Date()).toISOString();
6121
+ for (const doc of documents) {
6122
+ const rowValues = [];
6123
+ const metadata = {
6124
+ schemaVersion: CURRENT_SCHEMA_VERSION,
6125
+ contentType: uid,
6126
+ documentId: String(doc.documentId || doc.id || ""),
6127
+ locale: doc.locale || void 0,
6128
+ exportedAt
6129
+ };
6130
+ rowValues.push(escapeCsvCell(metadata));
6131
+ for (const key of schema.allExportKeys) {
6132
+ if (key === "documentId") {
6133
+ rowValues.push(escapeCsvCell(doc.documentId || doc.id || ""));
6134
+ } else if (key === "locale") {
6135
+ rowValues.push(escapeCsvCell(doc.locale || ""));
6136
+ } else {
6137
+ const field = schema.fields[key];
6138
+ const rawValue = doc[key];
6139
+ if (field) {
6140
+ const serialized = serializeFieldValue(rawValue, field);
6141
+ rowValues.push(escapeCsvCell(serialized));
6142
+ } else {
6143
+ rowValues.push(escapeCsvCell(rawValue));
6144
+ }
6145
+ }
6146
+ }
6147
+ lines.push(rowValues.join(","));
6148
+ }
6149
+ const csvContent = "\uFEFF" + lines.join("\r\n") + "\r\n";
6150
+ return {
6151
+ csvContent,
6152
+ headers,
6153
+ count: documents.length
6154
+ };
6155
+ }
6156
+ function extractMetadataFromRow(row) {
6157
+ if (!row || typeof row !== "object") return null;
6158
+ const rawMeta = row[METADATA_COLUMN_KEY] || row["__bulk_updater_metadata"];
6159
+ if (!rawMeta) return null;
6160
+ if (typeof rawMeta === "object") {
6161
+ return rawMeta;
6162
+ }
6163
+ if (typeof rawMeta === "string") {
6164
+ try {
6165
+ const parsed = JSON.parse(rawMeta);
6166
+ if (parsed && typeof parsed === "object") {
6167
+ return parsed;
6168
+ }
6169
+ } catch {
6170
+ }
6171
+ }
6172
+ return null;
6173
+ }
6174
+ function isValidDocumentId(val) {
5667
6175
  if (!val || typeof val !== "string") return false;
5668
6176
  const trimmed = val.trim();
5669
6177
  if (!trimmed) return false;
5670
- if (LIFECYCLE_STATUS_WORDS.has(trimmed.toLowerCase())) return false;
5671
6178
  if (/\s/.test(trimmed)) return false;
5672
6179
  return /^[a-zA-Z0-9_-]+$/.test(trimmed);
5673
6180
  }
5674
- function extractDocId(row) {
5675
- if (!row || typeof row !== "object") return "";
5676
- const candidates = [
5677
- row.documentId,
5678
- row.document_id,
5679
- row["Document ID"],
5680
- row["Document Id"],
5681
- row["document_id"],
5682
- row.docId,
5683
- row["docId"],
5684
- row.id,
5685
- row.ID,
5686
- row.Id
5687
- ];
5688
- for (const c of candidates) {
5689
- if (c !== void 0 && c !== null) {
6181
+ function parseNumeric(rawVal, isInteger) {
6182
+ if (rawVal === null || rawVal === void 0 || rawVal === "") return null;
6183
+ const cleanStr = String(rawVal).replace(/[$€£,\s]/g, "");
6184
+ if (isInteger) {
6185
+ const n = parseInt(cleanStr, 10);
6186
+ return isNaN(n) ? null : n;
6187
+ }
6188
+ const f = parseFloat(cleanStr);
6189
+ return isNaN(f) ? null : f;
6190
+ }
6191
+ function parseBoolean(rawVal) {
6192
+ if (rawVal === null || rawVal === void 0 || rawVal === "") return null;
6193
+ const s = String(rawVal).trim().toLowerCase();
6194
+ if (s === "true" || s === "1" || s === "yes" || s === "y" || s === "on") return true;
6195
+ if (s === "false" || s === "0" || s === "no" || s === "n" || s === "off") return false;
6196
+ return null;
6197
+ }
6198
+ async function resolveMediaIds(strapi, rawVal, isMultiple) {
6199
+ if (rawVal === null || rawVal === void 0 || rawVal === "") {
6200
+ return isMultiple ? [] : null;
6201
+ }
6202
+ let parsed = rawVal;
6203
+ if (typeof rawVal === "string") {
6204
+ const trimmed = rawVal.trim();
6205
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
6206
+ try {
6207
+ parsed = JSON.parse(trimmed);
6208
+ } catch {
6209
+ }
6210
+ }
6211
+ }
6212
+ const numericIds = [];
6213
+ const candidateLookups = [];
6214
+ const inspectItem = (item) => {
6215
+ if (item === null || item === void 0) return;
6216
+ if (typeof item === "number" && !isNaN(item)) {
6217
+ numericIds.push(item);
6218
+ return;
6219
+ }
6220
+ if (typeof item === "object") {
6221
+ if (typeof item.id === "number") {
6222
+ numericIds.push(item.id);
6223
+ return;
6224
+ }
6225
+ if (typeof item.id === "string" && /^\d+$/.test(item.id)) {
6226
+ numericIds.push(parseInt(item.id, 10));
6227
+ return;
6228
+ }
6229
+ if (item.documentId) {
6230
+ candidateLookups.push(String(item.documentId));
6231
+ return;
6232
+ }
6233
+ if (item.url) {
6234
+ candidateLookups.push(String(item.url));
6235
+ return;
6236
+ }
6237
+ }
6238
+ const str = String(item).trim();
6239
+ if (/^\d+$/.test(str)) {
6240
+ numericIds.push(parseInt(str, 10));
6241
+ } else if (str) {
6242
+ candidateLookups.push(str);
6243
+ }
6244
+ };
6245
+ if (Array.isArray(parsed)) {
6246
+ for (const el of parsed) {
6247
+ inspectItem(el);
6248
+ }
6249
+ } else if (typeof parsed === "object" && parsed !== null) {
6250
+ inspectItem(parsed);
6251
+ } else if (typeof rawVal === "string" && (rawVal.includes(",") || rawVal.includes(";"))) {
6252
+ const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter(Boolean);
6253
+ for (const part of parts) {
6254
+ inspectItem(part);
6255
+ }
6256
+ } else {
6257
+ inspectItem(parsed);
6258
+ }
6259
+ if (candidateLookups.length > 0) {
6260
+ try {
6261
+ const fileQuery = strapi.db?.query("plugin::upload.file");
6262
+ if (fileQuery) {
6263
+ for (const candidate of candidateLookups) {
6264
+ const found = await fileQuery.findOne({
6265
+ where: {
6266
+ $or: [
6267
+ { documentId: candidate },
6268
+ { url: candidate },
6269
+ { hash: candidate },
6270
+ { name: candidate }
6271
+ ]
6272
+ },
6273
+ select: ["id"]
6274
+ });
6275
+ if (found?.id) {
6276
+ numericIds.push(found.id);
6277
+ }
6278
+ }
6279
+ }
6280
+ } catch {
6281
+ }
6282
+ }
6283
+ const uniqueNumericIds = Array.from(new Set(numericIds));
6284
+ if (isMultiple) {
6285
+ return uniqueNumericIds;
6286
+ }
6287
+ return uniqueNumericIds.length > 0 ? uniqueNumericIds[0] : null;
6288
+ }
6289
+ function resolveRelationPayload(rawVal, isToMany) {
6290
+ if (rawVal === null || rawVal === void 0 || rawVal === "") {
6291
+ return isToMany ? { set: [] } : { set: [] };
6292
+ }
6293
+ let parsed = rawVal;
6294
+ if (typeof rawVal === "string") {
6295
+ const trimmed = rawVal.trim();
6296
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
6297
+ try {
6298
+ parsed = JSON.parse(trimmed);
6299
+ } catch {
6300
+ }
6301
+ }
6302
+ }
6303
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
6304
+ if (parsed.set || parsed.connect || parsed.disconnect) {
6305
+ return parsed;
6306
+ }
6307
+ const singleDocId = parsed.documentId || parsed.id;
6308
+ if (singleDocId && isValidDocumentId(String(singleDocId))) {
6309
+ return isToMany ? { set: [String(singleDocId).trim()] } : { set: [String(singleDocId).trim()] };
6310
+ }
6311
+ }
6312
+ const docIds = [];
6313
+ if (Array.isArray(parsed)) {
6314
+ for (const item of parsed) {
6315
+ if (item && typeof item === "object") {
6316
+ const id = item.documentId || item.id;
6317
+ if (id && isValidDocumentId(String(id))) {
6318
+ docIds.push(String(id).trim());
6319
+ }
6320
+ } else if (isValidDocumentId(String(item))) {
6321
+ docIds.push(String(item).trim());
6322
+ }
6323
+ }
6324
+ } else if (typeof rawVal === "string") {
6325
+ if (rawVal.includes(",") || rawVal.includes(";")) {
6326
+ const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter((p) => isValidDocumentId(p));
6327
+ docIds.push(...parts);
6328
+ } else if (isValidDocumentId(rawVal.trim())) {
6329
+ docIds.push(rawVal.trim());
6330
+ }
6331
+ }
6332
+ const uniqueDocIds = Array.from(new Set(docIds));
6333
+ return { set: uniqueDocIds };
6334
+ }
6335
+ async function resolveComponentPayload(strapi, compUid, rawVal, existingVal = {}) {
6336
+ const comp = strapi.components?.[compUid];
6337
+ if (!comp?.attributes) {
6338
+ return typeof rawVal === "object" ? rawVal : {};
6339
+ }
6340
+ let sourceObj = {};
6341
+ if (typeof rawVal === "string") {
6342
+ try {
6343
+ sourceObj = JSON.parse(rawVal);
6344
+ } catch {
6345
+ return existingVal || {};
6346
+ }
6347
+ } else if (typeof rawVal === "object" && rawVal !== null) {
6348
+ sourceObj = rawVal;
6349
+ } else {
6350
+ return existingVal || {};
6351
+ }
6352
+ const result = { ...existingVal || {} };
6353
+ for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
6354
+ if (SYSTEM_ATTRIBUTES.has(attrName.toLowerCase().replace(/[\s_-]/g, ""))) continue;
6355
+ if (!(attrName in sourceObj)) {
6356
+ continue;
6357
+ }
6358
+ const fieldVal = sourceObj[attrName];
6359
+ const type = String(attrDef.type || "").toLowerCase();
6360
+ if (type === "component") {
6361
+ if (attrDef.repeatable) {
6362
+ const list = Array.isArray(fieldVal) ? fieldVal : [];
6363
+ const cleanedList = [];
6364
+ for (const item of list) {
6365
+ const subCleaned = await resolveComponentPayload(strapi, attrDef.component, item, {});
6366
+ cleanedList.push(subCleaned);
6367
+ }
6368
+ result[attrName] = cleanedList;
6369
+ } else {
6370
+ result[attrName] = await resolveComponentPayload(
6371
+ strapi,
6372
+ attrDef.component,
6373
+ fieldVal,
6374
+ existingVal?.[attrName] || {}
6375
+ );
6376
+ }
6377
+ } else if (type === "relation") {
6378
+ const isToMany = String(attrDef.relation || "").toLowerCase().endsWith("many");
6379
+ result[attrName] = resolveRelationPayload(fieldVal, isToMany);
6380
+ } else if (type === "media") {
6381
+ result[attrName] = await resolveMediaIds(strapi, fieldVal, Boolean(attrDef.multiple));
6382
+ } else if (type === "integer" || type === "biginteger") {
6383
+ result[attrName] = parseNumeric(fieldVal, true);
6384
+ } else if (type === "float" || type === "decimal") {
6385
+ result[attrName] = parseNumeric(fieldVal, false);
6386
+ } else if (type === "boolean") {
6387
+ result[attrName] = parseBoolean(fieldVal);
6388
+ } else if (type === "json" || type === "blocks") {
6389
+ if (typeof fieldVal === "string") {
6390
+ try {
6391
+ result[attrName] = JSON.parse(fieldVal);
6392
+ } catch {
6393
+ result[attrName] = fieldVal;
6394
+ }
6395
+ } else {
6396
+ result[attrName] = fieldVal;
6397
+ }
6398
+ } else {
6399
+ result[attrName] = fieldVal === null || fieldVal === void 0 ? null : String(fieldVal);
6400
+ }
6401
+ }
6402
+ return result;
6403
+ }
6404
+ async function resolveDynamicZonePayload(strapi, allowedComponents, rawVal, existingVal = []) {
6405
+ let list = [];
6406
+ if (typeof rawVal === "string") {
6407
+ try {
6408
+ list = JSON.parse(rawVal);
6409
+ } catch {
6410
+ return existingVal || [];
6411
+ }
6412
+ } else if (Array.isArray(rawVal)) {
6413
+ list = rawVal;
6414
+ } else {
6415
+ return existingVal || [];
6416
+ }
6417
+ if (!Array.isArray(list)) return [];
6418
+ const allowedSet = new Set(allowedComponents || []);
6419
+ const resolvedBlocks = [];
6420
+ for (const block of list) {
6421
+ if (!block || typeof block !== "object") continue;
6422
+ const compUid = block.__component;
6423
+ if (!compUid || typeof compUid !== "string") {
6424
+ continue;
6425
+ }
6426
+ if (allowedSet.size > 0 && !allowedSet.has(compUid)) {
6427
+ continue;
6428
+ }
6429
+ const resolvedAttrs = await resolveComponentPayload(strapi, compUid, block, {});
6430
+ resolvedAttrs.__component = compUid;
6431
+ resolvedBlocks.push(resolvedAttrs);
6432
+ }
6433
+ return resolvedBlocks;
6434
+ }
6435
+ async function buildDocumentUpdatePayload(strapi, uid, existingDoc, rawRow, options = {}) {
6436
+ const schema = discoverSchema(strapi, uid);
6437
+ const payload = {};
6438
+ const unescapedRow = {};
6439
+ for (const [k, v] of Object.entries(rawRow)) {
6440
+ let cleanVal = v;
6441
+ if (typeof cleanVal === "string" && /^'[=+@-]/.test(cleanVal)) {
6442
+ cleanVal = cleanVal.substring(1);
6443
+ }
6444
+ unescapedRow[k] = cleanVal;
6445
+ }
6446
+ const dotNotationMap = {};
6447
+ for (const [k, v] of Object.entries(unescapedRow)) {
6448
+ if (k.includes(".")) {
6449
+ const [parent, ...rest] = k.split(".");
6450
+ const child = rest.join(".");
6451
+ if (!dotNotationMap[parent]) dotNotationMap[parent] = {};
6452
+ dotNotationMap[parent][child] = v;
6453
+ }
6454
+ }
6455
+ for (const [attrName, field] of Object.entries(schema.fields)) {
6456
+ const hasDirectKey = attrName in unescapedRow;
6457
+ const hasDotKeys = Boolean(dotNotationMap[attrName]);
6458
+ if (!hasDirectKey && !hasDotKeys) {
6459
+ continue;
6460
+ }
6461
+ const rawVal = hasDirectKey ? unescapedRow[attrName] : void 0;
6462
+ switch (field.category) {
6463
+ case "scalar": {
6464
+ if (rawVal === void 0 || rawVal === "" || rawVal === null) {
6465
+ payload[attrName] = null;
6466
+ } else if (field.rawType === "integer" || field.rawType === "biginteger") {
6467
+ payload[attrName] = parseNumeric(rawVal, true);
6468
+ } else if (field.rawType === "float" || field.rawType === "decimal") {
6469
+ payload[attrName] = parseNumeric(rawVal, false);
6470
+ } else if (field.rawType === "boolean") {
6471
+ payload[attrName] = parseBoolean(rawVal);
6472
+ } else if (field.rawType === "date" || field.rawType === "time" || field.rawType === "datetime" || field.rawType === "timestamp") {
6473
+ payload[attrName] = String(rawVal).trim() || null;
6474
+ } else if (field.rawType === "enumeration") {
6475
+ const trimmed = String(rawVal).trim();
6476
+ if (field.enumOptions && field.enumOptions.length > 0) {
6477
+ const match = field.enumOptions.find((o) => o.toLowerCase() === trimmed.toLowerCase());
6478
+ payload[attrName] = match || trimmed;
6479
+ } else {
6480
+ payload[attrName] = trimmed;
6481
+ }
6482
+ } else {
6483
+ payload[attrName] = String(rawVal).trim();
6484
+ }
6485
+ break;
6486
+ }
6487
+ case "blocks": {
6488
+ if (rawVal === void 0 || rawVal === "" || rawVal === null) {
6489
+ payload[attrName] = [];
6490
+ } else {
6491
+ try {
6492
+ const parsed = JSON.parse(rawVal);
6493
+ payload[attrName] = Array.isArray(parsed) ? parsed : [parsed];
6494
+ } catch {
6495
+ payload[attrName] = [
6496
+ { type: "paragraph", children: [{ type: "text", text: String(rawVal).trim() }] }
6497
+ ];
6498
+ }
6499
+ }
6500
+ break;
6501
+ }
6502
+ case "json": {
6503
+ if (rawVal === void 0 || rawVal === "" || rawVal === null) {
6504
+ payload[attrName] = null;
6505
+ } else {
6506
+ try {
6507
+ payload[attrName] = JSON.parse(rawVal);
6508
+ } catch {
6509
+ payload[attrName] = rawVal;
6510
+ }
6511
+ }
6512
+ break;
6513
+ }
6514
+ case "component_single": {
6515
+ if (field.componentUid) {
6516
+ let compInput = rawVal;
6517
+ if (hasDotKeys) {
6518
+ compInput = { ...existingDoc?.[attrName] || {}, ...dotNotationMap[attrName] };
6519
+ }
6520
+ if (compInput === "" || compInput === null) {
6521
+ payload[attrName] = null;
6522
+ } else {
6523
+ payload[attrName] = await resolveComponentPayload(
6524
+ strapi,
6525
+ field.componentUid,
6526
+ compInput,
6527
+ existingDoc?.[attrName] || {}
6528
+ );
6529
+ }
6530
+ }
6531
+ break;
6532
+ }
6533
+ case "component_repeatable": {
6534
+ if (field.componentUid) {
6535
+ if (rawVal === "" || rawVal === null || rawVal === void 0) {
6536
+ payload[attrName] = [];
6537
+ } else {
6538
+ let list = [];
6539
+ try {
6540
+ list = typeof rawVal === "string" ? JSON.parse(rawVal) : rawVal;
6541
+ } catch {
6542
+ }
6543
+ if (Array.isArray(list)) {
6544
+ const cleanedItems = [];
6545
+ for (const item of list) {
6546
+ const cleaned = await resolveComponentPayload(
6547
+ strapi,
6548
+ field.componentUid,
6549
+ item,
6550
+ {}
6551
+ );
6552
+ cleanedItems.push(cleaned);
6553
+ }
6554
+ payload[attrName] = cleanedItems;
6555
+ } else {
6556
+ payload[attrName] = [];
6557
+ }
6558
+ }
6559
+ }
6560
+ break;
6561
+ }
6562
+ case "dynamiczone": {
6563
+ const allowedComponents = field.dzComponents || [];
6564
+ if (rawVal === "" || rawVal === null || rawVal === void 0) {
6565
+ payload[attrName] = [];
6566
+ } else {
6567
+ payload[attrName] = await resolveDynamicZonePayload(
6568
+ strapi,
6569
+ allowedComponents,
6570
+ rawVal,
6571
+ existingDoc?.[attrName] || []
6572
+ );
6573
+ }
6574
+ break;
6575
+ }
6576
+ case "relation_to_one": {
6577
+ payload[attrName] = resolveRelationPayload(rawVal, false);
6578
+ break;
6579
+ }
6580
+ case "relation_to_many": {
6581
+ payload[attrName] = resolveRelationPayload(rawVal, true);
6582
+ break;
6583
+ }
6584
+ case "media_single": {
6585
+ payload[attrName] = await resolveMediaIds(strapi, rawVal, false);
6586
+ break;
6587
+ }
6588
+ case "media_to_many": {
6589
+ payload[attrName] = await resolveMediaIds(strapi, rawVal, true);
6590
+ break;
6591
+ }
6592
+ default:
6593
+ payload[attrName] = rawVal;
6594
+ }
6595
+ }
6596
+ return payload;
6597
+ }
6598
+ function normalizeVal(val) {
6599
+ if (val === null || val === void 0) return null;
6600
+ if (typeof val === "string") return val.trim();
6601
+ if (typeof val === "number" || typeof val === "boolean") return val;
6602
+ if (Array.isArray(val)) {
6603
+ return val.map(normalizeVal);
6604
+ }
6605
+ if (typeof val === "object") {
6606
+ const copy = {};
6607
+ for (const [k, v] of Object.entries(val)) {
6608
+ if (SYSTEM_ATTRIBUTES.has(k.toLowerCase().replace(/[\s_-]/g, ""))) continue;
6609
+ copy[k] = normalizeVal(v);
6610
+ }
6611
+ return copy;
6612
+ }
6613
+ return val;
6614
+ }
6615
+ function verifyDocumentIntegrity(strapi, uid, originalDoc, appliedPayload, savedDoc) {
6616
+ const schema = discoverSchema(strapi, uid);
6617
+ const diffs = [];
6618
+ let scalarOk = true;
6619
+ let componentsOk = true;
6620
+ let dynamicZonesOk = true;
6621
+ let relationsOk = true;
6622
+ let mediaOk = true;
6623
+ let missingDataCount = 0;
6624
+ let invalidRelationsCount = 0;
6625
+ let missingMediaCount = 0;
6626
+ let structuralDifferencesCount = 0;
6627
+ let hasComponents = false;
6628
+ let hasDynamicZones = false;
6629
+ let hasRelations = false;
6630
+ let hasMedia = false;
6631
+ for (const [key, field] of Object.entries(schema.fields)) {
6632
+ const isTargeted = key in appliedPayload;
6633
+ const expected = isTargeted ? appliedPayload[key] : originalDoc?.[key];
6634
+ const actual = savedDoc?.[key];
6635
+ switch (field.category) {
6636
+ case "scalar": {
6637
+ const normExpected = normalizeVal(expected);
6638
+ const normActual = normalizeVal(actual);
6639
+ if (normExpected !== null && normActual !== normExpected) {
6640
+ if (String(normExpected) !== String(normActual)) {
6641
+ diffs.push({
6642
+ path: key,
6643
+ expected: normExpected,
6644
+ actual: normActual,
6645
+ message: `Scalar value mismatch on "${key}"`
6646
+ });
6647
+ scalarOk = false;
6648
+ structuralDifferencesCount++;
6649
+ }
6650
+ }
6651
+ break;
6652
+ }
6653
+ case "component_single":
6654
+ case "component_repeatable": {
6655
+ hasComponents = true;
6656
+ if (field.category === "component_repeatable") {
6657
+ const expArr = Array.isArray(expected) ? expected : [];
6658
+ const actArr = Array.isArray(actual) ? actual : [];
6659
+ if (expArr.length !== actArr.length) {
6660
+ diffs.push({
6661
+ path: key,
6662
+ expected: `Array of length ${expArr.length}`,
6663
+ actual: `Array of length ${actArr.length}`,
6664
+ message: `Repeatable component length mismatch on "${key}"`
6665
+ });
6666
+ componentsOk = false;
6667
+ structuralDifferencesCount++;
6668
+ }
6669
+ }
6670
+ break;
6671
+ }
6672
+ case "dynamiczone": {
6673
+ hasDynamicZones = true;
6674
+ const expBlocks = Array.isArray(expected) ? expected : [];
6675
+ const actBlocks = Array.isArray(actual) ? actual : [];
6676
+ if (expBlocks.length !== actBlocks.length) {
6677
+ diffs.push({
6678
+ path: key,
6679
+ expected: `Dynamic zone of length ${expBlocks.length}`,
6680
+ actual: `Dynamic zone of length ${actBlocks.length}`,
6681
+ message: `Dynamic zone count mismatch on "${key}"`
6682
+ });
6683
+ dynamicZonesOk = false;
6684
+ structuralDifferencesCount++;
6685
+ } else {
6686
+ for (let b = 0; b < expBlocks.length; b++) {
6687
+ const expComp = expBlocks[b]?.__component;
6688
+ const actComp = actBlocks[b]?.__component;
6689
+ if (expComp !== actComp) {
6690
+ diffs.push({
6691
+ path: `${key}[${b}].__component`,
6692
+ expected: expComp || "(missing __component)",
6693
+ actual: actComp || "(missing __component)",
6694
+ message: `Dynamic zone block type mismatch at position ${b}: expected "${expComp}", found "${actComp || "missing __component"}"`
6695
+ });
6696
+ dynamicZonesOk = false;
6697
+ structuralDifferencesCount++;
6698
+ }
6699
+ }
6700
+ }
6701
+ break;
6702
+ }
6703
+ case "relation_to_one":
6704
+ case "relation_to_many": {
6705
+ hasRelations = true;
6706
+ if (isTargeted && expected && typeof expected === "object" && expected.set) {
6707
+ const expectedIds = expected.set || [];
6708
+ if (field.category === "relation_to_many") {
6709
+ const actualIds = Array.isArray(actual) ? actual.map((item) => String(item?.documentId || item?.id || item)).filter(Boolean) : [];
6710
+ const missing = expectedIds.filter((id) => !actualIds.includes(id));
6711
+ if (missing.length > 0) {
6712
+ diffs.push({
6713
+ path: key,
6714
+ expected: expectedIds,
6715
+ actual: actualIds,
6716
+ message: `Missing relations on "${key}": ${missing.join(", ")}`
6717
+ });
6718
+ relationsOk = false;
6719
+ invalidRelationsCount += missing.length;
6720
+ }
6721
+ }
6722
+ }
6723
+ break;
6724
+ }
6725
+ case "media_single":
6726
+ case "media_to_many": {
6727
+ hasMedia = true;
6728
+ if (isTargeted && expected !== null && expected !== void 0) {
6729
+ const expectedIds = Array.isArray(expected) ? expected : [expected];
6730
+ const actualIds = Array.isArray(actual) ? actual.map((f) => f?.id || f).filter(Boolean) : actual?.id ? [actual.id] : [];
6731
+ const missing = expectedIds.filter((id) => !actualIds.includes(id));
6732
+ if (missing.length > 0) {
6733
+ diffs.push({
6734
+ path: key,
6735
+ expected: expectedIds,
6736
+ actual: actualIds,
6737
+ message: `Missing media references on "${key}"`
6738
+ });
6739
+ mediaOk = false;
6740
+ missingMediaCount += missing.length;
6741
+ }
6742
+ }
6743
+ break;
6744
+ }
6745
+ }
6746
+ }
6747
+ const docId = String(savedDoc?.documentId || originalDoc?.documentId || "unknown");
6748
+ const title = String(savedDoc?.title || savedDoc?.name || `Entry #${docId}`);
6749
+ const status = diffs.length === 0 ? "SUCCESS" : diffs.length <= 2 ? "WARNING" : "FAILED";
6750
+ return {
6751
+ documentId: docId,
6752
+ title,
6753
+ status,
6754
+ scalarFields: scalarOk ? "Verified" : "Mismatch",
6755
+ components: hasComponents ? componentsOk ? "Verified" : "Mismatch" : "N/A",
6756
+ dynamicZones: hasDynamicZones ? dynamicZonesOk ? "Verified" : "Mismatch" : "N/A",
6757
+ relations: hasRelations ? relationsOk ? "Verified" : "Mismatch" : "N/A",
6758
+ media: hasMedia ? mediaOk ? "Verified" : "Mismatch" : "N/A",
6759
+ missingDataCount,
6760
+ invalidRelationsCount,
6761
+ missingMediaCount,
6762
+ structuralDifferencesCount,
6763
+ diffs
6764
+ };
6765
+ }
6766
+ function escapeCsvValue(val) {
6767
+ if (val === null || val === void 0) return "";
6768
+ let str = "";
6769
+ if (val instanceof Date) {
6770
+ str = val.toISOString();
6771
+ } else if (typeof val === "object") {
6772
+ str = JSON.stringify(val);
6773
+ } else {
6774
+ str = String(val);
6775
+ }
6776
+ str = str.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
6777
+ if (/^[=+@-]$/.test(str.charAt(0))) {
6778
+ str = `'${str}`;
6779
+ }
6780
+ if (str.includes(",") || str.includes('"') || str.includes("\n")) {
6781
+ return `"${str.replace(/"/g, '""')}"`;
6782
+ }
6783
+ return str;
6784
+ }
6785
+ function parseCsvRows(csvText) {
6786
+ if (!csvText) return [];
6787
+ let text = csvText;
6788
+ if (text.charCodeAt(0) === 65279) {
6789
+ text = text.slice(1);
6790
+ }
6791
+ const rows = [];
6792
+ let currentRow = [];
6793
+ let currentCell = "";
6794
+ let inQuotes = false;
6795
+ let cellIsQuoted = false;
6796
+ for (let i = 0; i < text.length; i++) {
6797
+ const char = text[i];
6798
+ const nextChar = text[i + 1];
6799
+ if (inQuotes) {
6800
+ if (char === '"') {
6801
+ if (nextChar === '"') {
6802
+ currentCell += '"';
6803
+ i++;
6804
+ } else {
6805
+ inQuotes = false;
6806
+ }
6807
+ } else {
6808
+ currentCell += char;
6809
+ }
6810
+ } else {
6811
+ if (char === '"' && !cellIsQuoted && currentCell.trim() === "") {
6812
+ inQuotes = true;
6813
+ cellIsQuoted = true;
6814
+ currentCell = "";
6815
+ } else if (char === ",") {
6816
+ currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
6817
+ currentCell = "";
6818
+ cellIsQuoted = false;
6819
+ } else if (char === "\r") {
6820
+ if (nextChar === "\n") {
6821
+ i++;
6822
+ }
6823
+ currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
6824
+ if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
6825
+ rows.push(currentRow);
6826
+ }
6827
+ currentRow = [];
6828
+ currentCell = "";
6829
+ cellIsQuoted = false;
6830
+ } else if (char === "\n") {
6831
+ currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
6832
+ if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
6833
+ rows.push(currentRow);
6834
+ }
6835
+ currentRow = [];
6836
+ currentCell = "";
6837
+ cellIsQuoted = false;
6838
+ } else {
6839
+ if (!(cellIsQuoted && !inQuotes && (char === " " || char === " "))) {
6840
+ currentCell += char;
6841
+ }
6842
+ }
6843
+ }
6844
+ }
6845
+ if (currentCell !== "" || cellIsQuoted || currentRow.length > 0) {
6846
+ currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
6847
+ if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
6848
+ rows.push(currentRow);
6849
+ }
6850
+ }
6851
+ return rows;
6852
+ }
6853
+ function parseCsv(csvText) {
6854
+ const rows = parseCsvRows(csvText);
6855
+ if (rows.length < 2) return [];
6856
+ const headers = rows[0].map((h) => h.trim());
6857
+ const records = [];
6858
+ for (let i = 1; i < rows.length; i++) {
6859
+ const row = rows[i];
6860
+ const record = {};
6861
+ headers.forEach((h, idx) => {
6862
+ let val = row[idx] !== void 0 ? row[idx] : "";
6863
+ if (typeof val === "string" && /^'[=+@-]/.test(val)) {
6864
+ val = val.substring(1);
6865
+ }
6866
+ record[h] = val;
6867
+ });
6868
+ records.push(record);
6869
+ }
6870
+ return records;
6871
+ }
6872
+ const LIFECYCLE_STATUS_WORDS = /* @__PURE__ */ new Set([
6873
+ "pending review",
6874
+ "pending_review",
6875
+ "pending approval",
6876
+ "pending_approval",
6877
+ "approved",
6878
+ "rejected",
6879
+ "draft",
6880
+ "published",
6881
+ "modified",
6882
+ "supported",
6883
+ "ignored",
6884
+ "editing",
6885
+ "in review",
6886
+ "in_review",
6887
+ "ready to publish",
6888
+ "ready_to_publish",
6889
+ "null",
6890
+ "undefined"
6891
+ ]);
6892
+ function isValidDocId(val) {
6893
+ if (!val || typeof val !== "string") return false;
6894
+ const trimmed = val.trim();
6895
+ if (!trimmed) return false;
6896
+ if (LIFECYCLE_STATUS_WORDS.has(trimmed.toLowerCase())) return false;
6897
+ if (/\s/.test(trimmed)) return false;
6898
+ return /^[a-zA-Z0-9_-]+$/.test(trimmed);
6899
+ }
6900
+ function extractDocId(row) {
6901
+ if (!row || typeof row !== "object") return "";
6902
+ const meta = extractMetadataFromRow(row);
6903
+ if (meta?.documentId && isValidDocId(String(meta.documentId).trim())) {
6904
+ return String(meta.documentId).trim();
6905
+ }
6906
+ const candidates = [
6907
+ row.documentId,
6908
+ row.document_id,
6909
+ row["Document ID"],
6910
+ row["Document Id"],
6911
+ row["document_id"],
6912
+ row.docId,
6913
+ row["docId"],
6914
+ row.id,
6915
+ row.ID,
6916
+ row.Id
6917
+ ];
6918
+ for (const c of candidates) {
6919
+ if (c !== void 0 && c !== null) {
5690
6920
  const str = String(c).trim();
5691
6921
  if (isValidDocId(str)) {
5692
6922
  return str;
@@ -5697,6 +6927,10 @@ function extractDocId(row) {
5697
6927
  }
5698
6928
  function extractLocale(row) {
5699
6929
  if (!row || typeof row !== "object") return void 0;
6930
+ const meta = extractMetadataFromRow(row);
6931
+ if (meta?.locale && String(meta.locale).trim()) {
6932
+ return String(meta.locale).trim();
6933
+ }
5700
6934
  const candidates = [
5701
6935
  row.locale,
5702
6936
  row.Locale,
@@ -5781,157 +7015,32 @@ function extractDetailedErrorMessage(err) {
5781
7015
  if (!e) return "";
5782
7016
  const path = Array.isArray(e.path) ? e.path.join(".") : e.path;
5783
7017
  const msg = e.message || (typeof e === "string" ? e : JSON.stringify(e));
5784
- return path ? `${path}: ${msg}` : msg;
5785
- }).filter(Boolean);
5786
- if (messages.length > 0) return messages.join("; ");
5787
- }
5788
- if (Array.isArray(err.inner) && err.inner.length > 0) {
5789
- const messages = err.inner.map((e) => {
5790
- if (!e) return "";
5791
- const path = e.path;
5792
- const msg = e.message || (typeof e === "string" ? e : JSON.stringify(e));
5793
- return path ? `${path}: ${msg}` : msg;
5794
- }).filter(Boolean);
5795
- if (messages.length > 0) return messages.join("; ");
5796
- }
5797
- if (Array.isArray(err.errors) && err.errors.length > 0) {
5798
- return err.errors.join("; ");
5799
- }
5800
- if (typeof err.details === "string" && err.details.trim()) {
5801
- return err.details;
5802
- }
5803
- if (err.details?.message) {
5804
- return err.details.message;
5805
- }
5806
- if (err.message && err.message !== "[object Object]") {
5807
- return err.message;
5808
- }
5809
- return "Error processing row";
5810
- }
5811
- function discoverExportFields(ct, allComponents, maxDepth = 4) {
5812
- const fields = [{ key: "documentId", label: "documentId", type: "string" }];
5813
- const excluded = ["createdBy", "updatedBy", "localizations"];
5814
- function walkComponent(compUid, pathPrefix, labelPrefix, depth) {
5815
- if (depth >= maxDepth) return;
5816
- const comp = allComponents[compUid];
5817
- if (!comp?.attributes) return;
5818
- for (const [subKey, subDef] of Object.entries(comp.attributes)) {
5819
- if (excluded.includes(subKey)) continue;
5820
- const keyPath = `${pathPrefix}.${subKey}`;
5821
- const displayLabel = `${labelPrefix} > ${subKey}`;
5822
- if (subDef.type === "component" && subDef.component) {
5823
- if (!subDef.repeatable) {
5824
- walkComponent(subDef.component, keyPath, displayLabel, depth + 1);
5825
- } else {
5826
- fields.push({ key: keyPath, label: displayLabel, type: "component" });
5827
- }
5828
- } else {
5829
- fields.push({ key: keyPath, label: displayLabel, type: subDef.type });
5830
- }
5831
- }
5832
- }
5833
- for (const [attrName, attrDef] of Object.entries(ct.attributes || {})) {
5834
- if (excluded.includes(attrName)) continue;
5835
- if (attrDef.type === "component" && attrDef.component) {
5836
- if (!attrDef.repeatable) {
5837
- walkComponent(attrDef.component, attrName, attrName, 0);
5838
- } else {
5839
- fields.push({ key: attrName, label: attrName, type: "component" });
5840
- }
5841
- } else {
5842
- fields.push({ key: attrName, label: attrName, type: attrDef.type });
5843
- }
5844
- }
5845
- return fields;
5846
- }
5847
- function buildDeepPopulate(attributes, allComponents, depth = 0) {
5848
- if (depth > 5) return void 0;
5849
- const populate = {};
5850
- for (const [key, def] of Object.entries(attributes || {})) {
5851
- if (def.type === "component" && def.component) {
5852
- const comp = allComponents[def.component];
5853
- if (comp?.attributes) {
5854
- const subPopulate = buildDeepPopulate(comp.attributes, allComponents, depth + 1);
5855
- if (subPopulate && Object.keys(subPopulate).length > 0) {
5856
- populate[key] = {
5857
- populate: subPopulate
5858
- };
5859
- } else {
5860
- populate[key] = true;
5861
- }
5862
- } else {
5863
- populate[key] = true;
5864
- }
5865
- } else if (def.type === "dynamiczone") {
5866
- populate[key] = true;
5867
- } else if (def.type === "relation" || def.type === "media") {
5868
- populate[key] = true;
5869
- }
5870
- }
5871
- return Object.keys(populate).length > 0 ? populate : void 0;
5872
- }
5873
- function getNestedExportValue(entry, path) {
5874
- if (!entry || !path) return "";
5875
- const parts = path.split(".");
5876
- let current = entry;
5877
- for (let i = 0; i < parts.length; i++) {
5878
- const part = parts[i];
5879
- if (current === null || current === void 0) return "";
5880
- if (Array.isArray(current)) {
5881
- const subPath = parts.slice(i).join(".");
5882
- return current.map((item) => {
5883
- if (!item) return "";
5884
- if (typeof item === "object") {
5885
- const val = getNestedExportValue(item, subPath);
5886
- return typeof val === "object" ? JSON.stringify(val) : String(val ?? "");
5887
- }
5888
- return String(item);
5889
- }).filter(Boolean).join("; ");
5890
- }
5891
- if (current && typeof current === "object") {
5892
- if (current[part] !== void 0) {
5893
- current = current[part];
5894
- } else {
5895
- const camel = part.replace(/_([a-z0-9])/g, (_, l) => l.toUpperCase());
5896
- const snake = part.replace(/([A-Z])/g, "_$1").toLowerCase();
5897
- if (current[camel] !== void 0) {
5898
- current = current[camel];
5899
- } else if (current[snake] !== void 0) {
5900
- current = current[snake];
5901
- } else {
5902
- current = void 0;
5903
- }
5904
- }
5905
- } else {
5906
- current = void 0;
5907
- }
7018
+ return path ? `${path}: ${msg}` : msg;
7019
+ }).filter(Boolean);
7020
+ if (messages.length > 0) return messages.join("; ");
5908
7021
  }
5909
- if (current === null || current === void 0) return "";
5910
- if (Array.isArray(current) && current.length > 0 && current[0]?.type && Array.isArray(current[0]?.children)) {
5911
- return JSON.stringify(current);
7022
+ if (Array.isArray(err.inner) && err.inner.length > 0) {
7023
+ const messages = err.inner.map((e) => {
7024
+ if (!e) return "";
7025
+ const path = e.path;
7026
+ const msg = e.message || (typeof e === "string" ? e : JSON.stringify(e));
7027
+ return path ? `${path}: ${msg}` : msg;
7028
+ }).filter(Boolean);
7029
+ if (messages.length > 0) return messages.join("; ");
5912
7030
  }
5913
- if (typeof current === "object" && current.url) {
5914
- return current.url;
7031
+ if (Array.isArray(err.errors) && err.errors.length > 0) {
7032
+ return err.errors.join("; ");
5915
7033
  }
5916
- if (typeof current === "object" && !Array.isArray(current)) {
5917
- if (current.name && (current.locale === null || !current.documentId)) {
5918
- return current.name;
5919
- }
5920
- if (current.documentId || current.id || current.name || current.title) {
5921
- return current.documentId || current.id || current.name || current.title;
5922
- }
7034
+ if (typeof err.details === "string" && err.details.trim()) {
7035
+ return err.details;
5923
7036
  }
5924
- if (Array.isArray(current)) {
5925
- return current.map((item) => {
5926
- if (!item) return "";
5927
- if (typeof item === "object") {
5928
- if (item.url) return item.url;
5929
- return item.documentId || item.id || item.name || item.title || JSON.stringify(item);
5930
- }
5931
- return String(item);
5932
- }).filter(Boolean).join("; ");
7037
+ if (err.details?.message) {
7038
+ return err.details.message;
5933
7039
  }
5934
- return current;
7040
+ if (err.message && err.message !== "[object Object]") {
7041
+ return err.message;
7042
+ }
7043
+ return "Error processing row";
5935
7044
  }
5936
7045
  const csvImportSessions = /* @__PURE__ */ new Map();
5937
7046
  function cleanupStaleSessions() {
@@ -5966,7 +7075,7 @@ async function findExistingDocument(strapi, uid, targetDocId, docLocale) {
5966
7075
  if (!targetDocId) return null;
5967
7076
  const ct = strapi.contentTypes[uid];
5968
7077
  const effectiveLocale = getEffectiveLocale(ct, docLocale);
5969
- const populateDef = ct?.attributes ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
7078
+ const populateDef = ct ? buildLosslessPopulate(strapi, uid) : void 0;
5970
7079
  try {
5971
7080
  const queryArgs = {
5972
7081
  documentId: targetDocId,
@@ -6018,329 +7127,229 @@ function deepMergeComponent(existingVal, newVal) {
6018
7127
  }
6019
7128
  return merged;
6020
7129
  }
6021
- function parseNumberValue(rawVal, isInteger) {
6022
- const cleanStr = String(rawVal).replace(/[$€£,\s]/g, "");
6023
- if (isInteger) {
6024
- const n = parseInt(cleanStr, 10);
6025
- return isNaN(n) ? null : n;
6026
- } else {
6027
- const f = parseFloat(cleanStr);
6028
- return isNaN(f) ? null : f;
6029
- }
6030
- }
6031
- function parseBooleanValue(rawVal) {
6032
- const s = String(rawVal).trim().toLowerCase();
6033
- return s === "true" || s === "1" || s === "yes" || s === "y" || s === "on";
6034
- }
6035
- function parseBlocksValue(rawVal) {
6036
- try {
6037
- const parsed = JSON.parse(rawVal);
6038
- if (Array.isArray(parsed)) {
6039
- return parsed;
7130
+ function formatValueDisplay(val) {
7131
+ if (val === null || val === void 0) return "(empty)";
7132
+ if (typeof val === "object") {
7133
+ try {
7134
+ return JSON.stringify(val);
7135
+ } catch {
7136
+ return String(val);
6040
7137
  }
6041
- } catch {
6042
7138
  }
6043
- const trimmed = String(rawVal).trim();
6044
- if (!trimmed) return [];
6045
- return [{ type: "paragraph", children: [{ type: "text", text: trimmed }] }];
6046
- }
6047
- function parseEnumValue(rawVal, allowedValues) {
6048
- const trimmed = String(rawVal).trim();
6049
- if (Array.isArray(allowedValues) && allowedValues.length > 0) {
6050
- const match = allowedValues.find((v) => v.toLowerCase() === trimmed.toLowerCase());
6051
- if (match) return match;
6052
- }
6053
- return trimmed;
7139
+ const s = String(val).trim();
7140
+ return s === "" ? "(empty)" : s;
6054
7141
  }
6055
- function parseRelationValue(rawVal, relationType) {
6056
- const isToMany = relationType ? relationType.toLowerCase().endsWith("many") : false;
6057
- if (rawVal === null || rawVal === void 0) return isToMany ? [] : null;
6058
- let parsed = rawVal;
6059
- if (typeof rawVal === "string") {
6060
- const trimmed = rawVal.trim();
6061
- if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
6062
- try {
6063
- parsed = JSON.parse(trimmed);
6064
- } catch {
6065
- }
6066
- }
6067
- }
6068
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
6069
- if (parsed.name && (parsed.locale === null || LIFECYCLE_STATUS_WORDS.has(String(parsed.name).trim().toLowerCase()))) {
6070
- return isToMany ? [] : null;
6071
- }
6072
- const docId = parsed.documentId || parsed.id || null;
6073
- if (docId && isValidDocId(String(docId).trim())) {
6074
- const validStr = String(docId).trim();
6075
- return isToMany ? [validStr] : validStr;
6076
- }
6077
- return isToMany ? [] : null;
6078
- }
6079
- if (Array.isArray(parsed)) {
6080
- const ids = parsed.map((item) => {
6081
- if (typeof item === "object" && item !== null) {
6082
- if (item.name && (item.locale === null || LIFECYCLE_STATUS_WORDS.has(String(item.name).trim().toLowerCase()))) {
6083
- return null;
6084
- }
6085
- const id = item.documentId || item.id;
6086
- return id && isValidDocId(String(id).trim()) ? String(id).trim() : null;
6087
- }
6088
- return isValidDocId(String(item).trim()) ? String(item).trim() : null;
6089
- }).filter(Boolean);
6090
- return isToMany ? ids : ids[0] || null;
6091
- }
6092
- if (typeof rawVal === "string") {
6093
- if (rawVal.includes(";") || rawVal.includes(",")) {
6094
- const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter((p) => isValidDocId(p));
6095
- return isToMany ? parts : parts[0] || null;
6096
- }
6097
- const trimmed = rawVal.trim();
6098
- if (isValidDocId(trimmed)) {
6099
- return isToMany ? [trimmed] : trimmed;
6100
- }
7142
+ async function executeUpdateMutation(strapi, ct, uid, existing, row, rowNumber, options, effectiveLocale, isEditing, isDraftAndPublish, publishedCounterparts, stats, actionLabel = "Updated") {
7143
+ const resolvedDocId = existing.documentId;
7144
+ const updatePayload = await buildDocumentUpdatePayload(
7145
+ strapi,
7146
+ uid,
7147
+ existing,
7148
+ row,
7149
+ { isPartialUpdate: options.mode === "update" }
7150
+ );
7151
+ if (Object.keys(updatePayload).length === 0) {
7152
+ stats.skipped++;
7153
+ stats.diffs.push({
7154
+ uid,
7155
+ collectionName: ct.info?.displayName || uid,
7156
+ documentId: resolvedDocId,
7157
+ label: existing.title || existing.name || `Entry #${resolvedDocId}`,
7158
+ attribute: "",
7159
+ oldValue: existing,
7160
+ newValue: {},
7161
+ status: "skipped",
7162
+ message: `Skipped (no editable attributes in row ${rowNumber})`
7163
+ });
7164
+ return;
6101
7165
  }
6102
- return isToMany ? [] : null;
6103
- }
6104
- function parseMediaValue(rawVal, isMultiple = false) {
6105
- const trimmed = String(rawVal).trim();
6106
- if (trimmed.startsWith("[") || trimmed.startsWith("{")) {
7166
+ let pubRecord = effectiveLocale && publishedCounterparts.get(`${resolvedDocId}@@@${effectiveLocale}`) || publishedCounterparts.get(String(resolvedDocId));
7167
+ if (!pubRecord && isDraftAndPublish && resolvedDocId) {
6107
7168
  try {
6108
- const parsed = JSON.parse(trimmed);
6109
- if (Array.isArray(parsed)) {
6110
- const ids = parsed.map((item) => typeof item === "object" && item !== null ? item.id || item.documentId : item).filter(Boolean);
6111
- return isMultiple ? ids : ids[0] || null;
6112
- }
6113
- if (typeof parsed === "number") {
6114
- return isMultiple ? [parsed] : parsed;
6115
- }
6116
- if (typeof parsed === "object" && parsed !== null) {
6117
- const id = parsed.id || parsed.documentId || parsed;
6118
- return isMultiple ? [id] : id;
7169
+ const singlePub = await strapi.documents(uid).findMany({
7170
+ status: "published",
7171
+ filters: { documentId: resolvedDocId },
7172
+ fields: ["documentId", "updatedAt", "publishedAt", "locale"],
7173
+ limit: 1
7174
+ });
7175
+ if (singlePub && singlePub.length > 0) {
7176
+ pubRecord = singlePub[0];
7177
+ publishedCounterparts.set(String(resolvedDocId), pubRecord);
6119
7178
  }
6120
7179
  } catch {
6121
7180
  }
6122
7181
  }
6123
- if (rawVal.includes(";") || rawVal.includes(",")) {
6124
- const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter(Boolean).map((s) => /^\d+$/.test(s) ? parseInt(s, 10) : s);
6125
- return isMultiple ? parts : parts[0] || null;
7182
+ const rowStatus = row.status || row.Status || row.STATUS || row["Published Status"] || row["published_status"] || row["strapi_status"];
7183
+ const rowPubAt = row.publishedAt || row.published_at || row.PublishedAt;
7184
+ const inspectionExisting = rowStatus || rowPubAt ? {
7185
+ ...existing,
7186
+ ...rowStatus ? { status: rowStatus } : {},
7187
+ ...rowPubAt ? { publishedAt: rowPubAt } : {}
7188
+ } : existing;
7189
+ const { hadPublishedVersion } = resolveRecordPublicationStatus(
7190
+ inspectionExisting,
7191
+ pubRecord,
7192
+ isDraftAndPublish
7193
+ );
7194
+ const shouldPublish = evaluateShouldPublish({
7195
+ isDraftAndPublish,
7196
+ hadPublishedVersion,
7197
+ isEditing,
7198
+ publishOnApproval: Boolean(options.publish),
7199
+ publishStrategy: options.publishStrategy || "safe",
7200
+ unreviewedConsent: options.unreviewedConsent
7201
+ });
7202
+ const proposedEntity = deepMergeEntities(existing, updatePayload);
7203
+ const valResult = await validateEntityQuotas(strapi, uid, proposedEntity);
7204
+ if (!valResult.isValid) {
7205
+ stats.skipped++;
7206
+ if (stats.failed !== void 0) stats.failed++;
7207
+ stats.errors.push({
7208
+ row: rowNumber,
7209
+ documentId: resolvedDocId,
7210
+ error: valResult.errorMessage
7211
+ });
7212
+ stats.diffs.push({
7213
+ uid,
7214
+ collectionName: ct.info?.displayName || uid,
7215
+ documentId: resolvedDocId,
7216
+ label: existing.title || existing.name || `Entry #${resolvedDocId}`,
7217
+ attribute: valResult.targetField || "",
7218
+ oldValue: existing?.[valResult.targetField || ""] ?? null,
7219
+ newValue: updatePayload?.[valResult.targetField || ""] ?? null,
7220
+ status: "error",
7221
+ message: valResult.errorMessage
7222
+ });
7223
+ return;
6126
7224
  }
6127
- if (/^\d+$/.test(trimmed)) {
6128
- const numId = parseInt(trimmed, 10);
6129
- return isMultiple ? [numId] : numId;
7225
+ const updateArgs = {
7226
+ documentId: resolvedDocId,
7227
+ data: updatePayload
7228
+ };
7229
+ if (effectiveLocale) updateArgs.locale = effectiveLocale;
7230
+ await strapi.documents(uid).update(updateArgs);
7231
+ if (shouldPublish) {
7232
+ try {
7233
+ const pubArgs = { documentId: resolvedDocId };
7234
+ if (effectiveLocale) pubArgs.locale = effectiveLocale;
7235
+ await strapi.documents(uid).publish(pubArgs);
7236
+ } catch (pubErr) {
7237
+ strapi.log.warn(`[bulk-updater] Auto-publish failed for ${resolvedDocId}:`, pubErr);
7238
+ }
6130
7239
  }
6131
- if (isValidDocId(trimmed)) {
6132
- return isMultiple ? [trimmed] : trimmed;
7240
+ try {
7241
+ await recordContentHistoryVersion(strapi, {
7242
+ uid,
7243
+ documentId: resolvedDocId,
7244
+ userId: options.user?.id,
7245
+ statusOverride: shouldPublish ? "published" : isDraftAndPublish ? hadPublishedVersion ? "modified" : "draft" : void 0
7246
+ });
7247
+ } catch {
6133
7248
  }
6134
- return isMultiple ? [] : null;
6135
- }
6136
- function parseRowToPayload(strapi, attrs, row) {
6137
- const payload2 = {};
6138
- for (const [key, rawVal] of Object.entries(row)) {
6139
- const normalizedKey = key.toLowerCase().replace(/[\s_-]/g, "");
6140
- if (SYSTEM_FIELD_KEYS.has(normalizedKey)) continue;
6141
- if (key.includes(".")) {
6142
- const topPart = key.split(".")[0].toLowerCase().replace(/[\s_-]/g, "");
6143
- if (SYSTEM_FIELD_KEYS.has(topPart)) continue;
6144
- const parts = key.split(".");
6145
- let currentAttrs = attrs;
6146
- let currentTarget = payload2;
6147
- for (let pIdx = 0; pIdx < parts.length; pIdx++) {
6148
- const part = parts[pIdx];
6149
- const isLeaf = pIdx === parts.length - 1;
6150
- if (isLeaf) {
6151
- let leafDef = currentAttrs[part];
6152
- if (!leafDef) {
6153
- const match = Object.keys(currentAttrs).find(
6154
- (k) => k.toLowerCase() === part.toLowerCase() || k.toLowerCase() === part.toLowerCase().replace(/\s+/g, "")
6155
- );
6156
- if (match) leafDef = currentAttrs[match];
6157
- }
6158
- if (!leafDef) {
6159
- break;
6160
- }
6161
- if (rawVal === "" || rawVal === null || rawVal === void 0) {
6162
- if (leafDef.type !== "dynamiczone" && !(leafDef.type === "component" && leafDef.repeatable) && leafDef.type !== "relation" && leafDef.type !== "password") {
6163
- currentTarget[part] = null;
6164
- }
6165
- } else if (leafDef.type === "integer" || leafDef.type === "biginteger") {
6166
- currentTarget[part] = parseNumberValue(rawVal, true);
6167
- } else if (leafDef.type === "float" || leafDef.type === "decimal") {
6168
- currentTarget[part] = parseNumberValue(rawVal, false);
6169
- } else if (leafDef.type === "boolean") {
6170
- currentTarget[part] = parseBooleanValue(rawVal);
6171
- } else if (leafDef.type === "blocks") {
6172
- currentTarget[part] = parseBlocksValue(rawVal);
6173
- } else if (leafDef.type === "enumeration") {
6174
- currentTarget[part] = parseEnumValue(rawVal, leafDef.enum);
6175
- } else if (leafDef.type === "relation") {
6176
- currentTarget[part] = parseRelationValue(rawVal, leafDef.relation);
6177
- } else if (leafDef.type === "media") {
6178
- currentTarget[part] = parseMediaValue(rawVal, Boolean(leafDef.multiple));
6179
- } else if (leafDef.type === "date" || leafDef.type === "time" || leafDef.type === "datetime" || leafDef.type === "timestamp") {
6180
- currentTarget[part] = String(rawVal).trim() || null;
6181
- } else if (leafDef.type === "email" || leafDef.type === "uid") {
6182
- currentTarget[part] = String(rawVal).trim();
6183
- } else if (leafDef.type === "password") {
6184
- if (String(rawVal).trim()) {
6185
- currentTarget[part] = String(rawVal).trim();
6186
- }
6187
- } else if (leafDef.type === "json") {
6188
- try {
6189
- currentTarget[part] = JSON.parse(rawVal);
6190
- } catch {
6191
- currentTarget[part] = rawVal;
6192
- }
6193
- } else if (leafDef.type === "component" && leafDef.repeatable) {
6194
- try {
6195
- const parsed = JSON.parse(rawVal);
6196
- if (Array.isArray(parsed)) {
6197
- currentTarget[part] = parsed;
6198
- }
6199
- } catch {
6200
- }
6201
- } else {
6202
- currentTarget[part] = rawVal;
6203
- }
6204
- } else {
6205
- let compDef = currentAttrs[part];
6206
- if (!compDef) {
6207
- const match = Object.keys(currentAttrs).find(
6208
- (k) => k.toLowerCase() === part.toLowerCase() || k.toLowerCase() === part.toLowerCase().replace(/\s+/g, "")
6209
- );
6210
- if (match) compDef = currentAttrs[match];
6211
- }
6212
- if (compDef?.type === "component" && !compDef.repeatable && compDef.component) {
6213
- const comp = strapi.components[compDef.component];
6214
- if (!comp?.attributes) {
6215
- break;
6216
- }
6217
- if (!currentTarget[part] || typeof currentTarget[part] !== "object" || Array.isArray(currentTarget[part])) {
6218
- currentTarget[part] = {};
6219
- }
6220
- currentTarget = currentTarget[part];
6221
- currentAttrs = comp.attributes;
6222
- } else {
6223
- break;
6224
- }
6225
- }
6226
- }
6227
- continue;
6228
- }
6229
- let attrDef = attrs[key];
6230
- if (!attrDef) {
6231
- const matchKey = Object.keys(attrs).find(
6232
- (k) => k.toLowerCase() === key.toLowerCase() || k.toLowerCase() === key.toLowerCase().replace(/\s+/g, "")
6233
- );
6234
- if (matchKey) {
6235
- attrDef = attrs[matchKey];
6236
- }
6237
- }
6238
- if (!attrDef) continue;
6239
- if (attrDef?.target?.includes("review-workflow") || attrDef?.target === "admin::review-workflow-stage") {
6240
- continue;
6241
- }
6242
- if (rawVal === "" || rawVal === null || rawVal === void 0) {
6243
- if (attrDef.type !== "dynamiczone" && !(attrDef.type === "component" && attrDef.repeatable) && attrDef.type !== "relation" && attrDef.type !== "password") {
6244
- payload2[key] = null;
6245
- }
6246
- continue;
6247
- }
6248
- switch (attrDef.type) {
6249
- case "integer":
6250
- case "biginteger":
6251
- payload2[key] = parseNumberValue(rawVal, true);
6252
- break;
6253
- case "float":
6254
- case "decimal":
6255
- payload2[key] = parseNumberValue(rawVal, false);
6256
- break;
6257
- case "boolean":
6258
- payload2[key] = parseBooleanValue(rawVal);
6259
- break;
6260
- case "blocks":
6261
- payload2[key] = parseBlocksValue(rawVal);
6262
- break;
6263
- case "enumeration":
6264
- payload2[key] = parseEnumValue(rawVal, attrDef.enum);
6265
- break;
6266
- case "relation":
6267
- payload2[key] = parseRelationValue(rawVal, attrDef.relation);
6268
- break;
6269
- case "media":
6270
- payload2[key] = parseMediaValue(rawVal, Boolean(attrDef.multiple));
6271
- break;
6272
- case "date":
6273
- case "time":
6274
- case "datetime":
6275
- case "timestamp":
6276
- payload2[key] = String(rawVal).trim() || null;
6277
- break;
6278
- case "email":
6279
- case "uid":
6280
- payload2[key] = String(rawVal).trim();
6281
- break;
6282
- case "password":
6283
- if (String(rawVal).trim()) {
6284
- payload2[key] = String(rawVal).trim();
6285
- }
6286
- break;
6287
- case "json":
6288
- try {
6289
- payload2[key] = JSON.parse(rawVal);
6290
- } catch {
6291
- payload2[key] = rawVal;
6292
- }
6293
- break;
6294
- case "dynamiczone": {
6295
- try {
6296
- const parsed = JSON.parse(rawVal);
6297
- if (Array.isArray(parsed) && parsed.every((item) => item && typeof item === "object" && typeof item.__component === "string")) {
6298
- payload2[key] = parsed;
6299
- }
6300
- } catch {
6301
- }
6302
- break;
6303
- }
6304
- case "component": {
6305
- if (attrDef.repeatable) {
6306
- try {
6307
- const parsed = JSON.parse(rawVal);
6308
- if (Array.isArray(parsed) && parsed.every((item) => item && typeof item === "object")) {
6309
- payload2[key] = parsed;
6310
- }
6311
- } catch {
6312
- }
6313
- } else {
6314
- try {
6315
- const parsed = JSON.parse(rawVal);
6316
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
6317
- payload2[key] = parsed;
6318
- }
6319
- } catch {
6320
- }
6321
- }
6322
- break;
7249
+ try {
7250
+ const postDoc = await strapi.documents(uid).findOne({
7251
+ documentId: resolvedDocId,
7252
+ ...effectiveLocale ? { locale: effectiveLocale } : {},
7253
+ populate: buildLosslessPopulate(strapi, uid)
7254
+ });
7255
+ if (postDoc) {
7256
+ const integrityReport = verifyDocumentIntegrity(strapi, uid, existing, updatePayload, postDoc);
7257
+ if (integrityReport.status === "FAILED") {
7258
+ strapi.log.warn(`[bulk-updater] Data integrity warning on row ${rowNumber}:`, integrityReport.diffs);
6323
7259
  }
6324
- default:
6325
- payload2[key] = rawVal;
6326
7260
  }
7261
+ } catch {
7262
+ }
7263
+ stats.updated++;
7264
+ for (const attrKey of Object.keys(updatePayload)) {
7265
+ const oldVal = existing?.[attrKey] ?? null;
7266
+ const newVal = updatePayload[attrKey];
7267
+ stats.diffs.push({
7268
+ uid,
7269
+ collectionName: ct.info?.displayName || uid,
7270
+ documentId: resolvedDocId,
7271
+ label: existing.title || existing.name || `Entry #${resolvedDocId}`,
7272
+ attribute: attrKey,
7273
+ oldValue: oldVal,
7274
+ newValue: newVal,
7275
+ status: "updated",
7276
+ message: `${actionLabel} "${attrKey}" via CSV import (row ${rowNumber})`
7277
+ });
6327
7278
  }
6328
- return payload2;
6329
7279
  }
6330
- function formatValueDisplay(val) {
6331
- if (val === null || val === void 0) return "(empty)";
6332
- if (typeof val === "object") {
7280
+ async function executeCreateMutation(strapi, ct, uid, docId, row, rowNumber, options, effectiveLocale, isEditing, isDraftAndPublish, stats) {
7281
+ const createPayload = await buildDocumentUpdatePayload(
7282
+ strapi,
7283
+ uid,
7284
+ null,
7285
+ row,
7286
+ {}
7287
+ );
7288
+ const valResultNew = await validateEntityQuotas(strapi, uid, createPayload);
7289
+ if (!valResultNew.isValid) {
7290
+ stats.skipped++;
7291
+ if (stats.failed !== void 0) stats.failed++;
7292
+ stats.errors.push({
7293
+ row: rowNumber,
7294
+ documentId: docId || "new",
7295
+ error: valResultNew.errorMessage
7296
+ });
7297
+ stats.diffs.push({
7298
+ uid,
7299
+ collectionName: ct.info?.displayName || uid,
7300
+ documentId: docId || "new",
7301
+ label: `Row ${rowNumber}`,
7302
+ attribute: valResultNew.targetField || "",
7303
+ oldValue: null,
7304
+ newValue: createPayload?.[valResultNew.targetField || ""] ?? null,
7305
+ status: "error",
7306
+ message: valResultNew.errorMessage
7307
+ });
7308
+ return;
7309
+ }
7310
+ const createArgs = { data: createPayload };
7311
+ if (effectiveLocale) createArgs.locale = effectiveLocale;
7312
+ const created = await strapi.documents(uid).create(createArgs);
7313
+ const newDocId = created?.documentId || docId;
7314
+ const shouldPublishNew = !isEditing && isDraftAndPublish && Boolean(options.publish) && (options.publishStrategy === "all" || options.unreviewedConsent ? true : false);
7315
+ if (shouldPublishNew && newDocId) {
6333
7316
  try {
6334
- return JSON.stringify(val);
6335
- } catch {
6336
- return String(val);
7317
+ const pubArgs = { documentId: newDocId };
7318
+ if (effectiveLocale) pubArgs.locale = effectiveLocale;
7319
+ await strapi.documents(uid).publish(pubArgs);
7320
+ } catch (pubErr) {
7321
+ strapi.log.warn(`[bulk-updater] Auto-publish failed for ${newDocId}:`, pubErr);
6337
7322
  }
6338
7323
  }
6339
- const s = String(val).trim();
6340
- return s === "" ? "(empty)" : s;
7324
+ try {
7325
+ await recordContentHistoryVersion(strapi, {
7326
+ uid,
7327
+ documentId: newDocId,
7328
+ userId: options.user?.id,
7329
+ statusOverride: shouldPublishNew ? "published" : isDraftAndPublish ? "draft" : void 0
7330
+ });
7331
+ } catch {
7332
+ }
7333
+ stats.created++;
7334
+ if (!docId) {
7335
+ stats.newWithoutDocId++;
7336
+ }
7337
+ for (const attrKey of Object.keys(createPayload)) {
7338
+ stats.diffs.push({
7339
+ uid,
7340
+ collectionName: ct.info?.displayName || uid,
7341
+ documentId: newDocId,
7342
+ label: created?.title || created?.name || `New Entry #${newDocId}`,
7343
+ attribute: attrKey,
7344
+ oldValue: null,
7345
+ newValue: createPayload[attrKey],
7346
+ status: "created",
7347
+ message: docId ? `Created "${attrKey}" via CSV import (row ${rowNumber})` : `Created "${attrKey}" as new entry (row ${rowNumber})`
7348
+ });
7349
+ }
6341
7350
  }
6342
7351
  async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6343
- const attrs = ct.attributes || {};
7352
+ ct.attributes || {};
6344
7353
  const { mode = "auto", publish = true, publishStrategy = "safe", user } = options;
6345
7354
  const isDraftAndPublish = Boolean(ct.options?.draftAndPublish);
6346
7355
  const docIdsInChunk = rows.map((r) => extractDocId(r)).filter(Boolean);
@@ -6387,320 +7396,81 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6387
7396
  if (effectiveLocale) findSingleArgs.locale = effectiveLocale;
6388
7397
  const singleDoc = await strapi.documents(uid).findFirst(findSingleArgs);
6389
7398
  if (singleDoc?.documentId) {
6390
- docId = singleDoc.documentId;
6391
- }
6392
- } catch {
6393
- }
6394
- }
6395
- const payload2 = parseRowToPayload(strapi, attrs, row);
6396
- try {
6397
- if (mode === "update") {
6398
- if (!docId) {
6399
- stats.skipped++;
6400
- stats.errors.push({
6401
- row: rowNumber,
6402
- error: "Missing or invalid documentId for Update mode. (Tip: Use Smart Auto-Detect mode to auto-add entries without document IDs)."
6403
- });
6404
- continue;
6405
- }
6406
- const existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
6407
- if (!existing) {
6408
- stats.skipped++;
6409
- stats.errors.push({
6410
- row: rowNumber,
6411
- documentId: docId,
6412
- error: `Document with ID "${docId}" not found in database.`
6413
- });
6414
- continue;
6415
- }
6416
- const resolvedDocId = existing.documentId || docId;
6417
- const mergedPayload = { ...payload2 };
6418
- for (const key of Object.keys(payload2)) {
6419
- if (attrs[key]?.type === "component" && typeof payload2[key] === "object" && payload2[key] !== null) {
6420
- mergedPayload[key] = deepMergeComponent(existing[key], payload2[key]);
6421
- }
6422
- }
6423
- if (Object.keys(mergedPayload).length === 0) {
6424
- stats.skipped++;
6425
- stats.diffs.push({
6426
- uid,
6427
- collectionName: ct.info?.displayName || uid,
6428
- documentId: resolvedDocId,
6429
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6430
- attribute: "",
6431
- oldValue: existing,
6432
- newValue: {},
6433
- status: "skipped",
6434
- message: `Skipped (no editable attributes in row ${rowNumber})`
6435
- });
6436
- continue;
6437
- }
6438
- let pubRecord = effectiveLocale && publishedCounterparts.get(`${resolvedDocId}@@@${effectiveLocale}`) || publishedCounterparts.get(String(resolvedDocId));
6439
- if (!pubRecord && isDraftAndPublish && resolvedDocId) {
6440
- try {
6441
- const singlePub = await strapi.documents(uid).findMany({
6442
- status: "published",
6443
- filters: { documentId: resolvedDocId },
6444
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6445
- limit: 1
6446
- });
6447
- if (singlePub && singlePub.length > 0) {
6448
- pubRecord = singlePub[0];
6449
- publishedCounterparts.set(String(resolvedDocId), pubRecord);
6450
- }
6451
- } catch {
6452
- }
6453
- }
6454
- const rowStatus = row.status || row.Status || row.STATUS || row["Published Status"] || row["published_status"] || row["strapi_status"];
6455
- const rowPubAt = row.publishedAt || row.published_at || row.PublishedAt;
6456
- const inspectionExisting = rowStatus || rowPubAt ? { ...existing, ...rowStatus ? { status: rowStatus } : {}, ...rowPubAt ? { publishedAt: rowPubAt } : {} } : existing;
6457
- const { hadPublishedVersion } = resolveRecordPublicationStatus(
6458
- inspectionExisting,
6459
- pubRecord,
6460
- isDraftAndPublish
6461
- );
6462
- const shouldPublish = evaluateShouldPublish({
6463
- isDraftAndPublish,
6464
- hadPublishedVersion,
6465
- isEditing,
6466
- publishOnApproval: Boolean(publish),
6467
- publishStrategy,
6468
- unreviewedConsent: options.unreviewedConsent
6469
- });
6470
- const updateArgs = {
6471
- documentId: resolvedDocId,
6472
- data: mergedPayload
6473
- };
6474
- if (effectiveLocale) updateArgs.locale = effectiveLocale;
6475
- const proposedEntity = deepMergeEntities(existing, mergedPayload);
6476
- const valResult = await validateEntityQuotas(strapi, uid, proposedEntity);
6477
- if (!valResult.isValid) {
7399
+ docId = singleDoc.documentId;
7400
+ }
7401
+ } catch {
7402
+ }
7403
+ }
7404
+ try {
7405
+ if (mode === "update") {
7406
+ if (!docId) {
6478
7407
  stats.skipped++;
6479
- if (stats.failed !== void 0) stats.failed++;
6480
7408
  stats.errors.push({
6481
7409
  row: rowNumber,
6482
- documentId: resolvedDocId,
6483
- error: valResult.errorMessage
6484
- });
6485
- stats.diffs.push({
6486
- uid,
6487
- collectionName: ct.info?.displayName || uid,
6488
- documentId: resolvedDocId,
6489
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6490
- attribute: valResult.targetField || "",
6491
- oldValue: existing?.[valResult.targetField || ""] ?? null,
6492
- newValue: mergedPayload?.[valResult.targetField || ""] ?? null,
6493
- status: "error",
6494
- message: valResult.errorMessage
7410
+ error: "Missing or invalid documentId for Update mode. (Tip: Use Smart Auto-Detect mode to auto-add entries without document IDs)."
6495
7411
  });
6496
7412
  continue;
6497
7413
  }
6498
- await strapi.documents(uid).update(updateArgs);
6499
- if (shouldPublish) {
6500
- try {
6501
- const pubArgs = { documentId: resolvedDocId };
6502
- if (effectiveLocale) pubArgs.locale = effectiveLocale;
6503
- await strapi.documents(uid).publish(pubArgs);
6504
- } catch (pubErr) {
6505
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${resolvedDocId}:`, pubErr);
6506
- }
6507
- }
6508
- try {
6509
- await recordContentHistoryVersion(strapi, {
6510
- uid,
6511
- documentId: resolvedDocId,
6512
- userId: user?.id,
6513
- statusOverride: shouldPublish ? "published" : isDraftAndPublish ? hadPublishedVersion ? "modified" : "draft" : void 0
6514
- });
6515
- } catch {
6516
- }
6517
- stats.updated++;
6518
- for (const attrKey of Object.keys(payload2)) {
6519
- const oldVal = existing?.[attrKey] ?? null;
6520
- const newVal = payload2[attrKey];
6521
- stats.diffs.push({
6522
- uid,
6523
- collectionName: ct.info?.displayName || uid,
6524
- documentId: resolvedDocId,
6525
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6526
- attribute: attrKey,
6527
- oldValue: oldVal,
6528
- newValue: newVal,
6529
- status: "updated",
6530
- message: `Updated "${attrKey}" via CSV import (row ${rowNumber})`
7414
+ const existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
7415
+ if (!existing) {
7416
+ stats.skipped++;
7417
+ stats.errors.push({
7418
+ row: rowNumber,
7419
+ documentId: docId,
7420
+ error: `Document with ID "${docId}" not found in database.`
6531
7421
  });
7422
+ continue;
6532
7423
  }
7424
+ await executeUpdateMutation(
7425
+ strapi,
7426
+ ct,
7427
+ uid,
7428
+ existing,
7429
+ row,
7430
+ rowNumber,
7431
+ options,
7432
+ effectiveLocale,
7433
+ isEditing,
7434
+ isDraftAndPublish,
7435
+ publishedCounterparts,
7436
+ stats,
7437
+ "Updated"
7438
+ );
6533
7439
  } else if (mode === "create_or_override") {
6534
7440
  let existing = null;
6535
7441
  if (docId) {
6536
7442
  existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
6537
7443
  }
6538
7444
  if (existing) {
6539
- const resolvedDocId = existing.documentId || docId;
6540
- const mergedPayload = { ...payload2 };
6541
- for (const key of Object.keys(payload2)) {
6542
- if (attrs[key]?.type === "component" && typeof payload2[key] === "object" && payload2[key] !== null) {
6543
- mergedPayload[key] = deepMergeComponent(existing[key], payload2[key]);
6544
- }
6545
- }
6546
- let pubRecord = effectiveLocale && publishedCounterparts.get(`${resolvedDocId}@@@${effectiveLocale}`) || publishedCounterparts.get(String(resolvedDocId));
6547
- if (!pubRecord && isDraftAndPublish && resolvedDocId) {
6548
- try {
6549
- const singlePub = await strapi.documents(uid).findMany({
6550
- status: "published",
6551
- filters: { documentId: resolvedDocId },
6552
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6553
- limit: 1
6554
- });
6555
- if (singlePub && singlePub.length > 0) {
6556
- pubRecord = singlePub[0];
6557
- publishedCounterparts.set(String(resolvedDocId), pubRecord);
6558
- }
6559
- } catch {
6560
- }
6561
- }
6562
- const rowStatus = row.status || row.Status || row.STATUS || row["Published Status"] || row["published_status"] || row["strapi_status"];
6563
- const rowPubAt = row.publishedAt || row.published_at || row.PublishedAt;
6564
- const inspectionExisting = rowStatus || rowPubAt ? { ...existing, ...rowStatus ? { status: rowStatus } : {}, ...rowPubAt ? { publishedAt: rowPubAt } : {} } : existing;
6565
- const { hadPublishedVersion } = resolveRecordPublicationStatus(
6566
- inspectionExisting,
6567
- pubRecord,
6568
- isDraftAndPublish
6569
- );
6570
- const shouldPublish = evaluateShouldPublish({
6571
- isDraftAndPublish,
6572
- hadPublishedVersion,
6573
- isEditing,
6574
- publishOnApproval: Boolean(publish),
6575
- publishStrategy,
6576
- unreviewedConsent: options.unreviewedConsent
6577
- });
6578
- const updateArgs = {
6579
- documentId: resolvedDocId,
6580
- data: mergedPayload
6581
- };
6582
- if (effectiveLocale) updateArgs.locale = effectiveLocale;
6583
- const proposedEntity = deepMergeEntities(existing, mergedPayload);
6584
- const valResult = await validateEntityQuotas(strapi, uid, proposedEntity);
6585
- if (!valResult.isValid) {
6586
- stats.skipped++;
6587
- if (stats.failed !== void 0) stats.failed++;
6588
- stats.errors.push({
6589
- row: rowNumber,
6590
- documentId: resolvedDocId,
6591
- error: valResult.errorMessage
6592
- });
6593
- stats.diffs.push({
6594
- uid,
6595
- collectionName: ct.info?.displayName || uid,
6596
- documentId: resolvedDocId,
6597
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6598
- attribute: valResult.targetField || "",
6599
- oldValue: existing?.[valResult.targetField || ""] ?? null,
6600
- newValue: mergedPayload?.[valResult.targetField || ""] ?? null,
6601
- status: "error",
6602
- message: valResult.errorMessage
6603
- });
6604
- continue;
6605
- }
6606
- await strapi.documents(uid).update(updateArgs);
6607
- if (shouldPublish) {
6608
- try {
6609
- const pubArgs = { documentId: resolvedDocId };
6610
- if (effectiveLocale) pubArgs.locale = effectiveLocale;
6611
- await strapi.documents(uid).publish(pubArgs);
6612
- } catch (pubErr) {
6613
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${resolvedDocId}:`, pubErr);
6614
- }
6615
- }
6616
- try {
6617
- await recordContentHistoryVersion(strapi, {
6618
- uid,
6619
- documentId: resolvedDocId,
6620
- userId: user?.id,
6621
- statusOverride: shouldPublish ? "published" : isDraftAndPublish ? hadPublishedVersion ? "modified" : "draft" : void 0
6622
- });
6623
- } catch {
6624
- }
6625
- stats.updated++;
6626
- for (const attrKey of Object.keys(payload2)) {
6627
- const oldVal = existing?.[attrKey] ?? null;
6628
- const newVal = payload2[attrKey];
6629
- stats.diffs.push({
6630
- uid,
6631
- collectionName: ct.info?.displayName || uid,
6632
- documentId: resolvedDocId,
6633
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6634
- attribute: attrKey,
6635
- oldValue: oldVal,
6636
- newValue: newVal,
6637
- status: "updated",
6638
- message: `Overridden "${attrKey}" via CSV import (row ${rowNumber})`
6639
- });
6640
- }
6641
- continue;
6642
- }
6643
- const valResultNew = await validateEntityQuotas(strapi, uid, payload2);
6644
- if (!valResultNew.isValid) {
6645
- stats.skipped++;
6646
- if (stats.failed !== void 0) stats.failed++;
6647
- stats.errors.push({
6648
- row: rowNumber,
6649
- documentId: docId || "new",
6650
- error: valResultNew.errorMessage
6651
- });
6652
- stats.diffs.push({
6653
- uid,
6654
- collectionName: ct.info?.displayName || uid,
6655
- documentId: docId || "new",
6656
- label: `Row ${rowNumber}`,
6657
- attribute: valResultNew.targetField || "",
6658
- oldValue: null,
6659
- newValue: payload2?.[valResultNew.targetField || ""] ?? null,
6660
- status: "error",
6661
- message: valResultNew.errorMessage
6662
- });
6663
- continue;
6664
- }
6665
- const createArgs = { data: payload2 };
6666
- if (effectiveLocale) createArgs.locale = effectiveLocale;
6667
- const created = await strapi.documents(uid).create(createArgs);
6668
- const newDocId = created?.documentId || docId;
6669
- const shouldPublishNew = !isEditing && isDraftAndPublish && Boolean(publish) && (publishStrategy === "all" || options.unreviewedConsent ? true : false);
6670
- if (shouldPublishNew && newDocId) {
6671
- try {
6672
- const pubArgs = { documentId: newDocId };
6673
- if (effectiveLocale) pubArgs.locale = effectiveLocale;
6674
- await strapi.documents(uid).publish(pubArgs);
6675
- } catch (pubErr) {
6676
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${newDocId}:`, pubErr);
6677
- }
6678
- }
6679
- try {
6680
- await recordContentHistoryVersion(strapi, {
7445
+ await executeUpdateMutation(
7446
+ strapi,
7447
+ ct,
6681
7448
  uid,
6682
- documentId: newDocId,
6683
- userId: user?.id,
6684
- statusOverride: shouldPublishNew ? "published" : isDraftAndPublish ? "draft" : void 0
6685
- });
6686
- } catch {
6687
- }
6688
- stats.created++;
6689
- if (!docId) {
6690
- stats.newWithoutDocId++;
6691
- }
6692
- for (const attrKey of Object.keys(payload2)) {
6693
- stats.diffs.push({
7449
+ existing,
7450
+ row,
7451
+ rowNumber,
7452
+ options,
7453
+ effectiveLocale,
7454
+ isEditing,
7455
+ isDraftAndPublish,
7456
+ publishedCounterparts,
7457
+ stats,
7458
+ "Overridden"
7459
+ );
7460
+ } else {
7461
+ await executeCreateMutation(
7462
+ strapi,
7463
+ ct,
6694
7464
  uid,
6695
- collectionName: ct.info?.displayName || uid,
6696
- documentId: newDocId,
6697
- label: created?.title || created?.name || `New Entry #${newDocId}`,
6698
- attribute: attrKey,
6699
- oldValue: null,
6700
- newValue: payload2[attrKey],
6701
- status: "created",
6702
- message: docId ? `Created "${attrKey}" via CSV import (row ${rowNumber})` : `Created "${attrKey}" as new entry (row ${rowNumber})`
6703
- });
7465
+ docId,
7466
+ row,
7467
+ rowNumber,
7468
+ options,
7469
+ effectiveLocale,
7470
+ isEditing,
7471
+ isDraftAndPublish,
7472
+ stats
7473
+ );
6704
7474
  }
6705
7475
  } else {
6706
7476
  let existing = null;
@@ -6708,178 +7478,56 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6708
7478
  existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
6709
7479
  }
6710
7480
  if (existing) {
6711
- const resolvedDocId = existing.documentId || docId;
6712
- const mergedPayload = { ...payload2 };
6713
- for (const key of Object.keys(payload2)) {
6714
- if (attrs[key]?.type === "component" && typeof payload2[key] === "object" && payload2[key] !== null) {
6715
- mergedPayload[key] = deepMergeComponent(existing[key], payload2[key]);
6716
- }
6717
- }
6718
- let pubRecord = effectiveLocale && publishedCounterparts.get(`${resolvedDocId}@@@${effectiveLocale}`) || publishedCounterparts.get(String(resolvedDocId));
6719
- if (!pubRecord && isDraftAndPublish && resolvedDocId) {
6720
- try {
6721
- const singlePub = await strapi.documents(uid).findMany({
6722
- status: "published",
6723
- filters: { documentId: resolvedDocId },
6724
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6725
- limit: 1
6726
- });
6727
- if (singlePub && singlePub.length > 0) {
6728
- pubRecord = singlePub[0];
6729
- publishedCounterparts.set(String(resolvedDocId), pubRecord);
6730
- }
6731
- } catch {
6732
- }
6733
- }
6734
- const rowStatus = row.status || row.Status || row.STATUS || row["Published Status"] || row["published_status"] || row["strapi_status"];
6735
- const rowPubAt = row.publishedAt || row.published_at || row.PublishedAt;
6736
- const inspectionExisting = rowStatus || rowPubAt ? { ...existing, ...rowStatus ? { status: rowStatus } : {}, ...rowPubAt ? { publishedAt: rowPubAt } : {} } : existing;
6737
- const { hadPublishedVersion } = resolveRecordPublicationStatus(
6738
- inspectionExisting,
6739
- pubRecord,
6740
- isDraftAndPublish
6741
- );
6742
- const shouldPublish = evaluateShouldPublish({
6743
- isDraftAndPublish,
6744
- hadPublishedVersion,
6745
- isEditing,
6746
- publishOnApproval: Boolean(publish),
6747
- publishStrategy,
6748
- unreviewedConsent: options.unreviewedConsent
6749
- });
6750
- const updateArgs = {
6751
- documentId: resolvedDocId,
6752
- data: mergedPayload
6753
- };
6754
- if (effectiveLocale) updateArgs.locale = effectiveLocale;
6755
- const proposedEntity = deepMergeEntities(existing, mergedPayload);
6756
- const valResult = await validateEntityQuotas(strapi, uid, proposedEntity);
6757
- if (!valResult.isValid) {
6758
- stats.skipped++;
6759
- if (stats.failed !== void 0) stats.failed++;
6760
- stats.errors.push({
6761
- row: rowNumber,
6762
- documentId: resolvedDocId,
6763
- error: valResult.errorMessage
6764
- });
6765
- stats.diffs.push({
6766
- uid,
6767
- collectionName: ct.info?.displayName || uid,
6768
- documentId: resolvedDocId,
6769
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6770
- attribute: valResult.targetField || "",
6771
- oldValue: existing?.[valResult.targetField || ""] ?? null,
6772
- newValue: mergedPayload?.[valResult.targetField || ""] ?? null,
6773
- status: "error",
6774
- message: valResult.errorMessage
6775
- });
6776
- continue;
6777
- }
6778
- await strapi.documents(uid).update(updateArgs);
6779
- if (shouldPublish) {
6780
- try {
6781
- const pubArgs = { documentId: resolvedDocId };
6782
- if (effectiveLocale) pubArgs.locale = effectiveLocale;
6783
- await strapi.documents(uid).publish(pubArgs);
6784
- } catch (pubErr) {
6785
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${resolvedDocId}:`, pubErr);
6786
- }
6787
- }
6788
- try {
6789
- await recordContentHistoryVersion(strapi, {
6790
- uid,
6791
- documentId: resolvedDocId,
6792
- userId: user?.id,
6793
- statusOverride: shouldPublish ? "published" : isDraftAndPublish ? hadPublishedVersion ? "modified" : "draft" : void 0
6794
- });
6795
- } catch {
6796
- }
6797
- stats.updated++;
6798
- for (const attrKey of Object.keys(payload2)) {
6799
- const oldVal = existing?.[attrKey] ?? null;
6800
- const newVal = payload2[attrKey];
6801
- stats.diffs.push({
6802
- uid,
6803
- collectionName: ct.info?.displayName || uid,
6804
- documentId: resolvedDocId,
6805
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6806
- attribute: attrKey,
6807
- oldValue: oldVal,
6808
- newValue: newVal,
6809
- status: "updated",
6810
- message: `Updated "${attrKey}" via CSV import (row ${rowNumber})`
6811
- });
6812
- }
6813
- continue;
6814
- }
6815
- const valResultNew = await validateEntityQuotas(strapi, uid, payload2);
6816
- if (!valResultNew.isValid) {
6817
- stats.skipped++;
6818
- if (stats.failed !== void 0) stats.failed++;
6819
- stats.errors.push({
6820
- row: rowNumber,
6821
- documentId: docId || "new",
6822
- error: valResultNew.errorMessage
6823
- });
6824
- stats.diffs.push({
6825
- uid,
6826
- collectionName: ct.info?.displayName || uid,
6827
- documentId: docId || "new",
6828
- label: `Row ${rowNumber}`,
6829
- attribute: valResultNew.targetField || "",
6830
- oldValue: null,
6831
- newValue: payload2?.[valResultNew.targetField || ""] ?? null,
6832
- status: "error",
6833
- message: valResultNew.errorMessage
6834
- });
6835
- continue;
6836
- }
6837
- const createArgs = { data: payload2 };
6838
- if (effectiveLocale) createArgs.locale = effectiveLocale;
6839
- const created = await strapi.documents(uid).create(createArgs);
6840
- const newDocId = created?.documentId || docId;
6841
- const shouldPublishNew = !isEditing && isDraftAndPublish && Boolean(publish) && (publishStrategy === "all" || options.unreviewedConsent ? true : false);
6842
- if (shouldPublishNew && newDocId) {
6843
- try {
6844
- const pubArgs = { documentId: newDocId };
6845
- if (effectiveLocale) pubArgs.locale = effectiveLocale;
6846
- await strapi.documents(uid).publish(pubArgs);
6847
- } catch (pubErr) {
6848
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${newDocId}:`, pubErr);
6849
- }
6850
- }
6851
- try {
6852
- await recordContentHistoryVersion(strapi, {
7481
+ await executeUpdateMutation(
7482
+ strapi,
7483
+ ct,
6853
7484
  uid,
6854
- documentId: newDocId,
6855
- userId: user?.id,
6856
- statusOverride: shouldPublishNew ? "published" : isDraftAndPublish ? "draft" : void 0
6857
- });
6858
- } catch {
6859
- }
6860
- stats.created++;
6861
- if (!docId) {
6862
- stats.newWithoutDocId++;
6863
- }
6864
- for (const attrKey of Object.keys(payload2)) {
6865
- stats.diffs.push({
7485
+ existing,
7486
+ row,
7487
+ rowNumber,
7488
+ options,
7489
+ effectiveLocale,
7490
+ isEditing,
7491
+ isDraftAndPublish,
7492
+ publishedCounterparts,
7493
+ stats,
7494
+ "Updated"
7495
+ );
7496
+ } else {
7497
+ await executeCreateMutation(
7498
+ strapi,
7499
+ ct,
6866
7500
  uid,
6867
- collectionName: ct.info?.displayName || uid,
6868
- documentId: newDocId,
6869
- label: created?.title || created?.name || `New Entry #${newDocId}`,
6870
- attribute: attrKey,
6871
- oldValue: null,
6872
- newValue: payload2[attrKey],
6873
- status: "created",
6874
- message: docId ? `Created "${attrKey}" as new entry (documentId "${docId}" not found in database - row ${rowNumber})` : `Created "${attrKey}" as new entry (no documentId provided in CSV - row ${rowNumber})`
6875
- });
7501
+ docId,
7502
+ row,
7503
+ rowNumber,
7504
+ options,
7505
+ effectiveLocale,
7506
+ isEditing,
7507
+ isDraftAndPublish,
7508
+ stats
7509
+ );
6876
7510
  }
6877
7511
  }
6878
7512
  } catch (err) {
7513
+ stats.skipped++;
7514
+ if (stats.failed !== void 0) stats.failed++;
7515
+ const errMsg = extractDetailedErrorMessage(err);
6879
7516
  stats.errors.push({
6880
7517
  row: rowNumber,
6881
7518
  documentId: docId || void 0,
6882
- error: extractDetailedErrorMessage(err)
7519
+ error: errMsg
7520
+ });
7521
+ stats.diffs.push({
7522
+ uid,
7523
+ collectionName: ct.info?.displayName || uid,
7524
+ documentId: docId || `(Row #${rowNumber})`,
7525
+ label: `Row #${rowNumber}`,
7526
+ attribute: "(record)",
7527
+ oldValue: null,
7528
+ newValue: null,
7529
+ status: "error",
7530
+ message: `Failed to process row ${rowNumber}: ${errMsg}`
6883
7531
  });
6884
7532
  }
6885
7533
  }
@@ -6958,63 +7606,79 @@ const csvService = ({ strapi }) => ({
6958
7606
  if (!ct) {
6959
7607
  throw new Error(`Content type ${uid} not found`);
6960
7608
  }
6961
- const attrs = ct.attributes || {};
6962
- const excluded = ["createdAt", "updatedAt", "publishedAt", "createdBy", "updatedBy", "localizations"];
6963
- const headers = ["documentId"];
6964
- const sampleRow = ["(Leave empty to create new, or enter existing docId)"];
6965
- for (const [attrName, attrDef] of Object.entries(attrs)) {
6966
- if (excluded.includes(attrName)) continue;
6967
- if (attrDef.type === "relation") continue;
6968
- if (attrDef.type === "component" || attrDef.type === "dynamiczone") continue;
6969
- headers.push(attrName);
6970
- let sampleVal = "";
6971
- switch (attrDef.type) {
6972
- case "string":
6973
- case "text":
6974
- case "richtext":
6975
- sampleVal = `Sample ${attrName}`;
6976
- break;
6977
- case "integer":
6978
- case "biginteger":
6979
- case "float":
6980
- case "decimal":
6981
- sampleVal = "10";
6982
- break;
6983
- case "boolean":
6984
- sampleVal = "true";
6985
- break;
6986
- case "email":
6987
- sampleVal = "sample@example.com";
6988
- break;
6989
- case "enumeration":
6990
- sampleVal = attrDef.enum?.[0] || "option1";
6991
- break;
6992
- case "customField":
6993
- sampleVal = "value";
6994
- break;
6995
- default:
7609
+ const schema = discoverSchema(strapi, uid);
7610
+ const headers = [METADATA_COLUMN_KEY, ...schema.allExportKeys];
7611
+ const sampleRow = [
7612
+ JSON.stringify({
7613
+ schemaVersion: CURRENT_SCHEMA_VERSION,
7614
+ contentType: uid,
7615
+ documentId: "",
7616
+ locale: schema.isLocalized ? "en" : void 0,
7617
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString()
7618
+ })
7619
+ ];
7620
+ for (const key of schema.allExportKeys) {
7621
+ if (key === "documentId") {
7622
+ sampleRow.push("(Leave empty to create new, or enter existing docId)");
7623
+ } else if (key === "locale") {
7624
+ sampleRow.push("en");
7625
+ } else {
7626
+ const field = schema.fields[key];
7627
+ let sampleVal = "";
7628
+ if (field) {
7629
+ switch (field.category) {
7630
+ case "scalar":
7631
+ sampleVal = field.rawType === "boolean" ? "true" : field.rawType === "integer" ? "10" : `Sample ${key}`;
7632
+ break;
7633
+ case "blocks":
7634
+ sampleVal = JSON.stringify([{ type: "paragraph", children: [{ type: "text", text: `Sample ${key}` }] }]);
7635
+ break;
7636
+ case "component_single":
7637
+ sampleVal = JSON.stringify({ sampleField: "Sample value" });
7638
+ break;
7639
+ case "component_repeatable":
7640
+ sampleVal = JSON.stringify([{ label: "Sample item", url: "/" }]);
7641
+ break;
7642
+ case "dynamiczone":
7643
+ sampleVal = JSON.stringify(
7644
+ field.dzComponents && field.dzComponents.length > 0 ? [{ __component: field.dzComponents[0], title: "Sample" }] : []
7645
+ );
7646
+ break;
7647
+ case "relation_to_one":
7648
+ sampleVal = JSON.stringify({ documentId: "target-doc-id" });
7649
+ break;
7650
+ case "relation_to_many":
7651
+ sampleVal = JSON.stringify([{ documentId: "target-doc-id-1" }]);
7652
+ break;
7653
+ case "media_single":
7654
+ sampleVal = JSON.stringify({ id: 1, url: "/uploads/sample.png" });
7655
+ break;
7656
+ case "media_to_many":
7657
+ sampleVal = JSON.stringify([{ id: 1, url: "/uploads/sample.png" }]);
7658
+ break;
7659
+ default:
7660
+ sampleVal = "sample";
7661
+ }
7662
+ } else {
6996
7663
  sampleVal = "sample";
7664
+ }
7665
+ sampleRow.push(sampleVal);
6997
7666
  }
6998
- sampleRow.push(sampleVal);
6999
7667
  }
7000
- const csvContent = "\uFEFF" + headers.map(escapeCsvValue).join(",") + "\r\n" + sampleRow.map(escapeCsvValue).join(",") + "\r\n";
7668
+ const csvContent = "\uFEFF" + headers.map(escapeCsvCell).join(",") + "\r\n" + sampleRow.map(escapeCsvCell).join(",") + "\r\n";
7001
7669
  return {
7002
7670
  filename: `${ct.info?.singularName || "template"}_template.csv`,
7003
7671
  csvContent,
7004
7672
  headers
7005
7673
  };
7006
7674
  },
7007
- /**
7008
- * Exports entries of a collection to CSV with deep nested component support,
7009
- * RFC-4180 CRLF line endings, and UTF-8 BOM for 100% Microsoft Excel compatibility.
7010
- */
7011
7675
  async exportCollectionCsv(uid, options = {}) {
7012
7676
  const ct = strapi.contentTypes[uid];
7013
7677
  if (!ct) {
7014
7678
  throw new Error(`Content type ${uid} not found`);
7015
7679
  }
7016
- const allComponents = strapi.components || {};
7017
- const fields = discoverExportFields(ct, allComponents);
7680
+ const schema = discoverSchema(strapi, uid);
7681
+ const deepPopulate = buildLosslessPopulate(strapi, uid);
7018
7682
  const filters = {};
7019
7683
  const { attribute, filterOperator, filterQuery, search, documentIds } = options;
7020
7684
  if (documentIds && Array.isArray(documentIds) && documentIds.length > 0) {
@@ -7071,12 +7735,13 @@ const csvService = ({ strapi }) => ({
7071
7735
  }
7072
7736
  }
7073
7737
  }
7074
- const deepPopulate = buildDeepPopulate(ct.attributes || {}, allComponents);
7738
+ const headers = [METADATA_COLUMN_KEY, ...schema.allExportKeys];
7075
7739
  const lines = [];
7076
- lines.push(fields.map((f) => escapeCsvValue(f.key)).join(","));
7740
+ lines.push(headers.map(escapeCsvCell).join(","));
7077
7741
  let totalExported = 0;
7078
7742
  const maxLimit = options.limit && options.limit > 0 ? options.limit : Infinity;
7079
7743
  const BATCH_SIZE = 200;
7744
+ const exportedAt = (/* @__PURE__ */ new Date()).toISOString();
7080
7745
  if (ct.kind === "singleType") {
7081
7746
  const findFirstArgs = {};
7082
7747
  if (deepPopulate) {
@@ -7084,7 +7749,26 @@ const csvService = ({ strapi }) => ({
7084
7749
  }
7085
7750
  const doc = await strapi.documents(uid).findFirst(findFirstArgs);
7086
7751
  if (doc) {
7087
- const rowValues = fields.map((f) => escapeCsvValue(getNestedExportValue(doc, f.key)));
7752
+ const rowValues = [];
7753
+ const metadata = {
7754
+ schemaVersion: CURRENT_SCHEMA_VERSION,
7755
+ contentType: uid,
7756
+ documentId: String(doc.documentId || doc.id || ""),
7757
+ locale: doc.locale || void 0,
7758
+ exportedAt
7759
+ };
7760
+ rowValues.push(escapeCsvCell(metadata));
7761
+ for (const key of schema.allExportKeys) {
7762
+ if (key === "documentId") {
7763
+ rowValues.push(escapeCsvCell(doc.documentId || doc.id || ""));
7764
+ } else if (key === "locale") {
7765
+ rowValues.push(escapeCsvCell(doc.locale || ""));
7766
+ } else {
7767
+ const field = schema.fields[key];
7768
+ const rawVal = doc[key];
7769
+ rowValues.push(escapeCsvCell(field ? serializeFieldValue(rawVal, field) : rawVal));
7770
+ }
7771
+ }
7088
7772
  lines.push(rowValues.join(","));
7089
7773
  totalExported = 1;
7090
7774
  }
@@ -7112,7 +7796,26 @@ const csvService = ({ strapi }) => ({
7112
7796
  break;
7113
7797
  }
7114
7798
  for (const entry of chunkEntries) {
7115
- const rowValues = fields.map((f) => escapeCsvValue(getNestedExportValue(entry, f.key)));
7799
+ const rowValues = [];
7800
+ const metadata = {
7801
+ schemaVersion: CURRENT_SCHEMA_VERSION,
7802
+ contentType: uid,
7803
+ documentId: String(entry.documentId || entry.id || ""),
7804
+ locale: entry.locale || void 0,
7805
+ exportedAt
7806
+ };
7807
+ rowValues.push(escapeCsvCell(metadata));
7808
+ for (const key of schema.allExportKeys) {
7809
+ if (key === "documentId") {
7810
+ rowValues.push(escapeCsvCell(entry.documentId || entry.id || ""));
7811
+ } else if (key === "locale") {
7812
+ rowValues.push(escapeCsvCell(entry.locale || ""));
7813
+ } else {
7814
+ const field = schema.fields[key];
7815
+ const rawVal = entry[key];
7816
+ rowValues.push(escapeCsvCell(field ? serializeFieldValue(rawVal, field) : rawVal));
7817
+ }
7818
+ }
7116
7819
  lines.push(rowValues.join(","));
7117
7820
  totalExported++;
7118
7821
  if (totalExported >= maxLimit) {
@@ -7134,12 +7837,9 @@ const csvService = ({ strapi }) => ({
7134
7837
  filename,
7135
7838
  csvContent,
7136
7839
  count: totalExported,
7137
- fields: fields.map((f) => f.key)
7840
+ fields: headers
7138
7841
  };
7139
7842
  },
7140
- /**
7141
- * Exports violations of a specific rule directly into a CSV
7142
- */
7143
7843
  async exportViolationsCsv(ruleId) {
7144
7844
  const validationRulesService2 = strapi.plugin("bulk-updater").service("validationRules");
7145
7845
  const scanReport = await validationRulesService2.scanViolations(ruleId);
@@ -7615,7 +8315,18 @@ const csvService = ({ strapi }) => ({
7615
8315
  }
7616
8316
  }
7617
8317
  if (activeRules.length > 0) {
7618
- const proposedEntity = existing ? deepMergeEntities(existing, payload) : payload;
8318
+ let proposedPayload = {};
8319
+ try {
8320
+ proposedPayload = await buildDocumentUpdatePayload(
8321
+ strapi,
8322
+ uid,
8323
+ existing,
8324
+ row,
8325
+ { isPartialUpdate: mode === "update" }
8326
+ );
8327
+ } catch {
8328
+ }
8329
+ const proposedEntity = existing ? deepMergeEntities(existing, proposedPayload) : proposedPayload;
7619
8330
  const valResult = await validateEntityQuotas(strapi, uid, proposedEntity, activeRules);
7620
8331
  if (!valResult.isValid) {
7621
8332
  errors2.push({
@@ -7701,12 +8412,18 @@ const csvService = ({ strapi }) => ({
7701
8412
  });
7702
8413
  continue;
7703
8414
  }
7704
- const payload2 = parseRowToPayload(strapi, attrs, row);
8415
+ const payload = await buildDocumentUpdatePayload(
8416
+ strapi,
8417
+ uid,
8418
+ existing,
8419
+ row,
8420
+ {}
8421
+ );
7705
8422
  if (existing) {
7706
8423
  const resolvedDocId = existing.documentId || docId;
7707
8424
  const entryLabel = existing.title || existing.name || existing.slug || `Entry #${resolvedDocId}`;
7708
8425
  let rowHasChanges = false;
7709
- const payloadKeys = Object.keys(payload2);
8426
+ const payloadKeys = Object.keys(payload);
7710
8427
  if (payloadKeys.length === 0) {
7711
8428
  unchangedCount++;
7712
8429
  diffs.push({
@@ -7727,7 +8444,7 @@ const csvService = ({ strapi }) => ({
7727
8444
  } else {
7728
8445
  for (const attrKey of payloadKeys) {
7729
8446
  const oldVal = existing?.[attrKey] ?? null;
7730
- let newVal = payload2[attrKey];
8447
+ let newVal = payload[attrKey];
7731
8448
  if (attrs[attrKey]?.type === "component" && typeof newVal === "object" && newVal !== null) {
7732
8449
  newVal = deepMergeComponent(existing[attrKey], newVal);
7733
8450
  }
@@ -7762,8 +8479,8 @@ const csvService = ({ strapi }) => ({
7762
8479
  } else {
7763
8480
  willCreateCount++;
7764
8481
  const resolvedDocId = docId || `(Auto-generated)`;
7765
- const entryLabel = payload2.title || payload2.name || payload2.slug || `New Entry (Row #${rowNumber})`;
7766
- const payloadKeys = Object.keys(payload2);
8482
+ const entryLabel = payload.title || payload.name || payload.slug || `New Entry (Row #${rowNumber})`;
8483
+ const payloadKeys = Object.keys(payload);
7767
8484
  if (payloadKeys.length === 0) {
7768
8485
  diffs.push({
7769
8486
  uid,
@@ -7782,7 +8499,7 @@ const csvService = ({ strapi }) => ({
7782
8499
  });
7783
8500
  } else {
7784
8501
  for (const attrKey of payloadKeys) {
7785
- const newVal = payload2[attrKey];
8502
+ const newVal = payload[attrKey];
7786
8503
  diffs.push({
7787
8504
  uid,
7788
8505
  collectionName: ct.info?.displayName || uid,
@@ -8136,7 +8853,7 @@ const index = {
8136
8853
  if (context.uid && docId) {
8137
8854
  try {
8138
8855
  const ct = strapi.contentTypes[context.uid];
8139
- const populateDef = ct?.attributes ? buildDeepPopulate$1(ct.attributes, strapi.components) : void 0;
8856
+ const populateDef = ct?.attributes ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
8140
8857
  const existing = await strapi.documents(context.uid).findOne({
8141
8858
  documentId: docId,
8142
8859
  ...params?.locale ? { locale: params.locale } : {},
@@ -8280,6 +8997,33 @@ const index = {
8280
8997
  }
8281
8998
  };
8282
8999
  export {
8283
- index as default
9000
+ CURRENT_SCHEMA_VERSION,
9001
+ METADATA_COLUMN_KEY,
9002
+ SYSTEM_ATTRIBUTES,
9003
+ buildDocumentUpdatePayload,
9004
+ buildLosslessPopulate,
9005
+ classifyAttribute,
9006
+ deepMergeEntities,
9007
+ index as default,
9008
+ discoverComponentFields,
9009
+ discoverSchema,
9010
+ escapeCsvCell,
9011
+ extractHeadingsFromRichText,
9012
+ extractMetadataFromRow,
9013
+ isValidDocumentId,
9014
+ parseBoolean,
9015
+ parseCsvToMatrix,
9016
+ parseCsvToRecords,
9017
+ parseNumeric,
9018
+ resolveComponentPayload,
9019
+ resolveDynamicZonePayload,
9020
+ resolveMediaIds,
9021
+ resolveRelationPayload,
9022
+ serializeDocumentsToCsv,
9023
+ serializeFieldValue,
9024
+ sortAuditRecordsDesc,
9025
+ validateEntityQuotas,
9026
+ verifyDocumentIntegrity,
9027
+ withRollbackLock
8284
9028
  };
8285
9029
  //# sourceMappingURL=index.mjs.map