strapi-plugin-bulk-updater 1.6.0 → 1.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_chunks/{BulkUpdater-D12SUhTd.js → BulkUpdater-DTJLdJJy.js} +344 -169
- package/dist/_chunks/BulkUpdater-DTJLdJJy.js.map +1 -0
- package/dist/_chunks/{BulkUpdater-CTKfvKhE.mjs → BulkUpdater-xj4wH_iI.mjs} +345 -170
- package/dist/_chunks/BulkUpdater-xj4wH_iI.mjs.map +1 -0
- package/dist/admin/index.js +1 -1
- package/dist/admin/index.mjs +1 -1
- package/dist/server/index.js +2367 -1587
- package/dist/server/index.js.map +1 -1
- package/dist/server/index.mjs +2367 -1587
- package/dist/server/index.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/_chunks/BulkUpdater-CTKfvKhE.mjs.map +0 -1
- package/dist/_chunks/BulkUpdater-D12SUhTd.js.map +0 -1
package/dist/server/index.js
CHANGED
|
@@ -1732,1021 +1732,2085 @@ function discoverSchema(strapi, uid) {
|
|
|
1732
1732
|
allExportKeys
|
|
1733
1733
|
};
|
|
1734
1734
|
}
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
if (
|
|
1739
|
-
if (
|
|
1740
|
-
|
|
1735
|
+
const EXPLICIT_CLEAR_TOKENS = /* @__PURE__ */ new Set(["__CLEAR__", "__NULL__"]);
|
|
1736
|
+
const FORBIDDEN_OBJECT_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
1737
|
+
function isPlainObject(val) {
|
|
1738
|
+
if (val === null || typeof val !== "object" || Array.isArray(val)) return false;
|
|
1739
|
+
if (val instanceof Date || val instanceof RegExp) return false;
|
|
1740
|
+
const proto = Object.getPrototypeOf(val);
|
|
1741
|
+
return proto === Object.prototype || proto === null;
|
|
1741
1742
|
}
|
|
1742
|
-
function
|
|
1743
|
-
if (
|
|
1744
|
-
|
|
1745
|
-
if (isInteger) {
|
|
1746
|
-
const n = parseInt(cleanStr, 10);
|
|
1747
|
-
return isNaN(n) ? null : n;
|
|
1743
|
+
function deepCloneValue(val) {
|
|
1744
|
+
if (val === null || val === void 0 || typeof val !== "object") {
|
|
1745
|
+
return val;
|
|
1748
1746
|
}
|
|
1749
|
-
|
|
1750
|
-
|
|
1747
|
+
if (val instanceof Date) {
|
|
1748
|
+
return new Date(val.getTime());
|
|
1749
|
+
}
|
|
1750
|
+
if (Array.isArray(val)) {
|
|
1751
|
+
return val.map((item) => deepCloneValue(item));
|
|
1752
|
+
}
|
|
1753
|
+
if (isPlainObject(val)) {
|
|
1754
|
+
const out = {};
|
|
1755
|
+
for (const [k, v] of Object.entries(val)) {
|
|
1756
|
+
if (FORBIDDEN_OBJECT_KEYS.has(k)) continue;
|
|
1757
|
+
out[k] = deepCloneValue(v);
|
|
1758
|
+
}
|
|
1759
|
+
return out;
|
|
1760
|
+
}
|
|
1761
|
+
return val;
|
|
1751
1762
|
}
|
|
1752
|
-
function
|
|
1753
|
-
|
|
1754
|
-
const s = String(rawVal).trim().toLowerCase();
|
|
1755
|
-
if (s === "true" || s === "1" || s === "yes" || s === "y" || s === "on") return true;
|
|
1756
|
-
if (s === "false" || s === "0" || s === "no" || s === "n" || s === "off") return false;
|
|
1757
|
-
return null;
|
|
1763
|
+
function isSafePathSegment(segment) {
|
|
1764
|
+
return Boolean(segment) && !FORBIDDEN_OBJECT_KEYS.has(segment);
|
|
1758
1765
|
}
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
const trimmed = rawVal.trim();
|
|
1766
|
-
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
1767
|
-
try {
|
|
1768
|
-
parsed = JSON.parse(trimmed);
|
|
1769
|
-
} catch {
|
|
1770
|
-
}
|
|
1766
|
+
function getValueAtPath(rootObj, pathSegments) {
|
|
1767
|
+
let cursor = rootObj;
|
|
1768
|
+
for (let i = 0; i < pathSegments.length; i++) {
|
|
1769
|
+
const seg = pathSegments[i];
|
|
1770
|
+
if (!isSafePathSegment(seg) || cursor === null || cursor === void 0 || typeof cursor !== "object") {
|
|
1771
|
+
return { exists: false, value: void 0 };
|
|
1771
1772
|
}
|
|
1773
|
+
if (Array.isArray(cursor) || !Object.prototype.hasOwnProperty.call(cursor, seg)) {
|
|
1774
|
+
return { exists: false, value: void 0 };
|
|
1775
|
+
}
|
|
1776
|
+
cursor = cursor[seg];
|
|
1772
1777
|
}
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1778
|
+
return { exists: true, value: cursor };
|
|
1779
|
+
}
|
|
1780
|
+
function setValueAtPath(target, pathSegments, value) {
|
|
1781
|
+
if (pathSegments.length === 0) return;
|
|
1782
|
+
let cursor = target;
|
|
1783
|
+
for (let i = 0; i < pathSegments.length - 1; i++) {
|
|
1784
|
+
const seg = pathSegments[i];
|
|
1785
|
+
if (!isSafePathSegment(seg)) return;
|
|
1786
|
+
if (!isPlainObject(cursor[seg])) {
|
|
1787
|
+
cursor[seg] = {};
|
|
1788
|
+
}
|
|
1789
|
+
cursor = cursor[seg];
|
|
1790
|
+
}
|
|
1791
|
+
const leafKey = pathSegments[pathSegments.length - 1];
|
|
1792
|
+
if (!isSafePathSegment(leafKey)) return;
|
|
1793
|
+
cursor[leafKey] = value;
|
|
1794
|
+
}
|
|
1795
|
+
function classifyLeafType(val) {
|
|
1796
|
+
if (val === null) return "null";
|
|
1797
|
+
if (Array.isArray(val)) return "array";
|
|
1798
|
+
if (isPlainObject(val)) return "object";
|
|
1799
|
+
if (typeof val === "number") return "number";
|
|
1800
|
+
if (typeof val === "boolean") return "boolean";
|
|
1801
|
+
return "string";
|
|
1802
|
+
}
|
|
1803
|
+
function needsTypeAnnotation(val) {
|
|
1804
|
+
if (val === null) return true;
|
|
1805
|
+
if (Array.isArray(val) || isPlainObject(val)) return true;
|
|
1806
|
+
if (typeof val === "number" || typeof val === "boolean") return true;
|
|
1807
|
+
if (typeof val === "string") {
|
|
1808
|
+
const trimmed = val.trim();
|
|
1809
|
+
if (val === "" || trimmed === "null" || trimmed === "true" || trimmed === "false" || trimmed.startsWith("[") || trimmed.startsWith("{") || /^-?\d+(?:\.\d+)?$/.test(trimmed)) {
|
|
1810
|
+
return true;
|
|
1780
1811
|
}
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1812
|
+
}
|
|
1813
|
+
return false;
|
|
1814
|
+
}
|
|
1815
|
+
function collectDynamicPlainObjectPaths(values, baseSegments, blockedRootNames) {
|
|
1816
|
+
const leafPaths = [];
|
|
1817
|
+
const seenJoined = /* @__PURE__ */ new Set();
|
|
1818
|
+
let hasAnyNonNullValue = false;
|
|
1819
|
+
for (const val of values) {
|
|
1820
|
+
if (val === null || val === void 0) continue;
|
|
1821
|
+
hasAnyNonNullValue = true;
|
|
1822
|
+
if (!isPlainObject(val)) {
|
|
1823
|
+
return { canFlatten: false, paths: [] };
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
if (!hasAnyNonNullValue) {
|
|
1827
|
+
return { canFlatten: false, paths: [] };
|
|
1828
|
+
}
|
|
1829
|
+
const walk = (node, relSegments, seenObjects) => {
|
|
1830
|
+
if (relSegments.length > 25 || seenObjects.has(node)) return;
|
|
1831
|
+
seenObjects.add(node);
|
|
1832
|
+
for (const [key, child] of Object.entries(node)) {
|
|
1833
|
+
if (!isSafePathSegment(key) || key.includes(".")) {
|
|
1834
|
+
continue;
|
|
1793
1835
|
}
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1836
|
+
const nextRel = [...relSegments, key];
|
|
1837
|
+
const fullPath = [...baseSegments, ...nextRel].join(".");
|
|
1838
|
+
if (blockedRootNames.has(fullPath)) continue;
|
|
1839
|
+
if (isPlainObject(child)) {
|
|
1840
|
+
const childKeys = Object.keys(child).filter((ck) => isSafePathSegment(ck) && !ck.includes("."));
|
|
1841
|
+
if (childKeys.length === 0) {
|
|
1842
|
+
if (!seenJoined.has(fullPath)) {
|
|
1843
|
+
seenJoined.add(fullPath);
|
|
1844
|
+
leafPaths.push(nextRel);
|
|
1845
|
+
}
|
|
1846
|
+
} else {
|
|
1847
|
+
if (seenJoined.has(fullPath)) {
|
|
1848
|
+
seenJoined.delete(fullPath);
|
|
1849
|
+
const idx = leafPaths.findIndex((p) => [...baseSegments, ...p].join(".") === fullPath);
|
|
1850
|
+
if (idx >= 0) leafPaths.splice(idx, 1);
|
|
1851
|
+
}
|
|
1852
|
+
walk(child, nextRel, seenObjects);
|
|
1853
|
+
}
|
|
1854
|
+
} else {
|
|
1855
|
+
if (!seenJoined.has(fullPath)) {
|
|
1856
|
+
seenJoined.add(fullPath);
|
|
1857
|
+
leafPaths.push(nextRel);
|
|
1858
|
+
}
|
|
1797
1859
|
}
|
|
1798
1860
|
}
|
|
1799
|
-
|
|
1800
|
-
if (/^\d+$/.test(str)) {
|
|
1801
|
-
numericIds.push(parseInt(str, 10));
|
|
1802
|
-
} else if (str) {
|
|
1803
|
-
candidateLookups.push(str);
|
|
1804
|
-
}
|
|
1861
|
+
seenObjects.delete(node);
|
|
1805
1862
|
};
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1863
|
+
for (const val of values) {
|
|
1864
|
+
if (isPlainObject(val)) {
|
|
1865
|
+
walk(val, [], /* @__PURE__ */ new WeakSet());
|
|
1809
1866
|
}
|
|
1810
|
-
}
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1867
|
+
}
|
|
1868
|
+
return { canFlatten: leafPaths.length > 0, paths: leafPaths };
|
|
1869
|
+
}
|
|
1870
|
+
function collectComponentExportColumns(strapi, compUid, baseSegments, documents, blockedRootNames, visitedComps) {
|
|
1871
|
+
const comp = strapi.components?.[compUid];
|
|
1872
|
+
if (!comp?.attributes || visitedComps.has(compUid)) {
|
|
1873
|
+
return [];
|
|
1874
|
+
}
|
|
1875
|
+
const nextVisited = new Set(visitedComps);
|
|
1876
|
+
nextVisited.add(compUid);
|
|
1877
|
+
const rootKey = baseSegments[0];
|
|
1878
|
+
const result = [];
|
|
1879
|
+
for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
|
|
1880
|
+
if (!isSafePathSegment(attrName)) continue;
|
|
1881
|
+
const norm = attrName.toLowerCase().replace(/[\s_-]/g, "");
|
|
1882
|
+
if (SYSTEM_ATTRIBUTES.has(norm) || attrName === "id" || attrName === "__component") continue;
|
|
1883
|
+
const attrType = String(attrDef?.type || "").toLowerCase();
|
|
1884
|
+
const nextSegments = [...baseSegments, attrName];
|
|
1885
|
+
const header = nextSegments.join(".");
|
|
1886
|
+
if (blockedRootNames.has(header)) continue;
|
|
1887
|
+
if (attrType === "component" && !attrDef.repeatable && attrDef.component) {
|
|
1888
|
+
const nested = collectComponentExportColumns(
|
|
1889
|
+
strapi,
|
|
1890
|
+
attrDef.component,
|
|
1891
|
+
nextSegments,
|
|
1892
|
+
documents,
|
|
1893
|
+
blockedRootNames,
|
|
1894
|
+
nextVisited
|
|
1895
|
+
);
|
|
1896
|
+
if (nested.length > 0) {
|
|
1897
|
+
result.push(...nested);
|
|
1898
|
+
} else {
|
|
1899
|
+
result.push({
|
|
1900
|
+
header,
|
|
1901
|
+
kind: "flattened_component_leaf",
|
|
1902
|
+
rootKey,
|
|
1903
|
+
pathSegments: nextSegments,
|
|
1904
|
+
componentSubDef: attrDef
|
|
1905
|
+
});
|
|
1906
|
+
}
|
|
1907
|
+
} else if (attrType === "json") {
|
|
1908
|
+
const vals = documents.map((d) => getValueAtPath(d, nextSegments).value);
|
|
1909
|
+
const { canFlatten, paths } = collectDynamicPlainObjectPaths(vals, nextSegments, blockedRootNames);
|
|
1910
|
+
if (canFlatten) {
|
|
1911
|
+
for (const relPath of paths) {
|
|
1912
|
+
const fullSegments = [...nextSegments, ...relPath];
|
|
1913
|
+
result.push({
|
|
1914
|
+
header: fullSegments.join("."),
|
|
1915
|
+
kind: "flattened_component_leaf",
|
|
1916
|
+
rootKey,
|
|
1917
|
+
pathSegments: fullSegments,
|
|
1918
|
+
componentSubDef: { type: "json_leaf" }
|
|
1919
|
+
});
|
|
1920
|
+
}
|
|
1921
|
+
} else {
|
|
1922
|
+
result.push({
|
|
1923
|
+
header,
|
|
1924
|
+
kind: "flattened_component_leaf",
|
|
1925
|
+
rootKey,
|
|
1926
|
+
pathSegments: nextSegments,
|
|
1927
|
+
componentSubDef: attrDef
|
|
1928
|
+
});
|
|
1929
|
+
}
|
|
1930
|
+
} else {
|
|
1931
|
+
result.push({
|
|
1932
|
+
header,
|
|
1933
|
+
kind: "flattened_component_leaf",
|
|
1934
|
+
rootKey,
|
|
1935
|
+
pathSegments: nextSegments,
|
|
1936
|
+
componentSubDef: attrDef
|
|
1937
|
+
});
|
|
1816
1938
|
}
|
|
1817
|
-
} else {
|
|
1818
|
-
inspectItem(parsed);
|
|
1819
1939
|
}
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1940
|
+
return result;
|
|
1941
|
+
}
|
|
1942
|
+
function buildExportColumnPlan(strapi, uid, documents, schemaOverride) {
|
|
1943
|
+
const schema = schemaOverride || discoverSchema(strapi, uid);
|
|
1944
|
+
const topLevelNames = new Set(schema.allExportKeys);
|
|
1945
|
+
const columns = [];
|
|
1946
|
+
const flattenedJsonRoots = /* @__PURE__ */ new Set();
|
|
1947
|
+
const flattenedComponentRoots = /* @__PURE__ */ new Set();
|
|
1948
|
+
for (const key of schema.allExportKeys) {
|
|
1949
|
+
if (key === "documentId" || key === "locale") {
|
|
1950
|
+
columns.push({
|
|
1951
|
+
header: key,
|
|
1952
|
+
kind: "system",
|
|
1953
|
+
rootKey: key,
|
|
1954
|
+
pathSegments: [key]
|
|
1955
|
+
});
|
|
1956
|
+
continue;
|
|
1957
|
+
}
|
|
1958
|
+
const field = schema.fields[key];
|
|
1959
|
+
if (!field) {
|
|
1960
|
+
columns.push({
|
|
1961
|
+
header: key,
|
|
1962
|
+
kind: "field",
|
|
1963
|
+
rootKey: key,
|
|
1964
|
+
pathSegments: [key]
|
|
1965
|
+
});
|
|
1966
|
+
continue;
|
|
1967
|
+
}
|
|
1968
|
+
if (field.category === "json") {
|
|
1969
|
+
const values = documents.map((d) => d?.[key]);
|
|
1970
|
+
const { canFlatten, paths } = collectDynamicPlainObjectPaths(values, [key], topLevelNames);
|
|
1971
|
+
if (canFlatten) {
|
|
1972
|
+
flattenedJsonRoots.add(key);
|
|
1973
|
+
for (const relPath of paths) {
|
|
1974
|
+
const fullSegments = [key, ...relPath];
|
|
1975
|
+
columns.push({
|
|
1976
|
+
header: fullSegments.join("."),
|
|
1977
|
+
kind: "flattened_json_leaf",
|
|
1978
|
+
rootKey: key,
|
|
1979
|
+
pathSegments: fullSegments,
|
|
1980
|
+
field
|
|
1835
1981
|
});
|
|
1836
|
-
if (found?.id) {
|
|
1837
|
-
numericIds.push(found.id);
|
|
1838
|
-
}
|
|
1839
1982
|
}
|
|
1983
|
+
continue;
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
if (field.category === "component_single" && field.componentUid) {
|
|
1987
|
+
const compColumns = collectComponentExportColumns(
|
|
1988
|
+
strapi,
|
|
1989
|
+
field.componentUid,
|
|
1990
|
+
[key],
|
|
1991
|
+
documents,
|
|
1992
|
+
topLevelNames,
|
|
1993
|
+
/* @__PURE__ */ new Set()
|
|
1994
|
+
);
|
|
1995
|
+
if (compColumns.length > 0) {
|
|
1996
|
+
flattenedComponentRoots.add(key);
|
|
1997
|
+
columns.push(...compColumns);
|
|
1998
|
+
continue;
|
|
1840
1999
|
}
|
|
1841
|
-
} catch {
|
|
1842
2000
|
}
|
|
2001
|
+
columns.push({
|
|
2002
|
+
header: key,
|
|
2003
|
+
kind: "field",
|
|
2004
|
+
rootKey: key,
|
|
2005
|
+
pathSegments: [key],
|
|
2006
|
+
field
|
|
2007
|
+
});
|
|
1843
2008
|
}
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
2009
|
+
return {
|
|
2010
|
+
columns,
|
|
2011
|
+
headers: columns.map((c) => c.header),
|
|
2012
|
+
flattenedJsonRoots,
|
|
2013
|
+
flattenedComponentRoots
|
|
2014
|
+
};
|
|
2015
|
+
}
|
|
2016
|
+
function extractRowFlattenedMetadata(plan, doc) {
|
|
2017
|
+
const applicableFields = [];
|
|
2018
|
+
const flatTypes = {};
|
|
2019
|
+
const flattenedRoots = /* @__PURE__ */ new Set([
|
|
2020
|
+
...plan.flattenedJsonRoots,
|
|
2021
|
+
...plan.flattenedComponentRoots
|
|
2022
|
+
]);
|
|
2023
|
+
for (const rootKey of flattenedRoots) {
|
|
2024
|
+
const val = doc?.[rootKey];
|
|
2025
|
+
if (val !== null && val !== void 0) {
|
|
2026
|
+
applicableFields.push(rootKey);
|
|
2027
|
+
if (plan.flattenedJsonRoots.has(rootKey) && isPlainObject(val) && Object.keys(val).length === 0) {
|
|
2028
|
+
flatTypes[rootKey] = "object";
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
1847
2031
|
}
|
|
1848
|
-
|
|
2032
|
+
for (const col of plan.columns) {
|
|
2033
|
+
if (col.kind !== "flattened_json_leaf") continue;
|
|
2034
|
+
const { exists, value } = getValueAtPath(doc, col.pathSegments);
|
|
2035
|
+
if (!exists || value === void 0) continue;
|
|
2036
|
+
if (needsTypeAnnotation(value)) {
|
|
2037
|
+
flatTypes[col.header] = classifyLeafType(value);
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
const out = {};
|
|
2041
|
+
if (flattenedRoots.size > 0) {
|
|
2042
|
+
out.applicableFields = applicableFields;
|
|
2043
|
+
}
|
|
2044
|
+
if (Object.keys(flatTypes).length > 0) {
|
|
2045
|
+
out.flatTypes = flatTypes;
|
|
2046
|
+
}
|
|
2047
|
+
return out;
|
|
1849
2048
|
}
|
|
1850
|
-
function
|
|
1851
|
-
if (
|
|
1852
|
-
|
|
2049
|
+
function serializeFlattenedLeafValue(val) {
|
|
2050
|
+
if (val === void 0 || val === null) return "";
|
|
2051
|
+
if (val instanceof Date) return val.toISOString();
|
|
2052
|
+
if (Array.isArray(val) || isPlainObject(val)) {
|
|
2053
|
+
return JSON.stringify(val);
|
|
2054
|
+
}
|
|
2055
|
+
if (typeof val === "boolean") return val ? "true" : "false";
|
|
2056
|
+
if (typeof val === "number") return Number.isFinite(val) ? String(val) : "";
|
|
2057
|
+
return String(val);
|
|
2058
|
+
}
|
|
2059
|
+
function serializePlannedCell(col, doc, serializeFieldFallback) {
|
|
2060
|
+
if (col.kind === "system") {
|
|
2061
|
+
if (col.header === "documentId") return doc?.documentId || doc?.id || "";
|
|
2062
|
+
if (col.header === "locale") return doc?.locale || "";
|
|
2063
|
+
return doc?.[col.header] ?? "";
|
|
2064
|
+
}
|
|
2065
|
+
if (col.kind === "flattened_json_leaf") {
|
|
2066
|
+
const { exists, value } = getValueAtPath(doc, col.pathSegments);
|
|
2067
|
+
if (!exists) return "";
|
|
2068
|
+
if (isPlainObject(value) && Object.keys(value).length === 0) return "";
|
|
2069
|
+
return serializeFlattenedLeafValue(value);
|
|
2070
|
+
}
|
|
2071
|
+
if (col.kind === "flattened_component_leaf") {
|
|
2072
|
+
const { exists, value } = getValueAtPath(doc, col.pathSegments);
|
|
2073
|
+
if (!exists || value === void 0 || value === null) return "";
|
|
2074
|
+
const subDef = col.componentSubDef || {};
|
|
2075
|
+
const subType = String(subDef.type || "").toLowerCase();
|
|
2076
|
+
if (subType === "media") {
|
|
2077
|
+
return serializeFieldFallback(value, {
|
|
2078
|
+
key: col.header,
|
|
2079
|
+
label: col.header,
|
|
2080
|
+
category: subDef.multiple ? "media_to_many" : "media_single",
|
|
2081
|
+
rawType: "media",
|
|
2082
|
+
multiple: Boolean(subDef.multiple)
|
|
2083
|
+
});
|
|
2084
|
+
}
|
|
2085
|
+
if (subType === "relation") {
|
|
2086
|
+
const isToMany = String(subDef.relation || "").toLowerCase().endsWith("many");
|
|
2087
|
+
return serializeFieldFallback(value, {
|
|
2088
|
+
key: col.header,
|
|
2089
|
+
label: col.header,
|
|
2090
|
+
category: isToMany ? "relation_to_many" : "relation_to_one",
|
|
2091
|
+
rawType: "relation",
|
|
2092
|
+
relationType: subDef.relation
|
|
2093
|
+
});
|
|
2094
|
+
}
|
|
2095
|
+
if (subType === "component" && subDef.repeatable) {
|
|
2096
|
+
return Array.isArray(value) ? JSON.stringify(value) : "";
|
|
2097
|
+
}
|
|
2098
|
+
if (subType === "blocks" || subType === "json") {
|
|
2099
|
+
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
2100
|
+
}
|
|
2101
|
+
return serializeFlattenedLeafValue(value);
|
|
1853
2102
|
}
|
|
1854
|
-
|
|
1855
|
-
if (
|
|
1856
|
-
|
|
1857
|
-
|
|
2103
|
+
const rawValue = doc?.[col.rootKey];
|
|
2104
|
+
if (col.field) {
|
|
2105
|
+
return serializeFieldFallback(rawValue, col.field);
|
|
2106
|
+
}
|
|
2107
|
+
return rawValue;
|
|
2108
|
+
}
|
|
2109
|
+
function parseFlattenedLeafValue(rawCell, annotatedType, existingLeafValue) {
|
|
2110
|
+
if (rawCell === null || rawCell === void 0) return null;
|
|
2111
|
+
if (typeof rawCell !== "string") return rawCell;
|
|
2112
|
+
const trimmed = rawCell.trim();
|
|
2113
|
+
if (EXPLICIT_CLEAR_TOKENS.has(trimmed)) {
|
|
2114
|
+
return null;
|
|
2115
|
+
}
|
|
2116
|
+
if (annotatedType === "string") {
|
|
2117
|
+
return rawCell;
|
|
2118
|
+
}
|
|
2119
|
+
if (annotatedType === "number" || typeof existingLeafValue === "number") {
|
|
2120
|
+
if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
|
|
2121
|
+
const num = Number(trimmed);
|
|
2122
|
+
if (Number.isFinite(num)) return num;
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
if (annotatedType === "boolean" || typeof existingLeafValue === "boolean") {
|
|
2126
|
+
const low = trimmed.toLowerCase();
|
|
2127
|
+
if (low === "true") return true;
|
|
2128
|
+
if (low === "false") return false;
|
|
2129
|
+
}
|
|
2130
|
+
if (annotatedType === "array" || Array.isArray(existingLeafValue)) {
|
|
2131
|
+
if (trimmed.startsWith("[")) {
|
|
1858
2132
|
try {
|
|
1859
|
-
|
|
2133
|
+
return JSON.parse(trimmed);
|
|
1860
2134
|
} catch {
|
|
1861
2135
|
}
|
|
1862
2136
|
}
|
|
1863
2137
|
}
|
|
1864
|
-
if (
|
|
1865
|
-
if (
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
return isToMany ? { set: [String(singleDocId).trim()] } : { set: [String(singleDocId).trim()] };
|
|
2138
|
+
if (annotatedType === "object" || isPlainObject(existingLeafValue)) {
|
|
2139
|
+
if (trimmed.startsWith("{")) {
|
|
2140
|
+
try {
|
|
2141
|
+
return JSON.parse(trimmed);
|
|
2142
|
+
} catch {
|
|
2143
|
+
}
|
|
1871
2144
|
}
|
|
1872
2145
|
}
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
if (id && isValidDocumentId(String(id))) {
|
|
1879
|
-
docIds.push(String(id).trim());
|
|
1880
|
-
}
|
|
1881
|
-
} else if (isValidDocumentId(String(item))) {
|
|
1882
|
-
docIds.push(String(item).trim());
|
|
2146
|
+
if (typeof existingLeafValue === "string") {
|
|
2147
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
2148
|
+
try {
|
|
2149
|
+
return JSON.parse(trimmed);
|
|
2150
|
+
} catch {
|
|
1883
2151
|
}
|
|
1884
2152
|
}
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
2153
|
+
return rawCell;
|
|
2154
|
+
}
|
|
2155
|
+
if (trimmed === "null") return null;
|
|
2156
|
+
if (trimmed === "true") return true;
|
|
2157
|
+
if (trimmed === "false") return false;
|
|
2158
|
+
if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
|
|
2159
|
+
const num = Number(trimmed);
|
|
2160
|
+
if (Number.isFinite(num)) return num;
|
|
2161
|
+
}
|
|
2162
|
+
if (trimmed.startsWith("[") && trimmed.endsWith("]") || trimmed.startsWith("{") && trimmed.endsWith("}")) {
|
|
2163
|
+
try {
|
|
2164
|
+
return JSON.parse(trimmed);
|
|
2165
|
+
} catch {
|
|
1891
2166
|
}
|
|
1892
2167
|
}
|
|
1893
|
-
|
|
1894
|
-
return { set: uniqueDocIds };
|
|
2168
|
+
return rawCell;
|
|
1895
2169
|
}
|
|
1896
|
-
|
|
1897
|
-
const
|
|
1898
|
-
|
|
1899
|
-
|
|
2170
|
+
function reconstructFlattenedJsonAttribute(params) {
|
|
2171
|
+
const {
|
|
2172
|
+
attrName,
|
|
2173
|
+
existingVal,
|
|
2174
|
+
hasDirectKey,
|
|
2175
|
+
directRawVal,
|
|
2176
|
+
dotEntries,
|
|
2177
|
+
rowMeta,
|
|
2178
|
+
isPartialUpdate
|
|
2179
|
+
} = params;
|
|
2180
|
+
const hasExistingPlainObj = isPlainObject(existingVal);
|
|
2181
|
+
const directTrimmed = typeof directRawVal === "string" ? directRawVal.trim() : "";
|
|
2182
|
+
if (dotEntries.length === 0) {
|
|
2183
|
+
if (!hasDirectKey) return { shouldSet: false, value: void 0 };
|
|
2184
|
+
if (EXPLICIT_CLEAR_TOKENS.has(directTrimmed) || directTrimmed === "null") {
|
|
2185
|
+
return { shouldSet: true, value: null };
|
|
2186
|
+
}
|
|
2187
|
+
if (directRawVal === "" || directRawVal === void 0 || directRawVal === null) {
|
|
2188
|
+
return { shouldSet: false, value: void 0 };
|
|
2189
|
+
}
|
|
2190
|
+
if (typeof directRawVal === "string") {
|
|
2191
|
+
try {
|
|
2192
|
+
return { shouldSet: true, value: JSON.parse(directRawVal) };
|
|
2193
|
+
} catch {
|
|
2194
|
+
return { shouldSet: true, value: directRawVal };
|
|
2195
|
+
}
|
|
2196
|
+
}
|
|
2197
|
+
return { shouldSet: true, value: directRawVal };
|
|
1900
2198
|
}
|
|
1901
|
-
let
|
|
1902
|
-
|
|
2199
|
+
let baseObj = hasExistingPlainObj ? deepCloneValue(existingVal) : null;
|
|
2200
|
+
let hasEffectiveChange = false;
|
|
2201
|
+
if (hasDirectKey && directRawVal !== "" && directRawVal !== void 0 && directRawVal !== null) {
|
|
2202
|
+
if (EXPLICIT_CLEAR_TOKENS.has(directTrimmed) || directTrimmed === "null") {
|
|
2203
|
+
return { shouldSet: true, value: null };
|
|
2204
|
+
}
|
|
1903
2205
|
try {
|
|
1904
|
-
|
|
2206
|
+
const parsedDirect = typeof directRawVal === "string" ? JSON.parse(directRawVal) : directRawVal;
|
|
2207
|
+
if (isPlainObject(parsedDirect)) {
|
|
2208
|
+
baseObj = { ...baseObj || {}, ...deepCloneValue(parsedDirect) };
|
|
2209
|
+
hasEffectiveChange = true;
|
|
2210
|
+
} else {
|
|
2211
|
+
return { shouldSet: true, value: parsedDirect };
|
|
2212
|
+
}
|
|
1905
2213
|
} catch {
|
|
1906
|
-
return
|
|
2214
|
+
return { shouldSet: true, value: directRawVal };
|
|
1907
2215
|
}
|
|
1908
|
-
} else if (typeof rawVal === "object" && rawVal !== null) {
|
|
1909
|
-
sourceObj = rawVal;
|
|
1910
|
-
} else {
|
|
1911
|
-
return existingVal || {};
|
|
1912
2216
|
}
|
|
1913
|
-
const
|
|
1914
|
-
|
|
1915
|
-
if (
|
|
1916
|
-
|
|
2217
|
+
for (const [fullKey, rawCell] of dotEntries) {
|
|
2218
|
+
const prefix = `${attrName}.`;
|
|
2219
|
+
if (!fullKey.startsWith(prefix)) continue;
|
|
2220
|
+
const relPathStr = fullKey.slice(prefix.length);
|
|
2221
|
+
const relSegments = relPathStr.split(".").filter(Boolean);
|
|
2222
|
+
if (relSegments.length === 0 || relSegments.some((s) => !isSafePathSegment(s))) {
|
|
1917
2223
|
continue;
|
|
1918
2224
|
}
|
|
1919
|
-
const
|
|
1920
|
-
const
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
2225
|
+
const strCell = rawCell === null || rawCell === void 0 ? "" : String(rawCell);
|
|
2226
|
+
const trimmed = strCell.trim();
|
|
2227
|
+
const annotatedType = rowMeta?.flatTypes?.[fullKey];
|
|
2228
|
+
if (EXPLICIT_CLEAR_TOKENS.has(trimmed)) {
|
|
2229
|
+
if (!baseObj) baseObj = {};
|
|
2230
|
+
setValueAtPath(baseObj, relSegments, null);
|
|
2231
|
+
hasEffectiveChange = true;
|
|
2232
|
+
continue;
|
|
2233
|
+
}
|
|
2234
|
+
if (strCell === "") {
|
|
2235
|
+
if (hasExistingPlainObj && annotatedType && (annotatedType === "string" || annotatedType === "null" || annotatedType === "object")) {
|
|
2236
|
+
const existingAtPath = getValueAtPath(existingVal, relSegments);
|
|
2237
|
+
if (existingAtPath.exists) {
|
|
2238
|
+
if (annotatedType === "object" && isPlainObject(existingAtPath.value)) {
|
|
2239
|
+
if (!isPartialUpdate) hasEffectiveChange = true;
|
|
2240
|
+
} else if (annotatedType === "null" && existingAtPath.value === null) {
|
|
2241
|
+
if (!isPartialUpdate) hasEffectiveChange = true;
|
|
2242
|
+
} else if (annotatedType === "string" && existingAtPath.value === "") {
|
|
2243
|
+
if (!isPartialUpdate) hasEffectiveChange = true;
|
|
2244
|
+
}
|
|
1928
2245
|
}
|
|
1929
|
-
result[attrName] = cleanedList;
|
|
1930
|
-
} else {
|
|
1931
|
-
result[attrName] = await resolveComponentPayload(
|
|
1932
|
-
strapi,
|
|
1933
|
-
attrDef.component,
|
|
1934
|
-
fieldVal,
|
|
1935
|
-
existingVal?.[attrName] || {}
|
|
1936
|
-
);
|
|
1937
|
-
}
|
|
1938
|
-
} else if (type === "relation") {
|
|
1939
|
-
const isToMany = String(attrDef.relation || "").toLowerCase().endsWith("many");
|
|
1940
|
-
result[attrName] = resolveRelationPayload(fieldVal, isToMany);
|
|
1941
|
-
} else if (type === "media") {
|
|
1942
|
-
result[attrName] = await resolveMediaIds(strapi, fieldVal, Boolean(attrDef.multiple));
|
|
1943
|
-
} else if (type === "integer" || type === "biginteger") {
|
|
1944
|
-
result[attrName] = parseNumeric(fieldVal, true);
|
|
1945
|
-
} else if (type === "float" || type === "decimal") {
|
|
1946
|
-
result[attrName] = parseNumeric(fieldVal, false);
|
|
1947
|
-
} else if (type === "boolean") {
|
|
1948
|
-
result[attrName] = parseBoolean(fieldVal);
|
|
1949
|
-
} else if (type === "json" || type === "blocks") {
|
|
1950
|
-
if (typeof fieldVal === "string") {
|
|
1951
|
-
try {
|
|
1952
|
-
result[attrName] = JSON.parse(fieldVal);
|
|
1953
|
-
} catch {
|
|
1954
|
-
result[attrName] = fieldVal;
|
|
1955
|
-
}
|
|
1956
|
-
} else {
|
|
1957
|
-
result[attrName] = fieldVal;
|
|
1958
2246
|
}
|
|
1959
|
-
|
|
1960
|
-
result[attrName] = fieldVal === null || fieldVal === void 0 ? null : String(fieldVal);
|
|
2247
|
+
continue;
|
|
1961
2248
|
}
|
|
2249
|
+
const existingLeaf = hasExistingPlainObj ? getValueAtPath(existingVal, relSegments).value : void 0;
|
|
2250
|
+
const parsedVal = parseFlattenedLeafValue(strCell, annotatedType, existingLeaf);
|
|
2251
|
+
if (!baseObj) baseObj = {};
|
|
2252
|
+
setValueAtPath(baseObj, relSegments, parsedVal);
|
|
2253
|
+
hasEffectiveChange = true;
|
|
1962
2254
|
}
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
let list = [];
|
|
1967
|
-
if (typeof rawVal === "string") {
|
|
1968
|
-
try {
|
|
1969
|
-
list = JSON.parse(rawVal);
|
|
1970
|
-
} catch {
|
|
1971
|
-
return existingVal || [];
|
|
2255
|
+
if (!hasEffectiveChange) {
|
|
2256
|
+
if (!isPartialUpdate && hasExistingPlainObj && (rowMeta?.applicableFields?.includes(attrName) || rowMeta?.flatTypes?.[attrName] === "object")) {
|
|
2257
|
+
return { shouldSet: true, value: deepCloneValue(existingVal) };
|
|
1972
2258
|
}
|
|
1973
|
-
|
|
1974
|
-
list = rawVal;
|
|
1975
|
-
} else {
|
|
1976
|
-
return existingVal || [];
|
|
2259
|
+
return { shouldSet: false, value: void 0 };
|
|
1977
2260
|
}
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
2261
|
+
return { shouldSet: true, value: baseObj || {} };
|
|
2262
|
+
}
|
|
2263
|
+
function buildNestedComponentPatchFromDots(attrName, dotEntries) {
|
|
2264
|
+
const patch = {};
|
|
2265
|
+
let hasEffectiveEdits = false;
|
|
2266
|
+
const prefix = `${attrName}.`;
|
|
2267
|
+
for (const [fullKey, rawCell] of dotEntries) {
|
|
2268
|
+
if (!fullKey.startsWith(prefix)) continue;
|
|
2269
|
+
const relPathStr = fullKey.slice(prefix.length);
|
|
2270
|
+
const relSegments = relPathStr.split(".").filter(Boolean);
|
|
2271
|
+
if (relSegments.length === 0 || relSegments.some((s) => !isSafePathSegment(s))) {
|
|
1985
2272
|
continue;
|
|
1986
2273
|
}
|
|
1987
|
-
if (
|
|
2274
|
+
if (rawCell === void 0 || rawCell === null || rawCell === "") {
|
|
1988
2275
|
continue;
|
|
1989
2276
|
}
|
|
1990
|
-
const
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
async function buildDocumentUpdatePayload(strapi, uid, existingDoc, rawRow, options = {}) {
|
|
1997
|
-
const schema = discoverSchema(strapi, uid);
|
|
1998
|
-
const payload = {};
|
|
1999
|
-
const unescapedRow = {};
|
|
2000
|
-
for (const [k, v] of Object.entries(rawRow)) {
|
|
2001
|
-
let cleanVal = v;
|
|
2002
|
-
if (typeof cleanVal === "string" && /^'[=+@-]/.test(cleanVal)) {
|
|
2003
|
-
cleanVal = cleanVal.substring(1);
|
|
2277
|
+
const strCell = String(rawCell);
|
|
2278
|
+
const trimmed = strCell.trim();
|
|
2279
|
+
if (EXPLICIT_CLEAR_TOKENS.has(trimmed)) {
|
|
2280
|
+
setValueAtPath(patch, relSegments, null);
|
|
2281
|
+
hasEffectiveEdits = true;
|
|
2282
|
+
continue;
|
|
2004
2283
|
}
|
|
2005
|
-
|
|
2284
|
+
setValueAtPath(patch, relSegments, strCell);
|
|
2285
|
+
hasEffectiveEdits = true;
|
|
2006
2286
|
}
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2287
|
+
return { hasEffectiveEdits, patch };
|
|
2288
|
+
}
|
|
2289
|
+
function resolveDottedComponentAttrDef(strapi, rootDef, segments) {
|
|
2290
|
+
if (!rootDef || segments.length === 0) return null;
|
|
2291
|
+
if (segments.length === 1) return rootDef;
|
|
2292
|
+
if (rootDef.type === "component" && !rootDef.repeatable && rootDef.component) {
|
|
2293
|
+
const comp = strapi.components?.[rootDef.component];
|
|
2294
|
+
if (!comp?.attributes) return null;
|
|
2295
|
+
const nextAttr = comp.attributes[segments[1]];
|
|
2296
|
+
if (!nextAttr) return null;
|
|
2297
|
+
return resolveDottedComponentAttrDef(strapi, nextAttr, segments.slice(1));
|
|
2015
2298
|
}
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
if (
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
} else {
|
|
2041
|
-
payload[attrName] = trimmed;
|
|
2042
|
-
}
|
|
2043
|
-
} else {
|
|
2044
|
-
payload[attrName] = String(rawVal).trim();
|
|
2045
|
-
}
|
|
2046
|
-
break;
|
|
2047
|
-
}
|
|
2048
|
-
case "blocks": {
|
|
2049
|
-
if (rawVal === void 0 || rawVal === "" || rawVal === null) {
|
|
2050
|
-
payload[attrName] = [];
|
|
2051
|
-
} else {
|
|
2052
|
-
try {
|
|
2053
|
-
const parsed = JSON.parse(rawVal);
|
|
2054
|
-
payload[attrName] = Array.isArray(parsed) ? parsed : [parsed];
|
|
2055
|
-
} catch {
|
|
2056
|
-
payload[attrName] = [
|
|
2057
|
-
{ type: "paragraph", children: [{ type: "text", text: String(rawVal).trim() }] }
|
|
2058
|
-
];
|
|
2059
|
-
}
|
|
2060
|
-
}
|
|
2061
|
-
break;
|
|
2062
|
-
}
|
|
2063
|
-
case "json": {
|
|
2064
|
-
if (rawVal === void 0 || rawVal === "" || rawVal === null) {
|
|
2065
|
-
payload[attrName] = null;
|
|
2066
|
-
} else {
|
|
2067
|
-
try {
|
|
2068
|
-
payload[attrName] = JSON.parse(rawVal);
|
|
2069
|
-
} catch {
|
|
2070
|
-
payload[attrName] = rawVal;
|
|
2071
|
-
}
|
|
2072
|
-
}
|
|
2073
|
-
break;
|
|
2074
|
-
}
|
|
2075
|
-
case "component_single": {
|
|
2076
|
-
if (field.componentUid) {
|
|
2077
|
-
let compInput = rawVal;
|
|
2078
|
-
if (hasDotKeys) {
|
|
2079
|
-
compInput = { ...existingDoc?.[attrName] || {}, ...dotNotationMap[attrName] };
|
|
2080
|
-
}
|
|
2081
|
-
if (compInput === "" || compInput === null) {
|
|
2082
|
-
payload[attrName] = null;
|
|
2083
|
-
} else {
|
|
2084
|
-
payload[attrName] = await resolveComponentPayload(
|
|
2085
|
-
strapi,
|
|
2086
|
-
field.componentUid,
|
|
2087
|
-
compInput,
|
|
2088
|
-
existingDoc?.[attrName] || {}
|
|
2089
|
-
);
|
|
2090
|
-
}
|
|
2091
|
-
}
|
|
2092
|
-
break;
|
|
2093
|
-
}
|
|
2094
|
-
case "component_repeatable": {
|
|
2095
|
-
if (field.componentUid) {
|
|
2096
|
-
if (rawVal === "" || rawVal === null || rawVal === void 0) {
|
|
2097
|
-
payload[attrName] = [];
|
|
2098
|
-
} else {
|
|
2099
|
-
let list = [];
|
|
2100
|
-
try {
|
|
2101
|
-
list = typeof rawVal === "string" ? JSON.parse(rawVal) : rawVal;
|
|
2102
|
-
} catch {
|
|
2299
|
+
return null;
|
|
2300
|
+
}
|
|
2301
|
+
function validateRecordSchemaConstraints(strapi, uid, existingDoc, payload, rawRow, options) {
|
|
2302
|
+
const ct = strapi.contentTypes?.[uid];
|
|
2303
|
+
if (!ct) return { errors: [], warnings: [] };
|
|
2304
|
+
const attrs = ct.attributes || {};
|
|
2305
|
+
const errors = [];
|
|
2306
|
+
const warnings = [];
|
|
2307
|
+
const applicableList = Array.isArray(options.rowMeta?.applicableFields) ? new Set(options.rowMeta.applicableFields) : null;
|
|
2308
|
+
const isMissingRequiredValue = (val) => val === void 0 || val === null || typeof val === "string" && val.trim() === "";
|
|
2309
|
+
for (const [colKey, rawVal] of Object.entries(rawRow)) {
|
|
2310
|
+
if (rawVal === void 0 || rawVal === null) continue;
|
|
2311
|
+
const strVal = String(rawVal);
|
|
2312
|
+
const trimmed = strVal.trim();
|
|
2313
|
+
if (!trimmed || EXPLICIT_CLEAR_TOKENS.has(trimmed)) continue;
|
|
2314
|
+
if (colKey.includes(".")) {
|
|
2315
|
+
const segments = colKey.split(".").filter(Boolean);
|
|
2316
|
+
const rootAttr = attrs[segments[0]];
|
|
2317
|
+
if (rootAttr?.type === "component" && !rootAttr.repeatable) {
|
|
2318
|
+
const subDef = resolveDottedComponentAttrDef(strapi, rootAttr, segments);
|
|
2319
|
+
if (subDef) {
|
|
2320
|
+
if (subDef.type === "integer" || subDef.type === "biginteger") {
|
|
2321
|
+
if (!/^-?\d+$/.test(trimmed)) {
|
|
2322
|
+
errors.push(`Column "${colKey}" expects an integer, received: "${rawVal}"`);
|
|
2103
2323
|
}
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
cleanedItems.push(cleaned);
|
|
2114
|
-
}
|
|
2115
|
-
payload[attrName] = cleanedItems;
|
|
2116
|
-
} else {
|
|
2117
|
-
payload[attrName] = [];
|
|
2324
|
+
} else if (subDef.type === "float" || subDef.type === "decimal") {
|
|
2325
|
+
if (isNaN(Number(trimmed))) {
|
|
2326
|
+
errors.push(`Column "${colKey}" expects a numeric float/decimal, received: "${rawVal}"`);
|
|
2327
|
+
}
|
|
2328
|
+
} else if (subDef.type === "enumeration" && Array.isArray(subDef.enum)) {
|
|
2329
|
+
if (!subDef.enum.includes(trimmed)) {
|
|
2330
|
+
warnings.push(
|
|
2331
|
+
`Column "${colKey}" value "${rawVal}" is not in defined enum options: [${subDef.enum.join(", ")}]`
|
|
2332
|
+
);
|
|
2118
2333
|
}
|
|
2119
2334
|
}
|
|
2120
2335
|
}
|
|
2121
|
-
break;
|
|
2122
|
-
}
|
|
2123
|
-
case "dynamiczone": {
|
|
2124
|
-
const allowedComponents = field.dzComponents || [];
|
|
2125
|
-
if (rawVal === "" || rawVal === null || rawVal === void 0) {
|
|
2126
|
-
payload[attrName] = [];
|
|
2127
|
-
} else {
|
|
2128
|
-
payload[attrName] = await resolveDynamicZonePayload(
|
|
2129
|
-
strapi,
|
|
2130
|
-
allowedComponents,
|
|
2131
|
-
rawVal,
|
|
2132
|
-
existingDoc?.[attrName] || []
|
|
2133
|
-
);
|
|
2134
|
-
}
|
|
2135
|
-
break;
|
|
2136
2336
|
}
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
for (const [attrName, attrDef] of Object.entries(attrs)) {
|
|
2340
|
+
if (!attrDef?.required) continue;
|
|
2341
|
+
const norm = attrName.toLowerCase().replace(/[\s_-]/g, "");
|
|
2342
|
+
if (SYSTEM_ATTRIBUTES.has(norm)) continue;
|
|
2343
|
+
if (options.isCreate) {
|
|
2344
|
+
if (applicableList && !applicableList.has(attrName) && payload[attrName] === void 0) {
|
|
2345
|
+
continue;
|
|
2140
2346
|
}
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
break;
|
|
2347
|
+
if (isMissingRequiredValue(payload[attrName])) {
|
|
2348
|
+
errors.push(`Missing mandatory field "${attrName}".`);
|
|
2144
2349
|
}
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2350
|
+
} else if (attrName in payload && isMissingRequiredValue(payload[attrName])) {
|
|
2351
|
+
errors.push(`Mandatory field "${attrName}" cannot be empty or cleared.`);
|
|
2352
|
+
}
|
|
2353
|
+
}
|
|
2354
|
+
const validateComponentRequired = (compUid, valueObj, pathPrefix) => {
|
|
2355
|
+
const comp = strapi.components?.[compUid];
|
|
2356
|
+
if (!comp?.attributes || !isPlainObject(valueObj)) return;
|
|
2357
|
+
for (const [subKey, subDef] of Object.entries(comp.attributes)) {
|
|
2358
|
+
const subPath = `${pathPrefix}.${subKey}`;
|
|
2359
|
+
const subVal = valueObj[subKey];
|
|
2360
|
+
if (subDef?.required && isMissingRequiredValue(subVal)) {
|
|
2361
|
+
errors.push(`Missing mandatory field "${subPath}".`);
|
|
2148
2362
|
}
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
break;
|
|
2363
|
+
if (subDef?.type === "component" && !subDef.repeatable && subDef.component && isPlainObject(subVal)) {
|
|
2364
|
+
validateComponentRequired(subDef.component, subVal, subPath);
|
|
2152
2365
|
}
|
|
2153
|
-
default:
|
|
2154
|
-
payload[attrName] = rawVal;
|
|
2155
2366
|
}
|
|
2156
|
-
}
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
}
|
|
2164
|
-
function parseAttrPath(path) {
|
|
2165
|
-
if (!path) return { cleanPath: "", rootKey: "", subPath: "" };
|
|
2166
|
-
const bracketMatch = path.match(/^([^.[]+)\[([^\]]+)\](?:\.(.+))?$/);
|
|
2167
|
-
if (bracketMatch) {
|
|
2168
|
-
const rootKey = bracketMatch[1];
|
|
2169
|
-
const selector = bracketMatch[2].trim();
|
|
2170
|
-
const subPath = bracketMatch[3] || "";
|
|
2171
|
-
const cleanPath = subPath ? `${rootKey}.${subPath}` : rootKey;
|
|
2172
|
-
const numMatch = selector.match(/^#?(\d+)/);
|
|
2173
|
-
if (numMatch) {
|
|
2174
|
-
return { cleanPath, rootKey, subPath, targetIndex: parseInt(numMatch[1], 10) };
|
|
2367
|
+
};
|
|
2368
|
+
for (const [attrName, attrDef] of Object.entries(attrs)) {
|
|
2369
|
+
if (attrDef?.type === "component" && !attrDef.repeatable && attrDef.component) {
|
|
2370
|
+
const nextCompVal = payload[attrName];
|
|
2371
|
+
if (isPlainObject(nextCompVal)) {
|
|
2372
|
+
validateComponentRequired(attrDef.component, nextCompVal, attrName);
|
|
2373
|
+
} else if (nextCompVal === void 0 && isPlainObject(existingDoc?.[attrName]) && (applicableList === null || applicableList.has(attrName))) ;
|
|
2175
2374
|
}
|
|
2176
|
-
return { cleanPath, rootKey, subPath, targetComponentUid: selector };
|
|
2177
2375
|
}
|
|
2178
|
-
|
|
2179
|
-
return {
|
|
2180
|
-
cleanPath: path,
|
|
2181
|
-
rootKey: parts[0] || "",
|
|
2182
|
-
subPath: parts.slice(1).join(".")
|
|
2183
|
-
};
|
|
2376
|
+
return { errors, warnings };
|
|
2184
2377
|
}
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2378
|
+
const METADATA_COLUMN_KEY = "__bulk_updater_metadata";
|
|
2379
|
+
const CURRENT_SCHEMA_VERSION = 1;
|
|
2380
|
+
function escapeCsvCell(val) {
|
|
2381
|
+
if (val === null || val === void 0) return "";
|
|
2382
|
+
let str = "";
|
|
2383
|
+
if (val instanceof Date) {
|
|
2384
|
+
str = val.toISOString();
|
|
2385
|
+
} else if (typeof val === "object") {
|
|
2386
|
+
str = JSON.stringify(val);
|
|
2387
|
+
} else {
|
|
2388
|
+
str = String(val);
|
|
2188
2389
|
}
|
|
2189
|
-
|
|
2190
|
-
if (
|
|
2191
|
-
|
|
2390
|
+
str = str.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
2391
|
+
if (/^[=+@-]/.test(str)) {
|
|
2392
|
+
str = `'${str}`;
|
|
2192
2393
|
}
|
|
2193
|
-
if (
|
|
2194
|
-
|
|
2195
|
-
...attrDef.options.scope !== void 0 ? { scope: attrDef.options.scope } : {},
|
|
2196
|
-
...attrDef.options.disabledBehavior !== void 0 ? { disabledBehavior: attrDef.options.disabledBehavior } : {},
|
|
2197
|
-
...attrDef.options.quotas ? { quotas: { ...attrDef.options.quotas } } : {},
|
|
2198
|
-
...Array.isArray(attrDef.options.items) ? { items: attrDef.options.items.map((it) => ({ ...it })) } : {}
|
|
2199
|
-
};
|
|
2394
|
+
if (str.includes(",") || str.includes('"') || str.includes("\n") || str.includes("\r")) {
|
|
2395
|
+
return `"${str.replace(/"/g, '""')}"`;
|
|
2200
2396
|
}
|
|
2201
|
-
|
|
2202
|
-
|
|
2397
|
+
return str;
|
|
2398
|
+
}
|
|
2399
|
+
function parseCsvToMatrix(csvText) {
|
|
2400
|
+
if (!csvText) return [];
|
|
2401
|
+
let text = csvText;
|
|
2402
|
+
if (text.charCodeAt(0) === 65279) {
|
|
2403
|
+
text = text.slice(1);
|
|
2203
2404
|
}
|
|
2204
|
-
|
|
2205
|
-
|
|
2405
|
+
const rows = [];
|
|
2406
|
+
let currentRow = [];
|
|
2407
|
+
let currentCell = "";
|
|
2408
|
+
let inQuotes = false;
|
|
2409
|
+
let cellIsQuoted = false;
|
|
2410
|
+
for (let i = 0; i < text.length; i++) {
|
|
2411
|
+
const char = text[i];
|
|
2412
|
+
const nextChar = text[i + 1];
|
|
2413
|
+
if (inQuotes) {
|
|
2414
|
+
if (char === '"') {
|
|
2415
|
+
if (nextChar === '"') {
|
|
2416
|
+
currentCell += '"';
|
|
2417
|
+
i++;
|
|
2418
|
+
} else {
|
|
2419
|
+
inQuotes = false;
|
|
2420
|
+
}
|
|
2421
|
+
} else {
|
|
2422
|
+
currentCell += char;
|
|
2423
|
+
}
|
|
2424
|
+
} else {
|
|
2425
|
+
if (char === '"' && !cellIsQuoted && currentCell.trim() === "") {
|
|
2426
|
+
inQuotes = true;
|
|
2427
|
+
cellIsQuoted = true;
|
|
2428
|
+
currentCell = "";
|
|
2429
|
+
} else if (char === ",") {
|
|
2430
|
+
currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
|
|
2431
|
+
currentCell = "";
|
|
2432
|
+
cellIsQuoted = false;
|
|
2433
|
+
} else if (char === "\r") {
|
|
2434
|
+
if (nextChar === "\n") {
|
|
2435
|
+
i++;
|
|
2436
|
+
}
|
|
2437
|
+
currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
|
|
2438
|
+
if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
|
|
2439
|
+
rows.push(currentRow);
|
|
2440
|
+
}
|
|
2441
|
+
currentRow = [];
|
|
2442
|
+
currentCell = "";
|
|
2443
|
+
cellIsQuoted = false;
|
|
2444
|
+
} else if (char === "\n") {
|
|
2445
|
+
currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
|
|
2446
|
+
if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
|
|
2447
|
+
rows.push(currentRow);
|
|
2448
|
+
}
|
|
2449
|
+
currentRow = [];
|
|
2450
|
+
currentCell = "";
|
|
2451
|
+
cellIsQuoted = false;
|
|
2452
|
+
} else {
|
|
2453
|
+
if (!(cellIsQuoted && !inQuotes && (char === " " || char === " "))) {
|
|
2454
|
+
currentCell += char;
|
|
2455
|
+
}
|
|
2456
|
+
}
|
|
2457
|
+
}
|
|
2206
2458
|
}
|
|
2207
|
-
if (
|
|
2208
|
-
|
|
2459
|
+
if (currentCell !== "" || cellIsQuoted || currentRow.length > 0) {
|
|
2460
|
+
currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
|
|
2461
|
+
if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
|
|
2462
|
+
rows.push(currentRow);
|
|
2463
|
+
}
|
|
2209
2464
|
}
|
|
2210
|
-
|
|
2211
|
-
if (typeof attrDef.max === "number") enriched.max = attrDef.max;
|
|
2212
|
-
if (typeof attrDef.minLength === "number") enriched.minLength = attrDef.minLength;
|
|
2213
|
-
if (typeof attrDef.maxLength === "number") enriched.maxLength = attrDef.maxLength;
|
|
2214
|
-
if (typeof attrDef.regex === "string") enriched.regex = attrDef.regex;
|
|
2215
|
-
if (attrDef.required) enriched.required = true;
|
|
2216
|
-
if (attrDef.target) enriched.target = attrDef.target;
|
|
2217
|
-
if (attrDef.relation) enriched.relationType = attrDef.relation;
|
|
2218
|
-
return enriched;
|
|
2465
|
+
return rows;
|
|
2219
2466
|
}
|
|
2220
|
-
function
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2467
|
+
function parseCsvToRecords(csvText) {
|
|
2468
|
+
const matrix = parseCsvToMatrix(csvText);
|
|
2469
|
+
if (matrix.length < 2) return [];
|
|
2470
|
+
const headers = matrix[0].map((h) => h.trim());
|
|
2471
|
+
const records = [];
|
|
2472
|
+
for (let i = 1; i < matrix.length; i++) {
|
|
2473
|
+
const row = matrix[i];
|
|
2474
|
+
const record = {};
|
|
2475
|
+
headers.forEach((h, idx) => {
|
|
2476
|
+
let val = row[idx] !== void 0 ? row[idx] : "";
|
|
2477
|
+
if (typeof val === "string" && /^'[=+@-]/.test(val)) {
|
|
2478
|
+
val = val.substring(1);
|
|
2479
|
+
}
|
|
2480
|
+
record[h] = val;
|
|
2481
|
+
});
|
|
2482
|
+
records.push(record);
|
|
2483
|
+
}
|
|
2484
|
+
return records;
|
|
2228
2485
|
}
|
|
2229
|
-
function
|
|
2230
|
-
if (
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2486
|
+
function serializeFieldValue(value, field) {
|
|
2487
|
+
if (value === null || value === void 0) {
|
|
2488
|
+
return "";
|
|
2489
|
+
}
|
|
2490
|
+
switch (field.category) {
|
|
2491
|
+
case "scalar": {
|
|
2492
|
+
if (value instanceof Date) {
|
|
2493
|
+
return value.toISOString();
|
|
2494
|
+
}
|
|
2495
|
+
return String(value);
|
|
2235
2496
|
}
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
function enumerateOccurrences(contentType, allComponents, entity, attrPath) {
|
|
2240
|
-
if (!contentType || !attrPath) return [];
|
|
2241
|
-
const parsed = parseAttrPath(attrPath);
|
|
2242
|
-
const parts = parsed.cleanPath.split(".").filter(Boolean);
|
|
2243
|
-
if (parts.length === 0) return [];
|
|
2244
|
-
const results = [];
|
|
2245
|
-
function walk(currentSchema, currentVal, remainingParts, segments, missingIntermediate, firstArrayIndex, resolvedCompUid, resolvedCompId, isRootLevel) {
|
|
2246
|
-
if (!currentSchema?.attributes || remainingParts.length === 0) return;
|
|
2247
|
-
const [head, ...tail] = remainingParts;
|
|
2248
|
-
const attrDef = currentSchema.attributes[head];
|
|
2249
|
-
if (!attrDef) return;
|
|
2250
|
-
const nextVal = currentVal && typeof currentVal === "object" ? currentVal[head] : void 0;
|
|
2251
|
-
if (tail.length === 0) {
|
|
2252
|
-
const nextSegs = [...segments, { key: head }];
|
|
2253
|
-
results.push({
|
|
2254
|
-
occurrenceKey: segments.length === 0 ? "__scalar__" : buildOccurrenceKey(nextSegs),
|
|
2255
|
-
displayPath: buildReadableOccurrencePath(nextSegs),
|
|
2256
|
-
segments: nextSegs,
|
|
2257
|
-
value: nextVal !== void 0 ? nextVal : null,
|
|
2258
|
-
componentUid: resolvedCompUid,
|
|
2259
|
-
componentName: resolvedCompUid ? formatComponentDisplayName(resolvedCompUid) : void 0,
|
|
2260
|
-
componentId: resolvedCompId,
|
|
2261
|
-
index: firstArrayIndex ?? 0,
|
|
2262
|
-
isMissingIntermediate: missingIntermediate,
|
|
2263
|
-
leafSchema: attrDef
|
|
2264
|
-
});
|
|
2265
|
-
return;
|
|
2497
|
+
case "blocks":
|
|
2498
|
+
case "json": {
|
|
2499
|
+
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
2266
2500
|
}
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
nextVal.forEach((item, idx) => {
|
|
2270
|
-
if (!item || typeof item !== "object") return;
|
|
2271
|
-
if (isRootLevel && parsed.targetIndex !== void 0 && idx !== parsed.targetIndex) return;
|
|
2272
|
-
if (isRootLevel && parsed.targetComponentUid && item.__component !== parsed.targetComponentUid) return;
|
|
2273
|
-
const compSchema = item.__component ? allComponents?.[item.__component] : null;
|
|
2274
|
-
if (!compSchema) return;
|
|
2275
|
-
const seg = {
|
|
2276
|
-
key: head,
|
|
2277
|
-
index: idx,
|
|
2278
|
-
componentId: item.id,
|
|
2279
|
-
componentUid: item.__component
|
|
2280
|
-
};
|
|
2281
|
-
walk(
|
|
2282
|
-
compSchema,
|
|
2283
|
-
item,
|
|
2284
|
-
tail,
|
|
2285
|
-
[...segments, seg],
|
|
2286
|
-
missingIntermediate,
|
|
2287
|
-
firstArrayIndex ?? idx,
|
|
2288
|
-
item.__component,
|
|
2289
|
-
resolvedCompId ?? item.id,
|
|
2290
|
-
false
|
|
2291
|
-
);
|
|
2292
|
-
});
|
|
2293
|
-
return;
|
|
2501
|
+
case "component_single": {
|
|
2502
|
+
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
2294
2503
|
}
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
};
|
|
2309
|
-
walk(
|
|
2310
|
-
compSchema,
|
|
2311
|
-
item,
|
|
2312
|
-
tail,
|
|
2313
|
-
[...segments, seg],
|
|
2314
|
-
missingIntermediate,
|
|
2315
|
-
firstArrayIndex ?? idx,
|
|
2316
|
-
attrDef.component,
|
|
2317
|
-
resolvedCompId ?? item.id,
|
|
2318
|
-
false
|
|
2319
|
-
);
|
|
2504
|
+
case "component_repeatable": {
|
|
2505
|
+
if (Array.isArray(value)) {
|
|
2506
|
+
return JSON.stringify(value);
|
|
2507
|
+
}
|
|
2508
|
+
return typeof value === "object" ? JSON.stringify([value]) : "";
|
|
2509
|
+
}
|
|
2510
|
+
case "dynamiczone": {
|
|
2511
|
+
if (Array.isArray(value)) {
|
|
2512
|
+
const cleaned = value.map((block) => {
|
|
2513
|
+
if (block && typeof block === "object") {
|
|
2514
|
+
return { ...block };
|
|
2515
|
+
}
|
|
2516
|
+
return block;
|
|
2320
2517
|
});
|
|
2321
|
-
|
|
2322
|
-
const isMissing = !nextVal || typeof nextVal !== "object";
|
|
2323
|
-
const seg = {
|
|
2324
|
-
key: head,
|
|
2325
|
-
componentId: !isMissing ? nextVal.id : void 0,
|
|
2326
|
-
componentUid: attrDef.component
|
|
2327
|
-
};
|
|
2328
|
-
walk(
|
|
2329
|
-
compSchema,
|
|
2330
|
-
isMissing ? void 0 : nextVal,
|
|
2331
|
-
tail,
|
|
2332
|
-
[...segments, seg],
|
|
2333
|
-
missingIntermediate || isMissing,
|
|
2334
|
-
firstArrayIndex,
|
|
2335
|
-
resolvedCompUid ?? attrDef.component,
|
|
2336
|
-
resolvedCompId ?? (!isMissing ? nextVal.id : void 0),
|
|
2337
|
-
false
|
|
2338
|
-
);
|
|
2518
|
+
return JSON.stringify(cleaned);
|
|
2339
2519
|
}
|
|
2520
|
+
return "";
|
|
2340
2521
|
}
|
|
2522
|
+
case "relation_to_one": {
|
|
2523
|
+
if (typeof value === "object" && value !== null) {
|
|
2524
|
+
const docId = value.documentId || value.id || "";
|
|
2525
|
+
return JSON.stringify({
|
|
2526
|
+
documentId: String(docId),
|
|
2527
|
+
title: value.title || value.name || value.slug || void 0
|
|
2528
|
+
});
|
|
2529
|
+
}
|
|
2530
|
+
return String(value);
|
|
2531
|
+
}
|
|
2532
|
+
case "relation_to_many": {
|
|
2533
|
+
if (Array.isArray(value)) {
|
|
2534
|
+
const list = value.map((item) => {
|
|
2535
|
+
if (typeof item === "object" && item !== null) {
|
|
2536
|
+
const docId = item.documentId || item.id || "";
|
|
2537
|
+
return {
|
|
2538
|
+
documentId: String(docId),
|
|
2539
|
+
title: item.title || item.name || item.slug || void 0
|
|
2540
|
+
};
|
|
2541
|
+
}
|
|
2542
|
+
return { documentId: String(item) };
|
|
2543
|
+
});
|
|
2544
|
+
return JSON.stringify(list);
|
|
2545
|
+
}
|
|
2546
|
+
return "";
|
|
2547
|
+
}
|
|
2548
|
+
case "media_single": {
|
|
2549
|
+
if (typeof value === "object" && value !== null) {
|
|
2550
|
+
return JSON.stringify({
|
|
2551
|
+
id: value.id,
|
|
2552
|
+
documentId: value.documentId,
|
|
2553
|
+
name: value.name,
|
|
2554
|
+
url: value.url,
|
|
2555
|
+
mime: value.mime
|
|
2556
|
+
});
|
|
2557
|
+
}
|
|
2558
|
+
return String(value);
|
|
2559
|
+
}
|
|
2560
|
+
case "media_to_many": {
|
|
2561
|
+
if (Array.isArray(value)) {
|
|
2562
|
+
const list = value.map((file) => {
|
|
2563
|
+
if (typeof file === "object" && file !== null) {
|
|
2564
|
+
return {
|
|
2565
|
+
id: file.id,
|
|
2566
|
+
documentId: file.documentId,
|
|
2567
|
+
name: file.name,
|
|
2568
|
+
url: file.url,
|
|
2569
|
+
mime: file.mime
|
|
2570
|
+
};
|
|
2571
|
+
}
|
|
2572
|
+
return file;
|
|
2573
|
+
});
|
|
2574
|
+
return JSON.stringify(list);
|
|
2575
|
+
}
|
|
2576
|
+
return "";
|
|
2577
|
+
}
|
|
2578
|
+
default:
|
|
2579
|
+
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
2341
2580
|
}
|
|
2342
|
-
walk(contentType, entity, parts, [], false, void 0, void 0, void 0, true);
|
|
2343
|
-
return results;
|
|
2344
|
-
}
|
|
2345
|
-
function formatRelationState(currentRel, isMulti) {
|
|
2346
|
-
if (isMulti && Array.isArray(currentRel)) {
|
|
2347
|
-
const oldDocIds = currentRel.map((r) => r?.documentId).filter(Boolean);
|
|
2348
|
-
const oldDisplay = currentRel.map((r) => r?.name || r?.title || r?.email || r?.username || r?.documentId).filter(Boolean).join(", ") || "(unlinked / none)";
|
|
2349
|
-
return { oldDocIds, oldDisplay };
|
|
2350
|
-
}
|
|
2351
|
-
if (currentRel && typeof currentRel === "object") {
|
|
2352
|
-
const oldDocIds = currentRel.documentId ? [currentRel.documentId] : [];
|
|
2353
|
-
const oldDisplay = currentRel.name || currentRel.title || currentRel.email || currentRel.username || currentRel.documentId || "(unlinked / none)";
|
|
2354
|
-
return { oldDocIds, oldDisplay };
|
|
2355
|
-
}
|
|
2356
|
-
return { oldDocIds: [], oldDisplay: "(unlinked / none)" };
|
|
2357
2581
|
}
|
|
2358
|
-
function
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2582
|
+
function serializeDocumentsToCsv(strapi, uid, documents, options = {}) {
|
|
2583
|
+
const schema = options.schema || discoverSchema(strapi, uid);
|
|
2584
|
+
const plan = buildExportColumnPlan(strapi, uid, documents || [], schema);
|
|
2585
|
+
const headers = [METADATA_COLUMN_KEY, ...plan.headers];
|
|
2586
|
+
const lines = [];
|
|
2587
|
+
lines.push(headers.map(escapeCsvCell).join(","));
|
|
2588
|
+
const exportedAt = options.exportedAt || (/* @__PURE__ */ new Date()).toISOString();
|
|
2589
|
+
for (const doc of documents) {
|
|
2590
|
+
const rowValues = [];
|
|
2591
|
+
const flattenedMeta = extractRowFlattenedMetadata(plan, doc);
|
|
2592
|
+
const metadata = {
|
|
2593
|
+
schemaVersion: CURRENT_SCHEMA_VERSION,
|
|
2594
|
+
contentType: uid,
|
|
2595
|
+
documentId: String(doc.documentId || doc.id || ""),
|
|
2596
|
+
locale: doc.locale || void 0,
|
|
2597
|
+
exportedAt,
|
|
2598
|
+
...flattenedMeta.applicableFields ? { applicableFields: flattenedMeta.applicableFields } : {},
|
|
2599
|
+
...flattenedMeta.flatTypes ? { flatTypes: flattenedMeta.flatTypes } : {}
|
|
2600
|
+
};
|
|
2601
|
+
rowValues.push(escapeCsvCell(metadata));
|
|
2602
|
+
for (const col of plan.columns) {
|
|
2603
|
+
const cellValue = serializePlannedCell(col, doc, serializeFieldValue);
|
|
2604
|
+
rowValues.push(escapeCsvCell(cellValue));
|
|
2373
2605
|
}
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2606
|
+
lines.push(rowValues.join(","));
|
|
2607
|
+
}
|
|
2608
|
+
const csvContent = "\uFEFF" + lines.join("\r\n") + "\r\n";
|
|
2609
|
+
return {
|
|
2610
|
+
csvContent,
|
|
2611
|
+
headers,
|
|
2612
|
+
count: documents.length
|
|
2613
|
+
};
|
|
2614
|
+
}
|
|
2615
|
+
function extractMetadataFromRow(row) {
|
|
2616
|
+
if (!row || typeof row !== "object") return null;
|
|
2617
|
+
const rawMeta = row[METADATA_COLUMN_KEY] || row["__bulk_updater_metadata"];
|
|
2618
|
+
if (!rawMeta) return null;
|
|
2619
|
+
if (typeof rawMeta === "object") {
|
|
2620
|
+
return rawMeta;
|
|
2621
|
+
}
|
|
2622
|
+
if (typeof rawMeta === "string") {
|
|
2380
2623
|
try {
|
|
2381
|
-
const parsed = JSON.parse(
|
|
2382
|
-
if (parsed && typeof parsed === "object"
|
|
2383
|
-
|
|
2384
|
-
targetDocIds = Array.isArray(parsed.documentIds) ? parsed.documentIds.filter(Boolean).map(String) : parsed.documentId ? [String(parsed.documentId)] : [];
|
|
2385
|
-
display = parsed.label || targetDocIds.join(", ") || `[${mode}]`;
|
|
2386
|
-
} else if (Array.isArray(parsed)) {
|
|
2387
|
-
targetDocIds = parsed.filter(Boolean).map(String);
|
|
2388
|
-
display = targetDocIds.join(", ");
|
|
2389
|
-
} else {
|
|
2390
|
-
targetDocIds = [strVal];
|
|
2391
|
-
display = strVal;
|
|
2624
|
+
const parsed = JSON.parse(rawMeta);
|
|
2625
|
+
if (parsed && typeof parsed === "object") {
|
|
2626
|
+
return parsed;
|
|
2392
2627
|
}
|
|
2393
2628
|
} catch {
|
|
2394
|
-
targetDocIds = [strVal];
|
|
2395
|
-
display = strVal;
|
|
2396
2629
|
}
|
|
2397
2630
|
}
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2631
|
+
return null;
|
|
2632
|
+
}
|
|
2633
|
+
function sanitizeUserErrorMessage(msg) {
|
|
2634
|
+
if (msg === null || msg === void 0) return "Error processing row";
|
|
2635
|
+
const raw = typeof msg === "string" ? msg : String(msg);
|
|
2636
|
+
const cleanedLines = raw.split(/\r?\n/).filter((line) => !/^\s+at\s+.+(\(.+\)|:\d+:\d+)\s*$/.test(line)).map((line) => line.trim()).filter(Boolean);
|
|
2637
|
+
const result = cleanedLines.join(" ").trim();
|
|
2638
|
+
return result || "Error processing row";
|
|
2639
|
+
}
|
|
2640
|
+
function resolveErrorColumnName(existingHeaders) {
|
|
2641
|
+
const existingLower = new Set(
|
|
2642
|
+
existingHeaders.map((h) => String(h || "").trim().toLowerCase())
|
|
2643
|
+
);
|
|
2644
|
+
if (!existingLower.has("error")) {
|
|
2645
|
+
return "Error";
|
|
2407
2646
|
}
|
|
2408
|
-
|
|
2647
|
+
if (!existingLower.has("import error")) {
|
|
2648
|
+
return "Import Error";
|
|
2649
|
+
}
|
|
2650
|
+
let suffix = 2;
|
|
2651
|
+
while (existingLower.has(`import error (${suffix})`)) {
|
|
2652
|
+
suffix++;
|
|
2653
|
+
}
|
|
2654
|
+
return `Import Error (${suffix})`;
|
|
2409
2655
|
}
|
|
2410
|
-
|
|
2411
|
-
|
|
2656
|
+
function formatErrorCsvFilename(collectionTypeOrUid, date = /* @__PURE__ */ new Date()) {
|
|
2657
|
+
const rawSegment = collectionTypeOrUid ? String(collectionTypeOrUid).split(".").pop() || String(collectionTypeOrUid) : "collection";
|
|
2658
|
+
const safeType = rawSegment.replace(/[^a-zA-Z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "collection";
|
|
2659
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
2660
|
+
const stamp = `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}_${pad(
|
|
2661
|
+
date.getHours()
|
|
2662
|
+
)}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
|
|
2663
|
+
return `error_${safeType}_${stamp}.csv`;
|
|
2664
|
+
}
|
|
2665
|
+
function buildErrorCsv(options) {
|
|
2666
|
+
const { headers, failedRows } = options || {};
|
|
2667
|
+
if (!Array.isArray(failedRows) || failedRows.length === 0) {
|
|
2412
2668
|
return {
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2669
|
+
csvContent: "",
|
|
2670
|
+
headers: headers ? [...headers] : [],
|
|
2671
|
+
errorColumnName: "Error",
|
|
2672
|
+
errorCount: 0
|
|
2416
2673
|
};
|
|
2417
2674
|
}
|
|
2418
|
-
const
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
const
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2675
|
+
const groupedByRow = /* @__PURE__ */ new Map();
|
|
2676
|
+
for (const item of failedRows) {
|
|
2677
|
+
if (!item || typeof item !== "object") continue;
|
|
2678
|
+
const rowNum = typeof item.row === "number" && !isNaN(item.row) ? item.row : groupedByRow.size + 2;
|
|
2679
|
+
const msg = sanitizeUserErrorMessage(item.error);
|
|
2680
|
+
const existing = groupedByRow.get(rowNum);
|
|
2681
|
+
if (existing) {
|
|
2682
|
+
if (!existing.messages.includes(msg)) {
|
|
2683
|
+
existing.messages.push(msg);
|
|
2684
|
+
}
|
|
2685
|
+
} else {
|
|
2686
|
+
groupedByRow.set(rowNum, {
|
|
2687
|
+
row: rowNum,
|
|
2688
|
+
documentId: item.documentId,
|
|
2689
|
+
messages: [msg],
|
|
2690
|
+
originalRow: item.originalRow && typeof item.originalRow === "object" ? item.originalRow : {}
|
|
2691
|
+
});
|
|
2430
2692
|
}
|
|
2693
|
+
}
|
|
2694
|
+
const orderedEntries = Array.from(groupedByRow.values()).sort((a, b) => a.row - b.row);
|
|
2695
|
+
if (orderedEntries.length === 0) {
|
|
2431
2696
|
return {
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
relationMeta: { isRelation: true, mode: cmd.mode, documentIds: cmd.targetDocIds, display: cmd.display }
|
|
2697
|
+
csvContent: "",
|
|
2698
|
+
headers: headers ? [...headers] : [],
|
|
2699
|
+
errorColumnName: "Error",
|
|
2700
|
+
errorCount: 0
|
|
2437
2701
|
};
|
|
2438
2702
|
}
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2703
|
+
let baseHeaders = [];
|
|
2704
|
+
if (Array.isArray(headers) && headers.length > 0) {
|
|
2705
|
+
baseHeaders = [...headers];
|
|
2706
|
+
} else {
|
|
2707
|
+
const keySet = /* @__PURE__ */ new Set();
|
|
2708
|
+
for (const entry of orderedEntries) {
|
|
2709
|
+
for (const k of Object.keys(entry.originalRow || {})) {
|
|
2710
|
+
if (!keySet.has(k)) {
|
|
2711
|
+
keySet.add(k);
|
|
2712
|
+
baseHeaders.push(k);
|
|
2713
|
+
}
|
|
2444
2714
|
}
|
|
2445
|
-
const cleared = isMultiple ? [] : null;
|
|
2446
|
-
return { valid: true, value: cleared, displayValue: "(cleared)" };
|
|
2447
|
-
}
|
|
2448
|
-
const mediaPayload = strapi ? await resolveMediaIds(strapi, rawValue, isMultiple) : rawValue;
|
|
2449
|
-
if (attrDef.required && (mediaPayload === null || Array.isArray(mediaPayload) && mediaPayload.length === 0)) {
|
|
2450
|
-
return { valid: false, value: rawValue, displayValue: "", error: "Media asset could not be resolved." };
|
|
2451
2715
|
}
|
|
2452
|
-
return {
|
|
2453
|
-
valid: true,
|
|
2454
|
-
value: mediaPayload,
|
|
2455
|
-
displayValue: Array.isArray(mediaPayload) ? `[${mediaPayload.length} asset(s)]` : mediaPayload !== null ? `#${mediaPayload}` : "(cleared)"
|
|
2456
|
-
};
|
|
2457
|
-
}
|
|
2458
|
-
const isEmptyInput = rawValue === null || rawValue === void 0 || rawValue === "";
|
|
2459
|
-
if (attrDef.required && (isEmptyInput || type === "boolean" && rawValue === null)) {
|
|
2460
|
-
return {
|
|
2461
|
-
valid: false,
|
|
2462
|
-
value: rawValue,
|
|
2463
|
-
displayValue: "",
|
|
2464
|
-
error: "Field is required and cannot be empty."
|
|
2465
|
-
};
|
|
2466
2716
|
}
|
|
2467
|
-
|
|
2468
|
-
|
|
2717
|
+
const errorColumnName = resolveErrorColumnName(baseHeaders);
|
|
2718
|
+
const finalHeaders = [...baseHeaders, errorColumnName];
|
|
2719
|
+
const lines = [];
|
|
2720
|
+
lines.push(finalHeaders.map(escapeCsvCell).join(","));
|
|
2721
|
+
for (const entry of orderedEntries) {
|
|
2722
|
+
const cells = baseHeaders.map((h) => {
|
|
2723
|
+
const val = entry.originalRow ? entry.originalRow[h] : "";
|
|
2724
|
+
return escapeCsvCell(val === void 0 || val === null ? "" : val);
|
|
2725
|
+
});
|
|
2726
|
+
cells.push(escapeCsvCell(entry.messages.join("; ")));
|
|
2727
|
+
lines.push(cells.join(","));
|
|
2469
2728
|
}
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2729
|
+
const csvContent = "\uFEFF" + lines.join("\r\n") + "\r\n";
|
|
2730
|
+
return {
|
|
2731
|
+
csvContent,
|
|
2732
|
+
headers: finalHeaders,
|
|
2733
|
+
errorColumnName,
|
|
2734
|
+
errorCount: orderedEntries.length
|
|
2735
|
+
};
|
|
2736
|
+
}
|
|
2737
|
+
function isValidDocumentId(val) {
|
|
2738
|
+
if (!val || typeof val !== "string") return false;
|
|
2739
|
+
const trimmed = val.trim();
|
|
2740
|
+
if (!trimmed) return false;
|
|
2741
|
+
if (/\s/.test(trimmed)) return false;
|
|
2742
|
+
return /^[a-zA-Z0-9_-]+$/.test(trimmed);
|
|
2743
|
+
}
|
|
2744
|
+
function parseNumeric(rawVal, isInteger) {
|
|
2745
|
+
if (rawVal === null || rawVal === void 0 || rawVal === "") return null;
|
|
2746
|
+
const cleanStr = String(rawVal).replace(/[$€£,\s]/g, "");
|
|
2747
|
+
if (isInteger) {
|
|
2748
|
+
const n = parseInt(cleanStr, 10);
|
|
2749
|
+
return isNaN(n) ? null : n;
|
|
2750
|
+
}
|
|
2751
|
+
const f = parseFloat(cleanStr);
|
|
2752
|
+
return isNaN(f) ? null : f;
|
|
2753
|
+
}
|
|
2754
|
+
function parseBoolean(rawVal) {
|
|
2755
|
+
if (rawVal === null || rawVal === void 0 || rawVal === "") return null;
|
|
2756
|
+
const s = String(rawVal).trim().toLowerCase();
|
|
2757
|
+
if (s === "true" || s === "1" || s === "yes" || s === "y" || s === "on") return true;
|
|
2758
|
+
if (s === "false" || s === "0" || s === "no" || s === "n" || s === "off") return false;
|
|
2759
|
+
return null;
|
|
2760
|
+
}
|
|
2761
|
+
async function resolveMediaIds(strapi, rawVal, isMultiple) {
|
|
2762
|
+
if (rawVal === null || rawVal === void 0 || rawVal === "") {
|
|
2763
|
+
return isMultiple ? [] : null;
|
|
2764
|
+
}
|
|
2765
|
+
let parsed = rawVal;
|
|
2766
|
+
if (typeof rawVal === "string") {
|
|
2767
|
+
const trimmed = rawVal.trim();
|
|
2768
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
2769
|
+
try {
|
|
2770
|
+
parsed = JSON.parse(trimmed);
|
|
2771
|
+
} catch {
|
|
2494
2772
|
}
|
|
2495
|
-
return { valid: true, value: str, displayValue: str };
|
|
2496
2773
|
}
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
if (!Number.isFinite(num)) {
|
|
2506
|
-
return { valid: false, value: rawValue, displayValue: str, error: `Number "${str}" is not finite.` };
|
|
2507
|
-
}
|
|
2508
|
-
if (typeof attrDef.min === "number" && num < attrDef.min) {
|
|
2509
|
-
return { valid: false, value: rawValue, displayValue: str, error: `Value ${num} is less than minimum ${attrDef.min}.` };
|
|
2510
|
-
}
|
|
2511
|
-
if (typeof attrDef.max === "number" && num > attrDef.max) {
|
|
2512
|
-
return { valid: false, value: rawValue, displayValue: str, error: `Value ${num} exceeds maximum ${attrDef.max}.` };
|
|
2513
|
-
}
|
|
2514
|
-
return { valid: true, value: num, displayValue: String(num) };
|
|
2774
|
+
}
|
|
2775
|
+
const numericIds = [];
|
|
2776
|
+
const candidateLookups = [];
|
|
2777
|
+
const inspectItem = (item) => {
|
|
2778
|
+
if (item === null || item === void 0) return;
|
|
2779
|
+
if (typeof item === "number" && !isNaN(item)) {
|
|
2780
|
+
numericIds.push(item);
|
|
2781
|
+
return;
|
|
2515
2782
|
}
|
|
2516
|
-
|
|
2517
|
-
if (
|
|
2518
|
-
|
|
2519
|
-
return
|
|
2520
|
-
}
|
|
2521
|
-
const lower = String(rawValue).trim().toLowerCase();
|
|
2522
|
-
if (lower === "true" || lower === "1" || lower === "yes") {
|
|
2523
|
-
return { valid: true, value: true, displayValue: "true" };
|
|
2524
|
-
}
|
|
2525
|
-
if (lower === "false" || lower === "0" || lower === "no") {
|
|
2526
|
-
return { valid: true, value: false, displayValue: "false" };
|
|
2783
|
+
if (typeof item === "object") {
|
|
2784
|
+
if (typeof item.id === "number") {
|
|
2785
|
+
numericIds.push(item.id);
|
|
2786
|
+
return;
|
|
2527
2787
|
}
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
|
|
2531
|
-
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
2532
|
-
const str = String(rawValue);
|
|
2533
|
-
if (Array.isArray(attrDef.enum) && !attrDef.enum.includes(str)) {
|
|
2534
|
-
return {
|
|
2535
|
-
valid: false,
|
|
2536
|
-
value: rawValue,
|
|
2537
|
-
displayValue: str,
|
|
2538
|
-
error: `Value "${str}" is not an allowed enum option (${attrDef.enum.join(", ")}).`
|
|
2539
|
-
};
|
|
2788
|
+
if (typeof item.id === "string" && /^\d+$/.test(item.id)) {
|
|
2789
|
+
numericIds.push(parseInt(item.id, 10));
|
|
2790
|
+
return;
|
|
2540
2791
|
}
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
const str = String(rawValue).trim();
|
|
2545
|
-
if (str === "") return { valid: true, value: "", displayValue: "(empty)" };
|
|
2546
|
-
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str)) {
|
|
2547
|
-
return { valid: false, value: rawValue, displayValue: str, error: `Invalid email address "${str}".` };
|
|
2792
|
+
if (item.documentId) {
|
|
2793
|
+
candidateLookups.push(String(item.documentId));
|
|
2794
|
+
return;
|
|
2548
2795
|
}
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
const str = String(rawValue).trim();
|
|
2553
|
-
if (str !== "" && !/^[A-Za-z0-9\-_.~]*$/.test(str)) {
|
|
2554
|
-
return { valid: false, value: rawValue, displayValue: str, error: `Invalid UID slug "${str}". Allowed characters: A-Z a-z 0-9 - _ . ~` };
|
|
2796
|
+
if (item.url) {
|
|
2797
|
+
candidateLookups.push(String(item.url));
|
|
2798
|
+
return;
|
|
2555
2799
|
}
|
|
2556
|
-
return { valid: true, value: str, displayValue: str || "(empty)" };
|
|
2557
2800
|
}
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
2563
|
-
try {
|
|
2564
|
-
parsedVal = JSON.parse(rawValue);
|
|
2565
|
-
} catch (err) {
|
|
2566
|
-
return {
|
|
2567
|
-
valid: false,
|
|
2568
|
-
value: rawValue,
|
|
2569
|
-
displayValue: rawValue,
|
|
2570
|
-
error: `Invalid ${type === "blocks" ? "Blocks" : "JSON"} syntax: ${err.message}`
|
|
2571
|
-
};
|
|
2572
|
-
}
|
|
2573
|
-
}
|
|
2574
|
-
if (type === "blocks" && parsedVal !== null && !Array.isArray(parsedVal)) {
|
|
2575
|
-
return { valid: false, value: rawValue, displayValue: String(rawValue), error: "Strapi Blocks field must be a JSON array." };
|
|
2576
|
-
}
|
|
2577
|
-
return {
|
|
2578
|
-
valid: true,
|
|
2579
|
-
value: parsedVal,
|
|
2580
|
-
displayValue: parsedVal === null ? "(empty)" : JSON.stringify(parsedVal)
|
|
2581
|
-
};
|
|
2801
|
+
const str = String(item).trim();
|
|
2802
|
+
if (/^\d+$/.test(str)) {
|
|
2803
|
+
numericIds.push(parseInt(str, 10));
|
|
2804
|
+
} else if (str) {
|
|
2805
|
+
candidateLookups.push(str);
|
|
2582
2806
|
}
|
|
2583
|
-
|
|
2584
|
-
|
|
2585
|
-
|
|
2586
|
-
|
|
2587
|
-
const d = new Date(str);
|
|
2588
|
-
if (isNaN(d.getTime())) {
|
|
2589
|
-
return { valid: false, value: rawValue, displayValue: str, error: `Invalid ${type} value "${str}".` };
|
|
2590
|
-
}
|
|
2591
|
-
const out = type === "date" ? /^\d{4}-\d{2}-\d{2}$/.test(str) ? str : d.toISOString().slice(0, 10) : d.toISOString();
|
|
2592
|
-
return { valid: true, value: out, displayValue: out };
|
|
2807
|
+
};
|
|
2808
|
+
if (Array.isArray(parsed)) {
|
|
2809
|
+
for (const el of parsed) {
|
|
2810
|
+
inspectItem(el);
|
|
2593
2811
|
}
|
|
2594
|
-
|
|
2595
|
-
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
return { valid: true, value: str, displayValue: str };
|
|
2812
|
+
} else if (typeof parsed === "object" && parsed !== null) {
|
|
2813
|
+
inspectItem(parsed);
|
|
2814
|
+
} else if (typeof rawVal === "string" && (rawVal.includes(",") || rawVal.includes(";"))) {
|
|
2815
|
+
const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter(Boolean);
|
|
2816
|
+
for (const part of parts) {
|
|
2817
|
+
inspectItem(part);
|
|
2601
2818
|
}
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
|
|
2614
|
-
|
|
2819
|
+
} else {
|
|
2820
|
+
inspectItem(parsed);
|
|
2821
|
+
}
|
|
2822
|
+
if (candidateLookups.length > 0) {
|
|
2823
|
+
try {
|
|
2824
|
+
const fileQuery = strapi.db?.query("plugin::upload.file");
|
|
2825
|
+
if (fileQuery) {
|
|
2826
|
+
for (const candidate of candidateLookups) {
|
|
2827
|
+
const found = await fileQuery.findOne({
|
|
2828
|
+
where: {
|
|
2829
|
+
$or: [
|
|
2830
|
+
{ documentId: candidate },
|
|
2831
|
+
{ url: candidate },
|
|
2832
|
+
{ hash: candidate },
|
|
2833
|
+
{ name: candidate }
|
|
2834
|
+
]
|
|
2835
|
+
},
|
|
2836
|
+
select: ["id"]
|
|
2837
|
+
});
|
|
2838
|
+
if (found?.id) {
|
|
2839
|
+
numericIds.push(found.id);
|
|
2615
2840
|
}
|
|
2616
|
-
} catch {
|
|
2617
2841
|
}
|
|
2618
2842
|
}
|
|
2619
|
-
|
|
2843
|
+
} catch {
|
|
2620
2844
|
}
|
|
2621
2845
|
}
|
|
2846
|
+
const uniqueNumericIds = Array.from(new Set(numericIds));
|
|
2847
|
+
if (isMultiple) {
|
|
2848
|
+
return uniqueNumericIds;
|
|
2849
|
+
}
|
|
2850
|
+
return uniqueNumericIds.length > 0 ? uniqueNumericIds[0] : null;
|
|
2622
2851
|
}
|
|
2623
|
-
function
|
|
2624
|
-
if (
|
|
2625
|
-
|
|
2852
|
+
function resolveRelationPayload(rawVal, isToMany) {
|
|
2853
|
+
if (rawVal === null || rawVal === void 0 || rawVal === "") {
|
|
2854
|
+
return isToMany ? { set: [] } : { set: [] };
|
|
2626
2855
|
}
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
throw new Error(
|
|
2636
|
-
`Stale target: component instance (id: ${seg.componentId}) in "${arrFieldKey}" was modified or deleted. Please refresh the grid and retry.`
|
|
2637
|
-
);
|
|
2856
|
+
let parsed = rawVal;
|
|
2857
|
+
if (typeof rawVal === "string") {
|
|
2858
|
+
const trimmed = rawVal.trim();
|
|
2859
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
2860
|
+
try {
|
|
2861
|
+
parsed = JSON.parse(trimmed);
|
|
2862
|
+
} catch {
|
|
2863
|
+
}
|
|
2638
2864
|
}
|
|
2639
|
-
return idMatchIdx;
|
|
2640
2865
|
}
|
|
2641
|
-
if (typeof
|
|
2642
|
-
if (
|
|
2643
|
-
|
|
2644
|
-
`Stale target: occurrence #${seg.index} in "${arrFieldKey}" no longer exists (length ${arr.length}). Please refresh the grid and retry.`
|
|
2645
|
-
);
|
|
2866
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
|
2867
|
+
if (parsed.set || parsed.connect || parsed.disconnect) {
|
|
2868
|
+
return parsed;
|
|
2646
2869
|
}
|
|
2647
|
-
const
|
|
2648
|
-
if (
|
|
2649
|
-
|
|
2650
|
-
`Stale target: occurrence #${seg.index} in "${arrFieldKey}" changed component type to "${item.__component}". Please refresh the grid.`
|
|
2651
|
-
);
|
|
2870
|
+
const singleDocId = parsed.documentId || parsed.id;
|
|
2871
|
+
if (singleDocId && isValidDocumentId(String(singleDocId))) {
|
|
2872
|
+
return isToMany ? { set: [String(singleDocId).trim()] } : { set: [String(singleDocId).trim()] };
|
|
2652
2873
|
}
|
|
2653
|
-
return seg.index;
|
|
2654
2874
|
}
|
|
2655
|
-
|
|
2875
|
+
const docIds = [];
|
|
2876
|
+
if (Array.isArray(parsed)) {
|
|
2877
|
+
for (const item of parsed) {
|
|
2878
|
+
if (item && typeof item === "object") {
|
|
2879
|
+
const id = item.documentId || item.id;
|
|
2880
|
+
if (id && isValidDocumentId(String(id))) {
|
|
2881
|
+
docIds.push(String(id).trim());
|
|
2882
|
+
}
|
|
2883
|
+
} else if (isValidDocumentId(String(item))) {
|
|
2884
|
+
docIds.push(String(item).trim());
|
|
2885
|
+
}
|
|
2886
|
+
}
|
|
2887
|
+
} else if (typeof rawVal === "string") {
|
|
2888
|
+
if (rawVal.includes(",") || rawVal.includes(";")) {
|
|
2889
|
+
const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter((p) => isValidDocumentId(p));
|
|
2890
|
+
docIds.push(...parts);
|
|
2891
|
+
} else if (isValidDocumentId(rawVal.trim())) {
|
|
2892
|
+
docIds.push(rawVal.trim());
|
|
2893
|
+
}
|
|
2894
|
+
}
|
|
2895
|
+
const uniqueDocIds = Array.from(new Set(docIds));
|
|
2896
|
+
return { set: uniqueDocIds };
|
|
2656
2897
|
}
|
|
2657
|
-
function
|
|
2658
|
-
|
|
2659
|
-
|
|
2898
|
+
async function resolveComponentPayload(strapi, compUid, rawVal, existingVal = {}) {
|
|
2899
|
+
const comp = strapi.components?.[compUid];
|
|
2900
|
+
if (!comp?.attributes) {
|
|
2901
|
+
return typeof rawVal === "object" ? rawVal : {};
|
|
2660
2902
|
}
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2903
|
+
let sourceObj = {};
|
|
2904
|
+
if (typeof rawVal === "string") {
|
|
2905
|
+
try {
|
|
2906
|
+
sourceObj = JSON.parse(rawVal);
|
|
2907
|
+
} catch {
|
|
2908
|
+
return existingVal || {};
|
|
2909
|
+
}
|
|
2910
|
+
} else if (typeof rawVal === "object" && rawVal !== null) {
|
|
2911
|
+
sourceObj = rawVal;
|
|
2912
|
+
} else {
|
|
2913
|
+
return existingVal || {};
|
|
2914
|
+
}
|
|
2915
|
+
const result = { ...existingVal || {} };
|
|
2916
|
+
for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
|
|
2917
|
+
if (SYSTEM_ATTRIBUTES.has(attrName.toLowerCase().replace(/[\s_-]/g, ""))) continue;
|
|
2918
|
+
if (!(attrName in sourceObj)) {
|
|
2919
|
+
continue;
|
|
2920
|
+
}
|
|
2921
|
+
const fieldVal = sourceObj[attrName];
|
|
2922
|
+
const type = String(attrDef.type || "").toLowerCase();
|
|
2923
|
+
if (type === "component") {
|
|
2924
|
+
if (attrDef.repeatable) {
|
|
2925
|
+
const list = Array.isArray(fieldVal) ? fieldVal : [];
|
|
2926
|
+
const cleanedList = [];
|
|
2927
|
+
for (const item of list) {
|
|
2928
|
+
const subCleaned = await resolveComponentPayload(strapi, attrDef.component, item, {});
|
|
2929
|
+
cleanedList.push(subCleaned);
|
|
2676
2930
|
}
|
|
2677
|
-
|
|
2931
|
+
result[attrName] = cleanedList;
|
|
2932
|
+
} else {
|
|
2933
|
+
result[attrName] = await resolveComponentPayload(
|
|
2934
|
+
strapi,
|
|
2935
|
+
attrDef.component,
|
|
2936
|
+
fieldVal,
|
|
2937
|
+
existingVal?.[attrName] || {}
|
|
2938
|
+
);
|
|
2678
2939
|
}
|
|
2679
|
-
|
|
2680
|
-
const
|
|
2681
|
-
|
|
2682
|
-
} else {
|
|
2683
|
-
|
|
2684
|
-
|
|
2685
|
-
|
|
2940
|
+
} else if (type === "relation") {
|
|
2941
|
+
const isToMany = String(attrDef.relation || "").toLowerCase().endsWith("many");
|
|
2942
|
+
result[attrName] = resolveRelationPayload(fieldVal, isToMany);
|
|
2943
|
+
} else if (type === "media") {
|
|
2944
|
+
result[attrName] = await resolveMediaIds(strapi, fieldVal, Boolean(attrDef.multiple));
|
|
2945
|
+
} else if (type === "integer" || type === "biginteger") {
|
|
2946
|
+
result[attrName] = parseNumeric(fieldVal, true);
|
|
2947
|
+
} else if (type === "float" || type === "decimal") {
|
|
2948
|
+
result[attrName] = parseNumeric(fieldVal, false);
|
|
2949
|
+
} else if (type === "boolean") {
|
|
2950
|
+
result[attrName] = parseBoolean(fieldVal);
|
|
2951
|
+
} else if (type === "json") {
|
|
2952
|
+
if (isPlainObject(fieldVal) && isPlainObject(existingVal?.[attrName])) {
|
|
2953
|
+
const deepMergePlain = (base, patch) => {
|
|
2954
|
+
if (!isPlainObject(base) || !isPlainObject(patch)) return patch;
|
|
2955
|
+
const next = deepCloneValue(base);
|
|
2956
|
+
for (const [k, v] of Object.entries(patch)) {
|
|
2957
|
+
if (isPlainObject(v) && isPlainObject(next[k])) {
|
|
2958
|
+
next[k] = deepMergePlain(next[k], v);
|
|
2959
|
+
} else {
|
|
2960
|
+
next[k] = parseFlattenedLeafValue(v, void 0, next[k]);
|
|
2961
|
+
}
|
|
2962
|
+
}
|
|
2963
|
+
return next;
|
|
2964
|
+
};
|
|
2965
|
+
result[attrName] = deepMergePlain(existingVal[attrName], fieldVal);
|
|
2966
|
+
} else if (isPlainObject(fieldVal)) {
|
|
2967
|
+
const parsedObj = {};
|
|
2968
|
+
for (const [k, v] of Object.entries(fieldVal)) {
|
|
2969
|
+
parsedObj[k] = isPlainObject(v) ? deepCloneValue(v) : parseFlattenedLeafValue(v);
|
|
2970
|
+
}
|
|
2971
|
+
result[attrName] = parsedObj;
|
|
2972
|
+
} else if (typeof fieldVal === "string") {
|
|
2973
|
+
try {
|
|
2974
|
+
result[attrName] = JSON.parse(fieldVal);
|
|
2975
|
+
} catch {
|
|
2976
|
+
result[attrName] = fieldVal;
|
|
2977
|
+
}
|
|
2978
|
+
} else {
|
|
2979
|
+
result[attrName] = fieldVal;
|
|
2980
|
+
}
|
|
2981
|
+
} else if (type === "blocks") {
|
|
2982
|
+
if (typeof fieldVal === "string") {
|
|
2983
|
+
try {
|
|
2984
|
+
result[attrName] = JSON.parse(fieldVal);
|
|
2985
|
+
} catch {
|
|
2986
|
+
result[attrName] = fieldVal;
|
|
2987
|
+
}
|
|
2988
|
+
} else {
|
|
2989
|
+
result[attrName] = fieldVal;
|
|
2686
2990
|
}
|
|
2991
|
+
} else {
|
|
2992
|
+
result[attrName] = fieldVal === null || fieldVal === void 0 ? null : String(fieldVal);
|
|
2687
2993
|
}
|
|
2688
2994
|
}
|
|
2689
|
-
return
|
|
2995
|
+
return result;
|
|
2690
2996
|
}
|
|
2691
|
-
function
|
|
2692
|
-
|
|
2693
|
-
|
|
2997
|
+
async function resolveDynamicZonePayload(strapi, allowedComponents, rawVal, existingVal = []) {
|
|
2998
|
+
let list = [];
|
|
2999
|
+
if (typeof rawVal === "string") {
|
|
3000
|
+
try {
|
|
3001
|
+
list = JSON.parse(rawVal);
|
|
3002
|
+
} catch {
|
|
3003
|
+
return existingVal || [];
|
|
3004
|
+
}
|
|
3005
|
+
} else if (Array.isArray(rawVal)) {
|
|
3006
|
+
list = rawVal;
|
|
3007
|
+
} else {
|
|
3008
|
+
return existingVal || [];
|
|
2694
3009
|
}
|
|
2695
|
-
if (
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
currentDoc,
|
|
2704
|
-
attribute,
|
|
2705
|
-
updates
|
|
2706
|
-
}) {
|
|
2707
|
-
const parsed = parseAttrPath(attribute);
|
|
2708
|
-
const parts = parsed.cleanPath.split(".").filter(Boolean);
|
|
2709
|
-
const rootKey = parts[0];
|
|
2710
|
-
const rootAttrDef = contentType?.attributes?.[rootKey];
|
|
2711
|
-
const diffs = [];
|
|
2712
|
-
const errors = [];
|
|
2713
|
-
if (parts.length === 1 && rootAttrDef?.type !== "component" && rootAttrDef?.type !== "dynamiczone") {
|
|
2714
|
-
const updateItem = updates[0];
|
|
2715
|
-
if (!updateItem) {
|
|
2716
|
-
return { updateData: {}, diffs: [], errors: [] };
|
|
3010
|
+
if (!Array.isArray(list)) return [];
|
|
3011
|
+
const allowedSet = new Set(allowedComponents || []);
|
|
3012
|
+
const resolvedBlocks = [];
|
|
3013
|
+
for (const block of list) {
|
|
3014
|
+
if (!block || typeof block !== "object") continue;
|
|
3015
|
+
const compUid = block.__component;
|
|
3016
|
+
if (!compUid || typeof compUid !== "string") {
|
|
3017
|
+
continue;
|
|
2717
3018
|
}
|
|
2718
|
-
|
|
2719
|
-
|
|
2720
|
-
const rawCurrent = currentDoc?.[rootKey];
|
|
2721
|
-
const coerced = await coerceAndValidateFieldValue(rootAttrDef, updateItem.value, strapi, { forComponentNested: false });
|
|
2722
|
-
if (!coerced.valid) {
|
|
2723
|
-
errors.push(coerced.error || `Invalid value for ${rootKey}`);
|
|
2724
|
-
return { updateData: {}, diffs: [], errors };
|
|
3019
|
+
if (allowedSet.size > 0 && !allowedSet.has(compUid)) {
|
|
3020
|
+
continue;
|
|
2725
3021
|
}
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
newValOut = coerced.value;
|
|
2742
|
-
newDisplay = coerced.displayValue;
|
|
2743
|
-
hasChange = !areValuesEquivalent(rawCurrent, coerced.value);
|
|
3022
|
+
const resolvedAttrs = await resolveComponentPayload(strapi, compUid, block, {});
|
|
3023
|
+
resolvedAttrs.__component = compUid;
|
|
3024
|
+
resolvedBlocks.push(resolvedAttrs);
|
|
3025
|
+
}
|
|
3026
|
+
return resolvedBlocks;
|
|
3027
|
+
}
|
|
3028
|
+
async function buildDocumentUpdatePayload(strapi, uid, existingDoc, rawRow, options = {}) {
|
|
3029
|
+
const schema = discoverSchema(strapi, uid);
|
|
3030
|
+
const payload = {};
|
|
3031
|
+
const isPartialUpdate = options.isPartialUpdate !== false;
|
|
3032
|
+
const unescapedRow = {};
|
|
3033
|
+
for (const [k, v] of Object.entries(rawRow)) {
|
|
3034
|
+
let cleanVal = v;
|
|
3035
|
+
if (typeof cleanVal === "string" && /^'[=+@-]/.test(cleanVal)) {
|
|
3036
|
+
cleanVal = cleanVal.substring(1);
|
|
2744
3037
|
}
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
|
|
3038
|
+
unescapedRow[k] = cleanVal;
|
|
3039
|
+
}
|
|
3040
|
+
const rowMeta = extractMetadataFromRow(unescapedRow);
|
|
3041
|
+
const dotEntriesByAttr = {};
|
|
3042
|
+
for (const [k, v] of Object.entries(unescapedRow)) {
|
|
3043
|
+
const firstDot = k.indexOf(".");
|
|
3044
|
+
if (firstDot > 0) {
|
|
3045
|
+
const parent = k.slice(0, firstDot);
|
|
3046
|
+
if (!dotEntriesByAttr[parent]) dotEntriesByAttr[parent] = [];
|
|
3047
|
+
dotEntriesByAttr[parent].push([k, v]);
|
|
3048
|
+
}
|
|
3049
|
+
}
|
|
3050
|
+
for (const [attrName, field] of Object.entries(schema.fields)) {
|
|
3051
|
+
const hasDirectKey = attrName in unescapedRow;
|
|
3052
|
+
const dotEntries = dotEntriesByAttr[attrName] || [];
|
|
3053
|
+
const hasDotKeys = dotEntries.length > 0;
|
|
3054
|
+
if (!hasDirectKey && !hasDotKeys) {
|
|
3055
|
+
continue;
|
|
3056
|
+
}
|
|
3057
|
+
const rawVal = hasDirectKey ? unescapedRow[attrName] : void 0;
|
|
3058
|
+
switch (field.category) {
|
|
3059
|
+
case "scalar": {
|
|
3060
|
+
if (rawVal === void 0 || rawVal === "" || rawVal === null) {
|
|
3061
|
+
payload[attrName] = null;
|
|
3062
|
+
} else if (field.rawType === "integer" || field.rawType === "biginteger") {
|
|
3063
|
+
payload[attrName] = parseNumeric(rawVal, true);
|
|
3064
|
+
} else if (field.rawType === "float" || field.rawType === "decimal") {
|
|
3065
|
+
payload[attrName] = parseNumeric(rawVal, false);
|
|
3066
|
+
} else if (field.rawType === "boolean") {
|
|
3067
|
+
payload[attrName] = parseBoolean(rawVal);
|
|
3068
|
+
} else if (field.rawType === "date" || field.rawType === "time" || field.rawType === "datetime" || field.rawType === "timestamp") {
|
|
3069
|
+
payload[attrName] = String(rawVal).trim() || null;
|
|
3070
|
+
} else if (field.rawType === "enumeration") {
|
|
3071
|
+
const trimmed = String(rawVal).trim();
|
|
3072
|
+
if (field.enumOptions && field.enumOptions.length > 0) {
|
|
3073
|
+
const match = field.enumOptions.find((o) => o.toLowerCase() === trimmed.toLowerCase());
|
|
3074
|
+
payload[attrName] = match || trimmed;
|
|
3075
|
+
} else {
|
|
3076
|
+
payload[attrName] = trimmed;
|
|
3077
|
+
}
|
|
3078
|
+
} else {
|
|
3079
|
+
payload[attrName] = String(rawVal).trim();
|
|
3080
|
+
}
|
|
3081
|
+
break;
|
|
3082
|
+
}
|
|
3083
|
+
case "blocks": {
|
|
3084
|
+
if (rawVal === void 0 || rawVal === "" || rawVal === null) {
|
|
3085
|
+
payload[attrName] = [];
|
|
3086
|
+
} else {
|
|
3087
|
+
try {
|
|
3088
|
+
const parsed = JSON.parse(rawVal);
|
|
3089
|
+
payload[attrName] = Array.isArray(parsed) ? parsed : [parsed];
|
|
3090
|
+
} catch {
|
|
3091
|
+
payload[attrName] = [
|
|
3092
|
+
{ type: "paragraph", children: [{ type: "text", text: String(rawVal).trim() }] }
|
|
3093
|
+
];
|
|
3094
|
+
}
|
|
3095
|
+
}
|
|
3096
|
+
break;
|
|
3097
|
+
}
|
|
3098
|
+
case "json": {
|
|
3099
|
+
const reconstructed = reconstructFlattenedJsonAttribute({
|
|
3100
|
+
attrName,
|
|
3101
|
+
existingVal: existingDoc?.[attrName],
|
|
3102
|
+
hasDirectKey,
|
|
3103
|
+
directRawVal: rawVal,
|
|
3104
|
+
dotEntries,
|
|
3105
|
+
rowMeta: rowMeta ? {
|
|
3106
|
+
applicableFields: rowMeta.applicableFields,
|
|
3107
|
+
flatTypes: rowMeta.flatTypes
|
|
3108
|
+
} : null,
|
|
3109
|
+
isPartialUpdate
|
|
3110
|
+
});
|
|
3111
|
+
if (reconstructed.shouldSet) {
|
|
3112
|
+
payload[attrName] = reconstructed.value;
|
|
3113
|
+
}
|
|
3114
|
+
break;
|
|
3115
|
+
}
|
|
3116
|
+
case "component_single": {
|
|
3117
|
+
if (field.componentUid) {
|
|
3118
|
+
const directTrimmed = typeof rawVal === "string" ? rawVal.trim() : "";
|
|
3119
|
+
if (hasDotKeys) {
|
|
3120
|
+
const { hasEffectiveEdits, patch } = buildNestedComponentPatchFromDots(
|
|
3121
|
+
attrName,
|
|
3122
|
+
dotEntries
|
|
3123
|
+
);
|
|
3124
|
+
if (hasEffectiveEdits) {
|
|
3125
|
+
payload[attrName] = await resolveComponentPayload(
|
|
3126
|
+
strapi,
|
|
3127
|
+
field.componentUid,
|
|
3128
|
+
patch,
|
|
3129
|
+
existingDoc?.[attrName] || {}
|
|
3130
|
+
);
|
|
3131
|
+
} else if (hasDirectKey && rawVal !== "" && rawVal !== void 0 && rawVal !== null) {
|
|
3132
|
+
if (EXPLICIT_CLEAR_TOKENS.has(directTrimmed) || directTrimmed === "null") {
|
|
3133
|
+
payload[attrName] = null;
|
|
3134
|
+
} else {
|
|
3135
|
+
payload[attrName] = await resolveComponentPayload(
|
|
3136
|
+
strapi,
|
|
3137
|
+
field.componentUid,
|
|
3138
|
+
rawVal,
|
|
3139
|
+
existingDoc?.[attrName] || {}
|
|
3140
|
+
);
|
|
3141
|
+
}
|
|
3142
|
+
}
|
|
3143
|
+
} else if (hasDirectKey) {
|
|
3144
|
+
if (EXPLICIT_CLEAR_TOKENS.has(directTrimmed) || directTrimmed === "null") {
|
|
3145
|
+
payload[attrName] = null;
|
|
3146
|
+
} else if (rawVal !== "" && rawVal !== null && rawVal !== void 0) {
|
|
3147
|
+
payload[attrName] = await resolveComponentPayload(
|
|
3148
|
+
strapi,
|
|
3149
|
+
field.componentUid,
|
|
3150
|
+
rawVal,
|
|
3151
|
+
existingDoc?.[attrName] || {}
|
|
3152
|
+
);
|
|
3153
|
+
}
|
|
3154
|
+
}
|
|
3155
|
+
}
|
|
3156
|
+
break;
|
|
3157
|
+
}
|
|
3158
|
+
case "component_repeatable": {
|
|
3159
|
+
if (field.componentUid) {
|
|
3160
|
+
if (rawVal === "" || rawVal === null || rawVal === void 0) {
|
|
3161
|
+
payload[attrName] = [];
|
|
3162
|
+
} else {
|
|
3163
|
+
let list = [];
|
|
3164
|
+
try {
|
|
3165
|
+
list = typeof rawVal === "string" ? JSON.parse(rawVal) : rawVal;
|
|
3166
|
+
} catch {
|
|
3167
|
+
}
|
|
3168
|
+
if (Array.isArray(list)) {
|
|
3169
|
+
const cleanedItems = [];
|
|
3170
|
+
for (const item of list) {
|
|
3171
|
+
const cleaned = await resolveComponentPayload(
|
|
3172
|
+
strapi,
|
|
3173
|
+
field.componentUid,
|
|
3174
|
+
item,
|
|
3175
|
+
{}
|
|
3176
|
+
);
|
|
3177
|
+
cleanedItems.push(cleaned);
|
|
3178
|
+
}
|
|
3179
|
+
payload[attrName] = cleanedItems;
|
|
3180
|
+
} else {
|
|
3181
|
+
payload[attrName] = [];
|
|
3182
|
+
}
|
|
3183
|
+
}
|
|
3184
|
+
}
|
|
3185
|
+
break;
|
|
3186
|
+
}
|
|
3187
|
+
case "dynamiczone": {
|
|
3188
|
+
const allowedComponents = field.dzComponents || [];
|
|
3189
|
+
if (rawVal === "" || rawVal === null || rawVal === void 0) {
|
|
3190
|
+
payload[attrName] = [];
|
|
3191
|
+
} else {
|
|
3192
|
+
payload[attrName] = await resolveDynamicZonePayload(
|
|
3193
|
+
strapi,
|
|
3194
|
+
allowedComponents,
|
|
3195
|
+
rawVal,
|
|
3196
|
+
existingDoc?.[attrName] || []
|
|
3197
|
+
);
|
|
3198
|
+
}
|
|
3199
|
+
break;
|
|
3200
|
+
}
|
|
3201
|
+
case "relation_to_one": {
|
|
3202
|
+
payload[attrName] = resolveRelationPayload(rawVal, false);
|
|
3203
|
+
break;
|
|
3204
|
+
}
|
|
3205
|
+
case "relation_to_many": {
|
|
3206
|
+
payload[attrName] = resolveRelationPayload(rawVal, true);
|
|
3207
|
+
break;
|
|
3208
|
+
}
|
|
3209
|
+
case "media_single": {
|
|
3210
|
+
payload[attrName] = await resolveMediaIds(strapi, rawVal, false);
|
|
3211
|
+
break;
|
|
3212
|
+
}
|
|
3213
|
+
case "media_to_many": {
|
|
3214
|
+
payload[attrName] = await resolveMediaIds(strapi, rawVal, true);
|
|
3215
|
+
break;
|
|
3216
|
+
}
|
|
3217
|
+
default:
|
|
3218
|
+
payload[attrName] = rawVal;
|
|
3219
|
+
}
|
|
3220
|
+
}
|
|
3221
|
+
return payload;
|
|
3222
|
+
}
|
|
3223
|
+
function formatComponentDisplayName(compUid) {
|
|
3224
|
+
if (!compUid) return "Component";
|
|
3225
|
+
const name = compUid.includes(".") ? compUid.split(".")[1] : compUid;
|
|
3226
|
+
return name.split(/[-_]/).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
|
|
3227
|
+
}
|
|
3228
|
+
function parseAttrPath(path) {
|
|
3229
|
+
if (!path) return { cleanPath: "", rootKey: "", subPath: "" };
|
|
3230
|
+
const bracketMatch = path.match(/^([^.[]+)\[([^\]]+)\](?:\.(.+))?$/);
|
|
3231
|
+
if (bracketMatch) {
|
|
3232
|
+
const rootKey = bracketMatch[1];
|
|
3233
|
+
const selector = bracketMatch[2].trim();
|
|
3234
|
+
const subPath = bracketMatch[3] || "";
|
|
3235
|
+
const cleanPath = subPath ? `${rootKey}.${subPath}` : rootKey;
|
|
3236
|
+
const numMatch = selector.match(/^#?(\d+)/);
|
|
3237
|
+
if (numMatch) {
|
|
3238
|
+
return { cleanPath, rootKey, subPath, targetIndex: parseInt(numMatch[1], 10) };
|
|
3239
|
+
}
|
|
3240
|
+
return { cleanPath, rootKey, subPath, targetComponentUid: selector };
|
|
3241
|
+
}
|
|
3242
|
+
const parts = path.split(".");
|
|
3243
|
+
return {
|
|
3244
|
+
cleanPath: path,
|
|
3245
|
+
rootKey: parts[0] || "",
|
|
3246
|
+
subPath: parts.slice(1).join(".")
|
|
3247
|
+
};
|
|
3248
|
+
}
|
|
3249
|
+
function buildRichAttributeMeta(attrDef, baseMeta) {
|
|
3250
|
+
if (!attrDef || typeof attrDef !== "object") {
|
|
3251
|
+
return { ...baseMeta };
|
|
3252
|
+
}
|
|
3253
|
+
const enriched = { ...baseMeta };
|
|
3254
|
+
if (attrDef.customField) {
|
|
3255
|
+
enriched.customField = String(attrDef.customField);
|
|
3256
|
+
}
|
|
3257
|
+
if (attrDef.options && typeof attrDef.options === "object") {
|
|
3258
|
+
enriched.options = {
|
|
3259
|
+
...attrDef.options.scope !== void 0 ? { scope: attrDef.options.scope } : {},
|
|
3260
|
+
...attrDef.options.disabledBehavior !== void 0 ? { disabledBehavior: attrDef.options.disabledBehavior } : {},
|
|
3261
|
+
...attrDef.options.quotas ? { quotas: { ...attrDef.options.quotas } } : {},
|
|
3262
|
+
...Array.isArray(attrDef.options.items) ? { items: attrDef.options.items.map((it) => ({ ...it })) } : {}
|
|
3263
|
+
};
|
|
3264
|
+
}
|
|
3265
|
+
if (Array.isArray(attrDef.enum)) {
|
|
3266
|
+
enriched.enumOptions = [...attrDef.enum];
|
|
3267
|
+
}
|
|
3268
|
+
if (attrDef.type === "media") {
|
|
3269
|
+
enriched.multiple = Boolean(attrDef.multiple);
|
|
3270
|
+
}
|
|
3271
|
+
if (attrDef.type === "component") {
|
|
3272
|
+
enriched.repeatable = Boolean(attrDef.repeatable);
|
|
3273
|
+
}
|
|
3274
|
+
if (typeof attrDef.min === "number") enriched.min = attrDef.min;
|
|
3275
|
+
if (typeof attrDef.max === "number") enriched.max = attrDef.max;
|
|
3276
|
+
if (typeof attrDef.minLength === "number") enriched.minLength = attrDef.minLength;
|
|
3277
|
+
if (typeof attrDef.maxLength === "number") enriched.maxLength = attrDef.maxLength;
|
|
3278
|
+
if (typeof attrDef.regex === "string") enriched.regex = attrDef.regex;
|
|
3279
|
+
if (attrDef.required) enriched.required = true;
|
|
3280
|
+
if (attrDef.target) enriched.target = attrDef.target;
|
|
3281
|
+
if (attrDef.relation) enriched.relationType = attrDef.relation;
|
|
3282
|
+
return enriched;
|
|
3283
|
+
}
|
|
3284
|
+
function buildOccurrenceKey(segments) {
|
|
3285
|
+
if (!segments || segments.length === 0) return "__scalar__";
|
|
3286
|
+
return segments.map((seg) => {
|
|
3287
|
+
if (seg.index !== void 0) {
|
|
3288
|
+
return seg.componentId !== void 0 && seg.componentId !== null ? `${seg.key}[${seg.index}#${seg.componentId}]` : `${seg.key}[${seg.index}]`;
|
|
3289
|
+
}
|
|
3290
|
+
return seg.key;
|
|
3291
|
+
}).join(".");
|
|
3292
|
+
}
|
|
3293
|
+
function buildReadableOccurrencePath(segments) {
|
|
3294
|
+
if (!segments || segments.length === 0) return "";
|
|
3295
|
+
return segments.map((seg) => {
|
|
3296
|
+
if (seg.index !== void 0) {
|
|
3297
|
+
const compLabel = seg.componentUid ? ` ${formatComponentDisplayName(seg.componentUid)}` : "";
|
|
3298
|
+
return `${seg.key}[#${seg.index}${compLabel}]`;
|
|
3299
|
+
}
|
|
3300
|
+
return seg.key;
|
|
3301
|
+
}).join(".");
|
|
3302
|
+
}
|
|
3303
|
+
function enumerateOccurrences(contentType, allComponents, entity, attrPath) {
|
|
3304
|
+
if (!contentType || !attrPath) return [];
|
|
3305
|
+
const parsed = parseAttrPath(attrPath);
|
|
3306
|
+
const parts = parsed.cleanPath.split(".").filter(Boolean);
|
|
3307
|
+
if (parts.length === 0) return [];
|
|
3308
|
+
const results = [];
|
|
3309
|
+
function walk(currentSchema, currentVal, remainingParts, segments, missingIntermediate, firstArrayIndex, resolvedCompUid, resolvedCompId, isRootLevel) {
|
|
3310
|
+
if (!currentSchema?.attributes || remainingParts.length === 0) return;
|
|
3311
|
+
const [head, ...tail] = remainingParts;
|
|
3312
|
+
const attrDef = currentSchema.attributes[head];
|
|
3313
|
+
if (!attrDef) return;
|
|
3314
|
+
const nextVal = currentVal && typeof currentVal === "object" ? currentVal[head] : void 0;
|
|
3315
|
+
if (tail.length === 0) {
|
|
3316
|
+
const nextSegs = [...segments, { key: head }];
|
|
3317
|
+
results.push({
|
|
3318
|
+
occurrenceKey: segments.length === 0 ? "__scalar__" : buildOccurrenceKey(nextSegs),
|
|
3319
|
+
displayPath: buildReadableOccurrencePath(nextSegs),
|
|
3320
|
+
segments: nextSegs,
|
|
3321
|
+
value: nextVal !== void 0 ? nextVal : null,
|
|
3322
|
+
componentUid: resolvedCompUid,
|
|
3323
|
+
componentName: resolvedCompUid ? formatComponentDisplayName(resolvedCompUid) : void 0,
|
|
3324
|
+
componentId: resolvedCompId,
|
|
3325
|
+
index: firstArrayIndex ?? 0,
|
|
3326
|
+
isMissingIntermediate: missingIntermediate,
|
|
3327
|
+
leafSchema: attrDef
|
|
3328
|
+
});
|
|
3329
|
+
return;
|
|
3330
|
+
}
|
|
3331
|
+
if (attrDef.type === "dynamiczone") {
|
|
3332
|
+
if (!Array.isArray(nextVal)) return;
|
|
3333
|
+
nextVal.forEach((item, idx) => {
|
|
3334
|
+
if (!item || typeof item !== "object") return;
|
|
3335
|
+
if (isRootLevel && parsed.targetIndex !== void 0 && idx !== parsed.targetIndex) return;
|
|
3336
|
+
if (isRootLevel && parsed.targetComponentUid && item.__component !== parsed.targetComponentUid) return;
|
|
3337
|
+
const compSchema = item.__component ? allComponents?.[item.__component] : null;
|
|
3338
|
+
if (!compSchema) return;
|
|
3339
|
+
const seg = {
|
|
3340
|
+
key: head,
|
|
3341
|
+
index: idx,
|
|
3342
|
+
componentId: item.id,
|
|
3343
|
+
componentUid: item.__component
|
|
3344
|
+
};
|
|
3345
|
+
walk(
|
|
3346
|
+
compSchema,
|
|
3347
|
+
item,
|
|
3348
|
+
tail,
|
|
3349
|
+
[...segments, seg],
|
|
3350
|
+
missingIntermediate,
|
|
3351
|
+
firstArrayIndex ?? idx,
|
|
3352
|
+
item.__component,
|
|
3353
|
+
resolvedCompId ?? item.id,
|
|
3354
|
+
false
|
|
3355
|
+
);
|
|
3356
|
+
});
|
|
3357
|
+
return;
|
|
3358
|
+
}
|
|
3359
|
+
if (attrDef.type === "component" && attrDef.component) {
|
|
3360
|
+
const compSchema = allComponents?.[attrDef.component];
|
|
3361
|
+
if (!compSchema) return;
|
|
3362
|
+
if (attrDef.repeatable) {
|
|
3363
|
+
if (!Array.isArray(nextVal)) return;
|
|
3364
|
+
nextVal.forEach((item, idx) => {
|
|
3365
|
+
if (!item || typeof item !== "object") return;
|
|
3366
|
+
if (isRootLevel && parsed.targetIndex !== void 0 && idx !== parsed.targetIndex) return;
|
|
3367
|
+
const seg = {
|
|
3368
|
+
key: head,
|
|
3369
|
+
index: idx,
|
|
3370
|
+
componentId: item.id,
|
|
3371
|
+
componentUid: attrDef.component
|
|
3372
|
+
};
|
|
3373
|
+
walk(
|
|
3374
|
+
compSchema,
|
|
3375
|
+
item,
|
|
3376
|
+
tail,
|
|
3377
|
+
[...segments, seg],
|
|
3378
|
+
missingIntermediate,
|
|
3379
|
+
firstArrayIndex ?? idx,
|
|
3380
|
+
attrDef.component,
|
|
3381
|
+
resolvedCompId ?? item.id,
|
|
3382
|
+
false
|
|
3383
|
+
);
|
|
3384
|
+
});
|
|
3385
|
+
} else {
|
|
3386
|
+
const isMissing = !nextVal || typeof nextVal !== "object";
|
|
3387
|
+
const seg = {
|
|
3388
|
+
key: head,
|
|
3389
|
+
componentId: !isMissing ? nextVal.id : void 0,
|
|
3390
|
+
componentUid: attrDef.component
|
|
3391
|
+
};
|
|
3392
|
+
walk(
|
|
3393
|
+
compSchema,
|
|
3394
|
+
isMissing ? void 0 : nextVal,
|
|
3395
|
+
tail,
|
|
3396
|
+
[...segments, seg],
|
|
3397
|
+
missingIntermediate || isMissing,
|
|
3398
|
+
firstArrayIndex,
|
|
3399
|
+
resolvedCompUid ?? attrDef.component,
|
|
3400
|
+
resolvedCompId ?? (!isMissing ? nextVal.id : void 0),
|
|
3401
|
+
false
|
|
3402
|
+
);
|
|
3403
|
+
}
|
|
3404
|
+
}
|
|
3405
|
+
}
|
|
3406
|
+
walk(contentType, entity, parts, [], false, void 0, void 0, void 0, true);
|
|
3407
|
+
return results;
|
|
3408
|
+
}
|
|
3409
|
+
function formatRelationState(currentRel, isMulti) {
|
|
3410
|
+
if (isMulti && Array.isArray(currentRel)) {
|
|
3411
|
+
const oldDocIds = currentRel.map((r) => r?.documentId).filter(Boolean);
|
|
3412
|
+
const oldDisplay = currentRel.map((r) => r?.name || r?.title || r?.email || r?.username || r?.documentId).filter(Boolean).join(", ") || "(unlinked / none)";
|
|
3413
|
+
return { oldDocIds, oldDisplay };
|
|
3414
|
+
}
|
|
3415
|
+
if (currentRel && typeof currentRel === "object") {
|
|
3416
|
+
const oldDocIds = currentRel.documentId ? [currentRel.documentId] : [];
|
|
3417
|
+
const oldDisplay = currentRel.name || currentRel.title || currentRel.email || currentRel.username || currentRel.documentId || "(unlinked / none)";
|
|
3418
|
+
return { oldDocIds, oldDisplay };
|
|
3419
|
+
}
|
|
3420
|
+
return { oldDocIds: [], oldDisplay: "(unlinked / none)" };
|
|
3421
|
+
}
|
|
3422
|
+
function resolveRelationCommand(rawValue, isMulti, forComponentNested = false) {
|
|
3423
|
+
let mode = "set";
|
|
3424
|
+
let targetDocIds = [];
|
|
3425
|
+
let display = "";
|
|
3426
|
+
if (rawValue === null || rawValue === void 0 || rawValue === "__clear__" || rawValue === "") {
|
|
3427
|
+
mode = "clear";
|
|
3428
|
+
display = "(cleared / unlinked)";
|
|
3429
|
+
} else if (typeof rawValue === "object" && !Array.isArray(rawValue)) {
|
|
3430
|
+
if (rawValue.mode) {
|
|
3431
|
+
mode = rawValue.mode;
|
|
3432
|
+
targetDocIds = Array.isArray(rawValue.documentIds) ? rawValue.documentIds.filter(Boolean).map(String) : rawValue.documentId ? [String(rawValue.documentId)] : [];
|
|
3433
|
+
display = rawValue.label || targetDocIds.join(", ") || `[${mode}]`;
|
|
3434
|
+
} else if (rawValue.documentId) {
|
|
3435
|
+
targetDocIds = [String(rawValue.documentId)];
|
|
3436
|
+
display = rawValue.label || targetDocIds[0];
|
|
3437
|
+
}
|
|
3438
|
+
} else if (Array.isArray(rawValue)) {
|
|
3439
|
+
targetDocIds = rawValue.map((v) => typeof v === "object" ? v?.documentId : v).filter(Boolean).map(String);
|
|
3440
|
+
display = targetDocIds.join(", ") || "(cleared / unlinked)";
|
|
3441
|
+
if (targetDocIds.length === 0) mode = "clear";
|
|
3442
|
+
} else {
|
|
3443
|
+
const strVal = String(rawValue);
|
|
3444
|
+
try {
|
|
3445
|
+
const parsed = JSON.parse(strVal);
|
|
3446
|
+
if (parsed && typeof parsed === "object" && parsed.mode) {
|
|
3447
|
+
mode = parsed.mode;
|
|
3448
|
+
targetDocIds = Array.isArray(parsed.documentIds) ? parsed.documentIds.filter(Boolean).map(String) : parsed.documentId ? [String(parsed.documentId)] : [];
|
|
3449
|
+
display = parsed.label || targetDocIds.join(", ") || `[${mode}]`;
|
|
3450
|
+
} else if (Array.isArray(parsed)) {
|
|
3451
|
+
targetDocIds = parsed.filter(Boolean).map(String);
|
|
3452
|
+
display = targetDocIds.join(", ");
|
|
3453
|
+
} else {
|
|
3454
|
+
targetDocIds = [strVal];
|
|
3455
|
+
display = strVal;
|
|
3456
|
+
}
|
|
3457
|
+
} catch {
|
|
3458
|
+
targetDocIds = [strVal];
|
|
3459
|
+
display = strVal;
|
|
3460
|
+
}
|
|
3461
|
+
}
|
|
3462
|
+
let relationPayload;
|
|
3463
|
+
if (mode === "clear") {
|
|
3464
|
+
relationPayload = isMulti ? { set: [] } : null;
|
|
3465
|
+
} else if (mode === "set") {
|
|
3466
|
+
relationPayload = isMulti ? { set: targetDocIds } : targetDocIds[0] || null;
|
|
3467
|
+
} else if (mode === "connect") {
|
|
3468
|
+
relationPayload = { connect: targetDocIds };
|
|
3469
|
+
} else if (mode === "disconnect") {
|
|
3470
|
+
relationPayload = { disconnect: targetDocIds };
|
|
3471
|
+
}
|
|
3472
|
+
return { mode, targetDocIds, relationPayload, display };
|
|
3473
|
+
}
|
|
3474
|
+
async function coerceAndValidateFieldValue(attrDef, rawValue, strapi, options = {}) {
|
|
3475
|
+
if (!attrDef || typeof attrDef !== "object") {
|
|
3476
|
+
return {
|
|
3477
|
+
valid: true,
|
|
3478
|
+
value: rawValue,
|
|
3479
|
+
displayValue: rawValue !== void 0 && rawValue !== null ? String(rawValue) : "(empty)"
|
|
3480
|
+
};
|
|
3481
|
+
}
|
|
3482
|
+
const type = String(attrDef.type || "").toLowerCase();
|
|
3483
|
+
if (type === "relation") {
|
|
3484
|
+
const isMulti = attrDef.relation === "oneToMany" || attrDef.relation === "manyToMany";
|
|
3485
|
+
const cmd = resolveRelationCommand(rawValue, isMulti, options.forComponentNested);
|
|
3486
|
+
if (attrDef.required && (cmd.mode === "clear" || cmd.mode === "set" && cmd.targetDocIds.length === 0)) {
|
|
3487
|
+
return {
|
|
3488
|
+
valid: false,
|
|
3489
|
+
value: rawValue,
|
|
3490
|
+
displayValue: cmd.display,
|
|
3491
|
+
isRelation: true,
|
|
3492
|
+
error: "Relation field is required and cannot be cleared."
|
|
3493
|
+
};
|
|
3494
|
+
}
|
|
3495
|
+
return {
|
|
3496
|
+
valid: true,
|
|
3497
|
+
value: cmd.relationPayload,
|
|
3498
|
+
displayValue: cmd.display,
|
|
3499
|
+
isRelation: true,
|
|
3500
|
+
relationMeta: { isRelation: true, mode: cmd.mode, documentIds: cmd.targetDocIds, display: cmd.display }
|
|
3501
|
+
};
|
|
3502
|
+
}
|
|
3503
|
+
if (type === "media") {
|
|
3504
|
+
const isMultiple = Boolean(attrDef.multiple);
|
|
3505
|
+
if (rawValue === null || rawValue === void 0 || rawValue === "" || rawValue === "__clear__") {
|
|
3506
|
+
if (attrDef.required) {
|
|
3507
|
+
return { valid: false, value: rawValue, displayValue: "", error: "Media field is required." };
|
|
3508
|
+
}
|
|
3509
|
+
const cleared = isMultiple ? [] : null;
|
|
3510
|
+
return { valid: true, value: cleared, displayValue: "(cleared)" };
|
|
3511
|
+
}
|
|
3512
|
+
const mediaPayload = strapi ? await resolveMediaIds(strapi, rawValue, isMultiple) : rawValue;
|
|
3513
|
+
if (attrDef.required && (mediaPayload === null || Array.isArray(mediaPayload) && mediaPayload.length === 0)) {
|
|
3514
|
+
return { valid: false, value: rawValue, displayValue: "", error: "Media asset could not be resolved." };
|
|
3515
|
+
}
|
|
3516
|
+
return {
|
|
3517
|
+
valid: true,
|
|
3518
|
+
value: mediaPayload,
|
|
3519
|
+
displayValue: Array.isArray(mediaPayload) ? `[${mediaPayload.length} asset(s)]` : mediaPayload !== null ? `#${mediaPayload}` : "(cleared)"
|
|
3520
|
+
};
|
|
3521
|
+
}
|
|
3522
|
+
const isEmptyInput = rawValue === null || rawValue === void 0 || rawValue === "";
|
|
3523
|
+
if (attrDef.required && (isEmptyInput || type === "boolean" && rawValue === null)) {
|
|
3524
|
+
return {
|
|
3525
|
+
valid: false,
|
|
3526
|
+
value: rawValue,
|
|
3527
|
+
displayValue: "",
|
|
3528
|
+
error: "Field is required and cannot be empty."
|
|
3529
|
+
};
|
|
3530
|
+
}
|
|
3531
|
+
if (rawValue === null || rawValue === void 0) {
|
|
3532
|
+
return { valid: true, value: null, displayValue: "(empty)" };
|
|
3533
|
+
}
|
|
3534
|
+
switch (type) {
|
|
3535
|
+
case "integer": {
|
|
3536
|
+
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
3537
|
+
const str = String(rawValue).trim();
|
|
3538
|
+
if (!/^-?\d+$/.test(str)) {
|
|
3539
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Invalid integer value "${str}".` };
|
|
3540
|
+
}
|
|
3541
|
+
const num = Number(str);
|
|
3542
|
+
if (!Number.isSafeInteger(num)) {
|
|
3543
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Integer "${str}" is out of safe range.` };
|
|
3544
|
+
}
|
|
3545
|
+
if (typeof attrDef.min === "number" && num < attrDef.min) {
|
|
3546
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Value ${num} is less than minimum ${attrDef.min}.` };
|
|
3547
|
+
}
|
|
3548
|
+
if (typeof attrDef.max === "number" && num > attrDef.max) {
|
|
3549
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Value ${num} exceeds maximum ${attrDef.max}.` };
|
|
3550
|
+
}
|
|
3551
|
+
return { valid: true, value: num, displayValue: String(num) };
|
|
3552
|
+
}
|
|
3553
|
+
case "biginteger": {
|
|
3554
|
+
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
3555
|
+
const str = String(rawValue).trim();
|
|
3556
|
+
if (!/^-?\d+$/.test(str)) {
|
|
3557
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Invalid biginteger value "${str}".` };
|
|
3558
|
+
}
|
|
3559
|
+
return { valid: true, value: str, displayValue: str };
|
|
3560
|
+
}
|
|
3561
|
+
case "float":
|
|
3562
|
+
case "decimal": {
|
|
3563
|
+
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
3564
|
+
const str = String(rawValue).trim();
|
|
3565
|
+
if (!/^-?\d+(\.\d+)?$/.test(str)) {
|
|
3566
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Invalid decimal number "${str}".` };
|
|
3567
|
+
}
|
|
3568
|
+
const num = Number(str);
|
|
3569
|
+
if (!Number.isFinite(num)) {
|
|
3570
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Number "${str}" is not finite.` };
|
|
3571
|
+
}
|
|
3572
|
+
if (typeof attrDef.min === "number" && num < attrDef.min) {
|
|
3573
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Value ${num} is less than minimum ${attrDef.min}.` };
|
|
3574
|
+
}
|
|
3575
|
+
if (typeof attrDef.max === "number" && num > attrDef.max) {
|
|
3576
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Value ${num} exceeds maximum ${attrDef.max}.` };
|
|
3577
|
+
}
|
|
3578
|
+
return { valid: true, value: num, displayValue: String(num) };
|
|
3579
|
+
}
|
|
3580
|
+
case "boolean": {
|
|
3581
|
+
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
3582
|
+
if (typeof rawValue === "boolean") {
|
|
3583
|
+
return { valid: true, value: rawValue, displayValue: String(rawValue) };
|
|
3584
|
+
}
|
|
3585
|
+
const lower = String(rawValue).trim().toLowerCase();
|
|
3586
|
+
if (lower === "true" || lower === "1" || lower === "yes") {
|
|
3587
|
+
return { valid: true, value: true, displayValue: "true" };
|
|
3588
|
+
}
|
|
3589
|
+
if (lower === "false" || lower === "0" || lower === "no") {
|
|
3590
|
+
return { valid: true, value: false, displayValue: "false" };
|
|
3591
|
+
}
|
|
3592
|
+
return { valid: false, value: rawValue, displayValue: String(rawValue), error: `Invalid boolean value "${rawValue}".` };
|
|
3593
|
+
}
|
|
3594
|
+
case "enumeration": {
|
|
3595
|
+
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
3596
|
+
const str = String(rawValue);
|
|
3597
|
+
if (Array.isArray(attrDef.enum) && !attrDef.enum.includes(str)) {
|
|
3598
|
+
return {
|
|
3599
|
+
valid: false,
|
|
3600
|
+
value: rawValue,
|
|
3601
|
+
displayValue: str,
|
|
3602
|
+
error: `Value "${str}" is not an allowed enum option (${attrDef.enum.join(", ")}).`
|
|
3603
|
+
};
|
|
3604
|
+
}
|
|
3605
|
+
return { valid: true, value: str, displayValue: str };
|
|
3606
|
+
}
|
|
3607
|
+
case "email": {
|
|
3608
|
+
const str = String(rawValue).trim();
|
|
3609
|
+
if (str === "") return { valid: true, value: "", displayValue: "(empty)" };
|
|
3610
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str)) {
|
|
3611
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Invalid email address "${str}".` };
|
|
3612
|
+
}
|
|
3613
|
+
return { valid: true, value: str, displayValue: str };
|
|
3614
|
+
}
|
|
3615
|
+
case "uid": {
|
|
3616
|
+
const str = String(rawValue).trim();
|
|
3617
|
+
if (str !== "" && !/^[A-Za-z0-9\-_.~]*$/.test(str)) {
|
|
3618
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Invalid UID slug "${str}". Allowed characters: A-Z a-z 0-9 - _ . ~` };
|
|
3619
|
+
}
|
|
3620
|
+
return { valid: true, value: str, displayValue: str || "(empty)" };
|
|
3621
|
+
}
|
|
3622
|
+
case "json":
|
|
3623
|
+
case "blocks": {
|
|
3624
|
+
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
3625
|
+
let parsedVal = rawValue;
|
|
3626
|
+
if (typeof rawValue === "string") {
|
|
3627
|
+
try {
|
|
3628
|
+
parsedVal = JSON.parse(rawValue);
|
|
3629
|
+
} catch (err) {
|
|
3630
|
+
return {
|
|
3631
|
+
valid: false,
|
|
3632
|
+
value: rawValue,
|
|
3633
|
+
displayValue: rawValue,
|
|
3634
|
+
error: `Invalid ${type === "blocks" ? "Blocks" : "JSON"} syntax: ${err.message}`
|
|
3635
|
+
};
|
|
3636
|
+
}
|
|
3637
|
+
}
|
|
3638
|
+
if (type === "blocks" && parsedVal !== null && !Array.isArray(parsedVal)) {
|
|
3639
|
+
return { valid: false, value: rawValue, displayValue: String(rawValue), error: "Strapi Blocks field must be a JSON array." };
|
|
3640
|
+
}
|
|
3641
|
+
return {
|
|
3642
|
+
valid: true,
|
|
3643
|
+
value: parsedVal,
|
|
3644
|
+
displayValue: parsedVal === null ? "(empty)" : JSON.stringify(parsedVal)
|
|
3645
|
+
};
|
|
3646
|
+
}
|
|
3647
|
+
case "date":
|
|
3648
|
+
case "datetime": {
|
|
3649
|
+
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
3650
|
+
const str = String(rawValue).trim();
|
|
3651
|
+
const d = new Date(str);
|
|
3652
|
+
if (isNaN(d.getTime())) {
|
|
3653
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Invalid ${type} value "${str}".` };
|
|
3654
|
+
}
|
|
3655
|
+
const out = type === "date" ? /^\d{4}-\d{2}-\d{2}$/.test(str) ? str : d.toISOString().slice(0, 10) : d.toISOString();
|
|
3656
|
+
return { valid: true, value: out, displayValue: out };
|
|
3657
|
+
}
|
|
3658
|
+
case "time": {
|
|
3659
|
+
if (rawValue === "") return { valid: true, value: null, displayValue: "(empty)" };
|
|
3660
|
+
const str = String(rawValue).trim();
|
|
3661
|
+
if (!/^\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?$/.test(str)) {
|
|
3662
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Invalid time format "${str}" (expected HH:mm or HH:mm:ss).` };
|
|
3663
|
+
}
|
|
3664
|
+
return { valid: true, value: str, displayValue: str };
|
|
3665
|
+
}
|
|
3666
|
+
default: {
|
|
3667
|
+
const str = typeof rawValue === "object" ? JSON.stringify(rawValue) : String(rawValue);
|
|
3668
|
+
if (typeof attrDef.minLength === "number" && str.length < attrDef.minLength) {
|
|
3669
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Length ${str.length} is shorter than minimum ${attrDef.minLength}.` };
|
|
3670
|
+
}
|
|
3671
|
+
if (typeof attrDef.maxLength === "number" && str.length > attrDef.maxLength) {
|
|
3672
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Length ${str.length} exceeds maximum ${attrDef.maxLength}.` };
|
|
3673
|
+
}
|
|
3674
|
+
if (typeof attrDef.regex === "string" && attrDef.regex && str !== "") {
|
|
3675
|
+
try {
|
|
3676
|
+
const re = new RegExp(attrDef.regex);
|
|
3677
|
+
if (!re.test(str)) {
|
|
3678
|
+
return { valid: false, value: rawValue, displayValue: str, error: `Value does not match required pattern /${attrDef.regex}/.` };
|
|
3679
|
+
}
|
|
3680
|
+
} catch {
|
|
3681
|
+
}
|
|
3682
|
+
}
|
|
3683
|
+
return { valid: true, value: rawValue, displayValue: str || "(empty)" };
|
|
3684
|
+
}
|
|
3685
|
+
}
|
|
3686
|
+
}
|
|
3687
|
+
function findTargetArrayIndex(arr, seg, arrFieldKey) {
|
|
3688
|
+
if (!Array.isArray(arr)) {
|
|
3689
|
+
throw new Error(`Expected array for component/dynamiczone field "${arrFieldKey}".`);
|
|
3690
|
+
}
|
|
3691
|
+
if (seg.componentId !== void 0 && seg.componentId !== null) {
|
|
3692
|
+
const idMatchIdx = arr.findIndex((item) => {
|
|
3693
|
+
if (!item || typeof item !== "object") return false;
|
|
3694
|
+
if (String(item.id) !== String(seg.componentId)) return false;
|
|
3695
|
+
if (seg.componentUid && item.__component && item.__component !== seg.componentUid) return false;
|
|
3696
|
+
return true;
|
|
3697
|
+
});
|
|
3698
|
+
if (idMatchIdx === -1) {
|
|
3699
|
+
throw new Error(
|
|
3700
|
+
`Stale target: component instance (id: ${seg.componentId}) in "${arrFieldKey}" was modified or deleted. Please refresh the grid and retry.`
|
|
3701
|
+
);
|
|
3702
|
+
}
|
|
3703
|
+
return idMatchIdx;
|
|
3704
|
+
}
|
|
3705
|
+
if (typeof seg.index === "number") {
|
|
3706
|
+
if (seg.index < 0 || seg.index >= arr.length) {
|
|
3707
|
+
throw new Error(
|
|
3708
|
+
`Stale target: occurrence #${seg.index} in "${arrFieldKey}" no longer exists (length ${arr.length}). Please refresh the grid and retry.`
|
|
3709
|
+
);
|
|
3710
|
+
}
|
|
3711
|
+
const item = arr[seg.index];
|
|
3712
|
+
if (seg.componentUid && item?.__component && item.__component !== seg.componentUid) {
|
|
3713
|
+
throw new Error(
|
|
3714
|
+
`Stale target: occurrence #${seg.index} in "${arrFieldKey}" changed component type to "${item.__component}". Please refresh the grid.`
|
|
3715
|
+
);
|
|
3716
|
+
}
|
|
3717
|
+
return seg.index;
|
|
3718
|
+
}
|
|
3719
|
+
throw new Error(`Missing occurrence index/componentId for "${arrFieldKey}".`);
|
|
3720
|
+
}
|
|
3721
|
+
function buildFallbackSegmentsFromUpdate(contentType, allComponents, cleanPath, occUpdate, parsedTargetCompUid) {
|
|
3722
|
+
if (Array.isArray(occUpdate.segments) && occUpdate.segments.length > 0) {
|
|
3723
|
+
return occUpdate.segments;
|
|
3724
|
+
}
|
|
3725
|
+
const parts = cleanPath.split(".").filter(Boolean);
|
|
3726
|
+
const segs = [];
|
|
3727
|
+
let curSchema = contentType;
|
|
3728
|
+
let usedFirstArrayMeta = false;
|
|
3729
|
+
for (let i = 0; i < parts.length; i++) {
|
|
3730
|
+
const key = parts[i];
|
|
3731
|
+
const attrDef = curSchema?.attributes?.[key];
|
|
3732
|
+
const isLast = i === parts.length - 1;
|
|
3733
|
+
if (!isLast && attrDef && (attrDef.type === "dynamiczone" || attrDef.type === "component" && attrDef.repeatable)) {
|
|
3734
|
+
const seg = { key };
|
|
3735
|
+
if (!usedFirstArrayMeta) {
|
|
3736
|
+
if (occUpdate.dynamicZoneIndex !== void 0) seg.index = occUpdate.dynamicZoneIndex;
|
|
3737
|
+
if (occUpdate.componentId !== void 0) seg.componentId = occUpdate.componentId;
|
|
3738
|
+
if (occUpdate.componentUid || parsedTargetCompUid) {
|
|
3739
|
+
seg.componentUid = occUpdate.componentUid || parsedTargetCompUid;
|
|
3740
|
+
}
|
|
3741
|
+
usedFirstArrayMeta = true;
|
|
3742
|
+
}
|
|
3743
|
+
segs.push(seg);
|
|
3744
|
+
const nextCompUid = seg.componentUid || attrDef.component;
|
|
3745
|
+
curSchema = nextCompUid ? allComponents?.[nextCompUid] : void 0;
|
|
3746
|
+
} else {
|
|
3747
|
+
segs.push({ key });
|
|
3748
|
+
if (!isLast && attrDef?.type === "component" && attrDef.component) {
|
|
3749
|
+
curSchema = allComponents?.[attrDef.component];
|
|
3750
|
+
}
|
|
3751
|
+
}
|
|
3752
|
+
}
|
|
3753
|
+
return segs;
|
|
3754
|
+
}
|
|
3755
|
+
function formatValueDisplay$1(val, isRelation = false, isMulti = false) {
|
|
3756
|
+
if (isRelation) {
|
|
3757
|
+
return formatRelationState(val, isMulti).oldDisplay;
|
|
3758
|
+
}
|
|
3759
|
+
if (val === void 0 || val === null || val === "") return "(empty)";
|
|
3760
|
+
if (typeof val === "object") return JSON.stringify(val);
|
|
3761
|
+
return String(val);
|
|
3762
|
+
}
|
|
3763
|
+
async function applyOccurrenceUpdatesToDocument({
|
|
3764
|
+
strapi,
|
|
3765
|
+
contentType,
|
|
3766
|
+
allComponents,
|
|
3767
|
+
currentDoc,
|
|
3768
|
+
attribute,
|
|
3769
|
+
updates
|
|
3770
|
+
}) {
|
|
3771
|
+
const parsed = parseAttrPath(attribute);
|
|
3772
|
+
const parts = parsed.cleanPath.split(".").filter(Boolean);
|
|
3773
|
+
const rootKey = parts[0];
|
|
3774
|
+
const rootAttrDef = contentType?.attributes?.[rootKey];
|
|
3775
|
+
const diffs = [];
|
|
3776
|
+
const errors = [];
|
|
3777
|
+
if (parts.length === 1 && rootAttrDef?.type !== "component" && rootAttrDef?.type !== "dynamiczone") {
|
|
3778
|
+
const updateItem = updates[0];
|
|
3779
|
+
if (!updateItem) {
|
|
3780
|
+
return { updateData: {}, diffs: [], errors: [] };
|
|
3781
|
+
}
|
|
3782
|
+
const isRelation = rootAttrDef?.type === "relation";
|
|
3783
|
+
const isMulti = isRelation && (rootAttrDef.relation === "oneToMany" || rootAttrDef.relation === "manyToMany");
|
|
3784
|
+
const rawCurrent = currentDoc?.[rootKey];
|
|
3785
|
+
const coerced = await coerceAndValidateFieldValue(rootAttrDef, updateItem.value, strapi, { forComponentNested: false });
|
|
3786
|
+
if (!coerced.valid) {
|
|
3787
|
+
errors.push(coerced.error || `Invalid value for ${rootKey}`);
|
|
3788
|
+
return { updateData: {}, diffs: [], errors };
|
|
3789
|
+
}
|
|
3790
|
+
let oldVal;
|
|
3791
|
+
let oldDisplay;
|
|
3792
|
+
let newValOut;
|
|
3793
|
+
let newDisplay;
|
|
3794
|
+
let hasChange;
|
|
3795
|
+
if (isRelation) {
|
|
3796
|
+
const relState = formatRelationState(rawCurrent, isMulti);
|
|
3797
|
+
oldVal = { isRelation: true, documentIds: relState.oldDocIds, display: relState.oldDisplay };
|
|
3798
|
+
oldDisplay = relState.oldDisplay;
|
|
3799
|
+
newValOut = coerced.relationMeta;
|
|
3800
|
+
newDisplay = coerced.displayValue;
|
|
3801
|
+
hasChange = coerced.relationMeta?.mode === "clear" ? relState.oldDocIds.length > 0 : JSON.stringify(relState.oldDocIds) !== JSON.stringify(coerced.relationMeta?.documentIds || []) || coerced.relationMeta?.mode !== "set";
|
|
3802
|
+
} else {
|
|
3803
|
+
oldVal = rawCurrent ?? null;
|
|
3804
|
+
oldDisplay = formatValueDisplay$1(rawCurrent);
|
|
3805
|
+
newValOut = coerced.value;
|
|
3806
|
+
newDisplay = coerced.displayValue;
|
|
3807
|
+
hasChange = !areValuesEquivalent(rawCurrent, coerced.value);
|
|
3808
|
+
}
|
|
3809
|
+
diffs.push({
|
|
3810
|
+
occurrenceKey: "__scalar__",
|
|
3811
|
+
segments: [{ key: rootKey }],
|
|
3812
|
+
index: 0,
|
|
3813
|
+
attribute: rootKey,
|
|
2750
3814
|
oldValue: oldVal,
|
|
2751
3815
|
newValue: newValOut,
|
|
2752
3816
|
oldDisplay,
|
|
@@ -7300,674 +8364,307 @@ const auditService = ({ strapi }) => ({
|
|
|
7300
8364
|
const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
|
|
7301
8365
|
if (bulkService?.invalidateCache) {
|
|
7302
8366
|
bulkService.invalidateCache(item.uid);
|
|
7303
|
-
}
|
|
7304
|
-
} catch {
|
|
7305
|
-
}
|
|
7306
|
-
revertedCount++;
|
|
7307
|
-
rollbackDetails.push({
|
|
7308
|
-
uid: item.uid,
|
|
7309
|
-
documentId: item.documentId,
|
|
7310
|
-
label: item.label,
|
|
7311
|
-
attribute: item.attribute,
|
|
7312
|
-
revertedTo: item.oldValue,
|
|
7313
|
-
status: "reverted"
|
|
7314
|
-
});
|
|
7315
|
-
} catch (err) {
|
|
7316
|
-
rollbackDetails.push({
|
|
7317
|
-
uid: item.uid,
|
|
7318
|
-
documentId: item.documentId,
|
|
7319
|
-
label: item.label,
|
|
7320
|
-
status: "error",
|
|
7321
|
-
message: err.message
|
|
7322
|
-
});
|
|
7323
|
-
}
|
|
7324
|
-
}
|
|
7325
|
-
}
|
|
7326
|
-
return { revertedCount, rollbackDetails };
|
|
7327
|
-
},
|
|
7328
|
-
/**
|
|
7329
|
-
* Performs deterministic rollback of a batch.
|
|
7330
|
-
* Strict invariant: ONLY the latest completed update is eligible for rollback.
|
|
7331
|
-
* Older completed updates, already rolled-back updates, and pending/failed/executing batches are strictly rejected.
|
|
7332
|
-
*/
|
|
7333
|
-
async rollbackBatch(batchId, currentUser) {
|
|
7334
|
-
return withRollbackLock(async () => {
|
|
7335
|
-
const config = this.getAuditConfig();
|
|
7336
|
-
if (!config.enabled) {
|
|
7337
|
-
throw new Error("Audit trail is not configured or disabled.");
|
|
7338
|
-
}
|
|
7339
|
-
if (!batchId) {
|
|
7340
|
-
throw new Error("A valid batchId is required to perform rollback.");
|
|
7341
|
-
}
|
|
7342
|
-
try {
|
|
7343
|
-
const bulkService = strapi.plugin("bulk-updater")?.service("bulkUpdater");
|
|
7344
|
-
if (bulkService && typeof bulkService.getBatchStatus === "function") {
|
|
7345
|
-
const statusRes = await bulkService.getBatchStatus(batchId);
|
|
7346
|
-
const batchJob = statusRes?.batch;
|
|
7347
|
-
if (batchJob) {
|
|
7348
|
-
if (batchJob.status === "pending_approval" || batchJob.status === "queued_offpeak") {
|
|
7349
|
-
throw new Error(`Batch "${batchId}" is currently pending and cannot be rolled back.`);
|
|
7350
|
-
}
|
|
7351
|
-
if (batchJob.status === "processing" || batchJob.status === "running" || batchJob.status === "executing") {
|
|
7352
|
-
throw new Error(`Batch "${batchId}" is currently executing and cannot be rolled back.`);
|
|
7353
|
-
}
|
|
7354
|
-
if (batchJob.status === "failed") {
|
|
7355
|
-
throw new Error(`Batch "${batchId}" failed during execution and cannot be rolled back.`);
|
|
7356
|
-
}
|
|
7357
|
-
}
|
|
7358
|
-
}
|
|
7359
|
-
} catch (checkErr) {
|
|
7360
|
-
if (checkErr.message?.startsWith('Batch "')) {
|
|
7361
|
-
throw checkErr;
|
|
7362
|
-
}
|
|
7363
|
-
}
|
|
7364
|
-
if (config.mode === "store") {
|
|
7365
|
-
const store = strapi.store({ type: "plugin", name: "bulk-updater", key: "audit-history" });
|
|
7366
|
-
const stored = await store.get({}) || { history: [] };
|
|
7367
|
-
const rawHistory = Array.isArray(stored.history) ? stored.history : [];
|
|
7368
|
-
if (rawHistory.length === 0) {
|
|
7369
|
-
throw new Error("No completed update records found in audit trail.");
|
|
7370
|
-
}
|
|
7371
|
-
const sortedHistory2 = sortAuditRecordsDesc(rawHistory);
|
|
7372
|
-
const targetRecord2 = sortedHistory2.find((r) => r.batchId === batchId);
|
|
7373
|
-
if (!targetRecord2) {
|
|
7374
|
-
throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
|
|
7375
|
-
}
|
|
7376
|
-
const latestRecord2 = sortedHistory2[0];
|
|
7377
|
-
if (latestRecord2.batchId !== batchId) {
|
|
7378
|
-
throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
|
|
7379
|
-
}
|
|
7380
|
-
if (targetRecord2.isRolledBack) {
|
|
7381
|
-
throw new Error(`Batch "${batchId}" has already been rolled back.`);
|
|
7382
|
-
}
|
|
7383
|
-
const diffs2 = Array.isArray(targetRecord2.diffs) ? targetRecord2.diffs : [];
|
|
7384
|
-
const { revertedCount: revertedCount2, rollbackDetails: rollbackDetails2 } = await this.revertDiffItems(diffs2, currentUser?.id);
|
|
7385
|
-
const recordIndex = rawHistory.findIndex((r) => r.batchId === batchId);
|
|
7386
|
-
if (recordIndex !== -1) {
|
|
7387
|
-
rawHistory[recordIndex] = {
|
|
7388
|
-
...rawHistory[recordIndex],
|
|
7389
|
-
isRolledBack: true,
|
|
7390
|
-
rolledBackAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
7391
|
-
rolledBackBy: currentUser?.email || "Admin"
|
|
7392
|
-
};
|
|
7393
|
-
await store.set({ value: { history: rawHistory } });
|
|
7394
|
-
}
|
|
7395
|
-
try {
|
|
7396
|
-
const affectedUids = new Set(rollbackDetails2.map((d) => d.uid));
|
|
7397
|
-
const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
|
|
7398
|
-
affectedUids.forEach((uid) => {
|
|
7399
|
-
if (uid && bulkService?.invalidateCache) {
|
|
7400
|
-
bulkService.invalidateCache(uid);
|
|
7401
|
-
}
|
|
7402
|
-
});
|
|
7403
|
-
} catch {
|
|
7404
|
-
}
|
|
7405
|
-
await this.recordToEnterpriseNative(
|
|
7406
|
-
"bulk-updater.rollback",
|
|
7407
|
-
{
|
|
7408
|
-
batchId,
|
|
7409
|
-
revertedCount: revertedCount2
|
|
7410
|
-
},
|
|
7411
|
-
currentUser
|
|
7412
|
-
);
|
|
7413
|
-
return {
|
|
7414
|
-
success: true,
|
|
7415
|
-
batchId,
|
|
7416
|
-
revertedCount: revertedCount2,
|
|
7417
|
-
details: rollbackDetails2
|
|
7418
|
-
};
|
|
7419
|
-
}
|
|
7420
|
-
if (!config.contentType || !config.fields) {
|
|
7421
|
-
throw new Error("Audit trail is not configured or disabled.");
|
|
7422
|
-
}
|
|
7423
|
-
const f = config.fields;
|
|
7424
|
-
const allRecords = await strapi.documents(config.contentType).findMany({
|
|
7425
|
-
sort: { createdAt: "desc" }
|
|
7426
|
-
});
|
|
7427
|
-
if (!allRecords || allRecords.length === 0) {
|
|
7428
|
-
throw new Error("No completed update records found in audit trail.");
|
|
7429
|
-
}
|
|
7430
|
-
const normalizedHistory = allRecords.map((r) => ({
|
|
7431
|
-
id: r.id,
|
|
7432
|
-
documentId: r.documentId,
|
|
7433
|
-
batchId: r[f.batchId] || r.documentId,
|
|
7434
|
-
attribute: r[f.attribute],
|
|
7435
|
-
value: r[f.value],
|
|
7436
|
-
userEmail: r[f.userEmail] || "admin@strapi.io",
|
|
7437
|
-
userName: r[f.userName] || "Admin",
|
|
7438
|
-
updatedCount: r[f.updatedCount] || 0,
|
|
7439
|
-
skippedCount: r[f.skippedCount] || 0,
|
|
7440
|
-
totalTargets: r[f.totalTargets] || 0,
|
|
7441
|
-
diffs: typeof r[f.diffs] === "string" ? JSON.parse(r[f.diffs]) : r[f.diffs] || [],
|
|
7442
|
-
isRolledBack: Boolean(r[f.isRolledBack]),
|
|
7443
|
-
rolledBackAt: r[f.rolledBackAt] || null,
|
|
7444
|
-
rolledBackBy: r[f.rolledBackBy] || null,
|
|
7445
|
-
executedAt: r[f.executedAt] || r.createdAt,
|
|
7446
|
-
createdAt: r.createdAt
|
|
7447
|
-
}));
|
|
7448
|
-
const sortedHistory = sortAuditRecordsDesc(normalizedHistory);
|
|
7449
|
-
const targetRecord = sortedHistory.find((r) => r.batchId === batchId);
|
|
7450
|
-
if (!targetRecord) {
|
|
7451
|
-
throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
|
|
7452
|
-
}
|
|
7453
|
-
const latestRecord = sortedHistory[0];
|
|
7454
|
-
if (latestRecord.batchId !== batchId) {
|
|
7455
|
-
throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
|
|
7456
|
-
}
|
|
7457
|
-
if (targetRecord.isRolledBack) {
|
|
7458
|
-
throw new Error(`Batch "${batchId}" has already been rolled back.`);
|
|
7459
|
-
}
|
|
7460
|
-
const diffs = Array.isArray(targetRecord.diffs) ? targetRecord.diffs : [];
|
|
7461
|
-
const { revertedCount, rollbackDetails } = await this.revertDiffItems(diffs, currentUser?.id);
|
|
7462
|
-
const updateData = {};
|
|
7463
|
-
if (f.isRolledBack) updateData[f.isRolledBack] = true;
|
|
7464
|
-
if (f.rolledBackAt) updateData[f.rolledBackAt] = (/* @__PURE__ */ new Date()).toISOString();
|
|
7465
|
-
if (f.rolledBackBy) {
|
|
7466
|
-
updateData[f.rolledBackBy] = currentUser?.email || "Admin";
|
|
7467
|
-
}
|
|
7468
|
-
await strapi.documents(config.contentType).update({
|
|
7469
|
-
documentId: targetRecord.documentId,
|
|
7470
|
-
data: updateData
|
|
7471
|
-
});
|
|
7472
|
-
try {
|
|
7473
|
-
const affectedUids = new Set(rollbackDetails.map((d) => d.uid));
|
|
7474
|
-
const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
|
|
7475
|
-
affectedUids.forEach((uid) => {
|
|
7476
|
-
if (uid && bulkService?.invalidateCache) {
|
|
7477
|
-
bulkService.invalidateCache(uid);
|
|
7478
|
-
}
|
|
7479
|
-
});
|
|
7480
|
-
} catch {
|
|
7481
|
-
}
|
|
7482
|
-
await this.recordToEnterpriseNative(
|
|
7483
|
-
"bulk-updater.rollback",
|
|
7484
|
-
{
|
|
7485
|
-
batchId,
|
|
7486
|
-
revertedCount
|
|
7487
|
-
},
|
|
7488
|
-
currentUser
|
|
7489
|
-
);
|
|
7490
|
-
return {
|
|
7491
|
-
success: true,
|
|
7492
|
-
batchId,
|
|
7493
|
-
revertedCount,
|
|
7494
|
-
details: rollbackDetails
|
|
7495
|
-
};
|
|
7496
|
-
});
|
|
7497
|
-
}
|
|
7498
|
-
});
|
|
7499
|
-
function buildComponentPopulate(strapi, compUid, visited, depth, maxDepth) {
|
|
7500
|
-
if (depth >= maxDepth) return true;
|
|
7501
|
-
if (visited.has(compUid)) return true;
|
|
7502
|
-
const comp = strapi.components?.[compUid];
|
|
7503
|
-
if (!comp?.attributes) return true;
|
|
7504
|
-
const nextVisited = new Set(visited);
|
|
7505
|
-
nextVisited.add(compUid);
|
|
7506
|
-
const populate = {};
|
|
7507
|
-
for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
|
|
7508
|
-
const category = classifyAttribute(attrName, attrDef);
|
|
7509
|
-
if (category === "component_single" || category === "component_repeatable") {
|
|
7510
|
-
if (attrDef.component) {
|
|
7511
|
-
const subPop = buildComponentPopulate(
|
|
7512
|
-
strapi,
|
|
7513
|
-
attrDef.component,
|
|
7514
|
-
nextVisited,
|
|
7515
|
-
depth + 1,
|
|
7516
|
-
maxDepth
|
|
7517
|
-
);
|
|
7518
|
-
populate[attrName] = typeof subPop === "object" && Object.keys(subPop).length > 0 ? { populate: subPop } : true;
|
|
7519
|
-
} else {
|
|
7520
|
-
populate[attrName] = true;
|
|
7521
|
-
}
|
|
7522
|
-
} else if (category === "dynamiczone") {
|
|
7523
|
-
const dzComponents = Array.isArray(attrDef.components) ? attrDef.components : [];
|
|
7524
|
-
if (dzComponents.length > 0) {
|
|
7525
|
-
const onPopulate = {};
|
|
7526
|
-
for (const dzCompUid of dzComponents) {
|
|
7527
|
-
const dzCompPop = buildComponentPopulate(
|
|
7528
|
-
strapi,
|
|
7529
|
-
dzCompUid,
|
|
7530
|
-
nextVisited,
|
|
7531
|
-
depth + 1,
|
|
7532
|
-
maxDepth
|
|
7533
|
-
);
|
|
7534
|
-
onPopulate[dzCompUid] = typeof dzCompPop === "object" && Object.keys(dzCompPop).length > 0 ? { populate: dzCompPop } : true;
|
|
8367
|
+
}
|
|
8368
|
+
} catch {
|
|
8369
|
+
}
|
|
8370
|
+
revertedCount++;
|
|
8371
|
+
rollbackDetails.push({
|
|
8372
|
+
uid: item.uid,
|
|
8373
|
+
documentId: item.documentId,
|
|
8374
|
+
label: item.label,
|
|
8375
|
+
attribute: item.attribute,
|
|
8376
|
+
revertedTo: item.oldValue,
|
|
8377
|
+
status: "reverted"
|
|
8378
|
+
});
|
|
8379
|
+
} catch (err) {
|
|
8380
|
+
rollbackDetails.push({
|
|
8381
|
+
uid: item.uid,
|
|
8382
|
+
documentId: item.documentId,
|
|
8383
|
+
label: item.label,
|
|
8384
|
+
status: "error",
|
|
8385
|
+
message: err.message
|
|
8386
|
+
});
|
|
7535
8387
|
}
|
|
7536
|
-
populate[attrName] = { on: onPopulate };
|
|
7537
|
-
} else {
|
|
7538
|
-
populate[attrName] = { populate: "*" };
|
|
7539
8388
|
}
|
|
7540
|
-
} else if (category === "relation_to_one" || category === "relation_to_many") {
|
|
7541
|
-
populate[attrName] = true;
|
|
7542
|
-
} else if (category === "media_single" || category === "media_to_many") {
|
|
7543
|
-
populate[attrName] = true;
|
|
7544
8389
|
}
|
|
7545
|
-
|
|
7546
|
-
|
|
7547
|
-
|
|
7548
|
-
|
|
7549
|
-
|
|
7550
|
-
|
|
7551
|
-
|
|
7552
|
-
|
|
7553
|
-
|
|
7554
|
-
|
|
7555
|
-
|
|
7556
|
-
|
|
7557
|
-
if (field.componentUid) {
|
|
7558
|
-
const compPop = buildComponentPopulate(
|
|
7559
|
-
strapi,
|
|
7560
|
-
field.componentUid,
|
|
7561
|
-
visited,
|
|
7562
|
-
0,
|
|
7563
|
-
maxDepth
|
|
7564
|
-
);
|
|
7565
|
-
populate[fieldName] = typeof compPop === "object" && Object.keys(compPop).length > 0 ? { populate: compPop } : true;
|
|
7566
|
-
} else {
|
|
7567
|
-
populate[fieldName] = true;
|
|
7568
|
-
}
|
|
7569
|
-
break;
|
|
8390
|
+
return { revertedCount, rollbackDetails };
|
|
8391
|
+
},
|
|
8392
|
+
/**
|
|
8393
|
+
* Performs deterministic rollback of a batch.
|
|
8394
|
+
* Strict invariant: ONLY the latest completed update is eligible for rollback.
|
|
8395
|
+
* Older completed updates, already rolled-back updates, and pending/failed/executing batches are strictly rejected.
|
|
8396
|
+
*/
|
|
8397
|
+
async rollbackBatch(batchId, currentUser) {
|
|
8398
|
+
return withRollbackLock(async () => {
|
|
8399
|
+
const config = this.getAuditConfig();
|
|
8400
|
+
if (!config.enabled) {
|
|
8401
|
+
throw new Error("Audit trail is not configured or disabled.");
|
|
7570
8402
|
}
|
|
7571
|
-
|
|
7572
|
-
|
|
7573
|
-
|
|
7574
|
-
|
|
7575
|
-
|
|
7576
|
-
|
|
7577
|
-
|
|
7578
|
-
|
|
7579
|
-
|
|
7580
|
-
|
|
7581
|
-
|
|
7582
|
-
|
|
7583
|
-
|
|
8403
|
+
if (!batchId) {
|
|
8404
|
+
throw new Error("A valid batchId is required to perform rollback.");
|
|
8405
|
+
}
|
|
8406
|
+
try {
|
|
8407
|
+
const bulkService = strapi.plugin("bulk-updater")?.service("bulkUpdater");
|
|
8408
|
+
if (bulkService && typeof bulkService.getBatchStatus === "function") {
|
|
8409
|
+
const statusRes = await bulkService.getBatchStatus(batchId);
|
|
8410
|
+
const batchJob = statusRes?.batch;
|
|
8411
|
+
if (batchJob) {
|
|
8412
|
+
if (batchJob.status === "pending_approval" || batchJob.status === "queued_offpeak") {
|
|
8413
|
+
throw new Error(`Batch "${batchId}" is currently pending and cannot be rolled back.`);
|
|
8414
|
+
}
|
|
8415
|
+
if (batchJob.status === "processing" || batchJob.status === "running" || batchJob.status === "executing") {
|
|
8416
|
+
throw new Error(`Batch "${batchId}" is currently executing and cannot be rolled back.`);
|
|
8417
|
+
}
|
|
8418
|
+
if (batchJob.status === "failed") {
|
|
8419
|
+
throw new Error(`Batch "${batchId}" failed during execution and cannot be rolled back.`);
|
|
8420
|
+
}
|
|
7584
8421
|
}
|
|
7585
|
-
populate[fieldName] = { on: onPopulate };
|
|
7586
|
-
} else {
|
|
7587
|
-
populate[fieldName] = { populate: "*" };
|
|
7588
8422
|
}
|
|
7589
|
-
|
|
7590
|
-
|
|
7591
|
-
|
|
7592
|
-
case "relation_to_many": {
|
|
7593
|
-
populate[fieldName] = true;
|
|
7594
|
-
break;
|
|
7595
|
-
}
|
|
7596
|
-
case "media_single":
|
|
7597
|
-
case "media_to_many": {
|
|
7598
|
-
populate[fieldName] = true;
|
|
7599
|
-
break;
|
|
7600
|
-
}
|
|
7601
|
-
}
|
|
7602
|
-
}
|
|
7603
|
-
return Object.keys(populate).length > 0 ? populate : void 0;
|
|
7604
|
-
}
|
|
7605
|
-
const METADATA_COLUMN_KEY = "__bulk_updater_metadata";
|
|
7606
|
-
const CURRENT_SCHEMA_VERSION = 1;
|
|
7607
|
-
function escapeCsvCell(val) {
|
|
7608
|
-
if (val === null || val === void 0) return "";
|
|
7609
|
-
let str = "";
|
|
7610
|
-
if (val instanceof Date) {
|
|
7611
|
-
str = val.toISOString();
|
|
7612
|
-
} else if (typeof val === "object") {
|
|
7613
|
-
str = JSON.stringify(val);
|
|
7614
|
-
} else {
|
|
7615
|
-
str = String(val);
|
|
7616
|
-
}
|
|
7617
|
-
str = str.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
7618
|
-
if (/^[=+@-]/.test(str)) {
|
|
7619
|
-
str = `'${str}`;
|
|
7620
|
-
}
|
|
7621
|
-
if (str.includes(",") || str.includes('"') || str.includes("\n") || str.includes("\r")) {
|
|
7622
|
-
return `"${str.replace(/"/g, '""')}"`;
|
|
7623
|
-
}
|
|
7624
|
-
return str;
|
|
7625
|
-
}
|
|
7626
|
-
function parseCsvToMatrix(csvText) {
|
|
7627
|
-
if (!csvText) return [];
|
|
7628
|
-
let text = csvText;
|
|
7629
|
-
if (text.charCodeAt(0) === 65279) {
|
|
7630
|
-
text = text.slice(1);
|
|
7631
|
-
}
|
|
7632
|
-
const rows = [];
|
|
7633
|
-
let currentRow = [];
|
|
7634
|
-
let currentCell = "";
|
|
7635
|
-
let inQuotes = false;
|
|
7636
|
-
let cellIsQuoted = false;
|
|
7637
|
-
for (let i = 0; i < text.length; i++) {
|
|
7638
|
-
const char = text[i];
|
|
7639
|
-
const nextChar = text[i + 1];
|
|
7640
|
-
if (inQuotes) {
|
|
7641
|
-
if (char === '"') {
|
|
7642
|
-
if (nextChar === '"') {
|
|
7643
|
-
currentCell += '"';
|
|
7644
|
-
i++;
|
|
7645
|
-
} else {
|
|
7646
|
-
inQuotes = false;
|
|
8423
|
+
} catch (checkErr) {
|
|
8424
|
+
if (checkErr.message?.startsWith('Batch "')) {
|
|
8425
|
+
throw checkErr;
|
|
7647
8426
|
}
|
|
7648
|
-
} else {
|
|
7649
|
-
currentCell += char;
|
|
7650
8427
|
}
|
|
7651
|
-
|
|
7652
|
-
|
|
7653
|
-
|
|
7654
|
-
|
|
7655
|
-
|
|
7656
|
-
|
|
7657
|
-
currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
|
|
7658
|
-
currentCell = "";
|
|
7659
|
-
cellIsQuoted = false;
|
|
7660
|
-
} else if (char === "\r") {
|
|
7661
|
-
if (nextChar === "\n") {
|
|
7662
|
-
i++;
|
|
8428
|
+
if (config.mode === "store") {
|
|
8429
|
+
const store = strapi.store({ type: "plugin", name: "bulk-updater", key: "audit-history" });
|
|
8430
|
+
const stored = await store.get({}) || { history: [] };
|
|
8431
|
+
const rawHistory = Array.isArray(stored.history) ? stored.history : [];
|
|
8432
|
+
if (rawHistory.length === 0) {
|
|
8433
|
+
throw new Error("No completed update records found in audit trail.");
|
|
7663
8434
|
}
|
|
7664
|
-
|
|
7665
|
-
|
|
7666
|
-
|
|
8435
|
+
const sortedHistory2 = sortAuditRecordsDesc(rawHistory);
|
|
8436
|
+
const targetRecord2 = sortedHistory2.find((r) => r.batchId === batchId);
|
|
8437
|
+
if (!targetRecord2) {
|
|
8438
|
+
throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
|
|
7667
8439
|
}
|
|
7668
|
-
|
|
7669
|
-
|
|
7670
|
-
|
|
7671
|
-
} else if (char === "\n") {
|
|
7672
|
-
currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
|
|
7673
|
-
if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
|
|
7674
|
-
rows.push(currentRow);
|
|
8440
|
+
const latestRecord2 = sortedHistory2[0];
|
|
8441
|
+
if (latestRecord2.batchId !== batchId) {
|
|
8442
|
+
throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
|
|
7675
8443
|
}
|
|
7676
|
-
|
|
7677
|
-
|
|
7678
|
-
cellIsQuoted = false;
|
|
7679
|
-
} else {
|
|
7680
|
-
if (!(cellIsQuoted && !inQuotes && (char === " " || char === " "))) {
|
|
7681
|
-
currentCell += char;
|
|
8444
|
+
if (targetRecord2.isRolledBack) {
|
|
8445
|
+
throw new Error(`Batch "${batchId}" has already been rolled back.`);
|
|
7682
8446
|
}
|
|
8447
|
+
const diffs2 = Array.isArray(targetRecord2.diffs) ? targetRecord2.diffs : [];
|
|
8448
|
+
const { revertedCount: revertedCount2, rollbackDetails: rollbackDetails2 } = await this.revertDiffItems(diffs2, currentUser?.id);
|
|
8449
|
+
const recordIndex = rawHistory.findIndex((r) => r.batchId === batchId);
|
|
8450
|
+
if (recordIndex !== -1) {
|
|
8451
|
+
rawHistory[recordIndex] = {
|
|
8452
|
+
...rawHistory[recordIndex],
|
|
8453
|
+
isRolledBack: true,
|
|
8454
|
+
rolledBackAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
8455
|
+
rolledBackBy: currentUser?.email || "Admin"
|
|
8456
|
+
};
|
|
8457
|
+
await store.set({ value: { history: rawHistory } });
|
|
8458
|
+
}
|
|
8459
|
+
try {
|
|
8460
|
+
const affectedUids = new Set(rollbackDetails2.map((d) => d.uid));
|
|
8461
|
+
const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
|
|
8462
|
+
affectedUids.forEach((uid) => {
|
|
8463
|
+
if (uid && bulkService?.invalidateCache) {
|
|
8464
|
+
bulkService.invalidateCache(uid);
|
|
8465
|
+
}
|
|
8466
|
+
});
|
|
8467
|
+
} catch {
|
|
8468
|
+
}
|
|
8469
|
+
await this.recordToEnterpriseNative(
|
|
8470
|
+
"bulk-updater.rollback",
|
|
8471
|
+
{
|
|
8472
|
+
batchId,
|
|
8473
|
+
revertedCount: revertedCount2
|
|
8474
|
+
},
|
|
8475
|
+
currentUser
|
|
8476
|
+
);
|
|
8477
|
+
return {
|
|
8478
|
+
success: true,
|
|
8479
|
+
batchId,
|
|
8480
|
+
revertedCount: revertedCount2,
|
|
8481
|
+
details: rollbackDetails2
|
|
8482
|
+
};
|
|
7683
8483
|
}
|
|
7684
|
-
|
|
7685
|
-
|
|
7686
|
-
if (currentCell !== "" || cellIsQuoted || currentRow.length > 0) {
|
|
7687
|
-
currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
|
|
7688
|
-
if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
|
|
7689
|
-
rows.push(currentRow);
|
|
7690
|
-
}
|
|
7691
|
-
}
|
|
7692
|
-
return rows;
|
|
7693
|
-
}
|
|
7694
|
-
function parseCsvToRecords(csvText) {
|
|
7695
|
-
const matrix = parseCsvToMatrix(csvText);
|
|
7696
|
-
if (matrix.length < 2) return [];
|
|
7697
|
-
const headers = matrix[0].map((h) => h.trim());
|
|
7698
|
-
const records = [];
|
|
7699
|
-
for (let i = 1; i < matrix.length; i++) {
|
|
7700
|
-
const row = matrix[i];
|
|
7701
|
-
const record = {};
|
|
7702
|
-
headers.forEach((h, idx) => {
|
|
7703
|
-
let val = row[idx] !== void 0 ? row[idx] : "";
|
|
7704
|
-
if (typeof val === "string" && /^'[=+@-]/.test(val)) {
|
|
7705
|
-
val = val.substring(1);
|
|
7706
|
-
}
|
|
7707
|
-
record[h] = val;
|
|
7708
|
-
});
|
|
7709
|
-
records.push(record);
|
|
7710
|
-
}
|
|
7711
|
-
return records;
|
|
7712
|
-
}
|
|
7713
|
-
function serializeFieldValue(value, field) {
|
|
7714
|
-
if (value === null || value === void 0) {
|
|
7715
|
-
return "";
|
|
7716
|
-
}
|
|
7717
|
-
switch (field.category) {
|
|
7718
|
-
case "scalar": {
|
|
7719
|
-
if (value instanceof Date) {
|
|
7720
|
-
return value.toISOString();
|
|
8484
|
+
if (!config.contentType || !config.fields) {
|
|
8485
|
+
throw new Error("Audit trail is not configured or disabled.");
|
|
7721
8486
|
}
|
|
7722
|
-
|
|
7723
|
-
|
|
7724
|
-
|
|
7725
|
-
|
|
7726
|
-
|
|
7727
|
-
|
|
7728
|
-
case "component_single": {
|
|
7729
|
-
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
7730
|
-
}
|
|
7731
|
-
case "component_repeatable": {
|
|
7732
|
-
if (Array.isArray(value)) {
|
|
7733
|
-
return JSON.stringify(value);
|
|
8487
|
+
const f = config.fields;
|
|
8488
|
+
const allRecords = await strapi.documents(config.contentType).findMany({
|
|
8489
|
+
sort: { createdAt: "desc" }
|
|
8490
|
+
});
|
|
8491
|
+
if (!allRecords || allRecords.length === 0) {
|
|
8492
|
+
throw new Error("No completed update records found in audit trail.");
|
|
7734
8493
|
}
|
|
7735
|
-
|
|
7736
|
-
|
|
7737
|
-
|
|
7738
|
-
|
|
7739
|
-
|
|
7740
|
-
|
|
7741
|
-
|
|
7742
|
-
|
|
7743
|
-
|
|
7744
|
-
|
|
7745
|
-
|
|
8494
|
+
const normalizedHistory = allRecords.map((r) => ({
|
|
8495
|
+
id: r.id,
|
|
8496
|
+
documentId: r.documentId,
|
|
8497
|
+
batchId: r[f.batchId] || r.documentId,
|
|
8498
|
+
attribute: r[f.attribute],
|
|
8499
|
+
value: r[f.value],
|
|
8500
|
+
userEmail: r[f.userEmail] || "admin@strapi.io",
|
|
8501
|
+
userName: r[f.userName] || "Admin",
|
|
8502
|
+
updatedCount: r[f.updatedCount] || 0,
|
|
8503
|
+
skippedCount: r[f.skippedCount] || 0,
|
|
8504
|
+
totalTargets: r[f.totalTargets] || 0,
|
|
8505
|
+
diffs: typeof r[f.diffs] === "string" ? JSON.parse(r[f.diffs]) : r[f.diffs] || [],
|
|
8506
|
+
isRolledBack: Boolean(r[f.isRolledBack]),
|
|
8507
|
+
rolledBackAt: r[f.rolledBackAt] || null,
|
|
8508
|
+
rolledBackBy: r[f.rolledBackBy] || null,
|
|
8509
|
+
executedAt: r[f.executedAt] || r.createdAt,
|
|
8510
|
+
createdAt: r.createdAt
|
|
8511
|
+
}));
|
|
8512
|
+
const sortedHistory = sortAuditRecordsDesc(normalizedHistory);
|
|
8513
|
+
const targetRecord = sortedHistory.find((r) => r.batchId === batchId);
|
|
8514
|
+
if (!targetRecord) {
|
|
8515
|
+
throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
|
|
7746
8516
|
}
|
|
7747
|
-
|
|
7748
|
-
|
|
7749
|
-
|
|
7750
|
-
if (typeof value === "object" && value !== null) {
|
|
7751
|
-
const docId = value.documentId || value.id || "";
|
|
7752
|
-
return JSON.stringify({
|
|
7753
|
-
documentId: String(docId),
|
|
7754
|
-
title: value.title || value.name || value.slug || void 0
|
|
7755
|
-
});
|
|
8517
|
+
const latestRecord = sortedHistory[0];
|
|
8518
|
+
if (latestRecord.batchId !== batchId) {
|
|
8519
|
+
throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
|
|
7756
8520
|
}
|
|
7757
|
-
|
|
7758
|
-
|
|
7759
|
-
case "relation_to_many": {
|
|
7760
|
-
if (Array.isArray(value)) {
|
|
7761
|
-
const list = value.map((item) => {
|
|
7762
|
-
if (typeof item === "object" && item !== null) {
|
|
7763
|
-
const docId = item.documentId || item.id || "";
|
|
7764
|
-
return {
|
|
7765
|
-
documentId: String(docId),
|
|
7766
|
-
title: item.title || item.name || item.slug || void 0
|
|
7767
|
-
};
|
|
7768
|
-
}
|
|
7769
|
-
return { documentId: String(item) };
|
|
7770
|
-
});
|
|
7771
|
-
return JSON.stringify(list);
|
|
8521
|
+
if (targetRecord.isRolledBack) {
|
|
8522
|
+
throw new Error(`Batch "${batchId}" has already been rolled back.`);
|
|
7772
8523
|
}
|
|
7773
|
-
|
|
7774
|
-
|
|
7775
|
-
|
|
7776
|
-
if (
|
|
7777
|
-
|
|
7778
|
-
|
|
7779
|
-
|
|
7780
|
-
name: value.name,
|
|
7781
|
-
url: value.url,
|
|
7782
|
-
mime: value.mime
|
|
7783
|
-
});
|
|
8524
|
+
const diffs = Array.isArray(targetRecord.diffs) ? targetRecord.diffs : [];
|
|
8525
|
+
const { revertedCount, rollbackDetails } = await this.revertDiffItems(diffs, currentUser?.id);
|
|
8526
|
+
const updateData = {};
|
|
8527
|
+
if (f.isRolledBack) updateData[f.isRolledBack] = true;
|
|
8528
|
+
if (f.rolledBackAt) updateData[f.rolledBackAt] = (/* @__PURE__ */ new Date()).toISOString();
|
|
8529
|
+
if (f.rolledBackBy) {
|
|
8530
|
+
updateData[f.rolledBackBy] = currentUser?.email || "Admin";
|
|
7784
8531
|
}
|
|
7785
|
-
|
|
7786
|
-
|
|
7787
|
-
|
|
7788
|
-
|
|
7789
|
-
|
|
7790
|
-
|
|
7791
|
-
|
|
7792
|
-
|
|
7793
|
-
|
|
7794
|
-
|
|
7795
|
-
url: file.url,
|
|
7796
|
-
mime: file.mime
|
|
7797
|
-
};
|
|
8532
|
+
await strapi.documents(config.contentType).update({
|
|
8533
|
+
documentId: targetRecord.documentId,
|
|
8534
|
+
data: updateData
|
|
8535
|
+
});
|
|
8536
|
+
try {
|
|
8537
|
+
const affectedUids = new Set(rollbackDetails.map((d) => d.uid));
|
|
8538
|
+
const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
|
|
8539
|
+
affectedUids.forEach((uid) => {
|
|
8540
|
+
if (uid && bulkService?.invalidateCache) {
|
|
8541
|
+
bulkService.invalidateCache(uid);
|
|
7798
8542
|
}
|
|
7799
|
-
return file;
|
|
7800
8543
|
});
|
|
7801
|
-
|
|
7802
|
-
}
|
|
7803
|
-
return "";
|
|
7804
|
-
}
|
|
7805
|
-
default:
|
|
7806
|
-
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
7807
|
-
}
|
|
7808
|
-
}
|
|
7809
|
-
function serializeDocumentsToCsv(strapi, uid, documents) {
|
|
7810
|
-
const schema = discoverSchema(strapi, uid);
|
|
7811
|
-
const headers = [METADATA_COLUMN_KEY, ...schema.allExportKeys];
|
|
7812
|
-
const lines = [];
|
|
7813
|
-
lines.push(headers.map(escapeCsvCell).join(","));
|
|
7814
|
-
const exportedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
7815
|
-
for (const doc of documents) {
|
|
7816
|
-
const rowValues = [];
|
|
7817
|
-
const metadata = {
|
|
7818
|
-
schemaVersion: CURRENT_SCHEMA_VERSION,
|
|
7819
|
-
contentType: uid,
|
|
7820
|
-
documentId: String(doc.documentId || doc.id || ""),
|
|
7821
|
-
locale: doc.locale || void 0,
|
|
7822
|
-
exportedAt
|
|
7823
|
-
};
|
|
7824
|
-
rowValues.push(escapeCsvCell(metadata));
|
|
7825
|
-
for (const key of schema.allExportKeys) {
|
|
7826
|
-
if (key === "documentId") {
|
|
7827
|
-
rowValues.push(escapeCsvCell(doc.documentId || doc.id || ""));
|
|
7828
|
-
} else if (key === "locale") {
|
|
7829
|
-
rowValues.push(escapeCsvCell(doc.locale || ""));
|
|
7830
|
-
} else {
|
|
7831
|
-
const field = schema.fields[key];
|
|
7832
|
-
const rawValue = doc[key];
|
|
7833
|
-
if (field) {
|
|
7834
|
-
const serialized = serializeFieldValue(rawValue, field);
|
|
7835
|
-
rowValues.push(escapeCsvCell(serialized));
|
|
7836
|
-
} else {
|
|
7837
|
-
rowValues.push(escapeCsvCell(rawValue));
|
|
7838
|
-
}
|
|
7839
|
-
}
|
|
7840
|
-
}
|
|
7841
|
-
lines.push(rowValues.join(","));
|
|
7842
|
-
}
|
|
7843
|
-
const csvContent = "\uFEFF" + lines.join("\r\n") + "\r\n";
|
|
7844
|
-
return {
|
|
7845
|
-
csvContent,
|
|
7846
|
-
headers,
|
|
7847
|
-
count: documents.length
|
|
7848
|
-
};
|
|
7849
|
-
}
|
|
7850
|
-
function extractMetadataFromRow(row) {
|
|
7851
|
-
if (!row || typeof row !== "object") return null;
|
|
7852
|
-
const rawMeta = row[METADATA_COLUMN_KEY] || row["__bulk_updater_metadata"];
|
|
7853
|
-
if (!rawMeta) return null;
|
|
7854
|
-
if (typeof rawMeta === "object") {
|
|
7855
|
-
return rawMeta;
|
|
7856
|
-
}
|
|
7857
|
-
if (typeof rawMeta === "string") {
|
|
7858
|
-
try {
|
|
7859
|
-
const parsed = JSON.parse(rawMeta);
|
|
7860
|
-
if (parsed && typeof parsed === "object") {
|
|
7861
|
-
return parsed;
|
|
8544
|
+
} catch {
|
|
7862
8545
|
}
|
|
7863
|
-
|
|
7864
|
-
|
|
7865
|
-
|
|
7866
|
-
|
|
7867
|
-
|
|
7868
|
-
|
|
7869
|
-
|
|
7870
|
-
|
|
7871
|
-
|
|
7872
|
-
|
|
7873
|
-
|
|
7874
|
-
|
|
7875
|
-
|
|
7876
|
-
|
|
7877
|
-
|
|
7878
|
-
);
|
|
7879
|
-
if (!existingLower.has("error")) {
|
|
7880
|
-
return "Error";
|
|
7881
|
-
}
|
|
7882
|
-
if (!existingLower.has("import error")) {
|
|
7883
|
-
return "Import Error";
|
|
7884
|
-
}
|
|
7885
|
-
let suffix = 2;
|
|
7886
|
-
while (existingLower.has(`import error (${suffix})`)) {
|
|
7887
|
-
suffix++;
|
|
7888
|
-
}
|
|
7889
|
-
return `Import Error (${suffix})`;
|
|
7890
|
-
}
|
|
7891
|
-
function formatErrorCsvFilename(collectionTypeOrUid, date = /* @__PURE__ */ new Date()) {
|
|
7892
|
-
const rawSegment = collectionTypeOrUid ? String(collectionTypeOrUid).split(".").pop() || String(collectionTypeOrUid) : "collection";
|
|
7893
|
-
const safeType = rawSegment.replace(/[^a-zA-Z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "collection";
|
|
7894
|
-
const pad = (n) => String(n).padStart(2, "0");
|
|
7895
|
-
const stamp = `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}_${pad(
|
|
7896
|
-
date.getHours()
|
|
7897
|
-
)}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
|
|
7898
|
-
return `error_${safeType}_${stamp}.csv`;
|
|
7899
|
-
}
|
|
7900
|
-
function buildErrorCsv(options) {
|
|
7901
|
-
const { headers, failedRows } = options || {};
|
|
7902
|
-
if (!Array.isArray(failedRows) || failedRows.length === 0) {
|
|
7903
|
-
return {
|
|
7904
|
-
csvContent: "",
|
|
7905
|
-
headers: headers ? [...headers] : [],
|
|
7906
|
-
errorColumnName: "Error",
|
|
7907
|
-
errorCount: 0
|
|
7908
|
-
};
|
|
8546
|
+
await this.recordToEnterpriseNative(
|
|
8547
|
+
"bulk-updater.rollback",
|
|
8548
|
+
{
|
|
8549
|
+
batchId,
|
|
8550
|
+
revertedCount
|
|
8551
|
+
},
|
|
8552
|
+
currentUser
|
|
8553
|
+
);
|
|
8554
|
+
return {
|
|
8555
|
+
success: true,
|
|
8556
|
+
batchId,
|
|
8557
|
+
revertedCount,
|
|
8558
|
+
details: rollbackDetails
|
|
8559
|
+
};
|
|
8560
|
+
});
|
|
7909
8561
|
}
|
|
7910
|
-
|
|
7911
|
-
|
|
7912
|
-
|
|
7913
|
-
|
|
7914
|
-
|
|
7915
|
-
|
|
7916
|
-
|
|
7917
|
-
|
|
7918
|
-
|
|
8562
|
+
});
|
|
8563
|
+
function buildComponentPopulate(strapi, compUid, visited, depth, maxDepth) {
|
|
8564
|
+
if (depth >= maxDepth) return true;
|
|
8565
|
+
if (visited.has(compUid)) return true;
|
|
8566
|
+
const comp = strapi.components?.[compUid];
|
|
8567
|
+
if (!comp?.attributes) return true;
|
|
8568
|
+
const nextVisited = new Set(visited);
|
|
8569
|
+
nextVisited.add(compUid);
|
|
8570
|
+
const populate = {};
|
|
8571
|
+
for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
|
|
8572
|
+
const category = classifyAttribute(attrName, attrDef);
|
|
8573
|
+
if (category === "component_single" || category === "component_repeatable") {
|
|
8574
|
+
if (attrDef.component) {
|
|
8575
|
+
const subPop = buildComponentPopulate(
|
|
8576
|
+
strapi,
|
|
8577
|
+
attrDef.component,
|
|
8578
|
+
nextVisited,
|
|
8579
|
+
depth + 1,
|
|
8580
|
+
maxDepth
|
|
8581
|
+
);
|
|
8582
|
+
populate[attrName] = typeof subPop === "object" && Object.keys(subPop).length > 0 ? { populate: subPop } : true;
|
|
8583
|
+
} else {
|
|
8584
|
+
populate[attrName] = true;
|
|
7919
8585
|
}
|
|
7920
|
-
} else {
|
|
7921
|
-
|
|
7922
|
-
|
|
7923
|
-
|
|
7924
|
-
|
|
7925
|
-
|
|
7926
|
-
|
|
8586
|
+
} else if (category === "dynamiczone") {
|
|
8587
|
+
const dzComponents = Array.isArray(attrDef.components) ? attrDef.components : [];
|
|
8588
|
+
if (dzComponents.length > 0) {
|
|
8589
|
+
const onPopulate = {};
|
|
8590
|
+
for (const dzCompUid of dzComponents) {
|
|
8591
|
+
const dzCompPop = buildComponentPopulate(
|
|
8592
|
+
strapi,
|
|
8593
|
+
dzCompUid,
|
|
8594
|
+
nextVisited,
|
|
8595
|
+
depth + 1,
|
|
8596
|
+
maxDepth
|
|
8597
|
+
);
|
|
8598
|
+
onPopulate[dzCompUid] = typeof dzCompPop === "object" && Object.keys(dzCompPop).length > 0 ? { populate: dzCompPop } : true;
|
|
8599
|
+
}
|
|
8600
|
+
populate[attrName] = { on: onPopulate };
|
|
8601
|
+
} else {
|
|
8602
|
+
populate[attrName] = { populate: "*" };
|
|
8603
|
+
}
|
|
8604
|
+
} else if (category === "relation_to_one" || category === "relation_to_many") {
|
|
8605
|
+
populate[attrName] = true;
|
|
8606
|
+
} else if (category === "media_single" || category === "media_to_many") {
|
|
8607
|
+
populate[attrName] = true;
|
|
7927
8608
|
}
|
|
7928
8609
|
}
|
|
7929
|
-
|
|
7930
|
-
|
|
7931
|
-
|
|
7932
|
-
|
|
7933
|
-
|
|
7934
|
-
|
|
7935
|
-
|
|
7936
|
-
|
|
7937
|
-
|
|
7938
|
-
|
|
7939
|
-
|
|
7940
|
-
|
|
7941
|
-
|
|
7942
|
-
|
|
7943
|
-
|
|
7944
|
-
|
|
7945
|
-
|
|
7946
|
-
|
|
7947
|
-
|
|
8610
|
+
return Object.keys(populate).length > 0 ? populate : true;
|
|
8611
|
+
}
|
|
8612
|
+
function buildLosslessPopulate(strapi, uid, options = {}) {
|
|
8613
|
+
const maxDepth = options.maxDepth || 5;
|
|
8614
|
+
const schema = discoverSchema(strapi, uid);
|
|
8615
|
+
const populate = {};
|
|
8616
|
+
const visited = /* @__PURE__ */ new Set([uid]);
|
|
8617
|
+
for (const [fieldName, field] of Object.entries(schema.fields)) {
|
|
8618
|
+
switch (field.category) {
|
|
8619
|
+
case "component_single":
|
|
8620
|
+
case "component_repeatable": {
|
|
8621
|
+
if (field.componentUid) {
|
|
8622
|
+
const compPop = buildComponentPopulate(
|
|
8623
|
+
strapi,
|
|
8624
|
+
field.componentUid,
|
|
8625
|
+
visited,
|
|
8626
|
+
0,
|
|
8627
|
+
maxDepth
|
|
8628
|
+
);
|
|
8629
|
+
populate[fieldName] = typeof compPop === "object" && Object.keys(compPop).length > 0 ? { populate: compPop } : true;
|
|
8630
|
+
} else {
|
|
8631
|
+
populate[fieldName] = true;
|
|
8632
|
+
}
|
|
8633
|
+
break;
|
|
8634
|
+
}
|
|
8635
|
+
case "dynamiczone": {
|
|
8636
|
+
const dzComponents = field.dzComponents || [];
|
|
8637
|
+
if (dzComponents.length > 0) {
|
|
8638
|
+
const onPopulate = {};
|
|
8639
|
+
for (const compUid of dzComponents) {
|
|
8640
|
+
const compPop = buildComponentPopulate(
|
|
8641
|
+
strapi,
|
|
8642
|
+
compUid,
|
|
8643
|
+
visited,
|
|
8644
|
+
0,
|
|
8645
|
+
maxDepth
|
|
8646
|
+
);
|
|
8647
|
+
onPopulate[compUid] = typeof compPop === "object" && Object.keys(compPop).length > 0 ? { populate: compPop } : true;
|
|
8648
|
+
}
|
|
8649
|
+
populate[fieldName] = { on: onPopulate };
|
|
8650
|
+
} else {
|
|
8651
|
+
populate[fieldName] = { populate: "*" };
|
|
7948
8652
|
}
|
|
8653
|
+
break;
|
|
8654
|
+
}
|
|
8655
|
+
case "relation_to_one":
|
|
8656
|
+
case "relation_to_many": {
|
|
8657
|
+
populate[fieldName] = true;
|
|
8658
|
+
break;
|
|
8659
|
+
}
|
|
8660
|
+
case "media_single":
|
|
8661
|
+
case "media_to_many": {
|
|
8662
|
+
populate[fieldName] = true;
|
|
8663
|
+
break;
|
|
7949
8664
|
}
|
|
7950
8665
|
}
|
|
7951
8666
|
}
|
|
7952
|
-
|
|
7953
|
-
const finalHeaders = [...baseHeaders, errorColumnName];
|
|
7954
|
-
const lines = [];
|
|
7955
|
-
lines.push(finalHeaders.map(escapeCsvCell).join(","));
|
|
7956
|
-
for (const entry of orderedEntries) {
|
|
7957
|
-
const cells = baseHeaders.map((h) => {
|
|
7958
|
-
const val = entry.originalRow ? entry.originalRow[h] : "";
|
|
7959
|
-
return escapeCsvCell(val === void 0 || val === null ? "" : val);
|
|
7960
|
-
});
|
|
7961
|
-
cells.push(escapeCsvCell(entry.messages.join("; ")));
|
|
7962
|
-
lines.push(cells.join(","));
|
|
7963
|
-
}
|
|
7964
|
-
const csvContent = "\uFEFF" + lines.join("\r\n") + "\r\n";
|
|
7965
|
-
return {
|
|
7966
|
-
csvContent,
|
|
7967
|
-
headers: finalHeaders,
|
|
7968
|
-
errorColumnName,
|
|
7969
|
-
errorCount: orderedEntries.length
|
|
7970
|
-
};
|
|
8667
|
+
return Object.keys(populate).length > 0 ? populate : void 0;
|
|
7971
8668
|
}
|
|
7972
8669
|
function normalizeVal(val) {
|
|
7973
8670
|
if (val === null || val === void 0) return null;
|
|
@@ -8603,6 +9300,46 @@ async function executeUpdateMutation(strapi, ct, uid, existing, row, rowNumber,
|
|
|
8603
9300
|
publishStrategy: options.publishStrategy || "safe",
|
|
8604
9301
|
unreviewedConsent: options.unreviewedConsent
|
|
8605
9302
|
});
|
|
9303
|
+
const rowMeta = extractMetadataFromRow(row);
|
|
9304
|
+
const schemaValidation = validateRecordSchemaConstraints(
|
|
9305
|
+
strapi,
|
|
9306
|
+
uid,
|
|
9307
|
+
existing,
|
|
9308
|
+
updatePayload,
|
|
9309
|
+
row,
|
|
9310
|
+
{
|
|
9311
|
+
isCreate: false,
|
|
9312
|
+
rowMeta: rowMeta ? {
|
|
9313
|
+
applicableFields: rowMeta.applicableFields,
|
|
9314
|
+
flatTypes: rowMeta.flatTypes
|
|
9315
|
+
} : null
|
|
9316
|
+
}
|
|
9317
|
+
);
|
|
9318
|
+
if (schemaValidation.errors.length > 0) {
|
|
9319
|
+
const errMsg = schemaValidation.errors[0];
|
|
9320
|
+
stats.skipped++;
|
|
9321
|
+
if (stats.failed !== void 0) stats.failed++;
|
|
9322
|
+
recordFailedCsvRow(
|
|
9323
|
+
stats,
|
|
9324
|
+
rowNumber,
|
|
9325
|
+
row,
|
|
9326
|
+
errMsg,
|
|
9327
|
+
resolvedDocId,
|
|
9328
|
+
options.originalHeaders
|
|
9329
|
+
);
|
|
9330
|
+
stats.diffs.push({
|
|
9331
|
+
uid,
|
|
9332
|
+
collectionName: ct.info?.displayName || uid,
|
|
9333
|
+
documentId: resolvedDocId,
|
|
9334
|
+
label: existing.title || existing.name || `Entry #${resolvedDocId}`,
|
|
9335
|
+
attribute: "",
|
|
9336
|
+
oldValue: null,
|
|
9337
|
+
newValue: null,
|
|
9338
|
+
status: "error",
|
|
9339
|
+
message: errMsg
|
|
9340
|
+
});
|
|
9341
|
+
return;
|
|
9342
|
+
}
|
|
8606
9343
|
const proposedEntity = deepMergeEntities(existing, updatePayload);
|
|
8607
9344
|
const valResult = await validateEntityQuotas(strapi, uid, proposedEntity);
|
|
8608
9345
|
if (!valResult.isValid) {
|
|
@@ -8690,8 +9427,48 @@ async function executeCreateMutation(strapi, ct, uid, docId, row, rowNumber, opt
|
|
|
8690
9427
|
uid,
|
|
8691
9428
|
null,
|
|
8692
9429
|
row,
|
|
8693
|
-
{}
|
|
9430
|
+
{ isPartialUpdate: false }
|
|
9431
|
+
);
|
|
9432
|
+
const rowMeta = extractMetadataFromRow(row);
|
|
9433
|
+
const schemaValidation = validateRecordSchemaConstraints(
|
|
9434
|
+
strapi,
|
|
9435
|
+
uid,
|
|
9436
|
+
null,
|
|
9437
|
+
createPayload,
|
|
9438
|
+
row,
|
|
9439
|
+
{
|
|
9440
|
+
isCreate: true,
|
|
9441
|
+
rowMeta: rowMeta ? {
|
|
9442
|
+
applicableFields: rowMeta.applicableFields,
|
|
9443
|
+
flatTypes: rowMeta.flatTypes
|
|
9444
|
+
} : null
|
|
9445
|
+
}
|
|
8694
9446
|
);
|
|
9447
|
+
if (schemaValidation.errors.length > 0) {
|
|
9448
|
+
const errMsg = schemaValidation.errors[0];
|
|
9449
|
+
stats.skipped++;
|
|
9450
|
+
if (stats.failed !== void 0) stats.failed++;
|
|
9451
|
+
recordFailedCsvRow(
|
|
9452
|
+
stats,
|
|
9453
|
+
rowNumber,
|
|
9454
|
+
row,
|
|
9455
|
+
errMsg,
|
|
9456
|
+
docId || "new",
|
|
9457
|
+
options.originalHeaders
|
|
9458
|
+
);
|
|
9459
|
+
stats.diffs.push({
|
|
9460
|
+
uid,
|
|
9461
|
+
collectionName: ct.info?.displayName || uid,
|
|
9462
|
+
documentId: docId || "new",
|
|
9463
|
+
label: `Row ${rowNumber}`,
|
|
9464
|
+
attribute: "",
|
|
9465
|
+
oldValue: null,
|
|
9466
|
+
newValue: null,
|
|
9467
|
+
status: "error",
|
|
9468
|
+
message: errMsg
|
|
9469
|
+
});
|
|
9470
|
+
return;
|
|
9471
|
+
}
|
|
8695
9472
|
const valResultNew = await validateEntityQuotas(strapi, uid, createPayload);
|
|
8696
9473
|
if (!valResultNew.isValid) {
|
|
8697
9474
|
stats.skipped++;
|
|
@@ -9100,9 +9877,6 @@ const csvService = ({ strapi }) => ({
|
|
|
9100
9877
|
}
|
|
9101
9878
|
const schema = discoverSchema(strapi, uid);
|
|
9102
9879
|
const deepPopulate = buildLosslessPopulate(strapi, uid);
|
|
9103
|
-
const headers = [METADATA_COLUMN_KEY, ...schema.allExportKeys];
|
|
9104
|
-
const lines = [];
|
|
9105
|
-
lines.push(headers.map(escapeCsvCell).join(","));
|
|
9106
9880
|
const filterMeta = buildCollectionQueryFilters(strapi, ct, {
|
|
9107
9881
|
attribute: options.attribute,
|
|
9108
9882
|
searchAttribute: options.searchAttribute || options.attribute,
|
|
@@ -9112,11 +9886,12 @@ const csvService = ({ strapi }) => ({
|
|
|
9112
9886
|
documentIds: options.documentIds
|
|
9113
9887
|
});
|
|
9114
9888
|
if (!filterMeta.colHasAttribute && filterMeta.normOp && filterMeta.normOp !== "none") {
|
|
9889
|
+
const emptySerialized = serializeDocumentsToCsv(strapi, uid, [], { schema });
|
|
9115
9890
|
return {
|
|
9116
9891
|
filename: `${ct.info?.singularName || uid}_export_${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`,
|
|
9117
|
-
csvContent:
|
|
9892
|
+
csvContent: emptySerialized.csvContent,
|
|
9118
9893
|
count: 0,
|
|
9119
|
-
fields: headers
|
|
9894
|
+
fields: emptySerialized.headers
|
|
9120
9895
|
};
|
|
9121
9896
|
}
|
|
9122
9897
|
const filters = filterMeta.filters;
|
|
@@ -9171,7 +9946,7 @@ const csvService = ({ strapi }) => ({
|
|
|
9171
9946
|
};
|
|
9172
9947
|
return matches.some((m) => testSingleValue(m.value));
|
|
9173
9948
|
};
|
|
9174
|
-
|
|
9949
|
+
const exportedDocs = [];
|
|
9175
9950
|
const maxLimit = options.limit && options.limit > 0 ? options.limit : Infinity;
|
|
9176
9951
|
const BATCH_SIZE = 200;
|
|
9177
9952
|
const exportedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -9184,35 +9959,14 @@ const csvService = ({ strapi }) => ({
|
|
|
9184
9959
|
}
|
|
9185
9960
|
const doc = await strapi.documents(uid).findFirst(findFirstArgs);
|
|
9186
9961
|
if (doc && passesDzFilter(doc)) {
|
|
9187
|
-
|
|
9188
|
-
const metadata = {
|
|
9189
|
-
schemaVersion: CURRENT_SCHEMA_VERSION,
|
|
9190
|
-
contentType: uid,
|
|
9191
|
-
documentId: String(doc.documentId || doc.id || ""),
|
|
9192
|
-
locale: doc.locale || void 0,
|
|
9193
|
-
exportedAt
|
|
9194
|
-
};
|
|
9195
|
-
rowValues.push(escapeCsvCell(metadata));
|
|
9196
|
-
for (const key of schema.allExportKeys) {
|
|
9197
|
-
if (key === "documentId") {
|
|
9198
|
-
rowValues.push(escapeCsvCell(doc.documentId || doc.id || ""));
|
|
9199
|
-
} else if (key === "locale") {
|
|
9200
|
-
rowValues.push(escapeCsvCell(doc.locale || ""));
|
|
9201
|
-
} else {
|
|
9202
|
-
const field = schema.fields[key];
|
|
9203
|
-
const rawVal = doc[key];
|
|
9204
|
-
rowValues.push(escapeCsvCell(field ? serializeFieldValue(rawVal, field) : rawVal));
|
|
9205
|
-
}
|
|
9206
|
-
}
|
|
9207
|
-
lines.push(rowValues.join(","));
|
|
9208
|
-
totalExported = 1;
|
|
9962
|
+
exportedDocs.push(doc);
|
|
9209
9963
|
}
|
|
9210
9964
|
} else {
|
|
9211
9965
|
let currentPage = 1;
|
|
9212
9966
|
let hasMore = true;
|
|
9213
9967
|
const sortClause = ct.attributes?.createdAt ? { createdAt: "desc" } : ct.attributes?.id ? { id: "desc" } : void 0;
|
|
9214
|
-
while (hasMore &&
|
|
9215
|
-
const remaining = maxLimit -
|
|
9968
|
+
while (hasMore && exportedDocs.length < maxLimit) {
|
|
9969
|
+
const remaining = maxLimit - exportedDocs.length;
|
|
9216
9970
|
const currentBatchLimit = Math.min(BATCH_SIZE, remaining);
|
|
9217
9971
|
const findPageArgs = {
|
|
9218
9972
|
filters: Object.keys(filters).length > 0 ? filters : void 0,
|
|
@@ -9234,29 +9988,8 @@ const csvService = ({ strapi }) => ({
|
|
|
9234
9988
|
if (!passesDzFilter(entry)) {
|
|
9235
9989
|
continue;
|
|
9236
9990
|
}
|
|
9237
|
-
|
|
9238
|
-
|
|
9239
|
-
schemaVersion: CURRENT_SCHEMA_VERSION,
|
|
9240
|
-
contentType: uid,
|
|
9241
|
-
documentId: String(entry.documentId || entry.id || ""),
|
|
9242
|
-
locale: entry.locale || void 0,
|
|
9243
|
-
exportedAt
|
|
9244
|
-
};
|
|
9245
|
-
rowValues.push(escapeCsvCell(metadata));
|
|
9246
|
-
for (const key of schema.allExportKeys) {
|
|
9247
|
-
if (key === "documentId") {
|
|
9248
|
-
rowValues.push(escapeCsvCell(entry.documentId || entry.id || ""));
|
|
9249
|
-
} else if (key === "locale") {
|
|
9250
|
-
rowValues.push(escapeCsvCell(entry.locale || ""));
|
|
9251
|
-
} else {
|
|
9252
|
-
const field = schema.fields[key];
|
|
9253
|
-
const rawVal = entry[key];
|
|
9254
|
-
rowValues.push(escapeCsvCell(field ? serializeFieldValue(rawVal, field) : rawVal));
|
|
9255
|
-
}
|
|
9256
|
-
}
|
|
9257
|
-
lines.push(rowValues.join(","));
|
|
9258
|
-
totalExported++;
|
|
9259
|
-
if (totalExported >= maxLimit) {
|
|
9991
|
+
exportedDocs.push(entry);
|
|
9992
|
+
if (exportedDocs.length >= maxLimit) {
|
|
9260
9993
|
hasMore = false;
|
|
9261
9994
|
break;
|
|
9262
9995
|
}
|
|
@@ -9269,13 +10002,13 @@ const csvService = ({ strapi }) => ({
|
|
|
9269
10002
|
await new Promise((resolve) => setImmediate(resolve));
|
|
9270
10003
|
}
|
|
9271
10004
|
}
|
|
9272
|
-
const
|
|
10005
|
+
const serialized = serializeDocumentsToCsv(strapi, uid, exportedDocs, { exportedAt, schema });
|
|
9273
10006
|
const filename = `${ct.info?.singularName || uid}_export_${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`;
|
|
9274
10007
|
return {
|
|
9275
10008
|
filename,
|
|
9276
|
-
csvContent,
|
|
9277
|
-
count:
|
|
9278
|
-
fields: headers
|
|
10009
|
+
csvContent: serialized.csvContent,
|
|
10010
|
+
count: serialized.count,
|
|
10011
|
+
fields: serialized.headers
|
|
9279
10012
|
};
|
|
9280
10013
|
},
|
|
9281
10014
|
async exportViolationsCsv(ruleId) {
|
|
@@ -9812,18 +10545,51 @@ const csvService = ({ strapi }) => ({
|
|
|
9812
10545
|
}
|
|
9813
10546
|
}
|
|
9814
10547
|
}
|
|
9815
|
-
|
|
9816
|
-
|
|
9817
|
-
|
|
9818
|
-
|
|
9819
|
-
|
|
9820
|
-
|
|
9821
|
-
|
|
9822
|
-
|
|
9823
|
-
|
|
9824
|
-
|
|
9825
|
-
|
|
10548
|
+
let proposedPayload = {};
|
|
10549
|
+
try {
|
|
10550
|
+
proposedPayload = await buildDocumentUpdatePayload(
|
|
10551
|
+
strapi,
|
|
10552
|
+
uid,
|
|
10553
|
+
existing,
|
|
10554
|
+
row,
|
|
10555
|
+
{ isPartialUpdate: mode === "update" }
|
|
10556
|
+
);
|
|
10557
|
+
} catch {
|
|
10558
|
+
}
|
|
10559
|
+
const rowMeta = extractMetadataFromRow(row);
|
|
10560
|
+
const isRowCreate = mode === "create_or_override" ? !existing : !existing && mode !== "update";
|
|
10561
|
+
if (!(mode === "update" && (!docId || !existing))) {
|
|
10562
|
+
const schemaValidation = validateRecordSchemaConstraints(
|
|
10563
|
+
strapi,
|
|
10564
|
+
uid,
|
|
10565
|
+
existing,
|
|
10566
|
+
proposedPayload,
|
|
10567
|
+
row,
|
|
10568
|
+
{
|
|
10569
|
+
isCreate: isRowCreate,
|
|
10570
|
+
rowMeta: rowMeta ? {
|
|
10571
|
+
applicableFields: rowMeta.applicableFields,
|
|
10572
|
+
flatTypes: rowMeta.flatTypes
|
|
10573
|
+
} : null
|
|
10574
|
+
}
|
|
10575
|
+
);
|
|
10576
|
+
for (const errStr of schemaValidation.errors) {
|
|
10577
|
+
errors.push({
|
|
10578
|
+
row: rowNumber,
|
|
10579
|
+
documentId: docId || void 0,
|
|
10580
|
+
error: errStr
|
|
10581
|
+
});
|
|
10582
|
+
rowHasError = true;
|
|
10583
|
+
}
|
|
10584
|
+
for (const warnStr of schemaValidation.warnings) {
|
|
10585
|
+
warnings.push({
|
|
10586
|
+
row: rowNumber,
|
|
10587
|
+
documentId: docId || void 0,
|
|
10588
|
+
warning: warnStr
|
|
10589
|
+
});
|
|
9826
10590
|
}
|
|
10591
|
+
}
|
|
10592
|
+
if (activeRules.length > 0) {
|
|
9827
10593
|
const proposedEntity = existing ? deepMergeEntities(existing, proposedPayload) : proposedPayload;
|
|
9828
10594
|
const valResult = await validateEntityQuotas(strapi, uid, proposedEntity, activeRules);
|
|
9829
10595
|
if (!valResult.isValid) {
|
|
@@ -9915,7 +10681,7 @@ const csvService = ({ strapi }) => ({
|
|
|
9915
10681
|
uid,
|
|
9916
10682
|
existing,
|
|
9917
10683
|
row,
|
|
9918
|
-
{}
|
|
10684
|
+
{ isPartialUpdate: mode === "update" }
|
|
9919
10685
|
);
|
|
9920
10686
|
if (existing) {
|
|
9921
10687
|
const resolvedDocId = existing.documentId || docId;
|
|
@@ -9948,7 +10714,7 @@ const csvService = ({ strapi }) => ({
|
|
|
9948
10714
|
}
|
|
9949
10715
|
const oldDisplay = formatValueDisplay(oldVal);
|
|
9950
10716
|
const newDisplay = formatValueDisplay(newVal);
|
|
9951
|
-
const hasChange = String(oldVal ?? "") !== String(newVal ?? "");
|
|
10717
|
+
const hasChange = typeof oldVal === "object" && oldVal !== null || typeof newVal === "object" && newVal !== null ? oldDisplay !== newDisplay : String(oldVal ?? "") !== String(newVal ?? "");
|
|
9952
10718
|
if (hasChange) {
|
|
9953
10719
|
rowHasChanges = true;
|
|
9954
10720
|
}
|
|
@@ -10495,16 +11261,21 @@ const index = {
|
|
|
10495
11261
|
}
|
|
10496
11262
|
};
|
|
10497
11263
|
exports.CURRENT_SCHEMA_VERSION = CURRENT_SCHEMA_VERSION;
|
|
11264
|
+
exports.EXPLICIT_CLEAR_TOKENS = EXPLICIT_CLEAR_TOKENS;
|
|
11265
|
+
exports.FORBIDDEN_OBJECT_KEYS = FORBIDDEN_OBJECT_KEYS;
|
|
10498
11266
|
exports.METADATA_COLUMN_KEY = METADATA_COLUMN_KEY;
|
|
10499
11267
|
exports.SYSTEM_ATTRIBUTES = SYSTEM_ATTRIBUTES;
|
|
10500
11268
|
exports.applyOccurrenceUpdatesToDocument = applyOccurrenceUpdatesToDocument;
|
|
10501
11269
|
exports.buildCollectionQueryFilters = buildCollectionQueryFilters;
|
|
10502
11270
|
exports.buildDocumentUpdatePayload = buildDocumentUpdatePayload;
|
|
10503
11271
|
exports.buildErrorCsv = buildErrorCsv;
|
|
11272
|
+
exports.buildExportColumnPlan = buildExportColumnPlan;
|
|
10504
11273
|
exports.buildLosslessPopulate = buildLosslessPopulate;
|
|
11274
|
+
exports.buildNestedComponentPatchFromDots = buildNestedComponentPatchFromDots;
|
|
10505
11275
|
exports.buildRichAttributeMeta = buildRichAttributeMeta;
|
|
10506
11276
|
exports.classifyAttribute = classifyAttribute;
|
|
10507
11277
|
exports.coerceAndValidateFieldValue = coerceAndValidateFieldValue;
|
|
11278
|
+
exports.deepCloneValue = deepCloneValue;
|
|
10508
11279
|
exports.deepMergeEntities = deepMergeEntities;
|
|
10509
11280
|
exports.default = index;
|
|
10510
11281
|
exports.discoverComponentFields = discoverComponentFields;
|
|
@@ -10513,13 +11284,18 @@ exports.enumerateOccurrences = enumerateOccurrences;
|
|
|
10513
11284
|
exports.escapeCsvCell = escapeCsvCell;
|
|
10514
11285
|
exports.extractHeadingsFromRichText = extractHeadingsFromRichText;
|
|
10515
11286
|
exports.extractMetadataFromRow = extractMetadataFromRow;
|
|
11287
|
+
exports.extractRowFlattenedMetadata = extractRowFlattenedMetadata;
|
|
10516
11288
|
exports.formatErrorCsvFilename = formatErrorCsvFilename;
|
|
10517
11289
|
exports.getAllNestedValues = getAllNestedValues;
|
|
11290
|
+
exports.getValueAtPath = getValueAtPath;
|
|
11291
|
+
exports.isPlainObject = isPlainObject;
|
|
10518
11292
|
exports.isValidDocumentId = isValidDocumentId;
|
|
10519
11293
|
exports.parseBoolean = parseBoolean;
|
|
10520
11294
|
exports.parseCsvToMatrix = parseCsvToMatrix;
|
|
10521
11295
|
exports.parseCsvToRecords = parseCsvToRecords;
|
|
11296
|
+
exports.parseFlattenedLeafValue = parseFlattenedLeafValue;
|
|
10522
11297
|
exports.parseNumeric = parseNumeric;
|
|
11298
|
+
exports.reconstructFlattenedJsonAttribute = reconstructFlattenedJsonAttribute;
|
|
10523
11299
|
exports.resolveBatchTargets = resolveBatchTargets;
|
|
10524
11300
|
exports.resolveComponentPayload = resolveComponentPayload;
|
|
10525
11301
|
exports.resolveDynamicZonePayload = resolveDynamicZonePayload;
|
|
@@ -10529,8 +11305,12 @@ exports.resolveRelationPayload = resolveRelationPayload;
|
|
|
10529
11305
|
exports.sanitizeUserErrorMessage = sanitizeUserErrorMessage;
|
|
10530
11306
|
exports.serializeDocumentsToCsv = serializeDocumentsToCsv;
|
|
10531
11307
|
exports.serializeFieldValue = serializeFieldValue;
|
|
11308
|
+
exports.serializeFlattenedLeafValue = serializeFlattenedLeafValue;
|
|
11309
|
+
exports.serializePlannedCell = serializePlannedCell;
|
|
11310
|
+
exports.setValueAtPath = setValueAtPath;
|
|
10532
11311
|
exports.sortAuditRecordsDesc = sortAuditRecordsDesc;
|
|
10533
11312
|
exports.validateEntityQuotas = validateEntityQuotas;
|
|
11313
|
+
exports.validateRecordSchemaConstraints = validateRecordSchemaConstraints;
|
|
10534
11314
|
exports.verifyDocumentIntegrity = verifyDocumentIntegrity;
|
|
10535
11315
|
exports.withRollbackLock = withRollbackLock;
|
|
10536
11316
|
//# sourceMappingURL=index.js.map
|