strapi-plugin-bulk-updater 1.6.1 → 1.6.2

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.
@@ -657,8 +657,8 @@ const csvController = ({ strapi }) => ({
657
657
  async exportCollection(ctx) {
658
658
  try {
659
659
  const { uid } = ctx.params;
660
- const { search, attribute, searchAttribute, filterOperator, filterQuery, limit, documentIds } = {
661
- ...ctx.query,
660
+ const { search, attribute, searchAttribute, filterOperator, filterQuery, limit, documentIds, exportMode } = {
661
+ ...ctx.query || {},
662
662
  ...ctx.request?.body || {}
663
663
  };
664
664
  const csvService2 = strapi.plugin("bulk-updater").service("csv");
@@ -673,7 +673,8 @@ const csvController = ({ strapi }) => ({
673
673
  filterOperator: filterOperator ? String(filterOperator) : void 0,
674
674
  filterQuery: filterQuery !== void 0 ? String(filterQuery) : void 0,
675
675
  limit: limit ? Number(limit) : void 0,
676
- documentIds: parsedDocIds
676
+ documentIds: parsedDocIds,
677
+ exportMode: exportMode ? String(exportMode) : void 0
677
678
  });
678
679
  ctx.body = {
679
680
  success: true,
@@ -1729,7 +1730,15 @@ function discoverSchema(strapi, uid) {
1729
1730
  };
1730
1731
  }
1731
1732
  const EXPLICIT_CLEAR_TOKENS = /* @__PURE__ */ new Set(["__CLEAR__", "__NULL__"]);
1733
+ const EXPLICIT_EMPTY_STRING_TOKEN = "__EMPTY__";
1734
+ const EXPLICIT_DELETE_KEY_TOKEN = "__DELETE__";
1732
1735
  const FORBIDDEN_OBJECT_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1736
+ function normalizeExportMode(raw) {
1737
+ const val = String(raw || "").trim().toLowerCase();
1738
+ if (val === "metafields") return "metafields";
1739
+ if (val === "topbarconfig") return "topbarconfig";
1740
+ return "all";
1741
+ }
1733
1742
  function isPlainObject(val) {
1734
1743
  if (val === null || typeof val !== "object" || Array.isArray(val)) return false;
1735
1744
  if (val instanceof Date || val instanceof RegExp) return false;
@@ -1756,37 +1765,39 @@ function deepCloneValue(val) {
1756
1765
  }
1757
1766
  return val;
1758
1767
  }
1759
- function isSafePathSegment(segment) {
1760
- return Boolean(segment) && !FORBIDDEN_OBJECT_KEYS.has(segment);
1761
- }
1762
- function getValueAtPath(rootObj, pathSegments) {
1763
- let cursor = rootObj;
1764
- for (let i = 0; i < pathSegments.length; i++) {
1765
- const seg = pathSegments[i];
1766
- if (!isSafePathSegment(seg) || cursor === null || cursor === void 0 || typeof cursor !== "object") {
1767
- return { exists: false, value: void 0 };
1768
+ function deepEqualValues(a, b) {
1769
+ if (a === b) return true;
1770
+ if (a === null || b === null || a === void 0 || b === void 0) return false;
1771
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
1772
+ if (Array.isArray(a) && Array.isArray(b)) {
1773
+ if (a.length !== b.length) return false;
1774
+ for (let i = 0; i < a.length; i++) {
1775
+ if (!deepEqualValues(a[i], b[i])) return false;
1768
1776
  }
1769
- if (Array.isArray(cursor) || !Object.prototype.hasOwnProperty.call(cursor, seg)) {
1770
- return { exists: false, value: void 0 };
1777
+ return true;
1778
+ }
1779
+ if (isPlainObject(a) && isPlainObject(b)) {
1780
+ const keysA = Object.keys(a).filter((k) => !FORBIDDEN_OBJECT_KEYS.has(k));
1781
+ const keysB = Object.keys(b).filter((k) => !FORBIDDEN_OBJECT_KEYS.has(k));
1782
+ if (keysA.length !== keysB.length) return false;
1783
+ for (const k of keysA) {
1784
+ if (!Object.prototype.hasOwnProperty.call(b, k)) return false;
1785
+ if (!deepEqualValues(a[k], b[k])) return false;
1771
1786
  }
1772
- cursor = cursor[seg];
1787
+ return true;
1773
1788
  }
1774
- return { exists: true, value: cursor };
1789
+ return false;
1775
1790
  }
1776
- function setValueAtPath(target, pathSegments, value) {
1777
- if (pathSegments.length === 0) return;
1778
- let cursor = target;
1779
- for (let i = 0; i < pathSegments.length - 1; i++) {
1780
- const seg = pathSegments[i];
1781
- if (!isSafePathSegment(seg)) return;
1782
- if (!isPlainObject(cursor[seg])) {
1783
- cursor[seg] = {};
1784
- }
1785
- cursor = cursor[seg];
1786
- }
1787
- const leafKey = pathSegments[pathSegments.length - 1];
1788
- if (!isSafePathSegment(leafKey)) return;
1789
- cursor[leafKey] = value;
1791
+ function isSafePropKey(segment) {
1792
+ return Boolean(segment) && !FORBIDDEN_OBJECT_KEYS.has(segment) && !segment.includes(".");
1793
+ }
1794
+ function resolveTargetObjectField(schema, exportMode) {
1795
+ if (exportMode === "all") return void 0;
1796
+ const keys = Object.keys(schema.fields || {});
1797
+ const exactMatch = keys.find((k) => k === exportMode);
1798
+ if (exactMatch) return exactMatch;
1799
+ const normalizedTarget = exportMode.toLowerCase().replace(/[_-]/g, "");
1800
+ return keys.find((k) => k.toLowerCase().replace(/[_-]/g, "") === normalizedTarget);
1790
1801
  }
1791
1802
  function classifyLeafType(val) {
1792
1803
  if (val === null) return "null";
@@ -1808,146 +1819,67 @@ function needsTypeAnnotation(val) {
1808
1819
  }
1809
1820
  return false;
1810
1821
  }
1811
- function collectDynamicPlainObjectPaths(values, baseSegments, blockedRootNames) {
1812
- const leafPaths = [];
1813
- const seenJoined = /* @__PURE__ */ new Set();
1814
- let hasAnyNonNullValue = false;
1815
- for (const val of values) {
1816
- if (val === null || val === void 0) continue;
1817
- hasAnyNonNullValue = true;
1818
- if (!isPlainObject(val)) {
1819
- return { canFlatten: false, paths: [] };
1820
- }
1821
- }
1822
- if (!hasAnyNonNullValue) {
1823
- return { canFlatten: false, paths: [] };
1824
- }
1825
- const walk = (node, relSegments, seenObjects) => {
1826
- if (relSegments.length > 25 || seenObjects.has(node)) return;
1827
- seenObjects.add(node);
1828
- for (const [key, child] of Object.entries(node)) {
1829
- if (!isSafePathSegment(key) || key.includes(".")) {
1830
- continue;
1831
- }
1832
- const nextRel = [...relSegments, key];
1833
- const fullPath = [...baseSegments, ...nextRel].join(".");
1834
- if (blockedRootNames.has(fullPath)) continue;
1835
- if (isPlainObject(child)) {
1836
- const childKeys = Object.keys(child).filter((ck) => isSafePathSegment(ck) && !ck.includes("."));
1837
- if (childKeys.length === 0) {
1838
- if (!seenJoined.has(fullPath)) {
1839
- seenJoined.add(fullPath);
1840
- leafPaths.push(nextRel);
1841
- }
1842
- } else {
1843
- if (seenJoined.has(fullPath)) {
1844
- seenJoined.delete(fullPath);
1845
- const idx = leafPaths.findIndex((p) => [...baseSegments, ...p].join(".") === fullPath);
1846
- if (idx >= 0) leafPaths.splice(idx, 1);
1847
- }
1848
- walk(child, nextRel, seenObjects);
1849
- }
1850
- } else {
1851
- if (!seenJoined.has(fullPath)) {
1852
- seenJoined.add(fullPath);
1853
- leafPaths.push(nextRel);
1854
- }
1855
- }
1856
- }
1857
- seenObjects.delete(node);
1858
- };
1859
- for (const val of values) {
1860
- if (isPlainObject(val)) {
1861
- walk(val, [], /* @__PURE__ */ new WeakSet());
1862
- }
1863
- }
1864
- return { canFlatten: leafPaths.length > 0, paths: leafPaths };
1865
- }
1866
- function collectComponentExportColumns(strapi, compUid, baseSegments, documents, blockedRootNames, visitedComps) {
1867
- const comp = strapi.components?.[compUid];
1868
- if (!comp?.attributes || visitedComps.has(compUid)) {
1869
- return [];
1870
- }
1871
- const nextVisited = new Set(visitedComps);
1872
- nextVisited.add(compUid);
1873
- const rootKey = baseSegments[0];
1822
+ function collectFirstLevelObjectColumns(strapi, rootKey, field, documents, blockedNames) {
1874
1823
  const result = [];
1875
- for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
1876
- if (!isSafePathSegment(attrName)) continue;
1877
- const norm = attrName.toLowerCase().replace(/[\s_-]/g, "");
1878
- if (SYSTEM_ATTRIBUTES.has(norm) || attrName === "id" || attrName === "__component") continue;
1879
- const attrType = String(attrDef?.type || "").toLowerCase();
1880
- const nextSegments = [...baseSegments, attrName];
1881
- const header = nextSegments.join(".");
1882
- if (blockedRootNames.has(header)) continue;
1883
- if (attrType === "component" && !attrDef.repeatable && attrDef.component) {
1884
- const nested = collectComponentExportColumns(
1885
- strapi,
1886
- attrDef.component,
1887
- nextSegments,
1888
- documents,
1889
- blockedRootNames,
1890
- nextVisited
1891
- );
1892
- if (nested.length > 0) {
1893
- result.push(...nested);
1894
- } else {
1824
+ const seenProps = /* @__PURE__ */ new Set();
1825
+ if (field.category === "component_single" && field.componentUid) {
1826
+ const comp = strapi.components?.[field.componentUid];
1827
+ if (comp?.attributes) {
1828
+ for (const [subKey, subDef] of Object.entries(comp.attributes)) {
1829
+ if (!isSafePropKey(subKey)) continue;
1830
+ const norm = subKey.toLowerCase().replace(/[\s_-]/g, "");
1831
+ if (SYSTEM_ATTRIBUTES.has(norm) || subKey === "id" || subKey === "__component") continue;
1832
+ const header = `${rootKey}.${subKey}`;
1833
+ if (blockedNames.has(header) || seenProps.has(subKey)) continue;
1834
+ seenProps.add(subKey);
1895
1835
  result.push({
1896
1836
  header,
1897
- kind: "flattened_component_leaf",
1837
+ kind: "flattened_first_level",
1898
1838
  rootKey,
1899
- pathSegments: nextSegments,
1900
- componentSubDef: attrDef
1839
+ propKey: subKey,
1840
+ field,
1841
+ componentSubDef: subDef
1901
1842
  });
1902
1843
  }
1903
- } else if (attrType === "json") {
1904
- const vals = documents.map((d) => getValueAtPath(d, nextSegments).value);
1905
- const { canFlatten, paths } = collectDynamicPlainObjectPaths(vals, nextSegments, blockedRootNames);
1906
- if (canFlatten) {
1907
- for (const relPath of paths) {
1908
- const fullSegments = [...nextSegments, ...relPath];
1909
- result.push({
1910
- header: fullSegments.join("."),
1911
- kind: "flattened_component_leaf",
1912
- rootKey,
1913
- pathSegments: fullSegments,
1914
- componentSubDef: { type: "json_leaf" }
1915
- });
1916
- }
1917
- } else {
1918
- result.push({
1919
- header,
1920
- kind: "flattened_component_leaf",
1921
- rootKey,
1922
- pathSegments: nextSegments,
1923
- componentSubDef: attrDef
1924
- });
1844
+ }
1845
+ }
1846
+ for (const doc of documents) {
1847
+ const obj = doc?.[rootKey];
1848
+ if (obj === null || obj === void 0) continue;
1849
+ if (!isPlainObject(obj)) {
1850
+ if (field.category === "json") {
1851
+ return [];
1925
1852
  }
1926
- } else {
1853
+ continue;
1854
+ }
1855
+ for (const propKey of Object.keys(obj)) {
1856
+ if (!isSafePropKey(propKey)) continue;
1857
+ const header = `${rootKey}.${propKey}`;
1858
+ if (blockedNames.has(header) || seenProps.has(propKey)) continue;
1859
+ seenProps.add(propKey);
1927
1860
  result.push({
1928
1861
  header,
1929
- kind: "flattened_component_leaf",
1862
+ kind: "flattened_first_level",
1930
1863
  rootKey,
1931
- pathSegments: nextSegments,
1932
- componentSubDef: attrDef
1864
+ propKey,
1865
+ field
1933
1866
  });
1934
1867
  }
1935
1868
  }
1936
1869
  return result;
1937
1870
  }
1938
- function buildExportColumnPlan(strapi, uid, documents, schemaOverride) {
1939
- const schema = schemaOverride || discoverSchema(strapi, uid);
1871
+ function buildExportColumnPlan(strapi, uid, documents, options = {}) {
1872
+ const schema = options.schema || discoverSchema(strapi, uid);
1873
+ const exportMode = normalizeExportMode(options.exportMode);
1874
+ const targetObjectField = resolveTargetObjectField(schema, exportMode);
1940
1875
  const topLevelNames = new Set(schema.allExportKeys);
1941
1876
  const columns = [];
1942
- const flattenedJsonRoots = /* @__PURE__ */ new Set();
1943
- const flattenedComponentRoots = /* @__PURE__ */ new Set();
1944
1877
  for (const key of schema.allExportKeys) {
1945
1878
  if (key === "documentId" || key === "locale") {
1946
1879
  columns.push({
1947
1880
  header: key,
1948
1881
  kind: "system",
1949
- rootKey: key,
1950
- pathSegments: [key]
1882
+ rootKey: key
1951
1883
  });
1952
1884
  continue;
1953
1885
  }
@@ -1956,121 +1888,99 @@ function buildExportColumnPlan(strapi, uid, documents, schemaOverride) {
1956
1888
  columns.push({
1957
1889
  header: key,
1958
1890
  kind: "field",
1959
- rootKey: key,
1960
- pathSegments: [key]
1891
+ rootKey: key
1961
1892
  });
1962
1893
  continue;
1963
1894
  }
1964
- if (field.category === "json") {
1965
- const values = documents.map((d) => d?.[key]);
1966
- const { canFlatten, paths } = collectDynamicPlainObjectPaths(values, [key], topLevelNames);
1967
- if (canFlatten) {
1968
- flattenedJsonRoots.add(key);
1969
- for (const relPath of paths) {
1970
- const fullSegments = [key, ...relPath];
1971
- columns.push({
1972
- header: fullSegments.join("."),
1973
- kind: "flattened_json_leaf",
1974
- rootKey: key,
1975
- pathSegments: fullSegments,
1976
- field
1977
- });
1895
+ if (exportMode !== "all" && targetObjectField && key === targetObjectField) {
1896
+ if (field.category === "json" || field.category === "component_single") {
1897
+ const firstLevelCols = collectFirstLevelObjectColumns(
1898
+ strapi,
1899
+ key,
1900
+ field,
1901
+ documents,
1902
+ topLevelNames
1903
+ );
1904
+ if (firstLevelCols.length > 0) {
1905
+ columns.push(...firstLevelCols);
1906
+ continue;
1978
1907
  }
1979
- continue;
1980
- }
1981
- }
1982
- if (field.category === "component_single" && field.componentUid) {
1983
- const compColumns = collectComponentExportColumns(
1984
- strapi,
1985
- field.componentUid,
1986
- [key],
1987
- documents,
1988
- topLevelNames,
1989
- /* @__PURE__ */ new Set()
1990
- );
1991
- if (compColumns.length > 0) {
1992
- flattenedComponentRoots.add(key);
1993
- columns.push(...compColumns);
1994
- continue;
1995
1908
  }
1996
1909
  }
1997
1910
  columns.push({
1998
1911
  header: key,
1999
1912
  kind: "field",
2000
1913
  rootKey: key,
2001
- pathSegments: [key],
2002
1914
  field
2003
1915
  });
2004
1916
  }
2005
1917
  return {
1918
+ exportMode,
1919
+ targetObjectField,
2006
1920
  columns,
2007
- headers: columns.map((c) => c.header),
2008
- flattenedJsonRoots,
2009
- flattenedComponentRoots
1921
+ headers: columns.map((c) => c.header)
2010
1922
  };
2011
1923
  }
2012
1924
  function extractRowFlattenedMetadata(plan, doc) {
2013
- const applicableFields = [];
2014
- const flatTypes = {};
2015
- const flattenedRoots = /* @__PURE__ */ new Set([
2016
- ...plan.flattenedJsonRoots,
2017
- ...plan.flattenedComponentRoots
2018
- ]);
2019
- for (const rootKey of flattenedRoots) {
2020
- const val = doc?.[rootKey];
2021
- if (val !== null && val !== void 0) {
2022
- applicableFields.push(rootKey);
2023
- if (plan.flattenedJsonRoots.has(rootKey) && isPlainObject(val) && Object.keys(val).length === 0) {
2024
- flatTypes[rootKey] = "object";
2025
- }
2026
- }
1925
+ const out = {
1926
+ exportMode: plan.exportMode
1927
+ };
1928
+ if (plan.exportMode === "all" || !plan.targetObjectField) {
1929
+ return out;
2027
1930
  }
2028
- for (const col of plan.columns) {
2029
- if (col.kind !== "flattened_json_leaf") continue;
2030
- const { exists, value } = getValueAtPath(doc, col.pathSegments);
2031
- if (!exists || value === void 0) continue;
2032
- if (needsTypeAnnotation(value)) {
2033
- flatTypes[col.header] = classifyLeafType(value);
2034
- }
1931
+ const rootKey = plan.targetObjectField;
1932
+ out.targetObjectField = rootKey;
1933
+ const hasOwn = doc && typeof doc === "object" && Object.prototype.hasOwnProperty.call(doc, rootKey);
1934
+ const rawVal = hasOwn ? doc[rootKey] : void 0;
1935
+ if (!hasOwn || rawVal === void 0) {
1936
+ out.targetObjectState = "absent";
1937
+ out.applicableFields = [];
1938
+ return out;
2035
1939
  }
2036
- const out = {};
2037
- if (flattenedRoots.size > 0) {
2038
- out.applicableFields = applicableFields;
1940
+ if (rawVal === null) {
1941
+ out.targetObjectState = "null";
1942
+ out.applicableFields = [];
1943
+ return out;
2039
1944
  }
2040
- if (Object.keys(flatTypes).length > 0) {
2041
- out.flatTypes = flatTypes;
1945
+ if (isPlainObject(rawVal)) {
1946
+ const keys = Object.keys(rawVal);
1947
+ out.targetObjectState = keys.length === 0 ? "empty_object" : "present";
1948
+ out.applicableFields = [rootKey];
1949
+ const flatTypes = {};
1950
+ for (const col of plan.columns) {
1951
+ if (col.kind !== "flattened_first_level" || !col.propKey) continue;
1952
+ if (!Object.prototype.hasOwnProperty.call(rawVal, col.propKey)) continue;
1953
+ const leafVal = rawVal[col.propKey];
1954
+ if (leafVal !== void 0 && needsTypeAnnotation(leafVal)) {
1955
+ flatTypes[col.header] = classifyLeafType(leafVal);
1956
+ }
1957
+ }
1958
+ if (Object.keys(flatTypes).length > 0) {
1959
+ out.flatTypes = flatTypes;
1960
+ }
1961
+ return out;
2042
1962
  }
1963
+ out.targetObjectState = "present";
1964
+ out.applicableFields = [rootKey];
2043
1965
  return out;
2044
1966
  }
2045
- function serializeFlattenedLeafValue(val) {
2046
- if (val === void 0 || val === null) return "";
2047
- if (val instanceof Date) return val.toISOString();
2048
- if (Array.isArray(val) || isPlainObject(val)) {
2049
- return JSON.stringify(val);
2050
- }
2051
- if (typeof val === "boolean") return val ? "true" : "false";
2052
- if (typeof val === "number") return Number.isFinite(val) ? String(val) : "";
2053
- return String(val);
2054
- }
2055
1967
  function serializePlannedCell(col, doc, serializeFieldFallback) {
2056
1968
  if (col.kind === "system") {
2057
1969
  if (col.header === "documentId") return doc?.documentId || doc?.id || "";
2058
1970
  if (col.header === "locale") return doc?.locale || "";
2059
1971
  return doc?.[col.header] ?? "";
2060
1972
  }
2061
- if (col.kind === "flattened_json_leaf") {
2062
- const { exists, value } = getValueAtPath(doc, col.pathSegments);
2063
- if (!exists) return "";
2064
- if (isPlainObject(value) && Object.keys(value).length === 0) return "";
2065
- return serializeFlattenedLeafValue(value);
2066
- }
2067
- if (col.kind === "flattened_component_leaf") {
2068
- const { exists, value } = getValueAtPath(doc, col.pathSegments);
2069
- if (!exists || value === void 0 || value === null) return "";
1973
+ if (col.kind === "flattened_first_level" && col.propKey) {
1974
+ const rootObj = doc?.[col.rootKey];
1975
+ if (!isPlainObject(rootObj) || !Object.prototype.hasOwnProperty.call(rootObj, col.propKey)) {
1976
+ return "";
1977
+ }
1978
+ const val = rootObj[col.propKey];
1979
+ if (val === void 0 || val === null) return "";
2070
1980
  const subDef = col.componentSubDef || {};
2071
1981
  const subType = String(subDef.type || "").toLowerCase();
2072
1982
  if (subType === "media") {
2073
- return serializeFieldFallback(value, {
1983
+ return serializeFieldFallback(val, {
2074
1984
  key: col.header,
2075
1985
  label: col.header,
2076
1986
  category: subDef.multiple ? "media_to_many" : "media_single",
@@ -2080,7 +1990,7 @@ function serializePlannedCell(col, doc, serializeFieldFallback) {
2080
1990
  }
2081
1991
  if (subType === "relation") {
2082
1992
  const isToMany = String(subDef.relation || "").toLowerCase().endsWith("many");
2083
- return serializeFieldFallback(value, {
1993
+ return serializeFieldFallback(val, {
2084
1994
  key: col.header,
2085
1995
  label: col.header,
2086
1996
  category: isToMany ? "relation_to_many" : "relation_to_one",
@@ -2088,13 +1998,13 @@ function serializePlannedCell(col, doc, serializeFieldFallback) {
2088
1998
  relationType: subDef.relation
2089
1999
  });
2090
2000
  }
2091
- if (subType === "component" && subDef.repeatable) {
2092
- return Array.isArray(value) ? JSON.stringify(value) : "";
2093
- }
2094
- if (subType === "blocks" || subType === "json") {
2095
- return typeof value === "object" ? JSON.stringify(value) : String(value);
2001
+ if (val instanceof Date) return val.toISOString();
2002
+ if (Array.isArray(val) || isPlainObject(val)) {
2003
+ return JSON.stringify(val);
2096
2004
  }
2097
- return serializeFlattenedLeafValue(value);
2005
+ if (typeof val === "boolean") return val ? "true" : "false";
2006
+ if (typeof val === "number") return Number.isFinite(val) ? String(val) : "";
2007
+ return String(val);
2098
2008
  }
2099
2009
  const rawValue = doc?.[col.rootKey];
2100
2010
  if (col.field) {
@@ -2102,197 +2012,272 @@ function serializePlannedCell(col, doc, serializeFieldFallback) {
2102
2012
  }
2103
2013
  return rawValue;
2104
2014
  }
2105
- function parseFlattenedLeafValue(rawCell, annotatedType, existingLeafValue) {
2106
- if (rawCell === null || rawCell === void 0) return null;
2107
- if (typeof rawCell !== "string") return rawCell;
2108
- const trimmed = rawCell.trim();
2109
- if (EXPLICIT_CLEAR_TOKENS.has(trimmed)) {
2110
- return null;
2015
+ function inspectRowMetadataMode(rawRow) {
2016
+ if (!rawRow || typeof rawRow !== "object") {
2017
+ return { mode: "legacy" };
2111
2018
  }
2112
- if (annotatedType === "string") {
2113
- return rawCell;
2019
+ const rawMetaCell = rawRow["__bulk_updater_metadata"] !== void 0 ? rawRow["__bulk_updater_metadata"] : rawRow["_bulk_updater_metadata"];
2020
+ if (rawMetaCell === void 0 || rawMetaCell === null || String(rawMetaCell).trim() === "") {
2021
+ return { mode: "legacy" };
2114
2022
  }
2115
- if (annotatedType === "number" || typeof existingLeafValue === "number") {
2116
- if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
2117
- const num = Number(trimmed);
2118
- if (Number.isFinite(num)) return num;
2023
+ let parsed = rawMetaCell;
2024
+ if (typeof rawMetaCell === "string") {
2025
+ try {
2026
+ parsed = JSON.parse(rawMetaCell);
2027
+ } catch {
2028
+ return {
2029
+ mode: "legacy",
2030
+ error: "Corrupted __bulk_updater_metadata cell: invalid JSON."
2031
+ };
2119
2032
  }
2120
2033
  }
2121
- if (annotatedType === "boolean" || typeof existingLeafValue === "boolean") {
2122
- const low = trimmed.toLowerCase();
2123
- if (low === "true") return true;
2124
- if (low === "false") return false;
2034
+ if (!isPlainObject(parsed)) {
2035
+ return {
2036
+ mode: "legacy",
2037
+ error: "Corrupted __bulk_updater_metadata cell: expected JSON object."
2038
+ };
2125
2039
  }
2126
- if (annotatedType === "array" || Array.isArray(existingLeafValue)) {
2127
- if (trimmed.startsWith("[")) {
2040
+ if (parsed.exportMode === void 0) {
2041
+ return {
2042
+ mode: "legacy",
2043
+ applicableFields: Array.isArray(parsed.applicableFields) ? parsed.applicableFields : void 0,
2044
+ flatTypes: isPlainObject(parsed.flatTypes) ? parsed.flatTypes : void 0
2045
+ };
2046
+ }
2047
+ const rawMode = String(parsed.exportMode).trim().toLowerCase();
2048
+ if (rawMode !== "all" && rawMode !== "metafields" && rawMode !== "topbarconfig") {
2049
+ return {
2050
+ mode: "legacy",
2051
+ error: `Unsupported CSV exportMode "${parsed.exportMode}" in metadata.`
2052
+ };
2053
+ }
2054
+ return {
2055
+ mode: rawMode,
2056
+ targetObjectField: typeof parsed.targetObjectField === "string" && parsed.targetObjectField.trim() ? parsed.targetObjectField.trim() : void 0,
2057
+ targetObjectState: parsed.targetObjectState,
2058
+ applicableFields: Array.isArray(parsed.applicableFields) ? parsed.applicableFields : void 0,
2059
+ flatTypes: isPlainObject(parsed.flatTypes) ? parsed.flatTypes : void 0
2060
+ };
2061
+ }
2062
+ function detectCsvBatchExportMode(rows) {
2063
+ const seenModes = /* @__PURE__ */ new Set();
2064
+ for (let i = 0; i < rows.length; i++) {
2065
+ const info = inspectRowMetadataMode(rows[i]);
2066
+ if (info.error) {
2067
+ return { mode: "legacy", error: `Row ${i + 2}: ${info.error}` };
2068
+ }
2069
+ seenModes.add(info.mode);
2070
+ }
2071
+ if (seenModes.size > 1) {
2072
+ return {
2073
+ mode: "legacy",
2074
+ error: `Inconsistent CSV export modes detected across rows (${Array.from(seenModes).join(", ")}). Re-export the file cleanly before importing.`
2075
+ };
2076
+ }
2077
+ const first = Array.from(seenModes)[0];
2078
+ return { mode: first || "legacy" };
2079
+ }
2080
+ function parseFirstLevelCellValue(rawCell, annotatedType, existingPropValue) {
2081
+ if (rawCell === null || rawCell === void 0) return { value: null };
2082
+ if (typeof rawCell !== "string") return { value: rawCell };
2083
+ const trimmed = rawCell.trim();
2084
+ if (EXPLICIT_CLEAR_TOKENS.has(trimmed)) {
2085
+ return { value: null };
2086
+ }
2087
+ if (trimmed === EXPLICIT_EMPTY_STRING_TOKEN) {
2088
+ return { value: "" };
2089
+ }
2090
+ if (annotatedType === "string") {
2091
+ return { value: rawCell };
2092
+ }
2093
+ if (annotatedType === "object" || isPlainObject(existingPropValue)) {
2094
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
2128
2095
  try {
2129
- return JSON.parse(trimmed);
2096
+ return { value: JSON.parse(trimmed) };
2130
2097
  } catch {
2098
+ return {
2099
+ value: rawCell,
2100
+ error: `Invalid JSON object value: "${rawCell}"`
2101
+ };
2131
2102
  }
2132
2103
  }
2133
2104
  }
2134
- if (annotatedType === "object" || isPlainObject(existingLeafValue)) {
2135
- if (trimmed.startsWith("{")) {
2105
+ if (annotatedType === "array" || Array.isArray(existingPropValue)) {
2106
+ if (trimmed.startsWith("[")) {
2136
2107
  try {
2137
- return JSON.parse(trimmed);
2108
+ const parsed = JSON.parse(trimmed);
2109
+ return { value: parsed };
2138
2110
  } catch {
2111
+ return {
2112
+ value: rawCell,
2113
+ error: `Invalid JSON array value: "${rawCell}"`
2114
+ };
2139
2115
  }
2140
2116
  }
2141
2117
  }
2142
- if (typeof existingLeafValue === "string") {
2118
+ if (annotatedType === "number" || typeof existingPropValue === "number") {
2119
+ if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
2120
+ const num = Number(trimmed);
2121
+ if (Number.isFinite(num)) return { value: num };
2122
+ }
2123
+ }
2124
+ if (annotatedType === "boolean" || typeof existingPropValue === "boolean") {
2125
+ const low = trimmed.toLowerCase();
2126
+ if (low === "true") return { value: true };
2127
+ if (low === "false") return { value: false };
2128
+ }
2129
+ if (typeof existingPropValue === "string") {
2143
2130
  if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
2144
2131
  try {
2145
- return JSON.parse(trimmed);
2132
+ return { value: JSON.parse(trimmed) };
2146
2133
  } catch {
2147
2134
  }
2148
2135
  }
2149
- return rawCell;
2136
+ return { value: rawCell };
2150
2137
  }
2151
- if (trimmed === "null") return null;
2152
- if (trimmed === "true") return true;
2153
- if (trimmed === "false") return false;
2138
+ if (trimmed === "null") return { value: null };
2139
+ if (trimmed === "true") return { value: true };
2140
+ if (trimmed === "false") return { value: false };
2154
2141
  if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
2155
2142
  const num = Number(trimmed);
2156
- if (Number.isFinite(num)) return num;
2143
+ if (Number.isFinite(num)) return { value: num };
2157
2144
  }
2158
2145
  if (trimmed.startsWith("[") && trimmed.endsWith("]") || trimmed.startsWith("{") && trimmed.endsWith("}")) {
2159
2146
  try {
2160
- return JSON.parse(trimmed);
2147
+ return { value: JSON.parse(trimmed) };
2161
2148
  } catch {
2162
2149
  }
2163
2150
  }
2164
- return rawCell;
2151
+ return { value: rawCell };
2165
2152
  }
2166
- function reconstructFlattenedJsonAttribute(params) {
2153
+ function reconstructTargetedFirstLevelObject(params) {
2167
2154
  const {
2168
- attrName,
2169
- existingVal,
2170
- hasDirectKey,
2171
- directRawVal,
2172
- dotEntries,
2155
+ targetAttr,
2156
+ exportMode,
2157
+ existingDoc,
2158
+ docIdForError,
2159
+ rawRow,
2173
2160
  rowMeta,
2174
- isPartialUpdate
2161
+ isAttrRequired = false
2175
2162
  } = params;
2176
- const hasExistingPlainObj = isPlainObject(existingVal);
2177
- const directTrimmed = typeof directRawVal === "string" ? directRawVal.trim() : "";
2178
- if (dotEntries.length === 0) {
2179
- if (!hasDirectKey) return { shouldSet: false, value: void 0 };
2180
- if (EXPLICIT_CLEAR_TOKENS.has(directTrimmed) || directTrimmed === "null") {
2181
- return { shouldSet: true, value: null };
2182
- }
2183
- if (directRawVal === "" || directRawVal === void 0 || directRawVal === null) {
2184
- return { shouldSet: false, value: void 0 };
2163
+ const prefix = `${targetAttr}.`;
2164
+ const firstLevelEntries = [];
2165
+ const invalidNestedColumns = [];
2166
+ for (const [colKey, val] of Object.entries(rawRow)) {
2167
+ if (!colKey.startsWith(prefix)) continue;
2168
+ const propKey = colKey.slice(prefix.length);
2169
+ if (!propKey) continue;
2170
+ if (propKey.includes(".")) {
2171
+ if (val !== void 0 && val !== null && String(val) !== "") {
2172
+ invalidNestedColumns.push(colKey);
2173
+ }
2174
+ continue;
2185
2175
  }
2186
- if (typeof directRawVal === "string") {
2187
- try {
2188
- return { shouldSet: true, value: JSON.parse(directRawVal) };
2189
- } catch {
2190
- return { shouldSet: true, value: directRawVal };
2176
+ if (!isSafePropKey(propKey)) continue;
2177
+ firstLevelEntries.push([colKey, propKey, val]);
2178
+ }
2179
+ if (invalidNestedColumns.length > 0) {
2180
+ return {
2181
+ shouldSet: false,
2182
+ value: void 0,
2183
+ errors: [
2184
+ `Deeply nested column(s) [${invalidNestedColumns.join(", ")}] are not valid in "${exportMode}" one-level targeted mode.`
2185
+ ]
2186
+ };
2187
+ }
2188
+ const directRawVal = targetAttr in rawRow ? rawRow[targetAttr] : void 0;
2189
+ const directTrimmed = typeof directRawVal === "string" ? directRawVal.trim() : "";
2190
+ const hasNonEmptyFirstLevelEdit = firstLevelEntries.some(
2191
+ ([, , val]) => val !== void 0 && val !== null && String(val) !== ""
2192
+ );
2193
+ if (existingDoc) {
2194
+ const existingObj = existingDoc[targetAttr];
2195
+ const hasObjectOnRecord = isPlainObject(existingObj);
2196
+ if (!hasObjectOnRecord) {
2197
+ const attemptedDirectEdit = directRawVal !== void 0 && directRawVal !== null && directTrimmed !== "";
2198
+ if (!hasNonEmptyFirstLevelEdit && !attemptedDirectEdit) {
2199
+ return { shouldSet: false, value: void 0, errors: [] };
2200
+ }
2201
+ if (!isAttrRequired) {
2202
+ const recordRef = docIdForError || existingDoc.documentId || existingDoc.id || "record";
2203
+ return {
2204
+ shouldSet: false,
2205
+ value: void 0,
2206
+ errors: [
2207
+ `Field "${targetAttr}" is not applicable or absent on document "${recordRef}". Targeted "${exportMode}" import will not create a new "${targetAttr}" object automatically.`
2208
+ ]
2209
+ };
2191
2210
  }
2192
2211
  }
2193
- return { shouldSet: true, value: directRawVal };
2212
+ } else {
2213
+ if (!hasNonEmptyFirstLevelEdit && (!directTrimmed || directTrimmed === "")) {
2214
+ return { shouldSet: false, value: void 0, errors: [] };
2215
+ }
2194
2216
  }
2195
- let baseObj = hasExistingPlainObj ? deepCloneValue(existingVal) : null;
2196
- let hasEffectiveChange = false;
2197
- if (hasDirectKey && directRawVal !== "" && directRawVal !== void 0 && directRawVal !== null) {
2217
+ const base = isPlainObject(existingDoc?.[targetAttr]) ? deepCloneValue(existingDoc[targetAttr]) : {};
2218
+ const errors2 = [];
2219
+ let appliedAnyModification = false;
2220
+ if (firstLevelEntries.length === 0 && directRawVal !== void 0 && directRawVal !== null && directTrimmed !== "") {
2198
2221
  if (EXPLICIT_CLEAR_TOKENS.has(directTrimmed) || directTrimmed === "null") {
2199
- return { shouldSet: true, value: null };
2222
+ return { shouldSet: true, value: null, errors: [] };
2200
2223
  }
2201
2224
  try {
2202
2225
  const parsedDirect = typeof directRawVal === "string" ? JSON.parse(directRawVal) : directRawVal;
2203
2226
  if (isPlainObject(parsedDirect)) {
2204
- baseObj = { ...baseObj || {}, ...deepCloneValue(parsedDirect) };
2205
- hasEffectiveChange = true;
2206
- } else {
2207
- return { shouldSet: true, value: parsedDirect };
2227
+ return {
2228
+ shouldSet: true,
2229
+ value: { ...base, ...deepCloneValue(parsedDirect) },
2230
+ errors: []
2231
+ };
2208
2232
  }
2233
+ return { shouldSet: true, value: parsedDirect, errors: [] };
2209
2234
  } catch {
2210
- return { shouldSet: true, value: directRawVal };
2235
+ return {
2236
+ shouldSet: false,
2237
+ value: void 0,
2238
+ errors: [`Column "${targetAttr}" contains invalid JSON: "${directRawVal}"`]
2239
+ };
2211
2240
  }
2212
2241
  }
2213
- for (const [fullKey, rawCell] of dotEntries) {
2214
- const prefix = `${attrName}.`;
2215
- if (!fullKey.startsWith(prefix)) continue;
2216
- const relPathStr = fullKey.slice(prefix.length);
2217
- const relSegments = relPathStr.split(".").filter(Boolean);
2218
- if (relSegments.length === 0 || relSegments.some((s) => !isSafePathSegment(s))) {
2219
- continue;
2220
- }
2221
- const strCell = rawCell === null || rawCell === void 0 ? "" : String(rawCell);
2242
+ for (const [colKey, propKey, rawCell] of firstLevelEntries) {
2243
+ if (rawCell === void 0 || rawCell === null) continue;
2244
+ const strCell = String(rawCell);
2222
2245
  const trimmed = strCell.trim();
2223
- const annotatedType = rowMeta?.flatTypes?.[fullKey];
2224
- if (EXPLICIT_CLEAR_TOKENS.has(trimmed)) {
2225
- if (!baseObj) baseObj = {};
2226
- setValueAtPath(baseObj, relSegments, null);
2227
- hasEffectiveChange = true;
2228
- continue;
2229
- }
2230
- if (strCell === "") {
2231
- if (hasExistingPlainObj && annotatedType && (annotatedType === "string" || annotatedType === "null" || annotatedType === "object")) {
2232
- const existingAtPath = getValueAtPath(existingVal, relSegments);
2233
- if (existingAtPath.exists) {
2234
- if (annotatedType === "object" && isPlainObject(existingAtPath.value)) {
2235
- if (!isPartialUpdate) hasEffectiveChange = true;
2236
- } else if (annotatedType === "null" && existingAtPath.value === null) {
2237
- if (!isPartialUpdate) hasEffectiveChange = true;
2238
- } else if (annotatedType === "string" && existingAtPath.value === "") {
2239
- if (!isPartialUpdate) hasEffectiveChange = true;
2240
- }
2241
- }
2246
+ if (trimmed === EXPLICIT_DELETE_KEY_TOKEN) {
2247
+ if (Object.prototype.hasOwnProperty.call(base, propKey)) {
2248
+ delete base[propKey];
2249
+ appliedAnyModification = true;
2242
2250
  }
2243
2251
  continue;
2244
2252
  }
2245
- const existingLeaf = hasExistingPlainObj ? getValueAtPath(existingVal, relSegments).value : void 0;
2246
- const parsedVal = parseFlattenedLeafValue(strCell, annotatedType, existingLeaf);
2247
- if (!baseObj) baseObj = {};
2248
- setValueAtPath(baseObj, relSegments, parsedVal);
2249
- hasEffectiveChange = true;
2250
- }
2251
- if (!hasEffectiveChange) {
2252
- if (!isPartialUpdate && hasExistingPlainObj && (rowMeta?.applicableFields?.includes(attrName) || rowMeta?.flatTypes?.[attrName] === "object")) {
2253
- return { shouldSet: true, value: deepCloneValue(existingVal) };
2254
- }
2255
- return { shouldSet: false, value: void 0 };
2256
- }
2257
- return { shouldSet: true, value: baseObj || {} };
2258
- }
2259
- function buildNestedComponentPatchFromDots(attrName, dotEntries) {
2260
- const patch = {};
2261
- let hasEffectiveEdits = false;
2262
- const prefix = `${attrName}.`;
2263
- for (const [fullKey, rawCell] of dotEntries) {
2264
- if (!fullKey.startsWith(prefix)) continue;
2265
- const relPathStr = fullKey.slice(prefix.length);
2266
- const relSegments = relPathStr.split(".").filter(Boolean);
2267
- if (relSegments.length === 0 || relSegments.some((s) => !isSafePathSegment(s))) {
2253
+ if (EXPLICIT_CLEAR_TOKENS.has(trimmed)) {
2254
+ base[propKey] = null;
2255
+ appliedAnyModification = true;
2268
2256
  continue;
2269
2257
  }
2270
- if (rawCell === void 0 || rawCell === null || rawCell === "") {
2258
+ if (strCell === "") {
2271
2259
  continue;
2272
2260
  }
2273
- const strCell = String(rawCell);
2274
- const trimmed = strCell.trim();
2275
- if (EXPLICIT_CLEAR_TOKENS.has(trimmed)) {
2276
- setValueAtPath(patch, relSegments, null);
2277
- hasEffectiveEdits = true;
2261
+ const annotatedType = rowMeta.flatTypes?.[colKey];
2262
+ const existingPropValue = isPlainObject(existingDoc?.[targetAttr]) ? existingDoc[targetAttr][propKey] : void 0;
2263
+ const parsed = parseFirstLevelCellValue(strCell, annotatedType, existingPropValue);
2264
+ if (parsed.error) {
2265
+ errors2.push(`Column "${colKey}": ${parsed.error}`);
2278
2266
  continue;
2279
2267
  }
2280
- setValueAtPath(patch, relSegments, strCell);
2281
- hasEffectiveEdits = true;
2268
+ base[propKey] = parsed.value;
2269
+ appliedAnyModification = true;
2282
2270
  }
2283
- return { hasEffectiveEdits, patch };
2284
- }
2285
- function resolveDottedComponentAttrDef(strapi, rootDef, segments) {
2286
- if (!rootDef || segments.length === 0) return null;
2287
- if (segments.length === 1) return rootDef;
2288
- if (rootDef.type === "component" && !rootDef.repeatable && rootDef.component) {
2289
- const comp = strapi.components?.[rootDef.component];
2290
- if (!comp?.attributes) return null;
2291
- const nextAttr = comp.attributes[segments[1]];
2292
- if (!nextAttr) return null;
2293
- return resolveDottedComponentAttrDef(strapi, nextAttr, segments.slice(1));
2271
+ if (errors2.length > 0) {
2272
+ return { shouldSet: false, value: void 0, errors: errors2 };
2294
2273
  }
2295
- return null;
2274
+ if (!appliedAnyModification) {
2275
+ return { shouldSet: false, value: void 0, errors: [] };
2276
+ }
2277
+ if (existingDoc && isPlainObject(existingDoc[targetAttr]) && deepEqualValues(base, existingDoc[targetAttr])) {
2278
+ return { shouldSet: false, value: void 0, errors: [] };
2279
+ }
2280
+ return { shouldSet: true, value: base, errors: [] };
2296
2281
  }
2297
2282
  function validateRecordSchemaConstraints(strapi, uid, existingDoc, payload, rawRow, options) {
2298
2283
  const ct = strapi.contentTypes?.[uid];
@@ -2300,51 +2285,25 @@ function validateRecordSchemaConstraints(strapi, uid, existingDoc, payload, rawR
2300
2285
  const attrs = ct.attributes || {};
2301
2286
  const errors2 = [];
2302
2287
  const warnings = [];
2303
- const applicableList = Array.isArray(options.rowMeta?.applicableFields) ? new Set(options.rowMeta.applicableFields) : null;
2288
+ const isTargeted = options.detectedMode === "metafields" || options.detectedMode === "topbarconfig";
2304
2289
  const isMissingRequiredValue = (val) => val === void 0 || val === null || typeof val === "string" && val.trim() === "";
2305
- for (const [colKey, rawVal] of Object.entries(rawRow)) {
2306
- if (rawVal === void 0 || rawVal === null) continue;
2307
- const strVal = String(rawVal);
2308
- const trimmed = strVal.trim();
2309
- if (!trimmed || EXPLICIT_CLEAR_TOKENS.has(trimmed)) continue;
2310
- if (colKey.includes(".")) {
2311
- const segments = colKey.split(".").filter(Boolean);
2312
- const rootAttr = attrs[segments[0]];
2313
- if (rootAttr?.type === "component" && !rootAttr.repeatable) {
2314
- const subDef = resolveDottedComponentAttrDef(strapi, rootAttr, segments);
2315
- if (subDef) {
2316
- if (subDef.type === "integer" || subDef.type === "biginteger") {
2317
- if (!/^-?\d+$/.test(trimmed)) {
2318
- errors2.push(`Column "${colKey}" expects an integer, received: "${rawVal}"`);
2319
- }
2320
- } else if (subDef.type === "float" || subDef.type === "decimal") {
2321
- if (isNaN(Number(trimmed))) {
2322
- errors2.push(`Column "${colKey}" expects a numeric float/decimal, received: "${rawVal}"`);
2323
- }
2324
- } else if (subDef.type === "enumeration" && Array.isArray(subDef.enum)) {
2325
- if (!subDef.enum.includes(trimmed)) {
2326
- warnings.push(
2327
- `Column "${colKey}" value "${rawVal}" is not in defined enum options: [${subDef.enum.join(", ")}]`
2328
- );
2329
- }
2330
- }
2290
+ if (!isTargeted || options.isCreate) {
2291
+ for (const [attrName, attrDef] of Object.entries(attrs)) {
2292
+ if (!attrDef?.required) continue;
2293
+ const norm = attrName.toLowerCase().replace(/[\s_-]/g, "");
2294
+ if (SYSTEM_ATTRIBUTES.has(norm)) continue;
2295
+ if (options.isCreate) {
2296
+ if (isMissingRequiredValue(payload[attrName])) {
2297
+ errors2.push(`Missing mandatory field "${attrName}".`);
2331
2298
  }
2299
+ } else if (attrName in payload && isMissingRequiredValue(payload[attrName])) {
2300
+ errors2.push(`Mandatory field "${attrName}" cannot be empty or cleared.`);
2332
2301
  }
2333
2302
  }
2334
- }
2335
- for (const [attrName, attrDef] of Object.entries(attrs)) {
2336
- if (!attrDef?.required) continue;
2337
- const norm = attrName.toLowerCase().replace(/[\s_-]/g, "");
2338
- if (SYSTEM_ATTRIBUTES.has(norm)) continue;
2339
- if (options.isCreate) {
2340
- if (applicableList && !applicableList.has(attrName) && payload[attrName] === void 0) {
2341
- continue;
2342
- }
2343
- if (isMissingRequiredValue(payload[attrName])) {
2344
- errors2.push(`Missing mandatory field "${attrName}".`);
2345
- }
2346
- } else if (attrName in payload && isMissingRequiredValue(payload[attrName])) {
2347
- errors2.push(`Mandatory field "${attrName}" cannot be empty or cleared.`);
2303
+ } else if (options.targetObjectField) {
2304
+ const tDef = attrs[options.targetObjectField];
2305
+ if (tDef?.required && options.targetObjectField in payload && isMissingRequiredValue(payload[options.targetObjectField])) {
2306
+ errors2.push(`Mandatory field "${options.targetObjectField}" cannot be empty or cleared.`);
2348
2307
  }
2349
2308
  }
2350
2309
  const validateComponentRequired = (compUid, valueObj, pathPrefix) => {
@@ -2366,754 +2325,581 @@ function validateRecordSchemaConstraints(strapi, uid, existingDoc, payload, rawR
2366
2325
  const nextCompVal = payload[attrName];
2367
2326
  if (isPlainObject(nextCompVal)) {
2368
2327
  validateComponentRequired(attrDef.component, nextCompVal, attrName);
2369
- } else if (nextCompVal === void 0 && isPlainObject(existingDoc?.[attrName]) && (applicableList === null || applicableList.has(attrName))) ;
2328
+ }
2329
+ }
2330
+ }
2331
+ if (isTargeted && options.targetObjectField) {
2332
+ const tDef = attrs[options.targetObjectField];
2333
+ if (tDef?.type === "component" && !tDef.repeatable && tDef.component && strapi.components?.[tDef.component]) {
2334
+ const compAttrs = strapi.components[tDef.component].attributes || {};
2335
+ const prefix = `${options.targetObjectField}.`;
2336
+ for (const [colKey, rawVal] of Object.entries(rawRow)) {
2337
+ if (!colKey.startsWith(prefix)) continue;
2338
+ const propKey = colKey.slice(prefix.length);
2339
+ const subDef = compAttrs[propKey];
2340
+ const trimmed = rawVal === void 0 || rawVal === null ? "" : String(rawVal).trim();
2341
+ if (!subDef || !trimmed || EXPLICIT_CLEAR_TOKENS.has(trimmed) || trimmed === EXPLICIT_DELETE_KEY_TOKEN || trimmed === EXPLICIT_EMPTY_STRING_TOKEN) {
2342
+ continue;
2343
+ }
2344
+ if (subDef.type === "integer" || subDef.type === "biginteger") {
2345
+ if (!/^-?\d+$/.test(trimmed)) {
2346
+ errors2.push(`Column "${colKey}" expects an integer, received: "${rawVal}"`);
2347
+ }
2348
+ } else if (subDef.type === "float" || subDef.type === "decimal") {
2349
+ if (isNaN(Number(trimmed))) {
2350
+ errors2.push(`Column "${colKey}" expects a numeric float/decimal, received: "${rawVal}"`);
2351
+ }
2352
+ } else if (subDef.type === "enumeration" && Array.isArray(subDef.enum)) {
2353
+ if (!subDef.enum.includes(trimmed)) {
2354
+ warnings.push(`Column "${colKey}" value "${rawVal}" is not in defined enum options: [${subDef.enum.join(", ")}]`);
2355
+ }
2356
+ }
2357
+ }
2370
2358
  }
2371
2359
  }
2372
2360
  return { errors: errors2, warnings };
2373
2361
  }
2374
- const METADATA_COLUMN_KEY = "__bulk_updater_metadata";
2375
- const CURRENT_SCHEMA_VERSION = 1;
2376
- function escapeCsvCell(val) {
2377
- if (val === null || val === void 0) return "";
2378
- let str = "";
2379
- if (val instanceof Date) {
2380
- str = val.toISOString();
2381
- } else if (typeof val === "object") {
2382
- str = JSON.stringify(val);
2383
- } else {
2384
- str = String(val);
2385
- }
2386
- str = str.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
2387
- if (/^[=+@-]/.test(str)) {
2388
- str = `'${str}`;
2389
- }
2390
- if (str.includes(",") || str.includes('"') || str.includes("\n") || str.includes("\r")) {
2391
- return `"${str.replace(/"/g, '""')}"`;
2362
+ function isValidDocumentId(val) {
2363
+ if (!val || typeof val !== "string") return false;
2364
+ const trimmed = val.trim();
2365
+ if (!trimmed) return false;
2366
+ if (/\s/.test(trimmed)) return false;
2367
+ return /^[a-zA-Z0-9_-]+$/.test(trimmed);
2368
+ }
2369
+ function parseNumeric(rawVal, isInteger) {
2370
+ if (rawVal === null || rawVal === void 0 || rawVal === "") return null;
2371
+ const cleanStr = String(rawVal).replace(/[$€£,\s]/g, "");
2372
+ if (isInteger) {
2373
+ const n = parseInt(cleanStr, 10);
2374
+ return isNaN(n) ? null : n;
2392
2375
  }
2393
- return str;
2376
+ const f = parseFloat(cleanStr);
2377
+ return isNaN(f) ? null : f;
2394
2378
  }
2395
- function parseCsvToMatrix(csvText) {
2396
- if (!csvText) return [];
2397
- let text = csvText;
2398
- if (text.charCodeAt(0) === 65279) {
2399
- text = text.slice(1);
2379
+ function parseBoolean(rawVal) {
2380
+ if (rawVal === null || rawVal === void 0 || rawVal === "") return null;
2381
+ const s = String(rawVal).trim().toLowerCase();
2382
+ if (s === "true" || s === "1" || s === "yes" || s === "y" || s === "on") return true;
2383
+ if (s === "false" || s === "0" || s === "no" || s === "n" || s === "off") return false;
2384
+ return null;
2385
+ }
2386
+ async function resolveMediaIds(strapi, rawVal, isMultiple) {
2387
+ if (rawVal === null || rawVal === void 0 || rawVal === "") {
2388
+ return isMultiple ? [] : null;
2400
2389
  }
2401
- const rows = [];
2402
- let currentRow = [];
2403
- let currentCell = "";
2404
- let inQuotes = false;
2405
- let cellIsQuoted = false;
2406
- for (let i = 0; i < text.length; i++) {
2407
- const char = text[i];
2408
- const nextChar = text[i + 1];
2409
- if (inQuotes) {
2410
- if (char === '"') {
2411
- if (nextChar === '"') {
2412
- currentCell += '"';
2413
- i++;
2414
- } else {
2415
- inQuotes = false;
2416
- }
2417
- } else {
2418
- currentCell += char;
2419
- }
2420
- } else {
2421
- if (char === '"' && !cellIsQuoted && currentCell.trim() === "") {
2422
- inQuotes = true;
2423
- cellIsQuoted = true;
2424
- currentCell = "";
2425
- } else if (char === ",") {
2426
- currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
2427
- currentCell = "";
2428
- cellIsQuoted = false;
2429
- } else if (char === "\r") {
2430
- if (nextChar === "\n") {
2431
- i++;
2432
- }
2433
- currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
2434
- if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
2435
- rows.push(currentRow);
2436
- }
2437
- currentRow = [];
2438
- currentCell = "";
2439
- cellIsQuoted = false;
2440
- } else if (char === "\n") {
2441
- currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
2442
- if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
2443
- rows.push(currentRow);
2444
- }
2445
- currentRow = [];
2446
- currentCell = "";
2447
- cellIsQuoted = false;
2448
- } else {
2449
- if (!(cellIsQuoted && !inQuotes && (char === " " || char === " "))) {
2450
- currentCell += char;
2451
- }
2390
+ let parsed = rawVal;
2391
+ if (typeof rawVal === "string") {
2392
+ const trimmed = rawVal.trim();
2393
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
2394
+ try {
2395
+ parsed = JSON.parse(trimmed);
2396
+ } catch {
2452
2397
  }
2453
2398
  }
2454
2399
  }
2455
- if (currentCell !== "" || cellIsQuoted || currentRow.length > 0) {
2456
- currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
2457
- if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
2458
- rows.push(currentRow);
2400
+ const numericIds = [];
2401
+ const candidateLookups = [];
2402
+ const inspectItem = (item) => {
2403
+ if (item === null || item === void 0) return;
2404
+ if (typeof item === "number" && !isNaN(item)) {
2405
+ numericIds.push(item);
2406
+ return;
2459
2407
  }
2460
- }
2461
- return rows;
2462
- }
2463
- function parseCsvToRecords(csvText) {
2464
- const matrix = parseCsvToMatrix(csvText);
2465
- if (matrix.length < 2) return [];
2466
- const headers = matrix[0].map((h) => h.trim());
2467
- const records = [];
2468
- for (let i = 1; i < matrix.length; i++) {
2469
- const row = matrix[i];
2470
- const record = {};
2471
- headers.forEach((h, idx) => {
2472
- let val = row[idx] !== void 0 ? row[idx] : "";
2473
- if (typeof val === "string" && /^'[=+@-]/.test(val)) {
2474
- val = val.substring(1);
2408
+ if (typeof item === "object") {
2409
+ if (typeof item.id === "number") {
2410
+ numericIds.push(item.id);
2411
+ return;
2475
2412
  }
2476
- record[h] = val;
2477
- });
2478
- records.push(record);
2479
- }
2480
- return records;
2481
- }
2482
- function serializeFieldValue(value, field) {
2483
- if (value === null || value === void 0) {
2484
- return "";
2485
- }
2486
- switch (field.category) {
2487
- case "scalar": {
2488
- if (value instanceof Date) {
2489
- return value.toISOString();
2413
+ if (typeof item.id === "string" && /^\d+$/.test(item.id)) {
2414
+ numericIds.push(parseInt(item.id, 10));
2415
+ return;
2416
+ }
2417
+ if (item.documentId) {
2418
+ candidateLookups.push(String(item.documentId));
2419
+ return;
2420
+ }
2421
+ if (item.url) {
2422
+ candidateLookups.push(String(item.url));
2423
+ return;
2490
2424
  }
2491
- return String(value);
2492
2425
  }
2493
- case "blocks":
2494
- case "json": {
2495
- return typeof value === "object" ? JSON.stringify(value) : String(value);
2426
+ const str = String(item).trim();
2427
+ if (/^\d+$/.test(str)) {
2428
+ numericIds.push(parseInt(str, 10));
2429
+ } else if (str) {
2430
+ candidateLookups.push(str);
2496
2431
  }
2497
- case "component_single": {
2498
- return typeof value === "object" ? JSON.stringify(value) : String(value);
2432
+ };
2433
+ if (Array.isArray(parsed)) {
2434
+ for (const el of parsed) {
2435
+ inspectItem(el);
2499
2436
  }
2500
- case "component_repeatable": {
2501
- if (Array.isArray(value)) {
2502
- return JSON.stringify(value);
2503
- }
2504
- return typeof value === "object" ? JSON.stringify([value]) : "";
2437
+ } else if (typeof parsed === "object" && parsed !== null) {
2438
+ inspectItem(parsed);
2439
+ } else if (typeof rawVal === "string" && (rawVal.includes(",") || rawVal.includes(";"))) {
2440
+ const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter(Boolean);
2441
+ for (const part of parts) {
2442
+ inspectItem(part);
2505
2443
  }
2506
- case "dynamiczone": {
2507
- if (Array.isArray(value)) {
2508
- const cleaned = value.map((block) => {
2509
- if (block && typeof block === "object") {
2510
- return { ...block };
2444
+ } else {
2445
+ inspectItem(parsed);
2446
+ }
2447
+ if (candidateLookups.length > 0) {
2448
+ try {
2449
+ const fileQuery = strapi.db?.query("plugin::upload.file");
2450
+ if (fileQuery) {
2451
+ for (const candidate of candidateLookups) {
2452
+ const found = await fileQuery.findOne({
2453
+ where: {
2454
+ $or: [
2455
+ { documentId: candidate },
2456
+ { url: candidate },
2457
+ { hash: candidate },
2458
+ { name: candidate }
2459
+ ]
2460
+ },
2461
+ select: ["id"]
2462
+ });
2463
+ if (found?.id) {
2464
+ numericIds.push(found.id);
2511
2465
  }
2512
- return block;
2513
- });
2514
- return JSON.stringify(cleaned);
2466
+ }
2515
2467
  }
2516
- return "";
2468
+ } catch {
2517
2469
  }
2518
- case "relation_to_one": {
2519
- if (typeof value === "object" && value !== null) {
2520
- const docId = value.documentId || value.id || "";
2521
- return JSON.stringify({
2522
- documentId: String(docId),
2523
- title: value.title || value.name || value.slug || void 0
2524
- });
2470
+ }
2471
+ const uniqueNumericIds = Array.from(new Set(numericIds));
2472
+ if (isMultiple) {
2473
+ return uniqueNumericIds;
2474
+ }
2475
+ return uniqueNumericIds.length > 0 ? uniqueNumericIds[0] : null;
2476
+ }
2477
+ function resolveRelationPayload(rawVal, isToMany) {
2478
+ if (rawVal === null || rawVal === void 0 || rawVal === "") {
2479
+ return isToMany ? { set: [] } : { set: [] };
2480
+ }
2481
+ let parsed = rawVal;
2482
+ if (typeof rawVal === "string") {
2483
+ const trimmed = rawVal.trim();
2484
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
2485
+ try {
2486
+ parsed = JSON.parse(trimmed);
2487
+ } catch {
2525
2488
  }
2526
- return String(value);
2527
2489
  }
2528
- case "relation_to_many": {
2529
- if (Array.isArray(value)) {
2530
- const list = value.map((item) => {
2531
- if (typeof item === "object" && item !== null) {
2532
- const docId = item.documentId || item.id || "";
2533
- return {
2534
- documentId: String(docId),
2535
- title: item.title || item.name || item.slug || void 0
2536
- };
2537
- }
2538
- return { documentId: String(item) };
2539
- });
2540
- return JSON.stringify(list);
2541
- }
2542
- return "";
2490
+ }
2491
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
2492
+ if (parsed.set || parsed.connect || parsed.disconnect) {
2493
+ return parsed;
2543
2494
  }
2544
- case "media_single": {
2545
- if (typeof value === "object" && value !== null) {
2546
- return JSON.stringify({
2547
- id: value.id,
2548
- documentId: value.documentId,
2549
- name: value.name,
2550
- url: value.url,
2551
- mime: value.mime
2552
- });
2553
- }
2554
- return String(value);
2495
+ const singleDocId = parsed.documentId || parsed.id;
2496
+ if (singleDocId && isValidDocumentId(String(singleDocId))) {
2497
+ return isToMany ? { set: [String(singleDocId).trim()] } : { set: [String(singleDocId).trim()] };
2555
2498
  }
2556
- case "media_to_many": {
2557
- if (Array.isArray(value)) {
2558
- const list = value.map((file) => {
2559
- if (typeof file === "object" && file !== null) {
2560
- return {
2561
- id: file.id,
2562
- documentId: file.documentId,
2563
- name: file.name,
2564
- url: file.url,
2565
- mime: file.mime
2566
- };
2567
- }
2568
- return file;
2569
- });
2570
- return JSON.stringify(list);
2499
+ }
2500
+ const docIds = [];
2501
+ if (Array.isArray(parsed)) {
2502
+ for (const item of parsed) {
2503
+ if (item && typeof item === "object") {
2504
+ const id = item.documentId || item.id;
2505
+ if (id && isValidDocumentId(String(id))) {
2506
+ docIds.push(String(id).trim());
2507
+ }
2508
+ } else if (isValidDocumentId(String(item))) {
2509
+ docIds.push(String(item).trim());
2571
2510
  }
2572
- return "";
2573
2511
  }
2574
- default:
2575
- return typeof value === "object" ? JSON.stringify(value) : String(value);
2512
+ } else if (typeof rawVal === "string") {
2513
+ if (rawVal.includes(",") || rawVal.includes(";")) {
2514
+ const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter((p) => isValidDocumentId(p));
2515
+ docIds.push(...parts);
2516
+ } else if (isValidDocumentId(rawVal.trim())) {
2517
+ docIds.push(rawVal.trim());
2518
+ }
2576
2519
  }
2520
+ const uniqueDocIds = Array.from(new Set(docIds));
2521
+ return { set: uniqueDocIds };
2577
2522
  }
2578
- function serializeDocumentsToCsv(strapi, uid, documents, options = {}) {
2579
- const schema = options.schema || discoverSchema(strapi, uid);
2580
- const plan = buildExportColumnPlan(strapi, uid, documents || [], schema);
2581
- const headers = [METADATA_COLUMN_KEY, ...plan.headers];
2582
- const lines = [];
2583
- lines.push(headers.map(escapeCsvCell).join(","));
2584
- const exportedAt = options.exportedAt || (/* @__PURE__ */ new Date()).toISOString();
2585
- for (const doc of documents) {
2586
- const rowValues = [];
2587
- const flattenedMeta = extractRowFlattenedMetadata(plan, doc);
2588
- const metadata = {
2589
- schemaVersion: CURRENT_SCHEMA_VERSION,
2590
- contentType: uid,
2591
- documentId: String(doc.documentId || doc.id || ""),
2592
- locale: doc.locale || void 0,
2593
- exportedAt,
2594
- ...flattenedMeta.applicableFields ? { applicableFields: flattenedMeta.applicableFields } : {},
2595
- ...flattenedMeta.flatTypes ? { flatTypes: flattenedMeta.flatTypes } : {}
2596
- };
2597
- rowValues.push(escapeCsvCell(metadata));
2598
- for (const col of plan.columns) {
2599
- const cellValue = serializePlannedCell(col, doc, serializeFieldValue);
2600
- rowValues.push(escapeCsvCell(cellValue));
2523
+ async function resolveComponentPayload(strapi, compUid, rawVal, existingVal = {}) {
2524
+ const comp = strapi.components?.[compUid];
2525
+ if (!comp?.attributes) {
2526
+ return typeof rawVal === "object" ? rawVal : {};
2527
+ }
2528
+ let sourceObj = {};
2529
+ if (typeof rawVal === "string") {
2530
+ try {
2531
+ sourceObj = JSON.parse(rawVal);
2532
+ } catch {
2533
+ return existingVal || {};
2601
2534
  }
2602
- lines.push(rowValues.join(","));
2535
+ } else if (typeof rawVal === "object" && rawVal !== null) {
2536
+ sourceObj = rawVal;
2537
+ } else {
2538
+ return existingVal || {};
2603
2539
  }
2604
- const csvContent = "\uFEFF" + lines.join("\r\n") + "\r\n";
2605
- return {
2606
- csvContent,
2607
- headers,
2608
- count: documents.length
2609
- };
2610
- }
2611
- function extractMetadataFromRow(row) {
2612
- if (!row || typeof row !== "object") return null;
2613
- const rawMeta = row[METADATA_COLUMN_KEY] || row["__bulk_updater_metadata"];
2614
- if (!rawMeta) return null;
2615
- if (typeof rawMeta === "object") {
2616
- return rawMeta;
2540
+ const result = { ...existingVal || {} };
2541
+ for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
2542
+ if (SYSTEM_ATTRIBUTES.has(attrName.toLowerCase().replace(/[\s_-]/g, ""))) continue;
2543
+ if (!(attrName in sourceObj)) {
2544
+ continue;
2545
+ }
2546
+ const fieldVal = sourceObj[attrName];
2547
+ const type = String(attrDef.type || "").toLowerCase();
2548
+ if (type === "component") {
2549
+ if (attrDef.repeatable) {
2550
+ const list = Array.isArray(fieldVal) ? fieldVal : [];
2551
+ const cleanedList = [];
2552
+ for (const item of list) {
2553
+ const subCleaned = await resolveComponentPayload(strapi, attrDef.component, item, {});
2554
+ cleanedList.push(subCleaned);
2555
+ }
2556
+ result[attrName] = cleanedList;
2557
+ } else {
2558
+ result[attrName] = await resolveComponentPayload(
2559
+ strapi,
2560
+ attrDef.component,
2561
+ fieldVal,
2562
+ existingVal?.[attrName] || {}
2563
+ );
2564
+ }
2565
+ } else if (type === "relation") {
2566
+ const isToMany = String(attrDef.relation || "").toLowerCase().endsWith("many");
2567
+ result[attrName] = resolveRelationPayload(fieldVal, isToMany);
2568
+ } else if (type === "media") {
2569
+ result[attrName] = await resolveMediaIds(strapi, fieldVal, Boolean(attrDef.multiple));
2570
+ } else if (type === "integer" || type === "biginteger") {
2571
+ result[attrName] = parseNumeric(fieldVal, true);
2572
+ } else if (type === "float" || type === "decimal") {
2573
+ result[attrName] = parseNumeric(fieldVal, false);
2574
+ } else if (type === "boolean") {
2575
+ result[attrName] = parseBoolean(fieldVal);
2576
+ } else if (type === "json") {
2577
+ if (isPlainObject(fieldVal) && isPlainObject(existingVal?.[attrName])) {
2578
+ const deepMergePlain = (base, patch) => {
2579
+ if (!isPlainObject(base) || !isPlainObject(patch)) return patch;
2580
+ const next = deepCloneValue(base);
2581
+ for (const [k, v] of Object.entries(patch)) {
2582
+ if (isPlainObject(v) && isPlainObject(next[k])) {
2583
+ next[k] = deepMergePlain(next[k], v);
2584
+ } else {
2585
+ next[k] = parseFirstLevelCellValue(v, void 0, next[k]).value;
2586
+ }
2587
+ }
2588
+ return next;
2589
+ };
2590
+ result[attrName] = deepMergePlain(existingVal[attrName], fieldVal);
2591
+ } else if (isPlainObject(fieldVal)) {
2592
+ const parsedObj = {};
2593
+ for (const [k, v] of Object.entries(fieldVal)) {
2594
+ parsedObj[k] = isPlainObject(v) ? deepCloneValue(v) : parseFirstLevelCellValue(v).value;
2595
+ }
2596
+ result[attrName] = parsedObj;
2597
+ } else if (typeof fieldVal === "string") {
2598
+ try {
2599
+ result[attrName] = JSON.parse(fieldVal);
2600
+ } catch {
2601
+ result[attrName] = fieldVal;
2602
+ }
2603
+ } else {
2604
+ result[attrName] = fieldVal;
2605
+ }
2606
+ } else if (type === "blocks") {
2607
+ if (typeof fieldVal === "string") {
2608
+ try {
2609
+ result[attrName] = JSON.parse(fieldVal);
2610
+ } catch {
2611
+ result[attrName] = fieldVal;
2612
+ }
2613
+ } else {
2614
+ result[attrName] = fieldVal;
2615
+ }
2616
+ } else {
2617
+ result[attrName] = fieldVal === null || fieldVal === void 0 ? null : String(fieldVal);
2618
+ }
2617
2619
  }
2618
- if (typeof rawMeta === "string") {
2620
+ return result;
2621
+ }
2622
+ async function resolveDynamicZonePayload(strapi, allowedComponents, rawVal, existingVal = []) {
2623
+ let list = [];
2624
+ if (typeof rawVal === "string") {
2619
2625
  try {
2620
- const parsed = JSON.parse(rawMeta);
2621
- if (parsed && typeof parsed === "object") {
2622
- return parsed;
2623
- }
2626
+ list = JSON.parse(rawVal);
2624
2627
  } catch {
2628
+ return existingVal || [];
2625
2629
  }
2630
+ } else if (Array.isArray(rawVal)) {
2631
+ list = rawVal;
2632
+ } else {
2633
+ return existingVal || [];
2626
2634
  }
2627
- return null;
2635
+ if (!Array.isArray(list)) return [];
2636
+ const allowedSet = new Set(allowedComponents || []);
2637
+ const resolvedBlocks = [];
2638
+ for (const block of list) {
2639
+ if (!block || typeof block !== "object") continue;
2640
+ const compUid = block.__component;
2641
+ if (!compUid || typeof compUid !== "string") {
2642
+ continue;
2643
+ }
2644
+ if (allowedSet.size > 0 && !allowedSet.has(compUid)) {
2645
+ continue;
2646
+ }
2647
+ const resolvedAttrs = await resolveComponentPayload(strapi, compUid, block, {});
2648
+ resolvedAttrs.__component = compUid;
2649
+ resolvedBlocks.push(resolvedAttrs);
2650
+ }
2651
+ return resolvedBlocks;
2628
2652
  }
2629
- function sanitizeUserErrorMessage(msg) {
2630
- if (msg === null || msg === void 0) return "Error processing row";
2631
- const raw = typeof msg === "string" ? msg : String(msg);
2632
- const cleanedLines = raw.split(/\r?\n/).filter((line) => !/^\s+at\s+.+(\(.+\)|:\d+:\d+)\s*$/.test(line)).map((line) => line.trim()).filter(Boolean);
2633
- const result = cleanedLines.join(" ").trim();
2634
- return result || "Error processing row";
2653
+ const UNSAFE_PROP_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
2654
+ function buildLegacyNestedPatchFromDots(attrName, dotEntries) {
2655
+ const patch = {};
2656
+ let hasEffectiveEdits = false;
2657
+ const prefix = `${attrName}.`;
2658
+ for (const [fullKey, rawVal] of dotEntries) {
2659
+ if (!fullKey.startsWith(prefix)) continue;
2660
+ if (rawVal === void 0 || rawVal === null || rawVal === "") continue;
2661
+ const segments = fullKey.slice(prefix.length).split(".").filter(Boolean);
2662
+ if (segments.length === 0 || segments.some((s) => UNSAFE_PROP_NAMES.has(s))) continue;
2663
+ const strVal = String(rawVal);
2664
+ const trimmed = strVal.trim();
2665
+ if (trimmed === EXPLICIT_DELETE_KEY_TOKEN) continue;
2666
+ const parsedValue = EXPLICIT_CLEAR_TOKENS.has(trimmed) ? null : trimmed === EXPLICIT_EMPTY_STRING_TOKEN ? "" : parseFirstLevelCellValue(strVal).value;
2667
+ let cursor = patch;
2668
+ for (let i = 0; i < segments.length - 1; i++) {
2669
+ const seg = segments[i];
2670
+ if (!isPlainObject(cursor[seg])) {
2671
+ cursor[seg] = {};
2672
+ }
2673
+ cursor = cursor[seg];
2674
+ }
2675
+ cursor[segments[segments.length - 1]] = parsedValue;
2676
+ hasEffectiveEdits = true;
2677
+ }
2678
+ return { hasEffectiveEdits, patch };
2635
2679
  }
2636
- function resolveErrorColumnName(existingHeaders) {
2637
- const existingLower = new Set(
2638
- existingHeaders.map((h) => String(h || "").trim().toLowerCase())
2639
- );
2640
- if (!existingLower.has("error")) {
2641
- return "Error";
2680
+ async function prepareCsvRowMutation(strapi, uid, existingDoc, rawRow, options = {}) {
2681
+ const schema = discoverSchema(strapi, uid);
2682
+ const payload = {};
2683
+ const errors2 = [];
2684
+ const warnings = [];
2685
+ const isPartialUpdate = options.isPartialUpdate !== false;
2686
+ const isCreate = options.isCreate !== void 0 ? options.isCreate : !existingDoc;
2687
+ const unescapedRow = {};
2688
+ for (const [k, v] of Object.entries(rawRow || {})) {
2689
+ let cleanVal = v;
2690
+ if (typeof cleanVal === "string" && /^'[=+@-]/.test(cleanVal)) {
2691
+ cleanVal = cleanVal.substring(1);
2692
+ }
2693
+ unescapedRow[k] = cleanVal;
2642
2694
  }
2643
- if (!existingLower.has("import error")) {
2644
- return "Import Error";
2695
+ const rowInfo = inspectRowMetadataMode(unescapedRow);
2696
+ if (rowInfo.error) {
2697
+ errors2.push(rowInfo.error);
2645
2698
  }
2646
- let suffix = 2;
2647
- while (existingLower.has(`import error (${suffix})`)) {
2648
- suffix++;
2699
+ const detectedMode = rowInfo.mode;
2700
+ if (options.expectedExportMode && detectedMode !== options.expectedExportMode) {
2701
+ errors2.push(
2702
+ `Row exportMode "${detectedMode}" conflicts with batch exportMode "${options.expectedExportMode}".`
2703
+ );
2649
2704
  }
2650
- return `Import Error (${suffix})`;
2651
- }
2652
- function formatErrorCsvFilename(collectionTypeOrUid, date = /* @__PURE__ */ new Date()) {
2653
- const rawSegment = collectionTypeOrUid ? String(collectionTypeOrUid).split(".").pop() || String(collectionTypeOrUid) : "collection";
2654
- const safeType = rawSegment.replace(/[^a-zA-Z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "collection";
2655
- const pad = (n) => String(n).padStart(2, "0");
2656
- const stamp = `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}_${pad(
2657
- date.getHours()
2658
- )}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
2659
- return `error_${safeType}_${stamp}.csv`;
2660
- }
2661
- function buildErrorCsv(options) {
2662
- const { headers, failedRows } = options || {};
2663
- if (!Array.isArray(failedRows) || failedRows.length === 0) {
2705
+ const isTargetedMode = detectedMode === "metafields" || detectedMode === "topbarconfig";
2706
+ const targetAttr = isTargetedMode ? rowInfo.targetObjectField || resolveTargetObjectField(schema, detectedMode) || detectedMode : void 0;
2707
+ if (isTargetedMode && targetAttr && !isCreate) {
2708
+ const targetField = schema.fields[targetAttr];
2709
+ if (!targetField || targetField.category !== "json" && targetField.category !== "component_single") {
2710
+ errors2.push(
2711
+ `Target object field "${targetAttr}" for exportMode "${detectedMode}" was not found as an object/component attribute on "${uid}".`
2712
+ );
2713
+ return {
2714
+ payload,
2715
+ errors: errors2,
2716
+ warnings,
2717
+ detectedMode,
2718
+ targetObjectField: targetAttr,
2719
+ rowMeta: rowInfo
2720
+ };
2721
+ }
2722
+ const ctAttr = strapi.contentTypes?.[uid]?.attributes?.[targetAttr];
2723
+ const reconstructed = reconstructTargetedFirstLevelObject({
2724
+ targetAttr,
2725
+ exportMode: detectedMode,
2726
+ existingDoc,
2727
+ docIdForError: options.docIdForError,
2728
+ rawRow: unescapedRow,
2729
+ rowMeta: rowInfo,
2730
+ isAttrRequired: Boolean(ctAttr?.required)
2731
+ });
2732
+ if (reconstructed.errors.length > 0) {
2733
+ errors2.push(...reconstructed.errors);
2734
+ }
2735
+ if (reconstructed.shouldSet) {
2736
+ if (targetField.category === "component_single" && targetField.componentUid && isPlainObject(reconstructed.value)) {
2737
+ payload[targetAttr] = await resolveComponentPayload(
2738
+ strapi,
2739
+ targetField.componentUid,
2740
+ reconstructed.value,
2741
+ existingDoc?.[targetAttr] || {}
2742
+ );
2743
+ } else {
2744
+ payload[targetAttr] = reconstructed.value;
2745
+ }
2746
+ }
2747
+ const schemaCheck2 = validateRecordSchemaConstraints(
2748
+ strapi,
2749
+ uid,
2750
+ existingDoc,
2751
+ payload,
2752
+ unescapedRow,
2753
+ {
2754
+ isCreate: false,
2755
+ detectedMode,
2756
+ targetObjectField: targetAttr
2757
+ }
2758
+ );
2759
+ errors2.push(...schemaCheck2.errors);
2760
+ warnings.push(...schemaCheck2.warnings);
2664
2761
  return {
2665
- csvContent: "",
2666
- headers: headers ? [...headers] : [],
2667
- errorColumnName: "Error",
2668
- errorCount: 0
2762
+ payload,
2763
+ errors: errors2,
2764
+ warnings,
2765
+ detectedMode,
2766
+ targetObjectField: targetAttr,
2767
+ rowMeta: rowInfo
2669
2768
  };
2670
2769
  }
2671
- const groupedByRow = /* @__PURE__ */ new Map();
2672
- for (const item of failedRows) {
2673
- if (!item || typeof item !== "object") continue;
2674
- const rowNum = typeof item.row === "number" && !isNaN(item.row) ? item.row : groupedByRow.size + 2;
2675
- const msg = sanitizeUserErrorMessage(item.error);
2676
- const existing = groupedByRow.get(rowNum);
2677
- if (existing) {
2678
- if (!existing.messages.includes(msg)) {
2679
- existing.messages.push(msg);
2680
- }
2681
- } else {
2682
- groupedByRow.set(rowNum, {
2683
- row: rowNum,
2684
- documentId: item.documentId,
2685
- messages: [msg],
2686
- originalRow: item.originalRow && typeof item.originalRow === "object" ? item.originalRow : {}
2687
- });
2688
- }
2689
- }
2690
- const orderedEntries = Array.from(groupedByRow.values()).sort((a, b) => a.row - b.row);
2691
- if (orderedEntries.length === 0) {
2692
- return {
2693
- csvContent: "",
2694
- headers: headers ? [...headers] : [],
2695
- errorColumnName: "Error",
2696
- errorCount: 0
2697
- };
2698
- }
2699
- let baseHeaders = [];
2700
- if (Array.isArray(headers) && headers.length > 0) {
2701
- baseHeaders = [...headers];
2702
- } else {
2703
- const keySet = /* @__PURE__ */ new Set();
2704
- for (const entry of orderedEntries) {
2705
- for (const k of Object.keys(entry.originalRow || {})) {
2706
- if (!keySet.has(k)) {
2707
- keySet.add(k);
2708
- baseHeaders.push(k);
2709
- }
2710
- }
2711
- }
2712
- }
2713
- const errorColumnName = resolveErrorColumnName(baseHeaders);
2714
- const finalHeaders = [...baseHeaders, errorColumnName];
2715
- const lines = [];
2716
- lines.push(finalHeaders.map(escapeCsvCell).join(","));
2717
- for (const entry of orderedEntries) {
2718
- const cells = baseHeaders.map((h) => {
2719
- const val = entry.originalRow ? entry.originalRow[h] : "";
2720
- return escapeCsvCell(val === void 0 || val === null ? "" : val);
2721
- });
2722
- cells.push(escapeCsvCell(entry.messages.join("; ")));
2723
- lines.push(cells.join(","));
2724
- }
2725
- const csvContent = "\uFEFF" + lines.join("\r\n") + "\r\n";
2726
- return {
2727
- csvContent,
2728
- headers: finalHeaders,
2729
- errorColumnName,
2730
- errorCount: orderedEntries.length
2731
- };
2732
- }
2733
- function isValidDocumentId(val) {
2734
- if (!val || typeof val !== "string") return false;
2735
- const trimmed = val.trim();
2736
- if (!trimmed) return false;
2737
- if (/\s/.test(trimmed)) return false;
2738
- return /^[a-zA-Z0-9_-]+$/.test(trimmed);
2739
- }
2740
- function parseNumeric(rawVal, isInteger) {
2741
- if (rawVal === null || rawVal === void 0 || rawVal === "") return null;
2742
- const cleanStr = String(rawVal).replace(/[$€£,\s]/g, "");
2743
- if (isInteger) {
2744
- const n = parseInt(cleanStr, 10);
2745
- return isNaN(n) ? null : n;
2746
- }
2747
- const f = parseFloat(cleanStr);
2748
- return isNaN(f) ? null : f;
2749
- }
2750
- function parseBoolean(rawVal) {
2751
- if (rawVal === null || rawVal === void 0 || rawVal === "") return null;
2752
- const s = String(rawVal).trim().toLowerCase();
2753
- if (s === "true" || s === "1" || s === "yes" || s === "y" || s === "on") return true;
2754
- if (s === "false" || s === "0" || s === "no" || s === "n" || s === "off") return false;
2755
- return null;
2756
- }
2757
- async function resolveMediaIds(strapi, rawVal, isMultiple) {
2758
- if (rawVal === null || rawVal === void 0 || rawVal === "") {
2759
- return isMultiple ? [] : null;
2760
- }
2761
- let parsed = rawVal;
2762
- if (typeof rawVal === "string") {
2763
- const trimmed = rawVal.trim();
2764
- if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
2765
- try {
2766
- parsed = JSON.parse(trimmed);
2767
- } catch {
2768
- }
2770
+ const dotEntriesByAttr = {};
2771
+ for (const [k, v] of Object.entries(unescapedRow)) {
2772
+ const firstDot = k.indexOf(".");
2773
+ if (firstDot > 0) {
2774
+ const parent = k.slice(0, firstDot);
2775
+ if (!dotEntriesByAttr[parent]) dotEntriesByAttr[parent] = [];
2776
+ dotEntriesByAttr[parent].push([k, v]);
2769
2777
  }
2770
2778
  }
2771
- const numericIds = [];
2772
- const candidateLookups = [];
2773
- const inspectItem = (item) => {
2774
- if (item === null || item === void 0) return;
2775
- if (typeof item === "number" && !isNaN(item)) {
2776
- numericIds.push(item);
2777
- return;
2778
- }
2779
- if (typeof item === "object") {
2780
- if (typeof item.id === "number") {
2781
- numericIds.push(item.id);
2782
- return;
2783
- }
2784
- if (typeof item.id === "string" && /^\d+$/.test(item.id)) {
2785
- numericIds.push(parseInt(item.id, 10));
2786
- return;
2787
- }
2788
- if (item.documentId) {
2789
- candidateLookups.push(String(item.documentId));
2790
- return;
2779
+ for (const [attrName, field] of Object.entries(schema.fields)) {
2780
+ const hasDirectKey = attrName in unescapedRow;
2781
+ const dotEntries = dotEntriesByAttr[attrName] || [];
2782
+ const hasDotKeys = dotEntries.length > 0;
2783
+ if (isTargetedMode && isCreate && targetAttr === attrName) {
2784
+ const ctAttr = strapi.contentTypes?.[uid]?.attributes?.[targetAttr];
2785
+ const reconstructed = reconstructTargetedFirstLevelObject({
2786
+ targetAttr,
2787
+ exportMode: detectedMode,
2788
+ existingDoc: null,
2789
+ docIdForError: options.docIdForError,
2790
+ rawRow: unescapedRow,
2791
+ rowMeta: rowInfo,
2792
+ isAttrRequired: Boolean(ctAttr?.required)
2793
+ });
2794
+ if (reconstructed.errors.length > 0) {
2795
+ errors2.push(...reconstructed.errors);
2791
2796
  }
2792
- if (item.url) {
2793
- candidateLookups.push(String(item.url));
2794
- return;
2797
+ if (reconstructed.shouldSet) {
2798
+ if (field.category === "component_single" && field.componentUid && isPlainObject(reconstructed.value)) {
2799
+ payload[attrName] = await resolveComponentPayload(
2800
+ strapi,
2801
+ field.componentUid,
2802
+ reconstructed.value,
2803
+ {}
2804
+ );
2805
+ } else {
2806
+ payload[attrName] = reconstructed.value;
2807
+ }
2795
2808
  }
2809
+ continue;
2796
2810
  }
2797
- const str = String(item).trim();
2798
- if (/^\d+$/.test(str)) {
2799
- numericIds.push(parseInt(str, 10));
2800
- } else if (str) {
2801
- candidateLookups.push(str);
2802
- }
2803
- };
2804
- if (Array.isArray(parsed)) {
2805
- for (const el of parsed) {
2806
- inspectItem(el);
2807
- }
2808
- } else if (typeof parsed === "object" && parsed !== null) {
2809
- inspectItem(parsed);
2810
- } else if (typeof rawVal === "string" && (rawVal.includes(",") || rawVal.includes(";"))) {
2811
- const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter(Boolean);
2812
- for (const part of parts) {
2813
- inspectItem(part);
2811
+ if (!hasDirectKey && !hasDotKeys) {
2812
+ continue;
2814
2813
  }
2815
- } else {
2816
- inspectItem(parsed);
2817
- }
2818
- if (candidateLookups.length > 0) {
2819
- try {
2820
- const fileQuery = strapi.db?.query("plugin::upload.file");
2821
- if (fileQuery) {
2822
- for (const candidate of candidateLookups) {
2823
- const found = await fileQuery.findOne({
2824
- where: {
2825
- $or: [
2826
- { documentId: candidate },
2827
- { url: candidate },
2828
- { hash: candidate },
2829
- { name: candidate }
2830
- ]
2831
- },
2832
- select: ["id"]
2833
- });
2834
- if (found?.id) {
2835
- numericIds.push(found.id);
2814
+ const rawVal = hasDirectKey ? unescapedRow[attrName] : void 0;
2815
+ switch (field.category) {
2816
+ case "scalar": {
2817
+ if (rawVal === void 0 || rawVal === "" || rawVal === null) {
2818
+ payload[attrName] = null;
2819
+ } else if (field.rawType === "integer" || field.rawType === "biginteger") {
2820
+ payload[attrName] = parseNumeric(rawVal, true);
2821
+ } else if (field.rawType === "float" || field.rawType === "decimal") {
2822
+ payload[attrName] = parseNumeric(rawVal, false);
2823
+ } else if (field.rawType === "boolean") {
2824
+ payload[attrName] = parseBoolean(rawVal);
2825
+ } else if (field.rawType === "date" || field.rawType === "time" || field.rawType === "datetime" || field.rawType === "timestamp") {
2826
+ payload[attrName] = String(rawVal).trim() || null;
2827
+ } else if (field.rawType === "enumeration") {
2828
+ const trimmed = String(rawVal).trim();
2829
+ if (field.enumOptions && field.enumOptions.length > 0) {
2830
+ const match = field.enumOptions.find((o) => o.toLowerCase() === trimmed.toLowerCase());
2831
+ payload[attrName] = match || trimmed;
2832
+ } else {
2833
+ payload[attrName] = trimmed;
2836
2834
  }
2835
+ } else {
2836
+ payload[attrName] = String(rawVal).trim();
2837
2837
  }
2838
+ break;
2838
2839
  }
2839
- } catch {
2840
- }
2841
- }
2842
- const uniqueNumericIds = Array.from(new Set(numericIds));
2843
- if (isMultiple) {
2844
- return uniqueNumericIds;
2845
- }
2846
- return uniqueNumericIds.length > 0 ? uniqueNumericIds[0] : null;
2847
- }
2848
- function resolveRelationPayload(rawVal, isToMany) {
2849
- if (rawVal === null || rawVal === void 0 || rawVal === "") {
2850
- return isToMany ? { set: [] } : { set: [] };
2851
- }
2852
- let parsed = rawVal;
2853
- if (typeof rawVal === "string") {
2854
- const trimmed = rawVal.trim();
2855
- if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
2856
- try {
2857
- parsed = JSON.parse(trimmed);
2858
- } catch {
2840
+ case "blocks": {
2841
+ if (rawVal === void 0 || rawVal === "" || rawVal === null) {
2842
+ payload[attrName] = [];
2843
+ } else {
2844
+ try {
2845
+ const parsed = JSON.parse(rawVal);
2846
+ payload[attrName] = Array.isArray(parsed) ? parsed : [parsed];
2847
+ } catch {
2848
+ payload[attrName] = [
2849
+ { type: "paragraph", children: [{ type: "text", text: String(rawVal).trim() }] }
2850
+ ];
2851
+ }
2852
+ }
2853
+ break;
2859
2854
  }
2860
- }
2861
- }
2862
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
2863
- if (parsed.set || parsed.connect || parsed.disconnect) {
2864
- return parsed;
2865
- }
2866
- const singleDocId = parsed.documentId || parsed.id;
2867
- if (singleDocId && isValidDocumentId(String(singleDocId))) {
2868
- return isToMany ? { set: [String(singleDocId).trim()] } : { set: [String(singleDocId).trim()] };
2869
- }
2870
- }
2871
- const docIds = [];
2872
- if (Array.isArray(parsed)) {
2873
- for (const item of parsed) {
2874
- if (item && typeof item === "object") {
2875
- const id = item.documentId || item.id;
2876
- if (id && isValidDocumentId(String(id))) {
2877
- docIds.push(String(id).trim());
2855
+ case "json": {
2856
+ if (hasDotKeys) {
2857
+ const { hasEffectiveEdits, patch } = buildLegacyNestedPatchFromDots(
2858
+ attrName,
2859
+ dotEntries
2860
+ );
2861
+ if (hasEffectiveEdits) {
2862
+ const mergeDeep = (base, p) => {
2863
+ if (!isPlainObject(base) || !isPlainObject(p)) return p;
2864
+ const next = deepCloneValue(base);
2865
+ for (const [k, v] of Object.entries(p)) {
2866
+ if (isPlainObject(v) && isPlainObject(next[k])) {
2867
+ next[k] = mergeDeep(next[k], v);
2868
+ } else {
2869
+ next[k] = deepCloneValue(v);
2870
+ }
2871
+ }
2872
+ return next;
2873
+ };
2874
+ payload[attrName] = isPlainObject(existingDoc?.[attrName]) ? mergeDeep(existingDoc[attrName], patch) : patch;
2875
+ break;
2876
+ }
2878
2877
  }
2879
- } else if (isValidDocumentId(String(item))) {
2880
- docIds.push(String(item).trim());
2881
- }
2882
- }
2883
- } else if (typeof rawVal === "string") {
2884
- if (rawVal.includes(",") || rawVal.includes(";")) {
2885
- const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter((p) => isValidDocumentId(p));
2886
- docIds.push(...parts);
2887
- } else if (isValidDocumentId(rawVal.trim())) {
2888
- docIds.push(rawVal.trim());
2889
- }
2890
- }
2891
- const uniqueDocIds = Array.from(new Set(docIds));
2892
- return { set: uniqueDocIds };
2893
- }
2894
- async function resolveComponentPayload(strapi, compUid, rawVal, existingVal = {}) {
2895
- const comp = strapi.components?.[compUid];
2896
- if (!comp?.attributes) {
2897
- return typeof rawVal === "object" ? rawVal : {};
2898
- }
2899
- let sourceObj = {};
2900
- if (typeof rawVal === "string") {
2901
- try {
2902
- sourceObj = JSON.parse(rawVal);
2903
- } catch {
2904
- return existingVal || {};
2905
- }
2906
- } else if (typeof rawVal === "object" && rawVal !== null) {
2907
- sourceObj = rawVal;
2908
- } else {
2909
- return existingVal || {};
2910
- }
2911
- const result = { ...existingVal || {} };
2912
- for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
2913
- if (SYSTEM_ATTRIBUTES.has(attrName.toLowerCase().replace(/[\s_-]/g, ""))) continue;
2914
- if (!(attrName in sourceObj)) {
2915
- continue;
2916
- }
2917
- const fieldVal = sourceObj[attrName];
2918
- const type = String(attrDef.type || "").toLowerCase();
2919
- if (type === "component") {
2920
- if (attrDef.repeatable) {
2921
- const list = Array.isArray(fieldVal) ? fieldVal : [];
2922
- const cleanedList = [];
2923
- for (const item of list) {
2924
- const subCleaned = await resolveComponentPayload(strapi, attrDef.component, item, {});
2925
- cleanedList.push(subCleaned);
2926
- }
2927
- result[attrName] = cleanedList;
2928
- } else {
2929
- result[attrName] = await resolveComponentPayload(
2930
- strapi,
2931
- attrDef.component,
2932
- fieldVal,
2933
- existingVal?.[attrName] || {}
2934
- );
2935
- }
2936
- } else if (type === "relation") {
2937
- const isToMany = String(attrDef.relation || "").toLowerCase().endsWith("many");
2938
- result[attrName] = resolveRelationPayload(fieldVal, isToMany);
2939
- } else if (type === "media") {
2940
- result[attrName] = await resolveMediaIds(strapi, fieldVal, Boolean(attrDef.multiple));
2941
- } else if (type === "integer" || type === "biginteger") {
2942
- result[attrName] = parseNumeric(fieldVal, true);
2943
- } else if (type === "float" || type === "decimal") {
2944
- result[attrName] = parseNumeric(fieldVal, false);
2945
- } else if (type === "boolean") {
2946
- result[attrName] = parseBoolean(fieldVal);
2947
- } else if (type === "json") {
2948
- if (isPlainObject(fieldVal) && isPlainObject(existingVal?.[attrName])) {
2949
- const deepMergePlain = (base, patch) => {
2950
- if (!isPlainObject(base) || !isPlainObject(patch)) return patch;
2951
- const next = deepCloneValue(base);
2952
- for (const [k, v] of Object.entries(patch)) {
2953
- if (isPlainObject(v) && isPlainObject(next[k])) {
2954
- next[k] = deepMergePlain(next[k], v);
2955
- } else {
2956
- next[k] = parseFlattenedLeafValue(v, void 0, next[k]);
2957
- }
2958
- }
2959
- return next;
2960
- };
2961
- result[attrName] = deepMergePlain(existingVal[attrName], fieldVal);
2962
- } else if (isPlainObject(fieldVal)) {
2963
- const parsedObj = {};
2964
- for (const [k, v] of Object.entries(fieldVal)) {
2965
- parsedObj[k] = isPlainObject(v) ? deepCloneValue(v) : parseFlattenedLeafValue(v);
2966
- }
2967
- result[attrName] = parsedObj;
2968
- } else if (typeof fieldVal === "string") {
2969
- try {
2970
- result[attrName] = JSON.parse(fieldVal);
2971
- } catch {
2972
- result[attrName] = fieldVal;
2973
- }
2974
- } else {
2975
- result[attrName] = fieldVal;
2976
- }
2977
- } else if (type === "blocks") {
2978
- if (typeof fieldVal === "string") {
2979
- try {
2980
- result[attrName] = JSON.parse(fieldVal);
2981
- } catch {
2982
- result[attrName] = fieldVal;
2983
- }
2984
- } else {
2985
- result[attrName] = fieldVal;
2986
- }
2987
- } else {
2988
- result[attrName] = fieldVal === null || fieldVal === void 0 ? null : String(fieldVal);
2989
- }
2990
- }
2991
- return result;
2992
- }
2993
- async function resolveDynamicZonePayload(strapi, allowedComponents, rawVal, existingVal = []) {
2994
- let list = [];
2995
- if (typeof rawVal === "string") {
2996
- try {
2997
- list = JSON.parse(rawVal);
2998
- } catch {
2999
- return existingVal || [];
3000
- }
3001
- } else if (Array.isArray(rawVal)) {
3002
- list = rawVal;
3003
- } else {
3004
- return existingVal || [];
3005
- }
3006
- if (!Array.isArray(list)) return [];
3007
- const allowedSet = new Set(allowedComponents || []);
3008
- const resolvedBlocks = [];
3009
- for (const block of list) {
3010
- if (!block || typeof block !== "object") continue;
3011
- const compUid = block.__component;
3012
- if (!compUid || typeof compUid !== "string") {
3013
- continue;
3014
- }
3015
- if (allowedSet.size > 0 && !allowedSet.has(compUid)) {
3016
- continue;
3017
- }
3018
- const resolvedAttrs = await resolveComponentPayload(strapi, compUid, block, {});
3019
- resolvedAttrs.__component = compUid;
3020
- resolvedBlocks.push(resolvedAttrs);
3021
- }
3022
- return resolvedBlocks;
3023
- }
3024
- async function buildDocumentUpdatePayload(strapi, uid, existingDoc, rawRow, options = {}) {
3025
- const schema = discoverSchema(strapi, uid);
3026
- const payload = {};
3027
- const isPartialUpdate = options.isPartialUpdate !== false;
3028
- const unescapedRow = {};
3029
- for (const [k, v] of Object.entries(rawRow)) {
3030
- let cleanVal = v;
3031
- if (typeof cleanVal === "string" && /^'[=+@-]/.test(cleanVal)) {
3032
- cleanVal = cleanVal.substring(1);
3033
- }
3034
- unescapedRow[k] = cleanVal;
3035
- }
3036
- const rowMeta = extractMetadataFromRow(unescapedRow);
3037
- const dotEntriesByAttr = {};
3038
- for (const [k, v] of Object.entries(unescapedRow)) {
3039
- const firstDot = k.indexOf(".");
3040
- if (firstDot > 0) {
3041
- const parent = k.slice(0, firstDot);
3042
- if (!dotEntriesByAttr[parent]) dotEntriesByAttr[parent] = [];
3043
- dotEntriesByAttr[parent].push([k, v]);
3044
- }
3045
- }
3046
- for (const [attrName, field] of Object.entries(schema.fields)) {
3047
- const hasDirectKey = attrName in unescapedRow;
3048
- const dotEntries = dotEntriesByAttr[attrName] || [];
3049
- const hasDotKeys = dotEntries.length > 0;
3050
- if (!hasDirectKey && !hasDotKeys) {
3051
- continue;
3052
- }
3053
- const rawVal = hasDirectKey ? unescapedRow[attrName] : void 0;
3054
- switch (field.category) {
3055
- case "scalar": {
3056
- if (rawVal === void 0 || rawVal === "" || rawVal === null) {
3057
- payload[attrName] = null;
3058
- } else if (field.rawType === "integer" || field.rawType === "biginteger") {
3059
- payload[attrName] = parseNumeric(rawVal, true);
3060
- } else if (field.rawType === "float" || field.rawType === "decimal") {
3061
- payload[attrName] = parseNumeric(rawVal, false);
3062
- } else if (field.rawType === "boolean") {
3063
- payload[attrName] = parseBoolean(rawVal);
3064
- } else if (field.rawType === "date" || field.rawType === "time" || field.rawType === "datetime" || field.rawType === "timestamp") {
3065
- payload[attrName] = String(rawVal).trim() || null;
3066
- } else if (field.rawType === "enumeration") {
3067
- const trimmed = String(rawVal).trim();
3068
- if (field.enumOptions && field.enumOptions.length > 0) {
3069
- const match = field.enumOptions.find((o) => o.toLowerCase() === trimmed.toLowerCase());
3070
- payload[attrName] = match || trimmed;
3071
- } else {
3072
- payload[attrName] = trimmed;
3073
- }
3074
- } else {
3075
- payload[attrName] = String(rawVal).trim();
3076
- }
3077
- break;
3078
- }
3079
- case "blocks": {
3080
- if (rawVal === void 0 || rawVal === "" || rawVal === null) {
3081
- payload[attrName] = [];
3082
- } else {
3083
- try {
3084
- const parsed = JSON.parse(rawVal);
3085
- payload[attrName] = Array.isArray(parsed) ? parsed : [parsed];
3086
- } catch {
3087
- payload[attrName] = [
3088
- { type: "paragraph", children: [{ type: "text", text: String(rawVal).trim() }] }
3089
- ];
3090
- }
3091
- }
3092
- break;
3093
- }
3094
- case "json": {
3095
- const reconstructed = reconstructFlattenedJsonAttribute({
3096
- attrName,
3097
- existingVal: existingDoc?.[attrName],
3098
- hasDirectKey,
3099
- directRawVal: rawVal,
3100
- dotEntries,
3101
- rowMeta: rowMeta ? {
3102
- applicableFields: rowMeta.applicableFields,
3103
- flatTypes: rowMeta.flatTypes
3104
- } : null,
3105
- isPartialUpdate
3106
- });
3107
- if (reconstructed.shouldSet) {
3108
- payload[attrName] = reconstructed.value;
3109
- }
3110
- break;
2878
+ if (hasDirectKey) {
2879
+ const trimmed = typeof rawVal === "string" ? rawVal.trim() : "";
2880
+ if (rawVal === void 0 || rawVal === null || rawVal === "") {
2881
+ if (!isPartialUpdate) {
2882
+ payload[attrName] = null;
2883
+ }
2884
+ } else if (EXPLICIT_CLEAR_TOKENS.has(trimmed) || trimmed === "null") {
2885
+ payload[attrName] = null;
2886
+ } else if (typeof rawVal === "string") {
2887
+ try {
2888
+ payload[attrName] = JSON.parse(rawVal);
2889
+ } catch {
2890
+ payload[attrName] = rawVal;
2891
+ }
2892
+ } else {
2893
+ payload[attrName] = rawVal;
2894
+ }
2895
+ }
2896
+ break;
3111
2897
  }
3112
2898
  case "component_single": {
3113
2899
  if (field.componentUid) {
3114
2900
  const directTrimmed = typeof rawVal === "string" ? rawVal.trim() : "";
3115
2901
  if (hasDotKeys) {
3116
- const { hasEffectiveEdits, patch } = buildNestedComponentPatchFromDots(
2902
+ const { hasEffectiveEdits, patch } = buildLegacyNestedPatchFromDots(
3117
2903
  attrName,
3118
2904
  dotEntries
3119
2905
  );
@@ -3214,7 +3000,32 @@ async function buildDocumentUpdatePayload(strapi, uid, existingDoc, rawRow, opti
3214
3000
  payload[attrName] = rawVal;
3215
3001
  }
3216
3002
  }
3217
- return payload;
3003
+ const schemaCheck = validateRecordSchemaConstraints(
3004
+ strapi,
3005
+ uid,
3006
+ existingDoc,
3007
+ payload,
3008
+ unescapedRow,
3009
+ {
3010
+ isCreate,
3011
+ detectedMode,
3012
+ targetObjectField: targetAttr
3013
+ }
3014
+ );
3015
+ errors2.push(...schemaCheck.errors);
3016
+ warnings.push(...schemaCheck.warnings);
3017
+ return {
3018
+ payload,
3019
+ errors: errors2,
3020
+ warnings,
3021
+ detectedMode,
3022
+ targetObjectField: targetAttr,
3023
+ rowMeta: rowInfo
3024
+ };
3025
+ }
3026
+ async function buildDocumentUpdatePayload(strapi, uid, existingDoc, rawRow, options = {}) {
3027
+ const plan = await prepareCsvRowMutation(strapi, uid, existingDoc, rawRow, options);
3028
+ return plan.payload;
3218
3029
  }
3219
3030
  function formatComponentDisplayName(compUid) {
3220
3031
  if (!compUid) return "Component";
@@ -8603,64 +8414,427 @@ function buildComponentPopulate(strapi, compUid, visited, depth, maxDepth) {
8603
8414
  populate[attrName] = true;
8604
8415
  }
8605
8416
  }
8606
- return Object.keys(populate).length > 0 ? populate : true;
8607
- }
8608
- function buildLosslessPopulate(strapi, uid, options = {}) {
8609
- const maxDepth = options.maxDepth || 5;
8610
- const schema = discoverSchema(strapi, uid);
8611
- const populate = {};
8612
- const visited = /* @__PURE__ */ new Set([uid]);
8613
- for (const [fieldName, field] of Object.entries(schema.fields)) {
8614
- switch (field.category) {
8615
- case "component_single":
8616
- case "component_repeatable": {
8617
- if (field.componentUid) {
8618
- const compPop = buildComponentPopulate(
8619
- strapi,
8620
- field.componentUid,
8621
- visited,
8622
- 0,
8623
- maxDepth
8624
- );
8625
- populate[fieldName] = typeof compPop === "object" && Object.keys(compPop).length > 0 ? { populate: compPop } : true;
8626
- } else {
8627
- populate[fieldName] = true;
8628
- }
8629
- break;
8630
- }
8631
- case "dynamiczone": {
8632
- const dzComponents = field.dzComponents || [];
8633
- if (dzComponents.length > 0) {
8634
- const onPopulate = {};
8635
- for (const compUid of dzComponents) {
8636
- const compPop = buildComponentPopulate(
8637
- strapi,
8638
- compUid,
8639
- visited,
8640
- 0,
8641
- maxDepth
8642
- );
8643
- onPopulate[compUid] = typeof compPop === "object" && Object.keys(compPop).length > 0 ? { populate: compPop } : true;
8644
- }
8645
- populate[fieldName] = { on: onPopulate };
8646
- } else {
8647
- populate[fieldName] = { populate: "*" };
8417
+ return Object.keys(populate).length > 0 ? populate : true;
8418
+ }
8419
+ function buildLosslessPopulate(strapi, uid, options = {}) {
8420
+ const maxDepth = options.maxDepth || 5;
8421
+ const schema = discoverSchema(strapi, uid);
8422
+ const populate = {};
8423
+ const visited = /* @__PURE__ */ new Set([uid]);
8424
+ for (const [fieldName, field] of Object.entries(schema.fields)) {
8425
+ switch (field.category) {
8426
+ case "component_single":
8427
+ case "component_repeatable": {
8428
+ if (field.componentUid) {
8429
+ const compPop = buildComponentPopulate(
8430
+ strapi,
8431
+ field.componentUid,
8432
+ visited,
8433
+ 0,
8434
+ maxDepth
8435
+ );
8436
+ populate[fieldName] = typeof compPop === "object" && Object.keys(compPop).length > 0 ? { populate: compPop } : true;
8437
+ } else {
8438
+ populate[fieldName] = true;
8439
+ }
8440
+ break;
8441
+ }
8442
+ case "dynamiczone": {
8443
+ const dzComponents = field.dzComponents || [];
8444
+ if (dzComponents.length > 0) {
8445
+ const onPopulate = {};
8446
+ for (const compUid of dzComponents) {
8447
+ const compPop = buildComponentPopulate(
8448
+ strapi,
8449
+ compUid,
8450
+ visited,
8451
+ 0,
8452
+ maxDepth
8453
+ );
8454
+ onPopulate[compUid] = typeof compPop === "object" && Object.keys(compPop).length > 0 ? { populate: compPop } : true;
8455
+ }
8456
+ populate[fieldName] = { on: onPopulate };
8457
+ } else {
8458
+ populate[fieldName] = { populate: "*" };
8459
+ }
8460
+ break;
8461
+ }
8462
+ case "relation_to_one":
8463
+ case "relation_to_many": {
8464
+ populate[fieldName] = true;
8465
+ break;
8466
+ }
8467
+ case "media_single":
8468
+ case "media_to_many": {
8469
+ populate[fieldName] = true;
8470
+ break;
8471
+ }
8472
+ }
8473
+ }
8474
+ return Object.keys(populate).length > 0 ? populate : void 0;
8475
+ }
8476
+ const METADATA_COLUMN_KEY = "__bulk_updater_metadata";
8477
+ const CURRENT_SCHEMA_VERSION = 1;
8478
+ function escapeCsvCell(val) {
8479
+ if (val === null || val === void 0) return "";
8480
+ let str = "";
8481
+ if (val instanceof Date) {
8482
+ str = val.toISOString();
8483
+ } else if (typeof val === "object") {
8484
+ str = JSON.stringify(val);
8485
+ } else {
8486
+ str = String(val);
8487
+ }
8488
+ str = str.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
8489
+ if (/^[=+@-]/.test(str)) {
8490
+ str = `'${str}`;
8491
+ }
8492
+ if (str.includes(",") || str.includes('"') || str.includes("\n") || str.includes("\r")) {
8493
+ return `"${str.replace(/"/g, '""')}"`;
8494
+ }
8495
+ return str;
8496
+ }
8497
+ function parseCsvToMatrix(csvText) {
8498
+ if (!csvText) return [];
8499
+ let text = csvText;
8500
+ if (text.charCodeAt(0) === 65279) {
8501
+ text = text.slice(1);
8502
+ }
8503
+ const rows = [];
8504
+ let currentRow = [];
8505
+ let currentCell = "";
8506
+ let inQuotes = false;
8507
+ let cellIsQuoted = false;
8508
+ for (let i = 0; i < text.length; i++) {
8509
+ const char = text[i];
8510
+ const nextChar = text[i + 1];
8511
+ if (inQuotes) {
8512
+ if (char === '"') {
8513
+ if (nextChar === '"') {
8514
+ currentCell += '"';
8515
+ i++;
8516
+ } else {
8517
+ inQuotes = false;
8518
+ }
8519
+ } else {
8520
+ currentCell += char;
8521
+ }
8522
+ } else {
8523
+ if (char === '"' && !cellIsQuoted && currentCell.trim() === "") {
8524
+ inQuotes = true;
8525
+ cellIsQuoted = true;
8526
+ currentCell = "";
8527
+ } else if (char === ",") {
8528
+ currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
8529
+ currentCell = "";
8530
+ cellIsQuoted = false;
8531
+ } else if (char === "\r") {
8532
+ if (nextChar === "\n") {
8533
+ i++;
8534
+ }
8535
+ currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
8536
+ if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
8537
+ rows.push(currentRow);
8538
+ }
8539
+ currentRow = [];
8540
+ currentCell = "";
8541
+ cellIsQuoted = false;
8542
+ } else if (char === "\n") {
8543
+ currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
8544
+ if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
8545
+ rows.push(currentRow);
8546
+ }
8547
+ currentRow = [];
8548
+ currentCell = "";
8549
+ cellIsQuoted = false;
8550
+ } else {
8551
+ if (!(cellIsQuoted && !inQuotes && (char === " " || char === " "))) {
8552
+ currentCell += char;
8553
+ }
8554
+ }
8555
+ }
8556
+ }
8557
+ if (currentCell !== "" || cellIsQuoted || currentRow.length > 0) {
8558
+ currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
8559
+ if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
8560
+ rows.push(currentRow);
8561
+ }
8562
+ }
8563
+ return rows;
8564
+ }
8565
+ function parseCsvToRecords(csvText) {
8566
+ const matrix = parseCsvToMatrix(csvText);
8567
+ if (matrix.length < 2) return [];
8568
+ const headers = matrix[0].map((h) => h.trim());
8569
+ const records = [];
8570
+ for (let i = 1; i < matrix.length; i++) {
8571
+ const row = matrix[i];
8572
+ const record = {};
8573
+ headers.forEach((h, idx) => {
8574
+ let val = row[idx] !== void 0 ? row[idx] : "";
8575
+ if (typeof val === "string" && /^'[=+@-]/.test(val)) {
8576
+ val = val.substring(1);
8577
+ }
8578
+ record[h] = val;
8579
+ });
8580
+ records.push(record);
8581
+ }
8582
+ return records;
8583
+ }
8584
+ function serializeFieldValue(value, field) {
8585
+ if (value === null || value === void 0) {
8586
+ return "";
8587
+ }
8588
+ switch (field.category) {
8589
+ case "scalar": {
8590
+ if (value instanceof Date) {
8591
+ return value.toISOString();
8592
+ }
8593
+ return String(value);
8594
+ }
8595
+ case "blocks":
8596
+ case "json": {
8597
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
8598
+ }
8599
+ case "component_single": {
8600
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
8601
+ }
8602
+ case "component_repeatable": {
8603
+ if (Array.isArray(value)) {
8604
+ return JSON.stringify(value);
8605
+ }
8606
+ return typeof value === "object" ? JSON.stringify([value]) : "";
8607
+ }
8608
+ case "dynamiczone": {
8609
+ if (Array.isArray(value)) {
8610
+ const cleaned = value.map((block) => {
8611
+ if (block && typeof block === "object") {
8612
+ return { ...block };
8613
+ }
8614
+ return block;
8615
+ });
8616
+ return JSON.stringify(cleaned);
8617
+ }
8618
+ return "";
8619
+ }
8620
+ case "relation_to_one": {
8621
+ if (typeof value === "object" && value !== null) {
8622
+ const docId = value.documentId || value.id || "";
8623
+ return JSON.stringify({
8624
+ documentId: String(docId),
8625
+ title: value.title || value.name || value.slug || void 0
8626
+ });
8627
+ }
8628
+ return String(value);
8629
+ }
8630
+ case "relation_to_many": {
8631
+ if (Array.isArray(value)) {
8632
+ const list = value.map((item) => {
8633
+ if (typeof item === "object" && item !== null) {
8634
+ const docId = item.documentId || item.id || "";
8635
+ return {
8636
+ documentId: String(docId),
8637
+ title: item.title || item.name || item.slug || void 0
8638
+ };
8639
+ }
8640
+ return { documentId: String(item) };
8641
+ });
8642
+ return JSON.stringify(list);
8643
+ }
8644
+ return "";
8645
+ }
8646
+ case "media_single": {
8647
+ if (typeof value === "object" && value !== null) {
8648
+ return JSON.stringify({
8649
+ id: value.id,
8650
+ documentId: value.documentId,
8651
+ name: value.name,
8652
+ url: value.url,
8653
+ mime: value.mime
8654
+ });
8655
+ }
8656
+ return String(value);
8657
+ }
8658
+ case "media_to_many": {
8659
+ if (Array.isArray(value)) {
8660
+ const list = value.map((file) => {
8661
+ if (typeof file === "object" && file !== null) {
8662
+ return {
8663
+ id: file.id,
8664
+ documentId: file.documentId,
8665
+ name: file.name,
8666
+ url: file.url,
8667
+ mime: file.mime
8668
+ };
8669
+ }
8670
+ return file;
8671
+ });
8672
+ return JSON.stringify(list);
8673
+ }
8674
+ return "";
8675
+ }
8676
+ default:
8677
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
8678
+ }
8679
+ }
8680
+ function serializeDocumentsToCsv(strapi, uid, documents, options = {}) {
8681
+ const schema = options.schema || discoverSchema(strapi, uid);
8682
+ const exportMode = normalizeExportMode(options.exportMode);
8683
+ const plan = buildExportColumnPlan(strapi, uid, documents || [], { schema, exportMode });
8684
+ const headers = [METADATA_COLUMN_KEY, ...plan.headers];
8685
+ const lines = [];
8686
+ lines.push(headers.map(escapeCsvCell).join(","));
8687
+ const exportedAt = options.exportedAt || (/* @__PURE__ */ new Date()).toISOString();
8688
+ for (const doc of documents) {
8689
+ const rowValues = [];
8690
+ const flattenedMeta = extractRowFlattenedMetadata(plan, doc);
8691
+ const metadata = {
8692
+ schemaVersion: CURRENT_SCHEMA_VERSION,
8693
+ contentType: uid,
8694
+ documentId: String(doc.documentId || doc.id || ""),
8695
+ locale: doc.locale || void 0,
8696
+ exportedAt,
8697
+ ...flattenedMeta.exportMode ? { exportMode: flattenedMeta.exportMode } : {},
8698
+ ...flattenedMeta.targetObjectField ? { targetObjectField: flattenedMeta.targetObjectField } : {},
8699
+ ...flattenedMeta.targetObjectState ? { targetObjectState: flattenedMeta.targetObjectState } : {},
8700
+ ...flattenedMeta.applicableFields ? { applicableFields: flattenedMeta.applicableFields } : {},
8701
+ ...flattenedMeta.flatTypes ? { flatTypes: flattenedMeta.flatTypes } : {}
8702
+ };
8703
+ rowValues.push(escapeCsvCell(metadata));
8704
+ for (const col of plan.columns) {
8705
+ const cellValue = serializePlannedCell(col, doc, serializeFieldValue);
8706
+ rowValues.push(escapeCsvCell(cellValue));
8707
+ }
8708
+ lines.push(rowValues.join(","));
8709
+ }
8710
+ const csvContent = "\uFEFF" + lines.join("\r\n") + "\r\n";
8711
+ return {
8712
+ csvContent,
8713
+ headers,
8714
+ count: documents.length
8715
+ };
8716
+ }
8717
+ function extractMetadataFromRow(row) {
8718
+ if (!row || typeof row !== "object") return null;
8719
+ const rawMeta = row[METADATA_COLUMN_KEY] || row["__bulk_updater_metadata"];
8720
+ if (!rawMeta) return null;
8721
+ if (typeof rawMeta === "object") {
8722
+ return rawMeta;
8723
+ }
8724
+ if (typeof rawMeta === "string") {
8725
+ try {
8726
+ const parsed = JSON.parse(rawMeta);
8727
+ if (parsed && typeof parsed === "object") {
8728
+ return parsed;
8729
+ }
8730
+ } catch {
8731
+ }
8732
+ }
8733
+ return null;
8734
+ }
8735
+ function sanitizeUserErrorMessage(msg) {
8736
+ if (msg === null || msg === void 0) return "Error processing row";
8737
+ const raw = typeof msg === "string" ? msg : String(msg);
8738
+ const cleanedLines = raw.split(/\r?\n/).filter((line) => !/^\s+at\s+.+(\(.+\)|:\d+:\d+)\s*$/.test(line)).map((line) => line.trim()).filter(Boolean);
8739
+ const result = cleanedLines.join(" ").trim();
8740
+ return result || "Error processing row";
8741
+ }
8742
+ function resolveErrorColumnName(existingHeaders) {
8743
+ const existingLower = new Set(
8744
+ existingHeaders.map((h) => String(h || "").trim().toLowerCase())
8745
+ );
8746
+ if (!existingLower.has("error")) {
8747
+ return "Error";
8748
+ }
8749
+ if (!existingLower.has("import error")) {
8750
+ return "Import Error";
8751
+ }
8752
+ let suffix = 2;
8753
+ while (existingLower.has(`import error (${suffix})`)) {
8754
+ suffix++;
8755
+ }
8756
+ return `Import Error (${suffix})`;
8757
+ }
8758
+ function formatErrorCsvFilename(collectionTypeOrUid, date = /* @__PURE__ */ new Date()) {
8759
+ const rawSegment = collectionTypeOrUid ? String(collectionTypeOrUid).split(".").pop() || String(collectionTypeOrUid) : "collection";
8760
+ const safeType = rawSegment.replace(/[^a-zA-Z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "collection";
8761
+ const pad = (n) => String(n).padStart(2, "0");
8762
+ const stamp = `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}_${pad(
8763
+ date.getHours()
8764
+ )}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
8765
+ return `error_${safeType}_${stamp}.csv`;
8766
+ }
8767
+ function buildErrorCsv(options) {
8768
+ const { headers, failedRows } = options || {};
8769
+ if (!Array.isArray(failedRows) || failedRows.length === 0) {
8770
+ return {
8771
+ csvContent: "",
8772
+ headers: headers ? [...headers] : [],
8773
+ errorColumnName: "Error",
8774
+ errorCount: 0
8775
+ };
8776
+ }
8777
+ const groupedByRow = /* @__PURE__ */ new Map();
8778
+ for (const item of failedRows) {
8779
+ if (!item || typeof item !== "object") continue;
8780
+ const rowNum = typeof item.row === "number" && !isNaN(item.row) ? item.row : groupedByRow.size + 2;
8781
+ const msg = sanitizeUserErrorMessage(item.error);
8782
+ const existing = groupedByRow.get(rowNum);
8783
+ if (existing) {
8784
+ if (!existing.messages.includes(msg)) {
8785
+ existing.messages.push(msg);
8786
+ }
8787
+ } else {
8788
+ groupedByRow.set(rowNum, {
8789
+ row: rowNum,
8790
+ documentId: item.documentId,
8791
+ messages: [msg],
8792
+ originalRow: item.originalRow && typeof item.originalRow === "object" ? item.originalRow : {}
8793
+ });
8794
+ }
8795
+ }
8796
+ const orderedEntries = Array.from(groupedByRow.values()).sort((a, b) => a.row - b.row);
8797
+ if (orderedEntries.length === 0) {
8798
+ return {
8799
+ csvContent: "",
8800
+ headers: headers ? [...headers] : [],
8801
+ errorColumnName: "Error",
8802
+ errorCount: 0
8803
+ };
8804
+ }
8805
+ let baseHeaders = [];
8806
+ if (Array.isArray(headers) && headers.length > 0) {
8807
+ baseHeaders = [...headers];
8808
+ } else {
8809
+ const keySet = /* @__PURE__ */ new Set();
8810
+ for (const entry of orderedEntries) {
8811
+ for (const k of Object.keys(entry.originalRow || {})) {
8812
+ if (!keySet.has(k)) {
8813
+ keySet.add(k);
8814
+ baseHeaders.push(k);
8648
8815
  }
8649
- break;
8650
- }
8651
- case "relation_to_one":
8652
- case "relation_to_many": {
8653
- populate[fieldName] = true;
8654
- break;
8655
- }
8656
- case "media_single":
8657
- case "media_to_many": {
8658
- populate[fieldName] = true;
8659
- break;
8660
8816
  }
8661
8817
  }
8662
8818
  }
8663
- return Object.keys(populate).length > 0 ? populate : void 0;
8819
+ const errorColumnName = resolveErrorColumnName(baseHeaders);
8820
+ const finalHeaders = [...baseHeaders, errorColumnName];
8821
+ const lines = [];
8822
+ lines.push(finalHeaders.map(escapeCsvCell).join(","));
8823
+ for (const entry of orderedEntries) {
8824
+ const cells = baseHeaders.map((h) => {
8825
+ const val = entry.originalRow ? entry.originalRow[h] : "";
8826
+ return escapeCsvCell(val === void 0 || val === null ? "" : val);
8827
+ });
8828
+ cells.push(escapeCsvCell(entry.messages.join("; ")));
8829
+ lines.push(cells.join(","));
8830
+ }
8831
+ const csvContent = "\uFEFF" + lines.join("\r\n") + "\r\n";
8832
+ return {
8833
+ csvContent,
8834
+ headers: finalHeaders,
8835
+ errorColumnName,
8836
+ errorCount: orderedEntries.length
8837
+ };
8664
8838
  }
8665
8839
  function normalizeVal(val) {
8666
8840
  if (val === null || val === void 0) return null;
@@ -9238,13 +9412,44 @@ function formatValueDisplay(val) {
9238
9412
  }
9239
9413
  async function executeUpdateMutation(strapi, ct, uid, existing, row, rowNumber, options, effectiveLocale, isEditing, isDraftAndPublish, publishedCounterparts, stats, actionLabel = "Updated") {
9240
9414
  const resolvedDocId = existing.documentId;
9241
- const updatePayload = await buildDocumentUpdatePayload(
9415
+ const mutationPlan = await prepareCsvRowMutation(
9242
9416
  strapi,
9243
9417
  uid,
9244
9418
  existing,
9245
9419
  row,
9246
- { isPartialUpdate: options.mode === "update" }
9420
+ {
9421
+ isPartialUpdate: options.mode === "update",
9422
+ isCreate: false,
9423
+ expectedExportMode: options.expectedExportMode,
9424
+ docIdForError: resolvedDocId
9425
+ }
9247
9426
  );
9427
+ const updatePayload = mutationPlan.payload;
9428
+ if (mutationPlan.errors.length > 0) {
9429
+ const errMsg = mutationPlan.errors[0];
9430
+ stats.skipped++;
9431
+ if (stats.failed !== void 0) stats.failed++;
9432
+ recordFailedCsvRow(
9433
+ stats,
9434
+ rowNumber,
9435
+ row,
9436
+ errMsg,
9437
+ resolvedDocId,
9438
+ options.originalHeaders
9439
+ );
9440
+ stats.diffs.push({
9441
+ uid,
9442
+ collectionName: ct.info?.displayName || uid,
9443
+ documentId: resolvedDocId,
9444
+ label: existing.title || existing.name || `Entry #${resolvedDocId}`,
9445
+ attribute: mutationPlan.targetObjectField || "",
9446
+ oldValue: null,
9447
+ newValue: null,
9448
+ status: "error",
9449
+ message: errMsg
9450
+ });
9451
+ return;
9452
+ }
9248
9453
  if (Object.keys(updatePayload).length === 0) {
9249
9454
  stats.skipped++;
9250
9455
  stats.diffs.push({
@@ -9296,46 +9501,6 @@ async function executeUpdateMutation(strapi, ct, uid, existing, row, rowNumber,
9296
9501
  publishStrategy: options.publishStrategy || "safe",
9297
9502
  unreviewedConsent: options.unreviewedConsent
9298
9503
  });
9299
- const rowMeta = extractMetadataFromRow(row);
9300
- const schemaValidation = validateRecordSchemaConstraints(
9301
- strapi,
9302
- uid,
9303
- existing,
9304
- updatePayload,
9305
- row,
9306
- {
9307
- isCreate: false,
9308
- rowMeta: rowMeta ? {
9309
- applicableFields: rowMeta.applicableFields,
9310
- flatTypes: rowMeta.flatTypes
9311
- } : null
9312
- }
9313
- );
9314
- if (schemaValidation.errors.length > 0) {
9315
- const errMsg = schemaValidation.errors[0];
9316
- stats.skipped++;
9317
- if (stats.failed !== void 0) stats.failed++;
9318
- recordFailedCsvRow(
9319
- stats,
9320
- rowNumber,
9321
- row,
9322
- errMsg,
9323
- resolvedDocId,
9324
- options.originalHeaders
9325
- );
9326
- stats.diffs.push({
9327
- uid,
9328
- collectionName: ct.info?.displayName || uid,
9329
- documentId: resolvedDocId,
9330
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
9331
- attribute: "",
9332
- oldValue: null,
9333
- newValue: null,
9334
- status: "error",
9335
- message: errMsg
9336
- });
9337
- return;
9338
- }
9339
9504
  const proposedEntity = deepMergeEntities(existing, updatePayload);
9340
9505
  const valResult = await validateEntityQuotas(strapi, uid, proposedEntity);
9341
9506
  if (!valResult.isValid) {
@@ -9418,30 +9583,21 @@ async function executeUpdateMutation(strapi, ct, uid, existing, row, rowNumber,
9418
9583
  }
9419
9584
  }
9420
9585
  async function executeCreateMutation(strapi, ct, uid, docId, row, rowNumber, options, effectiveLocale, isEditing, isDraftAndPublish, stats) {
9421
- const createPayload = await buildDocumentUpdatePayload(
9422
- strapi,
9423
- uid,
9424
- null,
9425
- row,
9426
- { isPartialUpdate: false }
9427
- );
9428
- const rowMeta = extractMetadataFromRow(row);
9429
- const schemaValidation = validateRecordSchemaConstraints(
9586
+ const mutationPlan = await prepareCsvRowMutation(
9430
9587
  strapi,
9431
9588
  uid,
9432
9589
  null,
9433
- createPayload,
9434
9590
  row,
9435
9591
  {
9592
+ isPartialUpdate: false,
9436
9593
  isCreate: true,
9437
- rowMeta: rowMeta ? {
9438
- applicableFields: rowMeta.applicableFields,
9439
- flatTypes: rowMeta.flatTypes
9440
- } : null
9594
+ expectedExportMode: options.expectedExportMode,
9595
+ docIdForError: docId || `row-${rowNumber}`
9441
9596
  }
9442
9597
  );
9443
- if (schemaValidation.errors.length > 0) {
9444
- const errMsg = schemaValidation.errors[0];
9598
+ const createPayload = mutationPlan.payload;
9599
+ if (mutationPlan.errors.length > 0) {
9600
+ const errMsg = mutationPlan.errors[0];
9445
9601
  stats.skipped++;
9446
9602
  if (stats.failed !== void 0) stats.failed++;
9447
9603
  recordFailedCsvRow(
@@ -9567,6 +9723,40 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
9567
9723
  failedRows: [],
9568
9724
  diffs: []
9569
9725
  };
9726
+ const batchModeInfo = detectCsvBatchExportMode(rows);
9727
+ if (batchModeInfo.error) {
9728
+ for (let i = 0; i < rows.length; i++) {
9729
+ const rowNumber = startRowNumber + i;
9730
+ const row = rows[i];
9731
+ const docId = extractDocId(row);
9732
+ stats.skipped++;
9733
+ if (stats.failed !== void 0) stats.failed++;
9734
+ recordFailedCsvRow(
9735
+ stats,
9736
+ rowNumber,
9737
+ row,
9738
+ batchModeInfo.error,
9739
+ docId || void 0,
9740
+ originalHeaders
9741
+ );
9742
+ stats.diffs.push({
9743
+ uid,
9744
+ collectionName: ct.info?.displayName || uid,
9745
+ documentId: docId || `(Row #${rowNumber})`,
9746
+ label: `Row #${rowNumber}`,
9747
+ attribute: "__bulk_updater_metadata",
9748
+ oldValue: null,
9749
+ newValue: null,
9750
+ status: "error",
9751
+ message: batchModeInfo.error
9752
+ });
9753
+ }
9754
+ return stats;
9755
+ }
9756
+ const rowOptions = {
9757
+ ...options,
9758
+ expectedExportMode: batchModeInfo.mode
9759
+ };
9570
9760
  for (let i = 0; i < rows.length; i++) {
9571
9761
  const rowNumber = startRowNumber + i;
9572
9762
  const row = rows[i];
@@ -9619,7 +9809,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
9619
9809
  existing,
9620
9810
  row,
9621
9811
  rowNumber,
9622
- options,
9812
+ rowOptions,
9623
9813
  effectiveLocale,
9624
9814
  isEditing,
9625
9815
  isDraftAndPublish,
@@ -9640,7 +9830,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
9640
9830
  existing,
9641
9831
  row,
9642
9832
  rowNumber,
9643
- options,
9833
+ rowOptions,
9644
9834
  effectiveLocale,
9645
9835
  isEditing,
9646
9836
  isDraftAndPublish,
@@ -9656,7 +9846,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
9656
9846
  docId,
9657
9847
  row,
9658
9848
  rowNumber,
9659
- options,
9849
+ rowOptions,
9660
9850
  effectiveLocale,
9661
9851
  isEditing,
9662
9852
  isDraftAndPublish,
@@ -9676,7 +9866,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
9676
9866
  existing,
9677
9867
  row,
9678
9868
  rowNumber,
9679
- options,
9869
+ rowOptions,
9680
9870
  effectiveLocale,
9681
9871
  isEditing,
9682
9872
  isDraftAndPublish,
@@ -9692,7 +9882,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
9692
9882
  docId,
9693
9883
  row,
9694
9884
  rowNumber,
9695
- options,
9885
+ rowOptions,
9696
9886
  effectiveLocale,
9697
9887
  isEditing,
9698
9888
  isDraftAndPublish,
@@ -9873,6 +10063,7 @@ const csvService = ({ strapi }) => ({
9873
10063
  }
9874
10064
  const schema = discoverSchema(strapi, uid);
9875
10065
  const deepPopulate = buildLosslessPopulate(strapi, uid);
10066
+ const exportMode = normalizeExportMode(options.exportMode);
9876
10067
  const filterMeta = buildCollectionQueryFilters(strapi, ct, {
9877
10068
  attribute: options.attribute,
9878
10069
  searchAttribute: options.searchAttribute || options.attribute,
@@ -9882,12 +10073,13 @@ const csvService = ({ strapi }) => ({
9882
10073
  documentIds: options.documentIds
9883
10074
  });
9884
10075
  if (!filterMeta.colHasAttribute && filterMeta.normOp && filterMeta.normOp !== "none") {
9885
- const emptySerialized = serializeDocumentsToCsv(strapi, uid, [], { schema });
10076
+ const emptySerialized = serializeDocumentsToCsv(strapi, uid, [], { schema, exportMode });
9886
10077
  return {
9887
10078
  filename: `${ct.info?.singularName || uid}_export_${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`,
9888
10079
  csvContent: emptySerialized.csvContent,
9889
10080
  count: 0,
9890
- fields: emptySerialized.headers
10081
+ fields: emptySerialized.headers,
10082
+ exportMode
9891
10083
  };
9892
10084
  }
9893
10085
  const filters = filterMeta.filters;
@@ -9998,13 +10190,18 @@ const csvService = ({ strapi }) => ({
9998
10190
  await new Promise((resolve) => setImmediate(resolve));
9999
10191
  }
10000
10192
  }
10001
- const serialized = serializeDocumentsToCsv(strapi, uid, exportedDocs, { exportedAt, schema });
10193
+ const serialized = serializeDocumentsToCsv(strapi, uid, exportedDocs, {
10194
+ exportedAt,
10195
+ schema,
10196
+ exportMode
10197
+ });
10002
10198
  const filename = `${ct.info?.singularName || uid}_export_${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`;
10003
10199
  return {
10004
10200
  filename,
10005
10201
  csvContent: serialized.csvContent,
10006
10202
  count: serialized.count,
10007
- fields: serialized.headers
10203
+ fields: serialized.headers,
10204
+ exportMode
10008
10205
  };
10009
10206
  },
10010
10207
  async exportViolationsCsv(ruleId) {
@@ -10379,6 +10576,28 @@ const csvService = ({ strapi }) => ({
10379
10576
  };
10380
10577
  const errors2 = [];
10381
10578
  const warnings = [];
10579
+ const batchModeInfo = detectCsvBatchExportMode(rows);
10580
+ if (batchModeInfo.error) {
10581
+ errors2.push({
10582
+ row: 1,
10583
+ error: batchModeInfo.error
10584
+ });
10585
+ return {
10586
+ success: true,
10587
+ detectedExportMode: "invalid",
10588
+ totalRows: rows.length,
10589
+ validRows: 0,
10590
+ estimatedUpdates: 0,
10591
+ estimatedCreates: 0,
10592
+ lifecycleStats,
10593
+ hasErrors: true,
10594
+ hasWarnings: false,
10595
+ errors: errors2,
10596
+ warnings: [],
10597
+ totalErrorCount: errors2.length,
10598
+ totalWarningCount: 0
10599
+ };
10600
+ }
10382
10601
  const docIdsInPreflight = rows.map((r) => extractDocId(r)).filter(Boolean);
10383
10602
  const publishedCounterparts = /* @__PURE__ */ new Map();
10384
10603
  if (isDraftAndPublish && docIdsInPreflight.length > 0) {
@@ -10541,49 +10760,46 @@ const csvService = ({ strapi }) => ({
10541
10760
  }
10542
10761
  }
10543
10762
  }
10544
- let proposedPayload = {};
10545
- try {
10546
- proposedPayload = await buildDocumentUpdatePayload(
10547
- strapi,
10548
- uid,
10549
- existing,
10550
- row,
10551
- { isPartialUpdate: mode === "update" }
10552
- );
10553
- } catch {
10554
- }
10555
- const rowMeta = extractMetadataFromRow(row);
10556
10763
  const isRowCreate = mode === "create_or_override" ? !existing : !existing && mode !== "update";
10764
+ let proposedPayload = {};
10557
10765
  if (!(mode === "update" && (!docId || !existing))) {
10558
- const schemaValidation = validateRecordSchemaConstraints(
10559
- strapi,
10560
- uid,
10561
- existing,
10562
- proposedPayload,
10563
- row,
10564
- {
10565
- isCreate: isRowCreate,
10566
- rowMeta: rowMeta ? {
10567
- applicableFields: rowMeta.applicableFields,
10568
- flatTypes: rowMeta.flatTypes
10569
- } : null
10766
+ try {
10767
+ const mutationPlan = await prepareCsvRowMutation(
10768
+ strapi,
10769
+ uid,
10770
+ existing,
10771
+ row,
10772
+ {
10773
+ isPartialUpdate: mode === "update",
10774
+ isCreate: isRowCreate,
10775
+ expectedExportMode: batchModeInfo.mode,
10776
+ docIdForError: docId || `row-${rowNumber}`
10777
+ }
10778
+ );
10779
+ proposedPayload = mutationPlan.payload;
10780
+ for (const errStr of mutationPlan.errors) {
10781
+ errors2.push({
10782
+ row: rowNumber,
10783
+ documentId: docId || void 0,
10784
+ error: errStr
10785
+ });
10786
+ rowHasError = true;
10570
10787
  }
10571
- );
10572
- for (const errStr of schemaValidation.errors) {
10788
+ for (const warnStr of mutationPlan.warnings) {
10789
+ warnings.push({
10790
+ row: rowNumber,
10791
+ documentId: docId || void 0,
10792
+ warning: warnStr
10793
+ });
10794
+ }
10795
+ } catch (prepErr) {
10573
10796
  errors2.push({
10574
10797
  row: rowNumber,
10575
10798
  documentId: docId || void 0,
10576
- error: errStr
10799
+ error: prepErr?.message || "Failed to reconstruct CSV payload."
10577
10800
  });
10578
10801
  rowHasError = true;
10579
10802
  }
10580
- for (const warnStr of schemaValidation.warnings) {
10581
- warnings.push({
10582
- row: rowNumber,
10583
- documentId: docId || void 0,
10584
- warning: warnStr
10585
- });
10586
- }
10587
10803
  }
10588
10804
  if (activeRules.length > 0) {
10589
10805
  const proposedEntity = existing ? deepMergeEntities(existing, proposedPayload) : proposedPayload;
@@ -10603,6 +10819,7 @@ const csvService = ({ strapi }) => ({
10603
10819
  }
10604
10820
  return {
10605
10821
  success: true,
10822
+ detectedExportMode: batchModeInfo.mode,
10606
10823
  totalRows: rows.length,
10607
10824
  validRows,
10608
10825
  estimatedUpdates,
@@ -10627,6 +10844,37 @@ const csvService = ({ strapi }) => ({
10627
10844
  }
10628
10845
  const attrs = ct.attributes || {};
10629
10846
  const { mode = "auto" } = options;
10847
+ const batchModeInfo = detectCsvBatchExportMode(rows);
10848
+ if (batchModeInfo.error) {
10849
+ return {
10850
+ success: true,
10851
+ detectedExportMode: "invalid",
10852
+ summary: {
10853
+ total: rows.length,
10854
+ willUpdate: 0,
10855
+ willCreate: 0,
10856
+ unchanged: 0,
10857
+ skipped: rows.length
10858
+ },
10859
+ diffs: [
10860
+ {
10861
+ uid,
10862
+ collectionName: ct.info?.displayName || uid,
10863
+ documentId: "(batch)",
10864
+ label: "CSV Export Mode Check",
10865
+ attribute: "__bulk_updater_metadata",
10866
+ oldValue: null,
10867
+ newValue: null,
10868
+ oldDisplay: "—",
10869
+ newDisplay: "—",
10870
+ hasChange: false,
10871
+ status: "error",
10872
+ action: "skip",
10873
+ message: batchModeInfo.error
10874
+ }
10875
+ ]
10876
+ };
10877
+ }
10630
10878
  const diffs = [];
10631
10879
  let willUpdateCount = 0;
10632
10880
  let willCreateCount = 0;
@@ -10672,13 +10920,39 @@ const csvService = ({ strapi }) => ({
10672
10920
  });
10673
10921
  continue;
10674
10922
  }
10675
- const payload = await buildDocumentUpdatePayload(
10923
+ const isRowCreate = !existing;
10924
+ const mutationPlan = await prepareCsvRowMutation(
10676
10925
  strapi,
10677
10926
  uid,
10678
10927
  existing,
10679
10928
  row,
10680
- { isPartialUpdate: mode === "update" }
10929
+ {
10930
+ isPartialUpdate: mode === "update",
10931
+ isCreate: isRowCreate,
10932
+ expectedExportMode: batchModeInfo.mode,
10933
+ docIdForError: docId || `row-${rowNumber}`
10934
+ }
10681
10935
  );
10936
+ if (mutationPlan.errors.length > 0) {
10937
+ skippedCount++;
10938
+ diffs.push({
10939
+ uid,
10940
+ collectionName: ct.info?.displayName || uid,
10941
+ documentId: existing?.documentId || docId || `(Row #${rowNumber})`,
10942
+ label: existing?.title || existing?.name || existing?.slug || `Row #${rowNumber}`,
10943
+ attribute: mutationPlan.targetObjectField || "(validation)",
10944
+ oldValue: null,
10945
+ newValue: null,
10946
+ oldDisplay: "—",
10947
+ newDisplay: "—",
10948
+ hasChange: false,
10949
+ status: "error",
10950
+ action: "skip",
10951
+ message: mutationPlan.errors.join(" | ")
10952
+ });
10953
+ continue;
10954
+ }
10955
+ const payload = mutationPlan.payload;
10682
10956
  if (existing) {
10683
10957
  const resolvedDocId = existing.documentId || docId;
10684
10958
  const entryLabel = existing.title || existing.name || existing.slug || `Entry #${resolvedDocId}`;
@@ -10781,6 +11055,7 @@ const csvService = ({ strapi }) => ({
10781
11055
  }
10782
11056
  return {
10783
11057
  success: true,
11058
+ detectedExportMode: batchModeInfo.mode,
10784
11059
  summary: {
10785
11060
  total: rows.length,
10786
11061
  willUpdate: willUpdateCount,
@@ -11259,6 +11534,8 @@ const index = {
11259
11534
  export {
11260
11535
  CURRENT_SCHEMA_VERSION,
11261
11536
  EXPLICIT_CLEAR_TOKENS,
11537
+ EXPLICIT_DELETE_KEY_TOKEN,
11538
+ EXPLICIT_EMPTY_STRING_TOKEN,
11262
11539
  FORBIDDEN_OBJECT_KEYS,
11263
11540
  METADATA_COLUMN_KEY,
11264
11541
  SYSTEM_ATTRIBUTES,
@@ -11268,13 +11545,14 @@ export {
11268
11545
  buildErrorCsv,
11269
11546
  buildExportColumnPlan,
11270
11547
  buildLosslessPopulate,
11271
- buildNestedComponentPatchFromDots,
11272
11548
  buildRichAttributeMeta,
11273
11549
  classifyAttribute,
11274
11550
  coerceAndValidateFieldValue,
11275
11551
  deepCloneValue,
11552
+ deepEqualValues,
11276
11553
  deepMergeEntities,
11277
11554
  index as default,
11555
+ detectCsvBatchExportMode,
11278
11556
  discoverComponentFields,
11279
11557
  discoverSchema,
11280
11558
  enumerateOccurrences,
@@ -11284,27 +11562,28 @@ export {
11284
11562
  extractRowFlattenedMetadata,
11285
11563
  formatErrorCsvFilename,
11286
11564
  getAllNestedValues,
11287
- getValueAtPath,
11565
+ inspectRowMetadataMode,
11288
11566
  isPlainObject,
11289
11567
  isValidDocumentId,
11568
+ normalizeExportMode,
11290
11569
  parseBoolean,
11291
11570
  parseCsvToMatrix,
11292
11571
  parseCsvToRecords,
11293
- parseFlattenedLeafValue,
11572
+ parseFirstLevelCellValue,
11294
11573
  parseNumeric,
11295
- reconstructFlattenedJsonAttribute,
11574
+ prepareCsvRowMutation,
11575
+ reconstructTargetedFirstLevelObject,
11296
11576
  resolveBatchTargets,
11297
11577
  resolveComponentPayload,
11298
11578
  resolveDynamicZonePayload,
11299
11579
  resolveErrorColumnName,
11300
11580
  resolveMediaIds,
11301
11581
  resolveRelationPayload,
11582
+ resolveTargetObjectField,
11302
11583
  sanitizeUserErrorMessage,
11303
11584
  serializeDocumentsToCsv,
11304
11585
  serializeFieldValue,
11305
- serializeFlattenedLeafValue,
11306
11586
  serializePlannedCell,
11307
- setValueAtPath,
11308
11587
  sortAuditRecordsDesc,
11309
11588
  validateEntityQuotas,
11310
11589
  validateRecordSchemaConstraints,