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