strapi-plugin-bulk-updater 1.5.13 → 1.5.15

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.
@@ -638,7 +638,7 @@ const csvController = ({ strapi }) => ({
638
638
  async exportCollection(ctx) {
639
639
  try {
640
640
  const { uid } = ctx.params;
641
- const { search, attribute, filterOperator, filterQuery, limit, documentIds } = {
641
+ const { search, attribute, searchAttribute, filterOperator, filterQuery, limit, documentIds } = {
642
642
  ...ctx.query,
643
643
  ...ctx.request?.body || {}
644
644
  };
@@ -650,6 +650,7 @@ const csvController = ({ strapi }) => ({
650
650
  const result = await csvService2.exportCollectionCsv(uid, {
651
651
  search: search ? String(search) : void 0,
652
652
  attribute: attribute ? String(attribute) : void 0,
653
+ searchAttribute: searchAttribute ? String(searchAttribute) : void 0,
653
654
  filterOperator: filterOperator ? String(filterOperator) : void 0,
654
655
  filterQuery: filterQuery !== void 0 ? String(filterQuery) : void 0,
655
656
  limit: limit ? Number(limit) : void 0,
@@ -1836,14 +1837,14 @@ function resolveContentTypeField(contentType, field) {
1836
1837
  if (matched) return matched;
1837
1838
  return null;
1838
1839
  }
1839
- function buildDeepPopulate$1(attributes, allComponents, depth = 0) {
1840
+ function buildDeepPopulate(attributes, allComponents, depth = 0) {
1840
1841
  if (depth > 5) return void 0;
1841
1842
  const populate = {};
1842
1843
  for (const [key, def] of Object.entries(attributes || {})) {
1843
1844
  if (def.type === "component" && def.component) {
1844
1845
  const comp = allComponents[def.component];
1845
1846
  if (comp?.attributes) {
1846
- const subPopulate = buildDeepPopulate$1(comp.attributes, allComponents, depth + 1);
1847
+ const subPopulate = buildDeepPopulate(comp.attributes, allComponents, depth + 1);
1847
1848
  if (subPopulate && Object.keys(subPopulate).length > 0) {
1848
1849
  populate[key] = {
1849
1850
  populate: subPopulate
@@ -2132,6 +2133,173 @@ function buildDeepFilter(pathParts, condition) {
2132
2133
  [head]: buildDeepFilter(tail, condition)
2133
2134
  };
2134
2135
  }
2136
+ function buildCollectionQueryFilters(strapi, contentType, options = {}) {
2137
+ const filters = {};
2138
+ const attrs = contentType?.attributes || {};
2139
+ const targetFilterAttr = options.searchAttribute || options.attribute || "";
2140
+ const normOp = (options.filterOperator || "").toLowerCase().replace(/_/g, "");
2141
+ const q = (options.filterQuery || "").trim();
2142
+ if (options.documentIds && Array.isArray(options.documentIds) && options.documentIds.length > 0) {
2143
+ filters.documentId = { $in: options.documentIds };
2144
+ }
2145
+ let colHasAttribute = false;
2146
+ let isNestedAttr = false;
2147
+ let isRootDz = false;
2148
+ let parts = [];
2149
+ let resolvedFilterAttr = targetFilterAttr;
2150
+ if (targetFilterAttr) {
2151
+ const resolvedField = resolveContentTypeField(contentType, targetFilterAttr);
2152
+ if (resolvedField) {
2153
+ resolvedFilterAttr = resolvedField;
2154
+ colHasAttribute = true;
2155
+ } else {
2156
+ const parsed = parseDynamicZonePath(targetFilterAttr);
2157
+ if (parsed.rootKey && contentType.attributes?.[parsed.rootKey]?.type === "dynamiczone") {
2158
+ isRootDz = true;
2159
+ colHasAttribute = true;
2160
+ isNestedAttr = true;
2161
+ parts = parsed.cleanPath.split(".");
2162
+ } else if (targetFilterAttr.includes(".") || targetFilterAttr.includes("[")) {
2163
+ isNestedAttr = isDeepComponentField(contentType, strapi?.components || {}, targetFilterAttr);
2164
+ if (isNestedAttr) {
2165
+ colHasAttribute = true;
2166
+ parts = parsed.cleanPath.split(".");
2167
+ }
2168
+ }
2169
+ }
2170
+ }
2171
+ if (normOp && normOp !== "none" && targetFilterAttr) {
2172
+ if (!colHasAttribute) {
2173
+ return {
2174
+ filters,
2175
+ colHasAttribute: false,
2176
+ isRootDz: false,
2177
+ targetFilterAttr,
2178
+ normOp,
2179
+ filterQuery: q
2180
+ };
2181
+ }
2182
+ let condition = void 0;
2183
+ const targetAttrSchema = isNestedAttr ? getLeafAttributeSchema(contentType, strapi?.components || {}, targetFilterAttr) : attrs[resolvedFilterAttr];
2184
+ const isRelation = targetAttrSchema?.type === "relation";
2185
+ const isStringLike = ["string", "text", "email", "richtext", "uid"].includes(targetAttrSchema?.type);
2186
+ if (isRelation) {
2187
+ const targetUid = targetAttrSchema?.target;
2188
+ const targetContentType = targetUid && strapi?.contentTypes ? strapi.contentTypes[targetUid] : void 0;
2189
+ const targetAttrs = targetContentType?.attributes || {};
2190
+ const targetStringAttrs = Object.keys(targetAttrs).filter(
2191
+ (k) => ["string", "text", "email", "uid"].includes(targetAttrs[k]?.type)
2192
+ );
2193
+ if (normOp === "empty") {
2194
+ condition = { documentId: { $null: true } };
2195
+ } else if (normOp === "notempty") {
2196
+ condition = { documentId: { $notNull: true } };
2197
+ } else if (q !== "") {
2198
+ const orConditions = [];
2199
+ targetStringAttrs.slice(0, 5).forEach((k) => {
2200
+ if (normOp === "equals") {
2201
+ orConditions.push({ [k]: { $eqi: q } });
2202
+ } else if (normOp === "startswith") {
2203
+ orConditions.push({ [k]: { $startsWithi: q } });
2204
+ } else if (normOp === "endswith") {
2205
+ orConditions.push({ [k]: { $endsWithi: q } });
2206
+ } else if (normOp === "notequals") {
2207
+ orConditions.push({ [k]: { $nei: q } });
2208
+ } else if (normOp === "notcontains") {
2209
+ orConditions.push({ [k]: { $notContainsi: q } });
2210
+ } else {
2211
+ orConditions.push({ [k]: { $containsi: q } });
2212
+ }
2213
+ });
2214
+ orConditions.push({ documentId: { $eq: q } });
2215
+ if (/^\d+$/.test(q)) {
2216
+ orConditions.push({ id: { $eq: Number(q) } });
2217
+ }
2218
+ condition = orConditions.length === 1 ? orConditions[0] : { $or: orConditions };
2219
+ }
2220
+ } else if (normOp === "empty") {
2221
+ condition = isStringLike ? { $or: [{ $null: true }, { $eq: "" }] } : { $null: true };
2222
+ } else if (normOp === "notempty") {
2223
+ condition = isStringLike ? { $and: [{ $notNull: true }, { $ne: "" }] } : { $notNull: true };
2224
+ } else if (q !== "") {
2225
+ let typedVal = q;
2226
+ const isNumeric = ["integer", "biginteger", "float", "decimal", "number"].includes(targetAttrSchema?.type);
2227
+ const isBoolean = targetAttrSchema?.type === "boolean";
2228
+ if (isNumeric && /^-?\d+(\.\d+)?$/.test(q)) {
2229
+ typedVal = Number(q);
2230
+ } else if (isBoolean) {
2231
+ if (q.toLowerCase() === "true") typedVal = true;
2232
+ else if (q.toLowerCase() === "false") typedVal = false;
2233
+ }
2234
+ switch (normOp) {
2235
+ case "equals":
2236
+ condition = isStringLike ? { $eqi: q } : { $eq: typedVal };
2237
+ break;
2238
+ case "notequals":
2239
+ condition = isStringLike ? { $nei: q } : { $ne: typedVal };
2240
+ break;
2241
+ case "contains":
2242
+ condition = { $containsi: q };
2243
+ break;
2244
+ case "notcontains":
2245
+ condition = { $notContainsi: q };
2246
+ break;
2247
+ case "startswith":
2248
+ condition = { $startsWithi: q };
2249
+ break;
2250
+ case "endswith":
2251
+ condition = { $endsWithi: q };
2252
+ break;
2253
+ }
2254
+ }
2255
+ if (condition !== void 0) {
2256
+ if (isNestedAttr) {
2257
+ if (isRootDz) ;
2258
+ else {
2259
+ const deepFilter = buildDeepFilter(parts, condition);
2260
+ Object.assign(filters, deepFilter);
2261
+ }
2262
+ } else {
2263
+ if (normOp === "empty" && isStringLike) {
2264
+ filters.$or = [
2265
+ { [resolvedFilterAttr]: { $null: true } },
2266
+ { [resolvedFilterAttr]: { $eq: "" } }
2267
+ ];
2268
+ } else if (normOp === "notempty" && isStringLike) {
2269
+ filters[resolvedFilterAttr] = { $notNull: true, $ne: "" };
2270
+ } else {
2271
+ filters[resolvedFilterAttr] = condition;
2272
+ }
2273
+ }
2274
+ }
2275
+ }
2276
+ if (options.search && options.search.trim() !== "") {
2277
+ const searchQ = options.search.trim();
2278
+ const searchableAttrs = Object.keys(attrs).filter(
2279
+ (k) => ["string", "text", "email", "uid"].includes(attrs[k]?.type)
2280
+ );
2281
+ if (searchableAttrs.length > 0) {
2282
+ const orList = searchableAttrs.slice(0, 6).map((k) => ({
2283
+ [k]: { $containsi: searchQ }
2284
+ }));
2285
+ if (Object.keys(filters).length > 0) {
2286
+ const existingFilters = { ...filters };
2287
+ Object.keys(filters).forEach((k) => delete filters[k]);
2288
+ filters.$and = [existingFilters, { $or: orList }];
2289
+ } else {
2290
+ filters.$or = orList;
2291
+ }
2292
+ }
2293
+ }
2294
+ return {
2295
+ filters,
2296
+ colHasAttribute: true,
2297
+ isRootDz,
2298
+ targetFilterAttr,
2299
+ normOp,
2300
+ filterQuery: q
2301
+ };
2302
+ }
2135
2303
  function getSafeTimezone(timeZone) {
2136
2304
  if (!timeZone || typeof timeZone !== "string") {
2137
2305
  return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
@@ -2377,7 +2545,7 @@ async function executeBatchInternal(strapi, {
2377
2545
  const loaderKey = `${uid}@@@${documentId}`;
2378
2546
  if (!documentLoader.has(loaderKey)) {
2379
2547
  const ct = strapi.contentTypes[uid];
2380
- const populateDef = ct?.attributes ? buildDeepPopulate$1(ct.attributes, strapi.components) : void 0;
2548
+ const populateDef = ct?.attributes ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
2381
2549
  documentLoader.set(
2382
2550
  loaderKey,
2383
2551
  strapi.documents(uid).findOne({
@@ -2407,7 +2575,7 @@ async function executeBatchInternal(strapi, {
2407
2575
  const hasAttribute = Boolean(attrDef) || isComponentNested;
2408
2576
  if (hasAttribute) {
2409
2577
  if (isComponentNested) {
2410
- const populateOption = buildDeepPopulate$1(contentType.attributes, strapi.components);
2578
+ const populateOption = buildDeepPopulate(contentType.attributes, strapi.components);
2411
2579
  const findOneArgs = { documentId: target.documentId };
2412
2580
  if (populateOption) {
2413
2581
  findOneArgs.populate = populateOption;
@@ -3251,7 +3419,7 @@ const bulkUpdaterService = ({ strapi }) => {
3251
3419
  let entries = [];
3252
3420
  let totalCount = 0;
3253
3421
  try {
3254
- const populateOption = buildDeepPopulate$1(allContentTypes[uid]?.attributes || {}, strapi.components);
3422
+ const populateOption = buildDeepPopulate(allContentTypes[uid]?.attributes || {}, strapi.components);
3255
3423
  if (meta.isSingleType) {
3256
3424
  const singleArgs = {};
3257
3425
  if (populateOption) {
@@ -3349,7 +3517,6 @@ const bulkUpdaterService = ({ strapi }) => {
3349
3517
  const currentPage = Math.max(Number(page) || 1, 1);
3350
3518
  const start = (currentPage - 1) * limit;
3351
3519
  const isSingleType = contentType.kind === "singleType";
3352
- const targetFilterAttr = searchAttribute || attribute;
3353
3520
  const signature = await getCollectionSignature(strapi, uid);
3354
3521
  const cacheKey = `${uid}:${limit}:${start}:${attribute || ""}:${searchAttribute || ""}:${filterOperator || ""}:${filterQuery || ""}:${search || ""}:${sortField || ""}:${sortOrder}`;
3355
3522
  const cached = queryCache.get(cacheKey);
@@ -3362,168 +3529,36 @@ const bulkUpdaterService = ({ strapi }) => {
3362
3529
  };
3363
3530
  }
3364
3531
  let result;
3365
- const filters = {};
3366
- const attrs = contentType.attributes || {};
3367
- let colHasAttribute = false;
3368
- let isNestedAttr = false;
3369
- let isRootDz = false;
3370
- let parts = [];
3371
- let resolvedFilterAttr = targetFilterAttr;
3372
- if (targetFilterAttr) {
3373
- const resolvedField = resolveContentTypeField(contentType, targetFilterAttr);
3374
- if (resolvedField) {
3375
- resolvedFilterAttr = resolvedField;
3376
- colHasAttribute = true;
3377
- } else {
3378
- const parsed = parseDynamicZonePath(targetFilterAttr);
3379
- if (parsed.rootKey && contentType.attributes?.[parsed.rootKey]?.type === "dynamiczone") {
3380
- isRootDz = true;
3381
- colHasAttribute = true;
3382
- isNestedAttr = true;
3383
- parts = parsed.cleanPath.split(".");
3384
- } else if (targetFilterAttr.includes(".") || targetFilterAttr.includes("[")) {
3385
- isNestedAttr = isDeepComponentField(contentType, strapi.components, targetFilterAttr);
3386
- if (isNestedAttr) {
3387
- colHasAttribute = true;
3388
- parts = parsed.cleanPath.split(".");
3389
- }
3390
- }
3391
- }
3392
- }
3393
- const normOp = (filterOperator || "").toLowerCase().replace(/_/g, "");
3394
- if (normOp && normOp !== "none") {
3395
- if (!colHasAttribute) {
3396
- result = {
3397
- uid,
3398
- status: "success",
3399
- displayName: contentType.info?.displayName || uid,
3400
- isSingleType,
3401
- draftAndPublish: Boolean(contentType.options?.draftAndPublish),
3402
- entries: [],
3403
- pagination: {
3404
- page: 1,
3405
- pageSize: limit,
3406
- total: 0,
3407
- pageCount: 0
3408
- }
3409
- };
3410
- queryCache.set(cacheKey, { signature, data: result, timestamp: Date.now() });
3411
- return { ...result, cached: false, etag };
3412
- }
3413
- let condition = void 0;
3414
- const q = (filterQuery || "").trim();
3415
- const targetAttrSchema = isNestedAttr ? getLeafAttributeSchema(contentType, strapi.components, targetFilterAttr) : attrs[resolvedFilterAttr];
3416
- const isRelation = targetAttrSchema?.type === "relation";
3417
- const isStringLike = ["string", "text", "email", "richtext", "uid"].includes(targetAttrSchema?.type);
3418
- if (isRelation) {
3419
- const targetUid = targetAttrSchema?.target;
3420
- const targetContentType = targetUid ? strapi.contentTypes[targetUid] : void 0;
3421
- const targetAttrs = targetContentType?.attributes || {};
3422
- const targetStringAttrs = Object.keys(targetAttrs).filter(
3423
- (k) => ["string", "text", "email", "uid"].includes(targetAttrs[k]?.type)
3424
- );
3425
- if (normOp === "empty") {
3426
- condition = { documentId: { $null: true } };
3427
- } else if (normOp === "notempty") {
3428
- condition = { documentId: { $notNull: true } };
3429
- } else if (q !== "") {
3430
- const orConditions = [];
3431
- targetStringAttrs.slice(0, 5).forEach((k) => {
3432
- if (normOp === "equals") {
3433
- orConditions.push({ [k]: { $eqi: q } });
3434
- } else if (normOp === "startswith") {
3435
- orConditions.push({ [k]: { $startsWithi: q } });
3436
- } else if (normOp === "endswith") {
3437
- orConditions.push({ [k]: { $endsWithi: q } });
3438
- } else if (normOp === "notequals") {
3439
- orConditions.push({ [k]: { $nei: q } });
3440
- } else if (normOp === "notcontains") {
3441
- orConditions.push({ [k]: { $notContainsi: q } });
3442
- } else {
3443
- orConditions.push({ [k]: { $containsi: q } });
3444
- }
3445
- });
3446
- orConditions.push({ documentId: { $eq: q } });
3447
- if (/^\d+$/.test(q)) {
3448
- orConditions.push({ id: { $eq: Number(q) } });
3449
- }
3450
- condition = orConditions.length === 1 ? orConditions[0] : { $or: orConditions };
3451
- }
3452
- } else if (normOp === "empty") {
3453
- condition = isStringLike ? { $or: [{ $null: true }, { $eq: "" }] } : { $null: true };
3454
- } else if (normOp === "notempty") {
3455
- condition = isStringLike ? { $and: [{ $notNull: true }, { $ne: "" }] } : { $notNull: true };
3456
- } else if (q !== "") {
3457
- let typedVal = q;
3458
- const isNumeric = ["integer", "biginteger", "float", "decimal", "number"].includes(targetAttrSchema?.type);
3459
- const isBoolean = targetAttrSchema?.type === "boolean";
3460
- if (isNumeric && /^-?\d+(\.\d+)?$/.test(q)) {
3461
- typedVal = Number(q);
3462
- } else if (isBoolean) {
3463
- if (q.toLowerCase() === "true") typedVal = true;
3464
- else if (q.toLowerCase() === "false") typedVal = false;
3465
- }
3466
- switch (normOp) {
3467
- case "equals":
3468
- condition = isStringLike ? { $eqi: q } : { $eq: typedVal };
3469
- break;
3470
- case "notequals":
3471
- condition = isStringLike ? { $nei: q } : { $ne: typedVal };
3472
- break;
3473
- case "contains":
3474
- condition = { $containsi: q };
3475
- break;
3476
- case "notcontains":
3477
- condition = { $notContainsi: q };
3478
- break;
3479
- case "startswith":
3480
- condition = { $startsWithi: q };
3481
- break;
3482
- case "endswith":
3483
- condition = { $endsWithi: q };
3484
- break;
3485
- }
3486
- }
3487
- if (condition !== void 0) {
3488
- if (isNestedAttr) {
3489
- if (isRootDz) ;
3490
- else {
3491
- const deepFilter = buildDeepFilter(parts, condition);
3492
- Object.assign(filters, deepFilter);
3493
- }
3494
- } else {
3495
- if (normOp === "empty" && isStringLike) {
3496
- filters.$or = [
3497
- { [resolvedFilterAttr]: { $null: true } },
3498
- { [resolvedFilterAttr]: { $eq: "" } }
3499
- ];
3500
- } else if (normOp === "notempty" && isStringLike) {
3501
- filters[resolvedFilterAttr] = { $notNull: true, $ne: "" };
3502
- } else {
3503
- filters[resolvedFilterAttr] = condition;
3504
- }
3505
- }
3506
- }
3507
- }
3508
- if (search && search.trim() !== "") {
3509
- const q = search.trim();
3510
- const searchableAttrs = Object.keys(attrs).filter(
3511
- (k) => ["string", "text", "email", "uid"].includes(attrs[k]?.type)
3512
- );
3513
- if (searchableAttrs.length > 0) {
3514
- const orList = searchableAttrs.slice(0, 6).map((k) => ({
3515
- [k]: { $containsi: q }
3516
- }));
3517
- if (Object.keys(filters).length > 0) {
3518
- const existingFilters = { ...filters };
3519
- Object.keys(filters).forEach((k) => delete filters[k]);
3520
- filters.$and = [existingFilters, { $or: orList }];
3521
- } else {
3522
- filters.$or = orList;
3532
+ const filterMeta = buildCollectionQueryFilters(strapi, contentType, {
3533
+ attribute,
3534
+ searchAttribute,
3535
+ filterOperator,
3536
+ filterQuery,
3537
+ search
3538
+ });
3539
+ if (!filterMeta.colHasAttribute && filterMeta.normOp && filterMeta.normOp !== "none") {
3540
+ result = {
3541
+ uid,
3542
+ status: "success",
3543
+ displayName: contentType.info?.displayName || uid,
3544
+ isSingleType,
3545
+ draftAndPublish: Boolean(contentType.options?.draftAndPublish),
3546
+ entries: [],
3547
+ pagination: {
3548
+ page: 1,
3549
+ pageSize: limit,
3550
+ total: 0,
3551
+ pageCount: 0
3523
3552
  }
3524
- }
3525
- }
3526
- const populateOption = buildDeepPopulate$1(contentType.attributes, strapi.components);
3553
+ };
3554
+ queryCache.set(cacheKey, { signature, data: result, timestamp: Date.now() });
3555
+ return { ...result, cached: false, etag };
3556
+ }
3557
+ const filters = filterMeta.filters;
3558
+ const isRootDz = filterMeta.isRootDz;
3559
+ const normOp = filterMeta.normOp;
3560
+ const targetFilterAttr = filterMeta.targetFilterAttr;
3561
+ const populateOption = buildDeepPopulate(contentType.attributes, strapi.components);
3527
3562
  if (isSingleType) {
3528
3563
  let singleDoc = null;
3529
3564
  try {
@@ -3801,7 +3836,7 @@ const bulkUpdaterService = ({ strapi }) => {
3801
3836
  let currentEntry;
3802
3837
  if (isComponentNested) {
3803
3838
  const findOneArgs = { documentId: target.documentId };
3804
- const populateOption = buildDeepPopulate$1(contentType.attributes, strapi.components);
3839
+ const populateOption = buildDeepPopulate(contentType.attributes, strapi.components);
3805
3840
  if (populateOption) {
3806
3841
  findOneArgs.populate = populateOption;
3807
3842
  }
@@ -5013,6 +5048,39 @@ const DEFAULT_CANDIDATE_TYPES = [
5013
5048
  "api::audit.audit",
5014
5049
  "api::bulk-audit-log.bulk-audit-log"
5015
5050
  ];
5051
+ function sortAuditRecordsDesc(records) {
5052
+ return [...records].sort((a, b) => {
5053
+ const timeA = a.executedAt || a.createdAt ? new Date(a.executedAt || a.createdAt).getTime() : 0;
5054
+ const validTimeA = Number.isNaN(timeA) ? 0 : timeA;
5055
+ const timeB = b.executedAt || b.createdAt ? new Date(b.executedAt || b.createdAt).getTime() : 0;
5056
+ const validTimeB = Number.isNaN(timeB) ? 0 : timeB;
5057
+ if (validTimeB !== validTimeA) {
5058
+ return validTimeB - validTimeA;
5059
+ }
5060
+ if (typeof a.id === "number" && typeof b.id === "number") {
5061
+ return b.id - a.id;
5062
+ }
5063
+ const idA = String(a.id ?? a.batchId ?? "");
5064
+ const idB = String(b.id ?? b.batchId ?? "");
5065
+ return idB.localeCompare(idA);
5066
+ });
5067
+ }
5068
+ let rollbackLock = Promise.resolve();
5069
+ function withRollbackLock(fn) {
5070
+ const previousLock = rollbackLock;
5071
+ let release = () => {
5072
+ };
5073
+ rollbackLock = new Promise((resolve) => {
5074
+ release = resolve;
5075
+ });
5076
+ return previousLock.then(async () => {
5077
+ try {
5078
+ return await fn();
5079
+ } finally {
5080
+ release();
5081
+ }
5082
+ });
5083
+ }
5016
5084
  const auditService = ({ strapi }) => ({
5017
5085
  /**
5018
5086
  * Detects whether Strapi Enterprise Native Audit Log service is available.
@@ -5119,7 +5187,7 @@ const auditService = ({ strapi }) => ({
5119
5187
  /**
5120
5188
  * Optionally writes an audit event directly to Strapi Enterprise's native Audit Logs table.
5121
5189
  */
5122
- async recordToEnterpriseNative(action, payload2, user) {
5190
+ async recordToEnterpriseNative(action, payload, user) {
5123
5191
  try {
5124
5192
  const eeService = this.getEnterpriseAuditService();
5125
5193
  if (eeService && typeof eeService.save === "function") {
@@ -5127,7 +5195,7 @@ const auditService = ({ strapi }) => ({
5127
5195
  action,
5128
5196
  date: /* @__PURE__ */ new Date(),
5129
5197
  userId: user?.id,
5130
- payload: payload2
5198
+ payload
5131
5199
  });
5132
5200
  strapi.log.info(
5133
5201
  `[bulk-updater] Successfully dispatched event to Strapi Enterprise Audit Log: ${action}`
@@ -5241,7 +5309,15 @@ const auditService = ({ strapi }) => ({
5241
5309
  try {
5242
5310
  const store = strapi.store({ type: "plugin", name: "bulk-updater", key: "audit-history" });
5243
5311
  const stored = await store.get({}) || { history: [] };
5244
- const history = Array.isArray(stored.history) ? stored.history : [];
5312
+ const rawHistory = Array.isArray(stored.history) ? stored.history : [];
5313
+ const sortedHistory = sortAuditRecordsDesc(rawHistory);
5314
+ const latestRecord = sortedHistory.length > 0 ? sortedHistory[0] : null;
5315
+ const history = sortedHistory.map((rec) => ({
5316
+ ...rec,
5317
+ isLatestEligible: Boolean(
5318
+ latestRecord && rec.batchId === latestRecord.batchId && !latestRecord.isRolledBack
5319
+ )
5320
+ }));
5245
5321
  return {
5246
5322
  enabled: true,
5247
5323
  mode: "store",
@@ -5283,14 +5359,23 @@ const auditService = ({ strapi }) => ({
5283
5359
  isRolledBack: Boolean(r[f.isRolledBack]),
5284
5360
  rolledBackAt: r[f.rolledBackAt] || null,
5285
5361
  rolledBackBy: r[f.rolledBackBy] || null,
5286
- executedAt: r[f.executedAt] || r.createdAt
5362
+ executedAt: r[f.executedAt] || r.createdAt,
5363
+ createdAt: r.createdAt
5364
+ }));
5365
+ const sortedHistory = sortAuditRecordsDesc(normalized);
5366
+ const latestRecord = sortedHistory.length > 0 ? sortedHistory[0] : null;
5367
+ const history = sortedHistory.map((rec) => ({
5368
+ ...rec,
5369
+ isLatestEligible: Boolean(
5370
+ latestRecord && rec.batchId === latestRecord.batchId && !latestRecord.isRolledBack
5371
+ )
5287
5372
  }));
5288
5373
  return {
5289
5374
  enabled: true,
5290
5375
  mode: config.mode,
5291
5376
  contentType: config.contentType,
5292
5377
  isEnterpriseNativeAvailable: config.isEnterpriseNativeAvailable,
5293
- history: normalized
5378
+ history
5294
5379
  };
5295
5380
  } catch (err) {
5296
5381
  return {
@@ -5329,7 +5414,7 @@ const auditService = ({ strapi }) => ({
5329
5414
  const isNested = item.attribute.includes(".") || item.attribute.includes("[") || isComponent || isDynamicZone || isDeepComponentField(ct, strapi.components, item.attribute);
5330
5415
  let wasPublished = false;
5331
5416
  if (isNested && (isComponent || isDynamicZone || rootAttrDef)) {
5332
- const populateOption = buildDeepPopulate$1(ct.attributes, strapi.components);
5417
+ const populateOption = buildDeepPopulate(ct.attributes, strapi.components);
5333
5418
  const findOneArgs = { documentId: item.documentId };
5334
5419
  if (populateOption) {
5335
5420
  findOneArgs.populate = populateOption;
@@ -5432,34 +5517,151 @@ const auditService = ({ strapi }) => ({
5432
5517
  return { revertedCount, rollbackDetails };
5433
5518
  },
5434
5519
  /**
5435
- * Performs deterministic rollback of a batch
5520
+ * Performs deterministic rollback of a batch.
5521
+ * Strict invariant: ONLY the latest completed update is eligible for rollback.
5522
+ * Older completed updates, already rolled-back updates, and pending/failed/executing batches are strictly rejected.
5436
5523
  */
5437
5524
  async rollbackBatch(batchId, currentUser) {
5438
- const config = this.getAuditConfig();
5439
- if (!config.enabled) {
5440
- throw new Error("Audit trail is not configured or disabled.");
5441
- }
5442
- if (config.mode === "store") {
5443
- const store = strapi.store({ type: "plugin", name: "bulk-updater", key: "audit-history" });
5444
- const stored = await store.get({}) || { history: [] };
5445
- const history = Array.isArray(stored.history) ? stored.history : [];
5446
- const recordIndex = history.findIndex((r) => r.batchId === batchId);
5447
- if (recordIndex === -1) {
5525
+ return withRollbackLock(async () => {
5526
+ const config = this.getAuditConfig();
5527
+ if (!config.enabled) {
5528
+ throw new Error("Audit trail is not configured or disabled.");
5529
+ }
5530
+ if (!batchId) {
5531
+ throw new Error("A valid batchId is required to perform rollback.");
5532
+ }
5533
+ try {
5534
+ const bulkService = strapi.plugin("bulk-updater")?.service("bulkUpdater");
5535
+ if (bulkService && typeof bulkService.getBatchStatus === "function") {
5536
+ const statusRes = await bulkService.getBatchStatus(batchId);
5537
+ const batchJob = statusRes?.batch;
5538
+ if (batchJob) {
5539
+ if (batchJob.status === "pending_approval" || batchJob.status === "queued_offpeak") {
5540
+ throw new Error(`Batch "${batchId}" is currently pending and cannot be rolled back.`);
5541
+ }
5542
+ if (batchJob.status === "processing" || batchJob.status === "running" || batchJob.status === "executing") {
5543
+ throw new Error(`Batch "${batchId}" is currently executing and cannot be rolled back.`);
5544
+ }
5545
+ if (batchJob.status === "failed") {
5546
+ throw new Error(`Batch "${batchId}" failed during execution and cannot be rolled back.`);
5547
+ }
5548
+ }
5549
+ }
5550
+ } catch (checkErr) {
5551
+ if (checkErr.message?.startsWith('Batch "')) {
5552
+ throw checkErr;
5553
+ }
5554
+ }
5555
+ if (config.mode === "store") {
5556
+ const store = strapi.store({ type: "plugin", name: "bulk-updater", key: "audit-history" });
5557
+ const stored = await store.get({}) || { history: [] };
5558
+ const rawHistory = Array.isArray(stored.history) ? stored.history : [];
5559
+ if (rawHistory.length === 0) {
5560
+ throw new Error("No completed update records found in audit trail.");
5561
+ }
5562
+ const sortedHistory2 = sortAuditRecordsDesc(rawHistory);
5563
+ const targetRecord2 = sortedHistory2.find((r) => r.batchId === batchId);
5564
+ if (!targetRecord2) {
5565
+ throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
5566
+ }
5567
+ const latestRecord2 = sortedHistory2[0];
5568
+ if (latestRecord2.batchId !== batchId) {
5569
+ throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
5570
+ }
5571
+ if (targetRecord2.isRolledBack) {
5572
+ throw new Error(`Batch "${batchId}" has already been rolled back.`);
5573
+ }
5574
+ const diffs2 = Array.isArray(targetRecord2.diffs) ? targetRecord2.diffs : [];
5575
+ const { revertedCount: revertedCount2, rollbackDetails: rollbackDetails2 } = await this.revertDiffItems(diffs2, currentUser?.id);
5576
+ const recordIndex = rawHistory.findIndex((r) => r.batchId === batchId);
5577
+ if (recordIndex !== -1) {
5578
+ rawHistory[recordIndex] = {
5579
+ ...rawHistory[recordIndex],
5580
+ isRolledBack: true,
5581
+ rolledBackAt: (/* @__PURE__ */ new Date()).toISOString(),
5582
+ rolledBackBy: currentUser?.email || "Admin"
5583
+ };
5584
+ await store.set({ value: { history: rawHistory } });
5585
+ }
5586
+ try {
5587
+ const affectedUids = new Set(rollbackDetails2.map((d) => d.uid));
5588
+ const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
5589
+ affectedUids.forEach((uid) => {
5590
+ if (uid && bulkService?.invalidateCache) {
5591
+ bulkService.invalidateCache(uid);
5592
+ }
5593
+ });
5594
+ } catch {
5595
+ }
5596
+ await this.recordToEnterpriseNative(
5597
+ "bulk-updater.rollback",
5598
+ {
5599
+ batchId,
5600
+ revertedCount: revertedCount2
5601
+ },
5602
+ currentUser
5603
+ );
5604
+ return {
5605
+ success: true,
5606
+ batchId,
5607
+ revertedCount: revertedCount2,
5608
+ details: rollbackDetails2
5609
+ };
5610
+ }
5611
+ if (!config.contentType || !config.fields) {
5612
+ throw new Error("Audit trail is not configured or disabled.");
5613
+ }
5614
+ const f = config.fields;
5615
+ const allRecords = await strapi.documents(config.contentType).findMany({
5616
+ sort: { createdAt: "desc" }
5617
+ });
5618
+ if (!allRecords || allRecords.length === 0) {
5619
+ throw new Error("No completed update records found in audit trail.");
5620
+ }
5621
+ const normalizedHistory = allRecords.map((r) => ({
5622
+ id: r.id,
5623
+ documentId: r.documentId,
5624
+ batchId: r[f.batchId] || r.documentId,
5625
+ attribute: r[f.attribute],
5626
+ value: r[f.value],
5627
+ userEmail: r[f.userEmail] || "admin@strapi.io",
5628
+ userName: r[f.userName] || "Admin",
5629
+ updatedCount: r[f.updatedCount] || 0,
5630
+ skippedCount: r[f.skippedCount] || 0,
5631
+ totalTargets: r[f.totalTargets] || 0,
5632
+ diffs: typeof r[f.diffs] === "string" ? JSON.parse(r[f.diffs]) : r[f.diffs] || [],
5633
+ isRolledBack: Boolean(r[f.isRolledBack]),
5634
+ rolledBackAt: r[f.rolledBackAt] || null,
5635
+ rolledBackBy: r[f.rolledBackBy] || null,
5636
+ executedAt: r[f.executedAt] || r.createdAt,
5637
+ createdAt: r.createdAt
5638
+ }));
5639
+ const sortedHistory = sortAuditRecordsDesc(normalizedHistory);
5640
+ const targetRecord = sortedHistory.find((r) => r.batchId === batchId);
5641
+ if (!targetRecord) {
5448
5642
  throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
5449
5643
  }
5450
- const record2 = history[recordIndex];
5451
- if (record2.isRolledBack) {
5644
+ const latestRecord = sortedHistory[0];
5645
+ if (latestRecord.batchId !== batchId) {
5646
+ throw new Error("Only the latest completed update can be rolled back. Older batch updates cannot be rolled back.");
5647
+ }
5648
+ if (targetRecord.isRolledBack) {
5452
5649
  throw new Error(`Batch "${batchId}" has already been rolled back.`);
5453
5650
  }
5454
- const diffs2 = Array.isArray(record2.diffs) ? record2.diffs : [];
5455
- const { revertedCount: revertedCount2, rollbackDetails: rollbackDetails2 } = await this.revertDiffItems(diffs2, currentUser?.id);
5456
- record2.isRolledBack = true;
5457
- record2.rolledBackAt = (/* @__PURE__ */ new Date()).toISOString();
5458
- record2.rolledBackBy = currentUser?.email || "Admin";
5459
- history[recordIndex] = record2;
5460
- await store.set({ value: { history } });
5651
+ const diffs = Array.isArray(targetRecord.diffs) ? targetRecord.diffs : [];
5652
+ const { revertedCount, rollbackDetails } = await this.revertDiffItems(diffs, currentUser?.id);
5653
+ const updateData = {};
5654
+ if (f.isRolledBack) updateData[f.isRolledBack] = true;
5655
+ if (f.rolledBackAt) updateData[f.rolledBackAt] = (/* @__PURE__ */ new Date()).toISOString();
5656
+ if (f.rolledBackBy) {
5657
+ updateData[f.rolledBackBy] = currentUser?.email || "Admin";
5658
+ }
5659
+ await strapi.documents(config.contentType).update({
5660
+ documentId: targetRecord.documentId,
5661
+ data: updateData
5662
+ });
5461
5663
  try {
5462
- const affectedUids = new Set(rollbackDetails2.map((d) => d.uid));
5664
+ const affectedUids = new Set(rollbackDetails.map((d) => d.uid));
5463
5665
  const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
5464
5666
  affectedUids.forEach((uid) => {
5465
5667
  if (uid && bulkService?.invalidateCache) {
@@ -5472,72 +5674,278 @@ const auditService = ({ strapi }) => ({
5472
5674
  "bulk-updater.rollback",
5473
5675
  {
5474
5676
  batchId,
5475
- revertedCount: revertedCount2
5677
+ revertedCount
5476
5678
  },
5477
5679
  currentUser
5478
5680
  );
5479
5681
  return {
5480
5682
  success: true,
5481
5683
  batchId,
5482
- revertedCount: revertedCount2,
5483
- details: rollbackDetails2
5684
+ revertedCount,
5685
+ details: rollbackDetails
5484
5686
  };
5687
+ });
5688
+ }
5689
+ });
5690
+ const SYSTEM_ATTRIBUTES = /* @__PURE__ */ new Set([
5691
+ "createdat",
5692
+ "updatedat",
5693
+ "publishedat",
5694
+ "createdby",
5695
+ "updatedby",
5696
+ "localizations",
5697
+ "locale",
5698
+ "documentid",
5699
+ "id",
5700
+ "strapistage",
5701
+ "strapi_stage",
5702
+ "strapiassignee",
5703
+ "strapi_assignee",
5704
+ "strapistatus",
5705
+ "strapi_status"
5706
+ ]);
5707
+ function classifyAttribute(attrName, attrDef) {
5708
+ const normKey = attrName.toLowerCase().replace(/[\s_-]/g, "");
5709
+ if (SYSTEM_ATTRIBUTES.has(normKey)) {
5710
+ return "system";
5711
+ }
5712
+ if (!attrDef || typeof attrDef !== "object") {
5713
+ return "scalar";
5714
+ }
5715
+ const type = String(attrDef.type || "").toLowerCase();
5716
+ if (type === "component") {
5717
+ return attrDef.repeatable ? "component_repeatable" : "component_single";
5718
+ }
5719
+ if (type === "dynamiczone") {
5720
+ return "dynamiczone";
5721
+ }
5722
+ if (type === "relation") {
5723
+ const rel = String(attrDef.relation || "").toLowerCase();
5724
+ const isMany = rel.endsWith("many") || rel === "onetomany" || rel === "manytomany" || rel === "morphone" || rel === "morphmany";
5725
+ return isMany ? "relation_to_many" : "relation_to_one";
5726
+ }
5727
+ if (type === "media") {
5728
+ return attrDef.multiple ? "media_to_many" : "media_single";
5729
+ }
5730
+ if (type === "blocks") {
5731
+ return "blocks";
5732
+ }
5733
+ if (type === "json") {
5734
+ return "json";
5735
+ }
5736
+ return "scalar";
5737
+ }
5738
+ function discoverComponentFields(strapi, compUid, visited = /* @__PURE__ */ new Set(), depth = 0, maxDepth = 6) {
5739
+ const result = {};
5740
+ if (depth >= maxDepth) return result;
5741
+ const comp = strapi.components?.[compUid];
5742
+ if (!comp?.attributes) return result;
5743
+ const nextVisited = new Set(visited);
5744
+ nextVisited.add(compUid);
5745
+ for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
5746
+ const normKey = attrName.toLowerCase().replace(/[\s_-]/g, "");
5747
+ if (SYSTEM_ATTRIBUTES.has(normKey)) continue;
5748
+ const category = classifyAttribute(attrName, attrDef);
5749
+ if (category === "system") continue;
5750
+ const field = {
5751
+ key: attrName,
5752
+ label: attrName,
5753
+ category,
5754
+ rawType: attrDef.type,
5755
+ repeatable: Boolean(attrDef.repeatable),
5756
+ componentUid: attrDef.component,
5757
+ dzComponents: Array.isArray(attrDef.components) ? attrDef.components : void 0,
5758
+ targetUid: attrDef.target,
5759
+ relationType: attrDef.relation,
5760
+ multiple: Boolean(attrDef.multiple),
5761
+ enumOptions: Array.isArray(attrDef.enum) ? attrDef.enum : void 0,
5762
+ required: Boolean(attrDef.required)
5763
+ };
5764
+ if (category === "component_single" && attrDef.component) {
5765
+ if (!visited.has(attrDef.component)) {
5766
+ field.subFields = discoverComponentFields(
5767
+ strapi,
5768
+ attrDef.component,
5769
+ nextVisited,
5770
+ depth + 1,
5771
+ maxDepth
5772
+ );
5773
+ }
5774
+ } else if (category === "component_repeatable" && attrDef.component) {
5775
+ if (!visited.has(attrDef.component)) {
5776
+ field.subFields = discoverComponentFields(
5777
+ strapi,
5778
+ attrDef.component,
5779
+ nextVisited,
5780
+ depth + 1,
5781
+ maxDepth
5782
+ );
5783
+ }
5485
5784
  }
5486
- if (!config.contentType || !config.fields) {
5487
- throw new Error("Audit trail is not configured or disabled.");
5785
+ result[attrName] = field;
5786
+ }
5787
+ return result;
5788
+ }
5789
+ function discoverSchema(strapi, uid) {
5790
+ const ct = strapi.contentTypes[uid];
5791
+ if (!ct) {
5792
+ throw new Error(`Content type "${uid}" not found in registered Strapi schema.`);
5793
+ }
5794
+ const fields = {};
5795
+ const allExportKeys = ["documentId"];
5796
+ const isLocalized = Boolean(ct.pluginOptions?.i18n?.localized);
5797
+ if (isLocalized) {
5798
+ allExportKeys.push("locale");
5799
+ }
5800
+ const isDraftAndPublish = Boolean(ct.options?.draftAndPublish);
5801
+ for (const [attrName, attrDef] of Object.entries(ct.attributes || {})) {
5802
+ const normKey = attrName.toLowerCase().replace(/[\s_-]/g, "");
5803
+ if (SYSTEM_ATTRIBUTES.has(normKey)) continue;
5804
+ if (attrDef?.target?.includes("review-workflow") || attrDef?.target === "admin::review-workflow-stage") {
5805
+ continue;
5488
5806
  }
5489
- const f = config.fields;
5490
- const records = await strapi.documents(config.contentType).findMany({
5491
- filters: {
5492
- [f.batchId]: { $eq: batchId }
5807
+ const category = classifyAttribute(attrName, attrDef);
5808
+ if (category === "system") continue;
5809
+ const field = {
5810
+ key: attrName,
5811
+ label: attrName,
5812
+ category,
5813
+ rawType: attrDef.type,
5814
+ repeatable: Boolean(attrDef.repeatable),
5815
+ componentUid: attrDef.component,
5816
+ dzComponents: Array.isArray(attrDef.components) ? attrDef.components : void 0,
5817
+ targetUid: attrDef.target,
5818
+ relationType: attrDef.relation,
5819
+ multiple: Boolean(attrDef.multiple),
5820
+ enumOptions: Array.isArray(attrDef.enum) ? attrDef.enum : void 0,
5821
+ required: Boolean(attrDef.required)
5822
+ };
5823
+ if ((category === "component_single" || category === "component_repeatable") && attrDef.component) {
5824
+ field.subFields = discoverComponentFields(strapi, attrDef.component, /* @__PURE__ */ new Set(), 0, 6);
5825
+ }
5826
+ fields[attrName] = field;
5827
+ allExportKeys.push(attrName);
5828
+ }
5829
+ return {
5830
+ uid,
5831
+ displayName: ct.info?.displayName || uid,
5832
+ singularName: ct.info?.singularName || uid,
5833
+ kind: ct.kind === "singleType" ? "singleType" : "collectionType",
5834
+ isDraftAndPublish,
5835
+ isLocalized,
5836
+ fields,
5837
+ allExportKeys
5838
+ };
5839
+ }
5840
+ function buildComponentPopulate(strapi, compUid, visited, depth, maxDepth) {
5841
+ if (depth >= maxDepth) return true;
5842
+ if (visited.has(compUid)) return true;
5843
+ const comp = strapi.components?.[compUid];
5844
+ if (!comp?.attributes) return true;
5845
+ const nextVisited = new Set(visited);
5846
+ nextVisited.add(compUid);
5847
+ const populate = {};
5848
+ for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
5849
+ const category = classifyAttribute(attrName, attrDef);
5850
+ if (category === "component_single" || category === "component_repeatable") {
5851
+ if (attrDef.component) {
5852
+ const subPop = buildComponentPopulate(
5853
+ strapi,
5854
+ attrDef.component,
5855
+ nextVisited,
5856
+ depth + 1,
5857
+ maxDepth
5858
+ );
5859
+ populate[attrName] = typeof subPop === "object" && Object.keys(subPop).length > 0 ? { populate: subPop } : true;
5860
+ } else {
5861
+ populate[attrName] = true;
5862
+ }
5863
+ } else if (category === "dynamiczone") {
5864
+ const dzComponents = Array.isArray(attrDef.components) ? attrDef.components : [];
5865
+ if (dzComponents.length > 0) {
5866
+ const onPopulate = {};
5867
+ for (const dzCompUid of dzComponents) {
5868
+ const dzCompPop = buildComponentPopulate(
5869
+ strapi,
5870
+ dzCompUid,
5871
+ nextVisited,
5872
+ depth + 1,
5873
+ maxDepth
5874
+ );
5875
+ onPopulate[dzCompUid] = typeof dzCompPop === "object" && Object.keys(dzCompPop).length > 0 ? { populate: dzCompPop } : true;
5876
+ }
5877
+ populate[attrName] = { on: onPopulate };
5878
+ } else {
5879
+ populate[attrName] = { populate: "*" };
5493
5880
  }
5494
- });
5495
- const record = records?.[0];
5496
- if (!record) {
5497
- throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
5498
- }
5499
- if (record[f.isRolledBack]) {
5500
- throw new Error(`Batch "${batchId}" has already been rolled back.`);
5501
- }
5502
- const diffs = typeof record[f.diffs] === "string" ? JSON.parse(record[f.diffs]) : record[f.diffs] || [];
5503
- const { revertedCount, rollbackDetails } = await this.revertDiffItems(diffs, currentUser?.id);
5504
- const updateData = {};
5505
- if (f.isRolledBack) updateData[f.isRolledBack] = true;
5506
- if (f.rolledBackAt) updateData[f.rolledBackAt] = (/* @__PURE__ */ new Date()).toISOString();
5507
- if (f.rolledBackBy) {
5508
- updateData[f.rolledBackBy] = currentUser?.email || "Admin";
5509
- }
5510
- await strapi.documents(config.contentType).update({
5511
- documentId: record.documentId,
5512
- data: updateData
5513
- });
5514
- try {
5515
- const affectedUids = new Set(rollbackDetails.map((d) => d.uid));
5516
- const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
5517
- affectedUids.forEach((uid) => {
5518
- if (uid && bulkService?.invalidateCache) {
5519
- bulkService.invalidateCache(uid);
5881
+ } else if (category === "relation_to_one" || category === "relation_to_many") {
5882
+ populate[attrName] = true;
5883
+ } else if (category === "media_single" || category === "media_to_many") {
5884
+ populate[attrName] = true;
5885
+ }
5886
+ }
5887
+ return Object.keys(populate).length > 0 ? populate : true;
5888
+ }
5889
+ function buildLosslessPopulate(strapi, uid, options = {}) {
5890
+ const maxDepth = options.maxDepth || 5;
5891
+ const schema = discoverSchema(strapi, uid);
5892
+ const populate = {};
5893
+ const visited = /* @__PURE__ */ new Set([uid]);
5894
+ for (const [fieldName, field] of Object.entries(schema.fields)) {
5895
+ switch (field.category) {
5896
+ case "component_single":
5897
+ case "component_repeatable": {
5898
+ if (field.componentUid) {
5899
+ const compPop = buildComponentPopulate(
5900
+ strapi,
5901
+ field.componentUid,
5902
+ visited,
5903
+ 0,
5904
+ maxDepth
5905
+ );
5906
+ populate[fieldName] = typeof compPop === "object" && Object.keys(compPop).length > 0 ? { populate: compPop } : true;
5907
+ } else {
5908
+ populate[fieldName] = true;
5520
5909
  }
5521
- });
5522
- } catch {
5910
+ break;
5911
+ }
5912
+ case "dynamiczone": {
5913
+ const dzComponents = field.dzComponents || [];
5914
+ if (dzComponents.length > 0) {
5915
+ const onPopulate = {};
5916
+ for (const compUid of dzComponents) {
5917
+ const compPop = buildComponentPopulate(
5918
+ strapi,
5919
+ compUid,
5920
+ visited,
5921
+ 0,
5922
+ maxDepth
5923
+ );
5924
+ onPopulate[compUid] = typeof compPop === "object" && Object.keys(compPop).length > 0 ? { populate: compPop } : true;
5925
+ }
5926
+ populate[fieldName] = { on: onPopulate };
5927
+ } else {
5928
+ populate[fieldName] = { populate: "*" };
5929
+ }
5930
+ break;
5931
+ }
5932
+ case "relation_to_one":
5933
+ case "relation_to_many": {
5934
+ populate[fieldName] = true;
5935
+ break;
5936
+ }
5937
+ case "media_single":
5938
+ case "media_to_many": {
5939
+ populate[fieldName] = true;
5940
+ break;
5941
+ }
5523
5942
  }
5524
- await this.recordToEnterpriseNative(
5525
- "bulk-updater.rollback",
5526
- {
5527
- batchId,
5528
- revertedCount
5529
- },
5530
- currentUser
5531
- );
5532
- return {
5533
- success: true,
5534
- batchId,
5535
- revertedCount,
5536
- details: rollbackDetails
5537
- };
5538
5943
  }
5539
- });
5540
- function escapeCsvValue(val) {
5944
+ return Object.keys(populate).length > 0 ? populate : void 0;
5945
+ }
5946
+ const METADATA_COLUMN_KEY = "__bulk_updater_metadata";
5947
+ const CURRENT_SCHEMA_VERSION = 1;
5948
+ function escapeCsvCell(val) {
5541
5949
  if (val === null || val === void 0) return "";
5542
5950
  let str = "";
5543
5951
  if (val instanceof Date) {
@@ -5548,15 +5956,15 @@ function escapeCsvValue(val) {
5548
5956
  str = String(val);
5549
5957
  }
5550
5958
  str = str.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
5551
- if (/^[=+@-]$/.test(str.charAt(0))) {
5959
+ if (/^[=+@-]/.test(str)) {
5552
5960
  str = `'${str}`;
5553
5961
  }
5554
- if (str.includes(",") || str.includes('"') || str.includes("\n")) {
5962
+ if (str.includes(",") || str.includes('"') || str.includes("\n") || str.includes("\r")) {
5555
5963
  return `"${str.replace(/"/g, '""')}"`;
5556
5964
  }
5557
5965
  return str;
5558
5966
  }
5559
- function parseCsvRows(csvText) {
5967
+ function parseCsvToMatrix(csvText) {
5560
5968
  if (!csvText) return [];
5561
5969
  let text = csvText;
5562
5970
  if (text.charCodeAt(0) === 65279) {
@@ -5624,13 +6032,13 @@ function parseCsvRows(csvText) {
5624
6032
  }
5625
6033
  return rows;
5626
6034
  }
5627
- function parseCsv(csvText) {
5628
- const rows = parseCsvRows(csvText);
5629
- if (rows.length < 2) return [];
5630
- const headers = rows[0].map((h) => h.trim());
6035
+ function parseCsvToRecords(csvText) {
6036
+ const matrix = parseCsvToMatrix(csvText);
6037
+ if (matrix.length < 2) return [];
6038
+ const headers = matrix[0].map((h) => h.trim());
5631
6039
  const records = [];
5632
- for (let i = 1; i < rows.length; i++) {
5633
- const row = rows[i];
6040
+ for (let i = 1; i < matrix.length; i++) {
6041
+ const row = matrix[i];
5634
6042
  const record = {};
5635
6043
  headers.forEach((h, idx) => {
5636
6044
  let val = row[idx] !== void 0 ? row[idx] : "";
@@ -5643,306 +6051,1042 @@ function parseCsv(csvText) {
5643
6051
  }
5644
6052
  return records;
5645
6053
  }
5646
- const LIFECYCLE_STATUS_WORDS = /* @__PURE__ */ new Set([
5647
- "pending review",
5648
- "pending_review",
5649
- "pending approval",
5650
- "pending_approval",
5651
- "approved",
5652
- "rejected",
5653
- "draft",
5654
- "published",
5655
- "modified",
5656
- "supported",
5657
- "ignored",
5658
- "editing",
5659
- "in review",
5660
- "in_review",
5661
- "ready to publish",
5662
- "ready_to_publish",
5663
- "null",
5664
- "undefined"
5665
- ]);
5666
- function isValidDocId(val) {
5667
- if (!val || typeof val !== "string") return false;
5668
- const trimmed = val.trim();
5669
- if (!trimmed) return false;
5670
- if (LIFECYCLE_STATUS_WORDS.has(trimmed.toLowerCase())) return false;
5671
- if (/\s/.test(trimmed)) return false;
5672
- return /^[a-zA-Z0-9_-]+$/.test(trimmed);
5673
- }
5674
- function extractDocId(row) {
5675
- if (!row || typeof row !== "object") return "";
5676
- const candidates = [
5677
- row.documentId,
5678
- row.document_id,
5679
- row["Document ID"],
5680
- row["Document Id"],
5681
- row["document_id"],
5682
- row.docId,
5683
- row["docId"],
5684
- row.id,
5685
- row.ID,
5686
- row.Id
5687
- ];
5688
- for (const c of candidates) {
5689
- if (c !== void 0 && c !== null) {
5690
- const str = String(c).trim();
5691
- if (isValidDocId(str)) {
5692
- return str;
6054
+ function serializeFieldValue(value, field) {
6055
+ if (value === null || value === void 0) {
6056
+ return "";
6057
+ }
6058
+ switch (field.category) {
6059
+ case "scalar": {
6060
+ if (value instanceof Date) {
6061
+ return value.toISOString();
5693
6062
  }
6063
+ return String(value);
5694
6064
  }
5695
- }
5696
- return "";
5697
- }
5698
- function extractLocale(row) {
5699
- if (!row || typeof row !== "object") return void 0;
5700
- const candidates = [
5701
- row.locale,
5702
- row.Locale,
5703
- row["locale"],
5704
- row["Locale"],
5705
- row.strapi_locale,
5706
- row["strapi_locale"]
5707
- ];
5708
- for (const c of candidates) {
5709
- if (c !== void 0 && c !== null) {
5710
- const str = String(c).trim();
5711
- if (str && str.toLowerCase() !== "null" && str.toLowerCase() !== "undefined" && str.toLowerCase() !== "[null]" && str.toLowerCase() !== '""') {
5712
- return str;
6065
+ case "blocks":
6066
+ case "json": {
6067
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
6068
+ }
6069
+ case "component_single": {
6070
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
6071
+ }
6072
+ case "component_repeatable": {
6073
+ if (Array.isArray(value)) {
6074
+ return JSON.stringify(value);
5713
6075
  }
6076
+ return typeof value === "object" ? JSON.stringify([value]) : "";
5714
6077
  }
5715
- }
5716
- return void 0;
5717
- }
5718
- function getEffectiveLocale(ct, rowLocale) {
5719
- if (!ct?.pluginOptions?.i18n?.localized) {
5720
- return void 0;
5721
- }
5722
- if (!rowLocale) {
5723
- return void 0;
5724
- }
5725
- const trimmed = rowLocale.trim();
5726
- if (!trimmed || trimmed.toLowerCase() === "null" || trimmed.toLowerCase() === "undefined" || trimmed.toLowerCase() === "[null]" || trimmed.toLowerCase() === '""') {
5727
- return void 0;
5728
- }
5729
- return trimmed;
5730
- }
5731
- function isRowInEditingStage(row) {
5732
- if (!row || typeof row !== "object") return false;
5733
- const candidates = [
5734
- row.strapi_stage,
5735
- row["strapi_stage"],
5736
- row.strapiStage,
5737
- row["Strapi Stage"],
5738
- row["strapi-stage"],
5739
- row.stage,
5740
- row.Stage,
5741
- row.status,
5742
- row.Status
5743
- ];
5744
- for (const c of candidates) {
5745
- if (c !== void 0 && c !== null) {
5746
- let stageName = "";
5747
- if (typeof c === "object") {
5748
- stageName = String(c.name || c.title || c.status || c.documentId || c.id || "").trim();
5749
- } else if (typeof c === "string") {
5750
- const trimmed = c.trim();
5751
- if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
5752
- try {
5753
- const parsed = JSON.parse(trimmed);
5754
- if (typeof parsed === "object" && parsed !== null) {
5755
- stageName = String(parsed.name || parsed.title || parsed.status || parsed.documentId || parsed.id || "").trim();
5756
- }
5757
- } catch {
6078
+ case "dynamiczone": {
6079
+ if (Array.isArray(value)) {
6080
+ const cleaned = value.map((block) => {
6081
+ if (block && typeof block === "object") {
6082
+ return { ...block };
5758
6083
  }
5759
- }
5760
- if (!stageName) {
5761
- stageName = trimmed;
5762
- }
5763
- } else {
5764
- stageName = String(c).trim();
6084
+ return block;
6085
+ });
6086
+ return JSON.stringify(cleaned);
5765
6087
  }
5766
- if (stageName) {
5767
- const s = stageName.toLowerCase();
5768
- if (s === "editing" || s === "in review" || s === "in_review" || s === "pending review" || s === "pending_review") {
5769
- return true;
5770
- }
6088
+ return "";
6089
+ }
6090
+ case "relation_to_one": {
6091
+ if (typeof value === "object" && value !== null) {
6092
+ const docId = value.documentId || value.id || "";
6093
+ return JSON.stringify({
6094
+ documentId: String(docId),
6095
+ title: value.title || value.name || value.slug || void 0
6096
+ });
5771
6097
  }
6098
+ return String(value);
5772
6099
  }
5773
- }
5774
- return false;
5775
- }
5776
- function extractDetailedErrorMessage(err) {
5777
- if (!err) return "Error processing row";
5778
- const detailsErrors = err.details?.errors || err.error?.details?.errors;
5779
- if (Array.isArray(detailsErrors) && detailsErrors.length > 0) {
5780
- const messages = detailsErrors.map((e) => {
5781
- if (!e) return "";
5782
- const path = Array.isArray(e.path) ? e.path.join(".") : e.path;
5783
- const msg = e.message || (typeof e === "string" ? e : JSON.stringify(e));
5784
- return path ? `${path}: ${msg}` : msg;
5785
- }).filter(Boolean);
5786
- if (messages.length > 0) return messages.join("; ");
5787
- }
5788
- if (Array.isArray(err.inner) && err.inner.length > 0) {
5789
- const messages = err.inner.map((e) => {
5790
- if (!e) return "";
5791
- const path = e.path;
5792
- const msg = e.message || (typeof e === "string" ? e : JSON.stringify(e));
5793
- return path ? `${path}: ${msg}` : msg;
5794
- }).filter(Boolean);
5795
- if (messages.length > 0) return messages.join("; ");
5796
- }
5797
- if (Array.isArray(err.errors) && err.errors.length > 0) {
5798
- return err.errors.join("; ");
5799
- }
5800
- if (typeof err.details === "string" && err.details.trim()) {
5801
- return err.details;
5802
- }
5803
- if (err.details?.message) {
5804
- return err.details.message;
5805
- }
5806
- if (err.message && err.message !== "[object Object]") {
5807
- return err.message;
5808
- }
5809
- return "Error processing row";
5810
- }
5811
- function discoverExportFields(ct, allComponents, maxDepth = 4) {
5812
- const fields = [{ key: "documentId", label: "documentId", type: "string" }];
5813
- const excluded = ["createdBy", "updatedBy", "localizations"];
5814
- function walkComponent(compUid, pathPrefix, labelPrefix, depth) {
5815
- if (depth >= maxDepth) return;
5816
- const comp = allComponents[compUid];
5817
- if (!comp?.attributes) return;
5818
- for (const [subKey, subDef] of Object.entries(comp.attributes)) {
5819
- if (excluded.includes(subKey)) continue;
5820
- const keyPath = `${pathPrefix}.${subKey}`;
5821
- const displayLabel = `${labelPrefix} > ${subKey}`;
5822
- if (subDef.type === "component" && subDef.component) {
5823
- if (!subDef.repeatable) {
5824
- walkComponent(subDef.component, keyPath, displayLabel, depth + 1);
5825
- } else {
5826
- fields.push({ key: keyPath, label: displayLabel, type: "component" });
5827
- }
5828
- } else {
5829
- fields.push({ key: keyPath, label: displayLabel, type: subDef.type });
6100
+ case "relation_to_many": {
6101
+ if (Array.isArray(value)) {
6102
+ const list = value.map((item) => {
6103
+ if (typeof item === "object" && item !== null) {
6104
+ const docId = item.documentId || item.id || "";
6105
+ return {
6106
+ documentId: String(docId),
6107
+ title: item.title || item.name || item.slug || void 0
6108
+ };
6109
+ }
6110
+ return { documentId: String(item) };
6111
+ });
6112
+ return JSON.stringify(list);
6113
+ }
6114
+ return "";
6115
+ }
6116
+ case "media_single": {
6117
+ if (typeof value === "object" && value !== null) {
6118
+ return JSON.stringify({
6119
+ id: value.id,
6120
+ documentId: value.documentId,
6121
+ name: value.name,
6122
+ url: value.url,
6123
+ mime: value.mime
6124
+ });
5830
6125
  }
6126
+ return String(value);
5831
6127
  }
5832
- }
5833
- for (const [attrName, attrDef] of Object.entries(ct.attributes || {})) {
5834
- if (excluded.includes(attrName)) continue;
5835
- if (attrDef.type === "component" && attrDef.component) {
5836
- if (!attrDef.repeatable) {
5837
- walkComponent(attrDef.component, attrName, attrName, 0);
5838
- } else {
5839
- fields.push({ key: attrName, label: attrName, type: "component" });
6128
+ case "media_to_many": {
6129
+ if (Array.isArray(value)) {
6130
+ const list = value.map((file) => {
6131
+ if (typeof file === "object" && file !== null) {
6132
+ return {
6133
+ id: file.id,
6134
+ documentId: file.documentId,
6135
+ name: file.name,
6136
+ url: file.url,
6137
+ mime: file.mime
6138
+ };
6139
+ }
6140
+ return file;
6141
+ });
6142
+ return JSON.stringify(list);
5840
6143
  }
5841
- } else {
5842
- fields.push({ key: attrName, label: attrName, type: attrDef.type });
6144
+ return "";
5843
6145
  }
6146
+ default:
6147
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
5844
6148
  }
5845
- return fields;
5846
6149
  }
5847
- function buildDeepPopulate(attributes, allComponents, depth = 0) {
5848
- if (depth > 5) return void 0;
5849
- const populate = {};
5850
- for (const [key, def] of Object.entries(attributes || {})) {
5851
- if (def.type === "component" && def.component) {
5852
- const comp = allComponents[def.component];
5853
- if (comp?.attributes) {
5854
- const subPopulate = buildDeepPopulate(comp.attributes, allComponents, depth + 1);
5855
- if (subPopulate && Object.keys(subPopulate).length > 0) {
5856
- populate[key] = {
5857
- populate: subPopulate
5858
- };
6150
+ function serializeDocumentsToCsv(strapi, uid, documents) {
6151
+ const schema = discoverSchema(strapi, uid);
6152
+ const headers = [METADATA_COLUMN_KEY, ...schema.allExportKeys];
6153
+ const lines = [];
6154
+ lines.push(headers.map(escapeCsvCell).join(","));
6155
+ const exportedAt = (/* @__PURE__ */ new Date()).toISOString();
6156
+ for (const doc of documents) {
6157
+ const rowValues = [];
6158
+ const metadata = {
6159
+ schemaVersion: CURRENT_SCHEMA_VERSION,
6160
+ contentType: uid,
6161
+ documentId: String(doc.documentId || doc.id || ""),
6162
+ locale: doc.locale || void 0,
6163
+ exportedAt
6164
+ };
6165
+ rowValues.push(escapeCsvCell(metadata));
6166
+ for (const key of schema.allExportKeys) {
6167
+ if (key === "documentId") {
6168
+ rowValues.push(escapeCsvCell(doc.documentId || doc.id || ""));
6169
+ } else if (key === "locale") {
6170
+ rowValues.push(escapeCsvCell(doc.locale || ""));
6171
+ } else {
6172
+ const field = schema.fields[key];
6173
+ const rawValue = doc[key];
6174
+ if (field) {
6175
+ const serialized = serializeFieldValue(rawValue, field);
6176
+ rowValues.push(escapeCsvCell(serialized));
5859
6177
  } else {
5860
- populate[key] = true;
6178
+ rowValues.push(escapeCsvCell(rawValue));
5861
6179
  }
5862
- } else {
5863
- populate[key] = true;
5864
6180
  }
5865
- } else if (def.type === "dynamiczone") {
5866
- populate[key] = true;
5867
- } else if (def.type === "relation" || def.type === "media") {
5868
- populate[key] = true;
5869
6181
  }
6182
+ lines.push(rowValues.join(","));
5870
6183
  }
5871
- return Object.keys(populate).length > 0 ? populate : void 0;
6184
+ const csvContent = "\uFEFF" + lines.join("\r\n") + "\r\n";
6185
+ return {
6186
+ csvContent,
6187
+ headers,
6188
+ count: documents.length
6189
+ };
5872
6190
  }
5873
- function getNestedExportValue(entry, path) {
5874
- if (!entry || !path) return "";
5875
- const parts = path.split(".");
5876
- let current = entry;
5877
- for (let i = 0; i < parts.length; i++) {
5878
- const part = parts[i];
5879
- if (current === null || current === void 0) return "";
5880
- if (Array.isArray(current)) {
5881
- const subPath = parts.slice(i).join(".");
5882
- return current.map((item) => {
5883
- if (!item) return "";
5884
- if (typeof item === "object") {
5885
- const val = getNestedExportValue(item, subPath);
5886
- return typeof val === "object" ? JSON.stringify(val) : String(val ?? "");
5887
- }
5888
- return String(item);
5889
- }).filter(Boolean).join("; ");
5890
- }
5891
- if (current && typeof current === "object") {
5892
- if (current[part] !== void 0) {
5893
- current = current[part];
5894
- } else {
5895
- const camel = part.replace(/_([a-z0-9])/g, (_, l) => l.toUpperCase());
5896
- const snake = part.replace(/([A-Z])/g, "_$1").toLowerCase();
5897
- if (current[camel] !== void 0) {
5898
- current = current[camel];
5899
- } else if (current[snake] !== void 0) {
5900
- current = current[snake];
5901
- } else {
5902
- current = void 0;
5903
- }
6191
+ function extractMetadataFromRow(row) {
6192
+ if (!row || typeof row !== "object") return null;
6193
+ const rawMeta = row[METADATA_COLUMN_KEY] || row["__bulk_updater_metadata"];
6194
+ if (!rawMeta) return null;
6195
+ if (typeof rawMeta === "object") {
6196
+ return rawMeta;
6197
+ }
6198
+ if (typeof rawMeta === "string") {
6199
+ try {
6200
+ const parsed = JSON.parse(rawMeta);
6201
+ if (parsed && typeof parsed === "object") {
6202
+ return parsed;
5904
6203
  }
5905
- } else {
5906
- current = void 0;
6204
+ } catch {
5907
6205
  }
5908
6206
  }
5909
- if (current === null || current === void 0) return "";
5910
- if (Array.isArray(current) && current.length > 0 && current[0]?.type && Array.isArray(current[0]?.children)) {
5911
- return JSON.stringify(current);
5912
- }
5913
- if (typeof current === "object" && current.url) {
5914
- return current.url;
6207
+ return null;
6208
+ }
6209
+ function isValidDocumentId(val) {
6210
+ if (!val || typeof val !== "string") return false;
6211
+ const trimmed = val.trim();
6212
+ if (!trimmed) return false;
6213
+ if (/\s/.test(trimmed)) return false;
6214
+ return /^[a-zA-Z0-9_-]+$/.test(trimmed);
6215
+ }
6216
+ function parseNumeric(rawVal, isInteger) {
6217
+ if (rawVal === null || rawVal === void 0 || rawVal === "") return null;
6218
+ const cleanStr = String(rawVal).replace(/[$€£,\s]/g, "");
6219
+ if (isInteger) {
6220
+ const n = parseInt(cleanStr, 10);
6221
+ return isNaN(n) ? null : n;
5915
6222
  }
5916
- if (typeof current === "object" && !Array.isArray(current)) {
5917
- if (current.name && (current.locale === null || !current.documentId)) {
5918
- return current.name;
5919
- }
5920
- if (current.documentId || current.id || current.name || current.title) {
5921
- return current.documentId || current.id || current.name || current.title;
5922
- }
6223
+ const f = parseFloat(cleanStr);
6224
+ return isNaN(f) ? null : f;
6225
+ }
6226
+ function parseBoolean(rawVal) {
6227
+ if (rawVal === null || rawVal === void 0 || rawVal === "") return null;
6228
+ const s = String(rawVal).trim().toLowerCase();
6229
+ if (s === "true" || s === "1" || s === "yes" || s === "y" || s === "on") return true;
6230
+ if (s === "false" || s === "0" || s === "no" || s === "n" || s === "off") return false;
6231
+ return null;
6232
+ }
6233
+ async function resolveMediaIds(strapi, rawVal, isMultiple) {
6234
+ if (rawVal === null || rawVal === void 0 || rawVal === "") {
6235
+ return isMultiple ? [] : null;
5923
6236
  }
5924
- if (Array.isArray(current)) {
5925
- return current.map((item) => {
5926
- if (!item) return "";
5927
- if (typeof item === "object") {
5928
- if (item.url) return item.url;
5929
- return item.documentId || item.id || item.name || item.title || JSON.stringify(item);
6237
+ let parsed = rawVal;
6238
+ if (typeof rawVal === "string") {
6239
+ const trimmed = rawVal.trim();
6240
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
6241
+ try {
6242
+ parsed = JSON.parse(trimmed);
6243
+ } catch {
5930
6244
  }
5931
- return String(item);
5932
- }).filter(Boolean).join("; ");
5933
- }
5934
- return current;
5935
- }
5936
- const csvImportSessions = /* @__PURE__ */ new Map();
5937
- function cleanupStaleSessions() {
5938
- const oneHourAgo = Date.now() - 36e5;
5939
- for (const [id, session] of csvImportSessions.entries()) {
5940
- if (session.createdAt < oneHourAgo) {
5941
- csvImportSessions.delete(id);
5942
6245
  }
5943
6246
  }
5944
- }
5945
- const SYSTEM_FIELD_KEYS = /* @__PURE__ */ new Set([
6247
+ const numericIds = [];
6248
+ const candidateLookups = [];
6249
+ const inspectItem = (item) => {
6250
+ if (item === null || item === void 0) return;
6251
+ if (typeof item === "number" && !isNaN(item)) {
6252
+ numericIds.push(item);
6253
+ return;
6254
+ }
6255
+ if (typeof item === "object") {
6256
+ if (typeof item.id === "number") {
6257
+ numericIds.push(item.id);
6258
+ return;
6259
+ }
6260
+ if (typeof item.id === "string" && /^\d+$/.test(item.id)) {
6261
+ numericIds.push(parseInt(item.id, 10));
6262
+ return;
6263
+ }
6264
+ if (item.documentId) {
6265
+ candidateLookups.push(String(item.documentId));
6266
+ return;
6267
+ }
6268
+ if (item.url) {
6269
+ candidateLookups.push(String(item.url));
6270
+ return;
6271
+ }
6272
+ }
6273
+ const str = String(item).trim();
6274
+ if (/^\d+$/.test(str)) {
6275
+ numericIds.push(parseInt(str, 10));
6276
+ } else if (str) {
6277
+ candidateLookups.push(str);
6278
+ }
6279
+ };
6280
+ if (Array.isArray(parsed)) {
6281
+ for (const el of parsed) {
6282
+ inspectItem(el);
6283
+ }
6284
+ } else if (typeof parsed === "object" && parsed !== null) {
6285
+ inspectItem(parsed);
6286
+ } else if (typeof rawVal === "string" && (rawVal.includes(",") || rawVal.includes(";"))) {
6287
+ const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter(Boolean);
6288
+ for (const part of parts) {
6289
+ inspectItem(part);
6290
+ }
6291
+ } else {
6292
+ inspectItem(parsed);
6293
+ }
6294
+ if (candidateLookups.length > 0) {
6295
+ try {
6296
+ const fileQuery = strapi.db?.query("plugin::upload.file");
6297
+ if (fileQuery) {
6298
+ for (const candidate of candidateLookups) {
6299
+ const found = await fileQuery.findOne({
6300
+ where: {
6301
+ $or: [
6302
+ { documentId: candidate },
6303
+ { url: candidate },
6304
+ { hash: candidate },
6305
+ { name: candidate }
6306
+ ]
6307
+ },
6308
+ select: ["id"]
6309
+ });
6310
+ if (found?.id) {
6311
+ numericIds.push(found.id);
6312
+ }
6313
+ }
6314
+ }
6315
+ } catch {
6316
+ }
6317
+ }
6318
+ const uniqueNumericIds = Array.from(new Set(numericIds));
6319
+ if (isMultiple) {
6320
+ return uniqueNumericIds;
6321
+ }
6322
+ return uniqueNumericIds.length > 0 ? uniqueNumericIds[0] : null;
6323
+ }
6324
+ function resolveRelationPayload(rawVal, isToMany) {
6325
+ if (rawVal === null || rawVal === void 0 || rawVal === "") {
6326
+ return isToMany ? { set: [] } : { set: [] };
6327
+ }
6328
+ let parsed = rawVal;
6329
+ if (typeof rawVal === "string") {
6330
+ const trimmed = rawVal.trim();
6331
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
6332
+ try {
6333
+ parsed = JSON.parse(trimmed);
6334
+ } catch {
6335
+ }
6336
+ }
6337
+ }
6338
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
6339
+ if (parsed.set || parsed.connect || parsed.disconnect) {
6340
+ return parsed;
6341
+ }
6342
+ const singleDocId = parsed.documentId || parsed.id;
6343
+ if (singleDocId && isValidDocumentId(String(singleDocId))) {
6344
+ return isToMany ? { set: [String(singleDocId).trim()] } : { set: [String(singleDocId).trim()] };
6345
+ }
6346
+ }
6347
+ const docIds = [];
6348
+ if (Array.isArray(parsed)) {
6349
+ for (const item of parsed) {
6350
+ if (item && typeof item === "object") {
6351
+ const id = item.documentId || item.id;
6352
+ if (id && isValidDocumentId(String(id))) {
6353
+ docIds.push(String(id).trim());
6354
+ }
6355
+ } else if (isValidDocumentId(String(item))) {
6356
+ docIds.push(String(item).trim());
6357
+ }
6358
+ }
6359
+ } else if (typeof rawVal === "string") {
6360
+ if (rawVal.includes(",") || rawVal.includes(";")) {
6361
+ const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter((p) => isValidDocumentId(p));
6362
+ docIds.push(...parts);
6363
+ } else if (isValidDocumentId(rawVal.trim())) {
6364
+ docIds.push(rawVal.trim());
6365
+ }
6366
+ }
6367
+ const uniqueDocIds = Array.from(new Set(docIds));
6368
+ return { set: uniqueDocIds };
6369
+ }
6370
+ async function resolveComponentPayload(strapi, compUid, rawVal, existingVal = {}) {
6371
+ const comp = strapi.components?.[compUid];
6372
+ if (!comp?.attributes) {
6373
+ return typeof rawVal === "object" ? rawVal : {};
6374
+ }
6375
+ let sourceObj = {};
6376
+ if (typeof rawVal === "string") {
6377
+ try {
6378
+ sourceObj = JSON.parse(rawVal);
6379
+ } catch {
6380
+ return existingVal || {};
6381
+ }
6382
+ } else if (typeof rawVal === "object" && rawVal !== null) {
6383
+ sourceObj = rawVal;
6384
+ } else {
6385
+ return existingVal || {};
6386
+ }
6387
+ const result = { ...existingVal || {} };
6388
+ for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
6389
+ if (SYSTEM_ATTRIBUTES.has(attrName.toLowerCase().replace(/[\s_-]/g, ""))) continue;
6390
+ if (!(attrName in sourceObj)) {
6391
+ continue;
6392
+ }
6393
+ const fieldVal = sourceObj[attrName];
6394
+ const type = String(attrDef.type || "").toLowerCase();
6395
+ if (type === "component") {
6396
+ if (attrDef.repeatable) {
6397
+ const list = Array.isArray(fieldVal) ? fieldVal : [];
6398
+ const cleanedList = [];
6399
+ for (const item of list) {
6400
+ const subCleaned = await resolveComponentPayload(strapi, attrDef.component, item, {});
6401
+ cleanedList.push(subCleaned);
6402
+ }
6403
+ result[attrName] = cleanedList;
6404
+ } else {
6405
+ result[attrName] = await resolveComponentPayload(
6406
+ strapi,
6407
+ attrDef.component,
6408
+ fieldVal,
6409
+ existingVal?.[attrName] || {}
6410
+ );
6411
+ }
6412
+ } else if (type === "relation") {
6413
+ const isToMany = String(attrDef.relation || "").toLowerCase().endsWith("many");
6414
+ result[attrName] = resolveRelationPayload(fieldVal, isToMany);
6415
+ } else if (type === "media") {
6416
+ result[attrName] = await resolveMediaIds(strapi, fieldVal, Boolean(attrDef.multiple));
6417
+ } else if (type === "integer" || type === "biginteger") {
6418
+ result[attrName] = parseNumeric(fieldVal, true);
6419
+ } else if (type === "float" || type === "decimal") {
6420
+ result[attrName] = parseNumeric(fieldVal, false);
6421
+ } else if (type === "boolean") {
6422
+ result[attrName] = parseBoolean(fieldVal);
6423
+ } else if (type === "json" || type === "blocks") {
6424
+ if (typeof fieldVal === "string") {
6425
+ try {
6426
+ result[attrName] = JSON.parse(fieldVal);
6427
+ } catch {
6428
+ result[attrName] = fieldVal;
6429
+ }
6430
+ } else {
6431
+ result[attrName] = fieldVal;
6432
+ }
6433
+ } else {
6434
+ result[attrName] = fieldVal === null || fieldVal === void 0 ? null : String(fieldVal);
6435
+ }
6436
+ }
6437
+ return result;
6438
+ }
6439
+ async function resolveDynamicZonePayload(strapi, allowedComponents, rawVal, existingVal = []) {
6440
+ let list = [];
6441
+ if (typeof rawVal === "string") {
6442
+ try {
6443
+ list = JSON.parse(rawVal);
6444
+ } catch {
6445
+ return existingVal || [];
6446
+ }
6447
+ } else if (Array.isArray(rawVal)) {
6448
+ list = rawVal;
6449
+ } else {
6450
+ return existingVal || [];
6451
+ }
6452
+ if (!Array.isArray(list)) return [];
6453
+ const allowedSet = new Set(allowedComponents || []);
6454
+ const resolvedBlocks = [];
6455
+ for (const block of list) {
6456
+ if (!block || typeof block !== "object") continue;
6457
+ const compUid = block.__component;
6458
+ if (!compUid || typeof compUid !== "string") {
6459
+ continue;
6460
+ }
6461
+ if (allowedSet.size > 0 && !allowedSet.has(compUid)) {
6462
+ continue;
6463
+ }
6464
+ const resolvedAttrs = await resolveComponentPayload(strapi, compUid, block, {});
6465
+ resolvedAttrs.__component = compUid;
6466
+ resolvedBlocks.push(resolvedAttrs);
6467
+ }
6468
+ return resolvedBlocks;
6469
+ }
6470
+ async function buildDocumentUpdatePayload(strapi, uid, existingDoc, rawRow, options = {}) {
6471
+ const schema = discoverSchema(strapi, uid);
6472
+ const payload = {};
6473
+ const unescapedRow = {};
6474
+ for (const [k, v] of Object.entries(rawRow)) {
6475
+ let cleanVal = v;
6476
+ if (typeof cleanVal === "string" && /^'[=+@-]/.test(cleanVal)) {
6477
+ cleanVal = cleanVal.substring(1);
6478
+ }
6479
+ unescapedRow[k] = cleanVal;
6480
+ }
6481
+ const dotNotationMap = {};
6482
+ for (const [k, v] of Object.entries(unescapedRow)) {
6483
+ if (k.includes(".")) {
6484
+ const [parent, ...rest] = k.split(".");
6485
+ const child = rest.join(".");
6486
+ if (!dotNotationMap[parent]) dotNotationMap[parent] = {};
6487
+ dotNotationMap[parent][child] = v;
6488
+ }
6489
+ }
6490
+ for (const [attrName, field] of Object.entries(schema.fields)) {
6491
+ const hasDirectKey = attrName in unescapedRow;
6492
+ const hasDotKeys = Boolean(dotNotationMap[attrName]);
6493
+ if (!hasDirectKey && !hasDotKeys) {
6494
+ continue;
6495
+ }
6496
+ const rawVal = hasDirectKey ? unescapedRow[attrName] : void 0;
6497
+ switch (field.category) {
6498
+ case "scalar": {
6499
+ if (rawVal === void 0 || rawVal === "" || rawVal === null) {
6500
+ payload[attrName] = null;
6501
+ } else if (field.rawType === "integer" || field.rawType === "biginteger") {
6502
+ payload[attrName] = parseNumeric(rawVal, true);
6503
+ } else if (field.rawType === "float" || field.rawType === "decimal") {
6504
+ payload[attrName] = parseNumeric(rawVal, false);
6505
+ } else if (field.rawType === "boolean") {
6506
+ payload[attrName] = parseBoolean(rawVal);
6507
+ } else if (field.rawType === "date" || field.rawType === "time" || field.rawType === "datetime" || field.rawType === "timestamp") {
6508
+ payload[attrName] = String(rawVal).trim() || null;
6509
+ } else if (field.rawType === "enumeration") {
6510
+ const trimmed = String(rawVal).trim();
6511
+ if (field.enumOptions && field.enumOptions.length > 0) {
6512
+ const match = field.enumOptions.find((o) => o.toLowerCase() === trimmed.toLowerCase());
6513
+ payload[attrName] = match || trimmed;
6514
+ } else {
6515
+ payload[attrName] = trimmed;
6516
+ }
6517
+ } else {
6518
+ payload[attrName] = String(rawVal).trim();
6519
+ }
6520
+ break;
6521
+ }
6522
+ case "blocks": {
6523
+ if (rawVal === void 0 || rawVal === "" || rawVal === null) {
6524
+ payload[attrName] = [];
6525
+ } else {
6526
+ try {
6527
+ const parsed = JSON.parse(rawVal);
6528
+ payload[attrName] = Array.isArray(parsed) ? parsed : [parsed];
6529
+ } catch {
6530
+ payload[attrName] = [
6531
+ { type: "paragraph", children: [{ type: "text", text: String(rawVal).trim() }] }
6532
+ ];
6533
+ }
6534
+ }
6535
+ break;
6536
+ }
6537
+ case "json": {
6538
+ if (rawVal === void 0 || rawVal === "" || rawVal === null) {
6539
+ payload[attrName] = null;
6540
+ } else {
6541
+ try {
6542
+ payload[attrName] = JSON.parse(rawVal);
6543
+ } catch {
6544
+ payload[attrName] = rawVal;
6545
+ }
6546
+ }
6547
+ break;
6548
+ }
6549
+ case "component_single": {
6550
+ if (field.componentUid) {
6551
+ let compInput = rawVal;
6552
+ if (hasDotKeys) {
6553
+ compInput = { ...existingDoc?.[attrName] || {}, ...dotNotationMap[attrName] };
6554
+ }
6555
+ if (compInput === "" || compInput === null) {
6556
+ payload[attrName] = null;
6557
+ } else {
6558
+ payload[attrName] = await resolveComponentPayload(
6559
+ strapi,
6560
+ field.componentUid,
6561
+ compInput,
6562
+ existingDoc?.[attrName] || {}
6563
+ );
6564
+ }
6565
+ }
6566
+ break;
6567
+ }
6568
+ case "component_repeatable": {
6569
+ if (field.componentUid) {
6570
+ if (rawVal === "" || rawVal === null || rawVal === void 0) {
6571
+ payload[attrName] = [];
6572
+ } else {
6573
+ let list = [];
6574
+ try {
6575
+ list = typeof rawVal === "string" ? JSON.parse(rawVal) : rawVal;
6576
+ } catch {
6577
+ }
6578
+ if (Array.isArray(list)) {
6579
+ const cleanedItems = [];
6580
+ for (const item of list) {
6581
+ const cleaned = await resolveComponentPayload(
6582
+ strapi,
6583
+ field.componentUid,
6584
+ item,
6585
+ {}
6586
+ );
6587
+ cleanedItems.push(cleaned);
6588
+ }
6589
+ payload[attrName] = cleanedItems;
6590
+ } else {
6591
+ payload[attrName] = [];
6592
+ }
6593
+ }
6594
+ }
6595
+ break;
6596
+ }
6597
+ case "dynamiczone": {
6598
+ const allowedComponents = field.dzComponents || [];
6599
+ if (rawVal === "" || rawVal === null || rawVal === void 0) {
6600
+ payload[attrName] = [];
6601
+ } else {
6602
+ payload[attrName] = await resolveDynamicZonePayload(
6603
+ strapi,
6604
+ allowedComponents,
6605
+ rawVal,
6606
+ existingDoc?.[attrName] || []
6607
+ );
6608
+ }
6609
+ break;
6610
+ }
6611
+ case "relation_to_one": {
6612
+ payload[attrName] = resolveRelationPayload(rawVal, false);
6613
+ break;
6614
+ }
6615
+ case "relation_to_many": {
6616
+ payload[attrName] = resolveRelationPayload(rawVal, true);
6617
+ break;
6618
+ }
6619
+ case "media_single": {
6620
+ payload[attrName] = await resolveMediaIds(strapi, rawVal, false);
6621
+ break;
6622
+ }
6623
+ case "media_to_many": {
6624
+ payload[attrName] = await resolveMediaIds(strapi, rawVal, true);
6625
+ break;
6626
+ }
6627
+ default:
6628
+ payload[attrName] = rawVal;
6629
+ }
6630
+ }
6631
+ return payload;
6632
+ }
6633
+ function normalizeVal(val) {
6634
+ if (val === null || val === void 0) return null;
6635
+ if (typeof val === "string") return val.trim();
6636
+ if (typeof val === "number" || typeof val === "boolean") return val;
6637
+ if (Array.isArray(val)) {
6638
+ return val.map(normalizeVal);
6639
+ }
6640
+ if (typeof val === "object") {
6641
+ const copy = {};
6642
+ for (const [k, v] of Object.entries(val)) {
6643
+ if (SYSTEM_ATTRIBUTES.has(k.toLowerCase().replace(/[\s_-]/g, ""))) continue;
6644
+ copy[k] = normalizeVal(v);
6645
+ }
6646
+ return copy;
6647
+ }
6648
+ return val;
6649
+ }
6650
+ function verifyDocumentIntegrity(strapi, uid, originalDoc, appliedPayload, savedDoc) {
6651
+ const schema = discoverSchema(strapi, uid);
6652
+ const diffs = [];
6653
+ let scalarOk = true;
6654
+ let componentsOk = true;
6655
+ let dynamicZonesOk = true;
6656
+ let relationsOk = true;
6657
+ let mediaOk = true;
6658
+ let missingDataCount = 0;
6659
+ let invalidRelationsCount = 0;
6660
+ let missingMediaCount = 0;
6661
+ let structuralDifferencesCount = 0;
6662
+ let hasComponents = false;
6663
+ let hasDynamicZones = false;
6664
+ let hasRelations = false;
6665
+ let hasMedia = false;
6666
+ for (const [key, field] of Object.entries(schema.fields)) {
6667
+ const isTargeted = key in appliedPayload;
6668
+ const expected = isTargeted ? appliedPayload[key] : originalDoc?.[key];
6669
+ const actual = savedDoc?.[key];
6670
+ switch (field.category) {
6671
+ case "scalar": {
6672
+ const normExpected = normalizeVal(expected);
6673
+ const normActual = normalizeVal(actual);
6674
+ if (normExpected !== null && normActual !== normExpected) {
6675
+ if (String(normExpected) !== String(normActual)) {
6676
+ diffs.push({
6677
+ path: key,
6678
+ expected: normExpected,
6679
+ actual: normActual,
6680
+ message: `Scalar value mismatch on "${key}"`
6681
+ });
6682
+ scalarOk = false;
6683
+ structuralDifferencesCount++;
6684
+ }
6685
+ }
6686
+ break;
6687
+ }
6688
+ case "component_single":
6689
+ case "component_repeatable": {
6690
+ hasComponents = true;
6691
+ if (field.category === "component_repeatable") {
6692
+ const expArr = Array.isArray(expected) ? expected : [];
6693
+ const actArr = Array.isArray(actual) ? actual : [];
6694
+ if (expArr.length !== actArr.length) {
6695
+ diffs.push({
6696
+ path: key,
6697
+ expected: `Array of length ${expArr.length}`,
6698
+ actual: `Array of length ${actArr.length}`,
6699
+ message: `Repeatable component length mismatch on "${key}"`
6700
+ });
6701
+ componentsOk = false;
6702
+ structuralDifferencesCount++;
6703
+ }
6704
+ }
6705
+ break;
6706
+ }
6707
+ case "dynamiczone": {
6708
+ hasDynamicZones = true;
6709
+ const expBlocks = Array.isArray(expected) ? expected : [];
6710
+ const actBlocks = Array.isArray(actual) ? actual : [];
6711
+ if (expBlocks.length !== actBlocks.length) {
6712
+ diffs.push({
6713
+ path: key,
6714
+ expected: `Dynamic zone of length ${expBlocks.length}`,
6715
+ actual: `Dynamic zone of length ${actBlocks.length}`,
6716
+ message: `Dynamic zone count mismatch on "${key}"`
6717
+ });
6718
+ dynamicZonesOk = false;
6719
+ structuralDifferencesCount++;
6720
+ } else {
6721
+ for (let b = 0; b < expBlocks.length; b++) {
6722
+ const expComp = expBlocks[b]?.__component;
6723
+ const actComp = actBlocks[b]?.__component;
6724
+ if (expComp !== actComp) {
6725
+ diffs.push({
6726
+ path: `${key}[${b}].__component`,
6727
+ expected: expComp || "(missing __component)",
6728
+ actual: actComp || "(missing __component)",
6729
+ message: `Dynamic zone block type mismatch at position ${b}: expected "${expComp}", found "${actComp || "missing __component"}"`
6730
+ });
6731
+ dynamicZonesOk = false;
6732
+ structuralDifferencesCount++;
6733
+ }
6734
+ }
6735
+ }
6736
+ break;
6737
+ }
6738
+ case "relation_to_one":
6739
+ case "relation_to_many": {
6740
+ hasRelations = true;
6741
+ if (isTargeted && expected && typeof expected === "object" && expected.set) {
6742
+ const expectedIds = expected.set || [];
6743
+ if (field.category === "relation_to_many") {
6744
+ const actualIds = Array.isArray(actual) ? actual.map((item) => String(item?.documentId || item?.id || item)).filter(Boolean) : [];
6745
+ const missing = expectedIds.filter((id) => !actualIds.includes(id));
6746
+ if (missing.length > 0) {
6747
+ diffs.push({
6748
+ path: key,
6749
+ expected: expectedIds,
6750
+ actual: actualIds,
6751
+ message: `Missing relations on "${key}": ${missing.join(", ")}`
6752
+ });
6753
+ relationsOk = false;
6754
+ invalidRelationsCount += missing.length;
6755
+ }
6756
+ }
6757
+ }
6758
+ break;
6759
+ }
6760
+ case "media_single":
6761
+ case "media_to_many": {
6762
+ hasMedia = true;
6763
+ if (isTargeted && expected !== null && expected !== void 0) {
6764
+ const expectedIds = Array.isArray(expected) ? expected : [expected];
6765
+ const actualIds = Array.isArray(actual) ? actual.map((f) => f?.id || f).filter(Boolean) : actual?.id ? [actual.id] : [];
6766
+ const missing = expectedIds.filter((id) => !actualIds.includes(id));
6767
+ if (missing.length > 0) {
6768
+ diffs.push({
6769
+ path: key,
6770
+ expected: expectedIds,
6771
+ actual: actualIds,
6772
+ message: `Missing media references on "${key}"`
6773
+ });
6774
+ mediaOk = false;
6775
+ missingMediaCount += missing.length;
6776
+ }
6777
+ }
6778
+ break;
6779
+ }
6780
+ }
6781
+ }
6782
+ const docId = String(savedDoc?.documentId || originalDoc?.documentId || "unknown");
6783
+ const title = String(savedDoc?.title || savedDoc?.name || `Entry #${docId}`);
6784
+ const status = diffs.length === 0 ? "SUCCESS" : diffs.length <= 2 ? "WARNING" : "FAILED";
6785
+ return {
6786
+ documentId: docId,
6787
+ title,
6788
+ status,
6789
+ scalarFields: scalarOk ? "Verified" : "Mismatch",
6790
+ components: hasComponents ? componentsOk ? "Verified" : "Mismatch" : "N/A",
6791
+ dynamicZones: hasDynamicZones ? dynamicZonesOk ? "Verified" : "Mismatch" : "N/A",
6792
+ relations: hasRelations ? relationsOk ? "Verified" : "Mismatch" : "N/A",
6793
+ media: hasMedia ? mediaOk ? "Verified" : "Mismatch" : "N/A",
6794
+ missingDataCount,
6795
+ invalidRelationsCount,
6796
+ missingMediaCount,
6797
+ structuralDifferencesCount,
6798
+ diffs
6799
+ };
6800
+ }
6801
+ function escapeCsvValue(val) {
6802
+ if (val === null || val === void 0) return "";
6803
+ let str = "";
6804
+ if (val instanceof Date) {
6805
+ str = val.toISOString();
6806
+ } else if (typeof val === "object") {
6807
+ str = JSON.stringify(val);
6808
+ } else {
6809
+ str = String(val);
6810
+ }
6811
+ str = str.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
6812
+ if (/^[=+@-]$/.test(str.charAt(0))) {
6813
+ str = `'${str}`;
6814
+ }
6815
+ if (str.includes(",") || str.includes('"') || str.includes("\n")) {
6816
+ return `"${str.replace(/"/g, '""')}"`;
6817
+ }
6818
+ return str;
6819
+ }
6820
+ function parseCsvRows(csvText) {
6821
+ if (!csvText) return [];
6822
+ let text = csvText;
6823
+ if (text.charCodeAt(0) === 65279) {
6824
+ text = text.slice(1);
6825
+ }
6826
+ const rows = [];
6827
+ let currentRow = [];
6828
+ let currentCell = "";
6829
+ let inQuotes = false;
6830
+ let cellIsQuoted = false;
6831
+ for (let i = 0; i < text.length; i++) {
6832
+ const char = text[i];
6833
+ const nextChar = text[i + 1];
6834
+ if (inQuotes) {
6835
+ if (char === '"') {
6836
+ if (nextChar === '"') {
6837
+ currentCell += '"';
6838
+ i++;
6839
+ } else {
6840
+ inQuotes = false;
6841
+ }
6842
+ } else {
6843
+ currentCell += char;
6844
+ }
6845
+ } else {
6846
+ if (char === '"' && !cellIsQuoted && currentCell.trim() === "") {
6847
+ inQuotes = true;
6848
+ cellIsQuoted = true;
6849
+ currentCell = "";
6850
+ } else if (char === ",") {
6851
+ currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
6852
+ currentCell = "";
6853
+ cellIsQuoted = false;
6854
+ } else if (char === "\r") {
6855
+ if (nextChar === "\n") {
6856
+ i++;
6857
+ }
6858
+ currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
6859
+ if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
6860
+ rows.push(currentRow);
6861
+ }
6862
+ currentRow = [];
6863
+ currentCell = "";
6864
+ cellIsQuoted = false;
6865
+ } else if (char === "\n") {
6866
+ currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
6867
+ if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
6868
+ rows.push(currentRow);
6869
+ }
6870
+ currentRow = [];
6871
+ currentCell = "";
6872
+ cellIsQuoted = false;
6873
+ } else {
6874
+ if (!(cellIsQuoted && !inQuotes && (char === " " || char === " "))) {
6875
+ currentCell += char;
6876
+ }
6877
+ }
6878
+ }
6879
+ }
6880
+ if (currentCell !== "" || cellIsQuoted || currentRow.length > 0) {
6881
+ currentRow.push(cellIsQuoted ? currentCell : currentCell.trim());
6882
+ if (currentRow.length > 1 || currentRow.length === 1 && currentRow[0] !== "") {
6883
+ rows.push(currentRow);
6884
+ }
6885
+ }
6886
+ return rows;
6887
+ }
6888
+ function parseCsv(csvText) {
6889
+ const rows = parseCsvRows(csvText);
6890
+ if (rows.length < 2) return [];
6891
+ const headers = rows[0].map((h) => h.trim());
6892
+ const records = [];
6893
+ for (let i = 1; i < rows.length; i++) {
6894
+ const row = rows[i];
6895
+ const record = {};
6896
+ headers.forEach((h, idx) => {
6897
+ let val = row[idx] !== void 0 ? row[idx] : "";
6898
+ if (typeof val === "string" && /^'[=+@-]/.test(val)) {
6899
+ val = val.substring(1);
6900
+ }
6901
+ record[h] = val;
6902
+ });
6903
+ records.push(record);
6904
+ }
6905
+ return records;
6906
+ }
6907
+ const LIFECYCLE_STATUS_WORDS = /* @__PURE__ */ new Set([
6908
+ "pending review",
6909
+ "pending_review",
6910
+ "pending approval",
6911
+ "pending_approval",
6912
+ "approved",
6913
+ "rejected",
6914
+ "draft",
6915
+ "published",
6916
+ "modified",
6917
+ "supported",
6918
+ "ignored",
6919
+ "editing",
6920
+ "in review",
6921
+ "in_review",
6922
+ "ready to publish",
6923
+ "ready_to_publish",
6924
+ "null",
6925
+ "undefined"
6926
+ ]);
6927
+ function isValidDocId(val) {
6928
+ if (!val || typeof val !== "string") return false;
6929
+ const trimmed = val.trim();
6930
+ if (!trimmed) return false;
6931
+ if (LIFECYCLE_STATUS_WORDS.has(trimmed.toLowerCase())) return false;
6932
+ if (/\s/.test(trimmed)) return false;
6933
+ return /^[a-zA-Z0-9_-]+$/.test(trimmed);
6934
+ }
6935
+ function extractDocId(row) {
6936
+ if (!row || typeof row !== "object") return "";
6937
+ const meta = extractMetadataFromRow(row);
6938
+ if (meta?.documentId && isValidDocId(String(meta.documentId).trim())) {
6939
+ return String(meta.documentId).trim();
6940
+ }
6941
+ const candidates = [
6942
+ row.documentId,
6943
+ row.document_id,
6944
+ row["Document ID"],
6945
+ row["Document Id"],
6946
+ row["document_id"],
6947
+ row.docId,
6948
+ row["docId"],
6949
+ row.id,
6950
+ row.ID,
6951
+ row.Id
6952
+ ];
6953
+ for (const c of candidates) {
6954
+ if (c !== void 0 && c !== null) {
6955
+ const str = String(c).trim();
6956
+ if (isValidDocId(str)) {
6957
+ return str;
6958
+ }
6959
+ }
6960
+ }
6961
+ return "";
6962
+ }
6963
+ function extractLocale(row) {
6964
+ if (!row || typeof row !== "object") return void 0;
6965
+ const meta = extractMetadataFromRow(row);
6966
+ if (meta?.locale && String(meta.locale).trim()) {
6967
+ return String(meta.locale).trim();
6968
+ }
6969
+ const candidates = [
6970
+ row.locale,
6971
+ row.Locale,
6972
+ row["locale"],
6973
+ row["Locale"],
6974
+ row.strapi_locale,
6975
+ row["strapi_locale"]
6976
+ ];
6977
+ for (const c of candidates) {
6978
+ if (c !== void 0 && c !== null) {
6979
+ const str = String(c).trim();
6980
+ if (str && str.toLowerCase() !== "null" && str.toLowerCase() !== "undefined" && str.toLowerCase() !== "[null]" && str.toLowerCase() !== '""') {
6981
+ return str;
6982
+ }
6983
+ }
6984
+ }
6985
+ return void 0;
6986
+ }
6987
+ function getEffectiveLocale(ct, rowLocale) {
6988
+ if (!ct?.pluginOptions?.i18n?.localized) {
6989
+ return void 0;
6990
+ }
6991
+ if (!rowLocale) {
6992
+ return void 0;
6993
+ }
6994
+ const trimmed = rowLocale.trim();
6995
+ if (!trimmed || trimmed.toLowerCase() === "null" || trimmed.toLowerCase() === "undefined" || trimmed.toLowerCase() === "[null]" || trimmed.toLowerCase() === '""') {
6996
+ return void 0;
6997
+ }
6998
+ return trimmed;
6999
+ }
7000
+ function isRowInEditingStage(row) {
7001
+ if (!row || typeof row !== "object") return false;
7002
+ const candidates = [
7003
+ row.strapi_stage,
7004
+ row["strapi_stage"],
7005
+ row.strapiStage,
7006
+ row["Strapi Stage"],
7007
+ row["strapi-stage"],
7008
+ row.stage,
7009
+ row.Stage,
7010
+ row.status,
7011
+ row.Status
7012
+ ];
7013
+ for (const c of candidates) {
7014
+ if (c !== void 0 && c !== null) {
7015
+ let stageName = "";
7016
+ if (typeof c === "object") {
7017
+ stageName = String(c.name || c.title || c.status || c.documentId || c.id || "").trim();
7018
+ } else if (typeof c === "string") {
7019
+ const trimmed = c.trim();
7020
+ if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
7021
+ try {
7022
+ const parsed = JSON.parse(trimmed);
7023
+ if (typeof parsed === "object" && parsed !== null) {
7024
+ stageName = String(parsed.name || parsed.title || parsed.status || parsed.documentId || parsed.id || "").trim();
7025
+ }
7026
+ } catch {
7027
+ }
7028
+ }
7029
+ if (!stageName) {
7030
+ stageName = trimmed;
7031
+ }
7032
+ } else {
7033
+ stageName = String(c).trim();
7034
+ }
7035
+ if (stageName) {
7036
+ const s = stageName.toLowerCase();
7037
+ if (s === "editing" || s === "in review" || s === "in_review" || s === "pending review" || s === "pending_review") {
7038
+ return true;
7039
+ }
7040
+ }
7041
+ }
7042
+ }
7043
+ return false;
7044
+ }
7045
+ function extractDetailedErrorMessage(err) {
7046
+ if (!err) return "Error processing row";
7047
+ const detailsErrors = err.details?.errors || err.error?.details?.errors;
7048
+ if (Array.isArray(detailsErrors) && detailsErrors.length > 0) {
7049
+ const messages = detailsErrors.map((e) => {
7050
+ if (!e) return "";
7051
+ const path = Array.isArray(e.path) ? e.path.join(".") : e.path;
7052
+ const msg = e.message || (typeof e === "string" ? e : JSON.stringify(e));
7053
+ return path ? `${path}: ${msg}` : msg;
7054
+ }).filter(Boolean);
7055
+ if (messages.length > 0) return messages.join("; ");
7056
+ }
7057
+ if (Array.isArray(err.inner) && err.inner.length > 0) {
7058
+ const messages = err.inner.map((e) => {
7059
+ if (!e) return "";
7060
+ const path = e.path;
7061
+ const msg = e.message || (typeof e === "string" ? e : JSON.stringify(e));
7062
+ return path ? `${path}: ${msg}` : msg;
7063
+ }).filter(Boolean);
7064
+ if (messages.length > 0) return messages.join("; ");
7065
+ }
7066
+ if (Array.isArray(err.errors) && err.errors.length > 0) {
7067
+ return err.errors.join("; ");
7068
+ }
7069
+ if (typeof err.details === "string" && err.details.trim()) {
7070
+ return err.details;
7071
+ }
7072
+ if (err.details?.message) {
7073
+ return err.details.message;
7074
+ }
7075
+ if (err.message && err.message !== "[object Object]") {
7076
+ return err.message;
7077
+ }
7078
+ return "Error processing row";
7079
+ }
7080
+ const csvImportSessions = /* @__PURE__ */ new Map();
7081
+ function cleanupStaleSessions() {
7082
+ const oneHourAgo = Date.now() - 36e5;
7083
+ for (const [id, session] of csvImportSessions.entries()) {
7084
+ if (session.createdAt < oneHourAgo) {
7085
+ csvImportSessions.delete(id);
7086
+ }
7087
+ }
7088
+ }
7089
+ const SYSTEM_FIELD_KEYS = /* @__PURE__ */ new Set([
5946
7090
  "documentid",
5947
7091
  "document_id",
5948
7092
  "docid",
@@ -5966,7 +7110,7 @@ async function findExistingDocument(strapi, uid, targetDocId, docLocale) {
5966
7110
  if (!targetDocId) return null;
5967
7111
  const ct = strapi.contentTypes[uid];
5968
7112
  const effectiveLocale = getEffectiveLocale(ct, docLocale);
5969
- const populateDef = ct?.attributes ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
7113
+ const populateDef = ct ? buildLosslessPopulate(strapi, uid) : void 0;
5970
7114
  try {
5971
7115
  const queryArgs = {
5972
7116
  documentId: targetDocId,
@@ -5995,352 +7139,252 @@ async function findExistingDocument(strapi, uid, targetDocId, docLocale) {
5995
7139
  };
5996
7140
  if (effectiveLocale) queryArgs.locale = effectiveLocale;
5997
7141
  const list = await strapi.documents(uid).findMany(queryArgs);
5998
- if (list && list.length > 0) return list[0];
5999
- } catch {
6000
- }
6001
- }
6002
- return null;
6003
- }
6004
- function deepMergeComponent(existingVal, newVal) {
6005
- if (!existingVal || typeof existingVal !== "object" || Array.isArray(existingVal)) {
6006
- return newVal;
6007
- }
6008
- if (!newVal || typeof newVal !== "object" || Array.isArray(newVal)) {
6009
- return newVal;
6010
- }
6011
- const merged = { ...existingVal };
6012
- for (const k of Object.keys(newVal)) {
6013
- if (newVal[k] && typeof newVal[k] === "object" && !Array.isArray(newVal[k])) {
6014
- merged[k] = deepMergeComponent(existingVal[k], newVal[k]);
6015
- } else if (newVal[k] !== void 0) {
6016
- merged[k] = newVal[k];
6017
- }
6018
- }
6019
- return merged;
6020
- }
6021
- function parseNumberValue(rawVal, isInteger) {
6022
- const cleanStr = String(rawVal).replace(/[$€£,\s]/g, "");
6023
- if (isInteger) {
6024
- const n = parseInt(cleanStr, 10);
6025
- return isNaN(n) ? null : n;
6026
- } else {
6027
- const f = parseFloat(cleanStr);
6028
- return isNaN(f) ? null : f;
6029
- }
6030
- }
6031
- function parseBooleanValue(rawVal) {
6032
- const s = String(rawVal).trim().toLowerCase();
6033
- return s === "true" || s === "1" || s === "yes" || s === "y" || s === "on";
6034
- }
6035
- function parseBlocksValue(rawVal) {
6036
- try {
6037
- const parsed = JSON.parse(rawVal);
6038
- if (Array.isArray(parsed)) {
6039
- return parsed;
6040
- }
6041
- } catch {
6042
- }
6043
- const trimmed = String(rawVal).trim();
6044
- if (!trimmed) return [];
6045
- return [{ type: "paragraph", children: [{ type: "text", text: trimmed }] }];
6046
- }
6047
- function parseEnumValue(rawVal, allowedValues) {
6048
- const trimmed = String(rawVal).trim();
6049
- if (Array.isArray(allowedValues) && allowedValues.length > 0) {
6050
- const match = allowedValues.find((v) => v.toLowerCase() === trimmed.toLowerCase());
6051
- if (match) return match;
6052
- }
6053
- return trimmed;
6054
- }
6055
- function parseRelationValue(rawVal, relationType) {
6056
- const isToMany = relationType ? relationType.toLowerCase().endsWith("many") : false;
6057
- if (rawVal === null || rawVal === void 0) return isToMany ? [] : null;
6058
- let parsed = rawVal;
6059
- if (typeof rawVal === "string") {
6060
- const trimmed = rawVal.trim();
6061
- if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
6062
- try {
6063
- parsed = JSON.parse(trimmed);
6064
- } catch {
6065
- }
7142
+ if (list && list.length > 0) return list[0];
7143
+ } catch {
6066
7144
  }
6067
7145
  }
6068
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
6069
- if (parsed.name && (parsed.locale === null || LIFECYCLE_STATUS_WORDS.has(String(parsed.name).trim().toLowerCase()))) {
6070
- return isToMany ? [] : null;
6071
- }
6072
- const docId = parsed.documentId || parsed.id || null;
6073
- if (docId && isValidDocId(String(docId).trim())) {
6074
- const validStr = String(docId).trim();
6075
- return isToMany ? [validStr] : validStr;
6076
- }
6077
- return isToMany ? [] : null;
7146
+ return null;
7147
+ }
7148
+ function deepMergeComponent(existingVal, newVal) {
7149
+ if (!existingVal || typeof existingVal !== "object" || Array.isArray(existingVal)) {
7150
+ return newVal;
6078
7151
  }
6079
- if (Array.isArray(parsed)) {
6080
- const ids = parsed.map((item) => {
6081
- if (typeof item === "object" && item !== null) {
6082
- if (item.name && (item.locale === null || LIFECYCLE_STATUS_WORDS.has(String(item.name).trim().toLowerCase()))) {
6083
- return null;
6084
- }
6085
- const id = item.documentId || item.id;
6086
- return id && isValidDocId(String(id).trim()) ? String(id).trim() : null;
6087
- }
6088
- return isValidDocId(String(item).trim()) ? String(item).trim() : null;
6089
- }).filter(Boolean);
6090
- return isToMany ? ids : ids[0] || null;
7152
+ if (!newVal || typeof newVal !== "object" || Array.isArray(newVal)) {
7153
+ return newVal;
6091
7154
  }
6092
- if (typeof rawVal === "string") {
6093
- if (rawVal.includes(";") || rawVal.includes(",")) {
6094
- const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter((p) => isValidDocId(p));
6095
- return isToMany ? parts : parts[0] || null;
7155
+ const merged = { ...existingVal };
7156
+ for (const k of Object.keys(newVal)) {
7157
+ if (newVal[k] && typeof newVal[k] === "object" && !Array.isArray(newVal[k])) {
7158
+ merged[k] = deepMergeComponent(existingVal[k], newVal[k]);
7159
+ } else if (newVal[k] !== void 0) {
7160
+ merged[k] = newVal[k];
6096
7161
  }
6097
- const trimmed = rawVal.trim();
6098
- if (isValidDocId(trimmed)) {
6099
- return isToMany ? [trimmed] : trimmed;
7162
+ }
7163
+ return merged;
7164
+ }
7165
+ function formatValueDisplay(val) {
7166
+ if (val === null || val === void 0) return "(empty)";
7167
+ if (typeof val === "object") {
7168
+ try {
7169
+ return JSON.stringify(val);
7170
+ } catch {
7171
+ return String(val);
6100
7172
  }
6101
7173
  }
6102
- return isToMany ? [] : null;
7174
+ const s = String(val).trim();
7175
+ return s === "" ? "(empty)" : s;
6103
7176
  }
6104
- function parseMediaValue(rawVal, isMultiple = false) {
6105
- const trimmed = String(rawVal).trim();
6106
- if (trimmed.startsWith("[") || trimmed.startsWith("{")) {
7177
+ async function executeUpdateMutation(strapi, ct, uid, existing, row, rowNumber, options, effectiveLocale, isEditing, isDraftAndPublish, publishedCounterparts, stats, actionLabel = "Updated") {
7178
+ const resolvedDocId = existing.documentId;
7179
+ const updatePayload = await buildDocumentUpdatePayload(
7180
+ strapi,
7181
+ uid,
7182
+ existing,
7183
+ row,
7184
+ { isPartialUpdate: options.mode === "update" }
7185
+ );
7186
+ if (Object.keys(updatePayload).length === 0) {
7187
+ stats.skipped++;
7188
+ stats.diffs.push({
7189
+ uid,
7190
+ collectionName: ct.info?.displayName || uid,
7191
+ documentId: resolvedDocId,
7192
+ label: existing.title || existing.name || `Entry #${resolvedDocId}`,
7193
+ attribute: "",
7194
+ oldValue: existing,
7195
+ newValue: {},
7196
+ status: "skipped",
7197
+ message: `Skipped (no editable attributes in row ${rowNumber})`
7198
+ });
7199
+ return;
7200
+ }
7201
+ let pubRecord = effectiveLocale && publishedCounterparts.get(`${resolvedDocId}@@@${effectiveLocale}`) || publishedCounterparts.get(String(resolvedDocId));
7202
+ if (!pubRecord && isDraftAndPublish && resolvedDocId) {
6107
7203
  try {
6108
- const parsed = JSON.parse(trimmed);
6109
- if (Array.isArray(parsed)) {
6110
- const ids = parsed.map((item) => typeof item === "object" && item !== null ? item.id || item.documentId : item).filter(Boolean);
6111
- return isMultiple ? ids : ids[0] || null;
6112
- }
6113
- if (typeof parsed === "number") {
6114
- return isMultiple ? [parsed] : parsed;
6115
- }
6116
- if (typeof parsed === "object" && parsed !== null) {
6117
- const id = parsed.id || parsed.documentId || parsed;
6118
- return isMultiple ? [id] : id;
7204
+ const singlePub = await strapi.documents(uid).findMany({
7205
+ status: "published",
7206
+ filters: { documentId: resolvedDocId },
7207
+ fields: ["documentId", "updatedAt", "publishedAt", "locale"],
7208
+ limit: 1
7209
+ });
7210
+ if (singlePub && singlePub.length > 0) {
7211
+ pubRecord = singlePub[0];
7212
+ publishedCounterparts.set(String(resolvedDocId), pubRecord);
6119
7213
  }
6120
7214
  } catch {
6121
7215
  }
6122
7216
  }
6123
- if (rawVal.includes(";") || rawVal.includes(",")) {
6124
- const parts = rawVal.split(/[;,]/).map((s) => s.trim()).filter(Boolean).map((s) => /^\d+$/.test(s) ? parseInt(s, 10) : s);
6125
- return isMultiple ? parts : parts[0] || null;
7217
+ const rowStatus = row.status || row.Status || row.STATUS || row["Published Status"] || row["published_status"] || row["strapi_status"];
7218
+ const rowPubAt = row.publishedAt || row.published_at || row.PublishedAt;
7219
+ const inspectionExisting = rowStatus || rowPubAt ? {
7220
+ ...existing,
7221
+ ...rowStatus ? { status: rowStatus } : {},
7222
+ ...rowPubAt ? { publishedAt: rowPubAt } : {}
7223
+ } : existing;
7224
+ const { hadPublishedVersion } = resolveRecordPublicationStatus(
7225
+ inspectionExisting,
7226
+ pubRecord,
7227
+ isDraftAndPublish
7228
+ );
7229
+ const shouldPublish = evaluateShouldPublish({
7230
+ isDraftAndPublish,
7231
+ hadPublishedVersion,
7232
+ isEditing,
7233
+ publishOnApproval: Boolean(options.publish),
7234
+ publishStrategy: options.publishStrategy || "safe",
7235
+ unreviewedConsent: options.unreviewedConsent
7236
+ });
7237
+ const proposedEntity = deepMergeEntities(existing, updatePayload);
7238
+ const valResult = await validateEntityQuotas(strapi, uid, proposedEntity);
7239
+ if (!valResult.isValid) {
7240
+ stats.skipped++;
7241
+ if (stats.failed !== void 0) stats.failed++;
7242
+ stats.errors.push({
7243
+ row: rowNumber,
7244
+ documentId: resolvedDocId,
7245
+ error: valResult.errorMessage
7246
+ });
7247
+ stats.diffs.push({
7248
+ uid,
7249
+ collectionName: ct.info?.displayName || uid,
7250
+ documentId: resolvedDocId,
7251
+ label: existing.title || existing.name || `Entry #${resolvedDocId}`,
7252
+ attribute: valResult.targetField || "",
7253
+ oldValue: existing?.[valResult.targetField || ""] ?? null,
7254
+ newValue: updatePayload?.[valResult.targetField || ""] ?? null,
7255
+ status: "error",
7256
+ message: valResult.errorMessage
7257
+ });
7258
+ return;
6126
7259
  }
6127
- if (/^\d+$/.test(trimmed)) {
6128
- const numId = parseInt(trimmed, 10);
6129
- return isMultiple ? [numId] : numId;
7260
+ const updateArgs = {
7261
+ documentId: resolvedDocId,
7262
+ data: updatePayload
7263
+ };
7264
+ if (effectiveLocale) updateArgs.locale = effectiveLocale;
7265
+ await strapi.documents(uid).update(updateArgs);
7266
+ if (shouldPublish) {
7267
+ try {
7268
+ const pubArgs = { documentId: resolvedDocId };
7269
+ if (effectiveLocale) pubArgs.locale = effectiveLocale;
7270
+ await strapi.documents(uid).publish(pubArgs);
7271
+ } catch (pubErr) {
7272
+ strapi.log.warn(`[bulk-updater] Auto-publish failed for ${resolvedDocId}:`, pubErr);
7273
+ }
6130
7274
  }
6131
- if (isValidDocId(trimmed)) {
6132
- return isMultiple ? [trimmed] : trimmed;
7275
+ try {
7276
+ await recordContentHistoryVersion(strapi, {
7277
+ uid,
7278
+ documentId: resolvedDocId,
7279
+ userId: options.user?.id,
7280
+ statusOverride: shouldPublish ? "published" : isDraftAndPublish ? hadPublishedVersion ? "modified" : "draft" : void 0
7281
+ });
7282
+ } catch {
6133
7283
  }
6134
- return isMultiple ? [] : null;
6135
- }
6136
- function parseRowToPayload(strapi, attrs, row) {
6137
- const payload2 = {};
6138
- for (const [key, rawVal] of Object.entries(row)) {
6139
- const normalizedKey = key.toLowerCase().replace(/[\s_-]/g, "");
6140
- if (SYSTEM_FIELD_KEYS.has(normalizedKey)) continue;
6141
- if (key.includes(".")) {
6142
- const topPart = key.split(".")[0].toLowerCase().replace(/[\s_-]/g, "");
6143
- if (SYSTEM_FIELD_KEYS.has(topPart)) continue;
6144
- const parts = key.split(".");
6145
- let currentAttrs = attrs;
6146
- let currentTarget = payload2;
6147
- for (let pIdx = 0; pIdx < parts.length; pIdx++) {
6148
- const part = parts[pIdx];
6149
- const isLeaf = pIdx === parts.length - 1;
6150
- if (isLeaf) {
6151
- let leafDef = currentAttrs[part];
6152
- if (!leafDef) {
6153
- const match = Object.keys(currentAttrs).find(
6154
- (k) => k.toLowerCase() === part.toLowerCase() || k.toLowerCase() === part.toLowerCase().replace(/\s+/g, "")
6155
- );
6156
- if (match) leafDef = currentAttrs[match];
6157
- }
6158
- if (!leafDef) {
6159
- break;
6160
- }
6161
- if (rawVal === "" || rawVal === null || rawVal === void 0) {
6162
- if (leafDef.type !== "dynamiczone" && !(leafDef.type === "component" && leafDef.repeatable) && leafDef.type !== "relation" && leafDef.type !== "password") {
6163
- currentTarget[part] = null;
6164
- }
6165
- } else if (leafDef.type === "integer" || leafDef.type === "biginteger") {
6166
- currentTarget[part] = parseNumberValue(rawVal, true);
6167
- } else if (leafDef.type === "float" || leafDef.type === "decimal") {
6168
- currentTarget[part] = parseNumberValue(rawVal, false);
6169
- } else if (leafDef.type === "boolean") {
6170
- currentTarget[part] = parseBooleanValue(rawVal);
6171
- } else if (leafDef.type === "blocks") {
6172
- currentTarget[part] = parseBlocksValue(rawVal);
6173
- } else if (leafDef.type === "enumeration") {
6174
- currentTarget[part] = parseEnumValue(rawVal, leafDef.enum);
6175
- } else if (leafDef.type === "relation") {
6176
- currentTarget[part] = parseRelationValue(rawVal, leafDef.relation);
6177
- } else if (leafDef.type === "media") {
6178
- currentTarget[part] = parseMediaValue(rawVal, Boolean(leafDef.multiple));
6179
- } else if (leafDef.type === "date" || leafDef.type === "time" || leafDef.type === "datetime" || leafDef.type === "timestamp") {
6180
- currentTarget[part] = String(rawVal).trim() || null;
6181
- } else if (leafDef.type === "email" || leafDef.type === "uid") {
6182
- currentTarget[part] = String(rawVal).trim();
6183
- } else if (leafDef.type === "password") {
6184
- if (String(rawVal).trim()) {
6185
- currentTarget[part] = String(rawVal).trim();
6186
- }
6187
- } else if (leafDef.type === "json") {
6188
- try {
6189
- currentTarget[part] = JSON.parse(rawVal);
6190
- } catch {
6191
- currentTarget[part] = rawVal;
6192
- }
6193
- } else if (leafDef.type === "component" && leafDef.repeatable) {
6194
- try {
6195
- const parsed = JSON.parse(rawVal);
6196
- if (Array.isArray(parsed)) {
6197
- currentTarget[part] = parsed;
6198
- }
6199
- } catch {
6200
- }
6201
- } else {
6202
- currentTarget[part] = rawVal;
6203
- }
6204
- } else {
6205
- let compDef = currentAttrs[part];
6206
- if (!compDef) {
6207
- const match = Object.keys(currentAttrs).find(
6208
- (k) => k.toLowerCase() === part.toLowerCase() || k.toLowerCase() === part.toLowerCase().replace(/\s+/g, "")
6209
- );
6210
- if (match) compDef = currentAttrs[match];
6211
- }
6212
- if (compDef?.type === "component" && !compDef.repeatable && compDef.component) {
6213
- const comp = strapi.components[compDef.component];
6214
- if (!comp?.attributes) {
6215
- break;
6216
- }
6217
- if (!currentTarget[part] || typeof currentTarget[part] !== "object" || Array.isArray(currentTarget[part])) {
6218
- currentTarget[part] = {};
6219
- }
6220
- currentTarget = currentTarget[part];
6221
- currentAttrs = comp.attributes;
6222
- } else {
6223
- break;
6224
- }
6225
- }
6226
- }
6227
- continue;
6228
- }
6229
- let attrDef = attrs[key];
6230
- if (!attrDef) {
6231
- const matchKey = Object.keys(attrs).find(
6232
- (k) => k.toLowerCase() === key.toLowerCase() || k.toLowerCase() === key.toLowerCase().replace(/\s+/g, "")
6233
- );
6234
- if (matchKey) {
6235
- attrDef = attrs[matchKey];
6236
- }
6237
- }
6238
- if (!attrDef) continue;
6239
- if (attrDef?.target?.includes("review-workflow") || attrDef?.target === "admin::review-workflow-stage") {
6240
- continue;
6241
- }
6242
- if (rawVal === "" || rawVal === null || rawVal === void 0) {
6243
- if (attrDef.type !== "dynamiczone" && !(attrDef.type === "component" && attrDef.repeatable) && attrDef.type !== "relation" && attrDef.type !== "password") {
6244
- payload2[key] = null;
6245
- }
6246
- continue;
6247
- }
6248
- switch (attrDef.type) {
6249
- case "integer":
6250
- case "biginteger":
6251
- payload2[key] = parseNumberValue(rawVal, true);
6252
- break;
6253
- case "float":
6254
- case "decimal":
6255
- payload2[key] = parseNumberValue(rawVal, false);
6256
- break;
6257
- case "boolean":
6258
- payload2[key] = parseBooleanValue(rawVal);
6259
- break;
6260
- case "blocks":
6261
- payload2[key] = parseBlocksValue(rawVal);
6262
- break;
6263
- case "enumeration":
6264
- payload2[key] = parseEnumValue(rawVal, attrDef.enum);
6265
- break;
6266
- case "relation":
6267
- payload2[key] = parseRelationValue(rawVal, attrDef.relation);
6268
- break;
6269
- case "media":
6270
- payload2[key] = parseMediaValue(rawVal, Boolean(attrDef.multiple));
6271
- break;
6272
- case "date":
6273
- case "time":
6274
- case "datetime":
6275
- case "timestamp":
6276
- payload2[key] = String(rawVal).trim() || null;
6277
- break;
6278
- case "email":
6279
- case "uid":
6280
- payload2[key] = String(rawVal).trim();
6281
- break;
6282
- case "password":
6283
- if (String(rawVal).trim()) {
6284
- payload2[key] = String(rawVal).trim();
6285
- }
6286
- break;
6287
- case "json":
6288
- try {
6289
- payload2[key] = JSON.parse(rawVal);
6290
- } catch {
6291
- payload2[key] = rawVal;
6292
- }
6293
- break;
6294
- case "dynamiczone": {
6295
- try {
6296
- const parsed = JSON.parse(rawVal);
6297
- if (Array.isArray(parsed) && parsed.every((item) => item && typeof item === "object" && typeof item.__component === "string")) {
6298
- payload2[key] = parsed;
6299
- }
6300
- } catch {
6301
- }
6302
- break;
6303
- }
6304
- case "component": {
6305
- if (attrDef.repeatable) {
6306
- try {
6307
- const parsed = JSON.parse(rawVal);
6308
- if (Array.isArray(parsed) && parsed.every((item) => item && typeof item === "object")) {
6309
- payload2[key] = parsed;
6310
- }
6311
- } catch {
6312
- }
6313
- } else {
6314
- try {
6315
- const parsed = JSON.parse(rawVal);
6316
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
6317
- payload2[key] = parsed;
6318
- }
6319
- } catch {
6320
- }
6321
- }
6322
- break;
7284
+ try {
7285
+ const postDoc = await strapi.documents(uid).findOne({
7286
+ documentId: resolvedDocId,
7287
+ ...effectiveLocale ? { locale: effectiveLocale } : {},
7288
+ populate: buildLosslessPopulate(strapi, uid)
7289
+ });
7290
+ if (postDoc) {
7291
+ const integrityReport = verifyDocumentIntegrity(strapi, uid, existing, updatePayload, postDoc);
7292
+ if (integrityReport.status === "FAILED") {
7293
+ strapi.log.warn(`[bulk-updater] Data integrity warning on row ${rowNumber}:`, integrityReport.diffs);
6323
7294
  }
6324
- default:
6325
- payload2[key] = rawVal;
6326
7295
  }
7296
+ } catch {
7297
+ }
7298
+ stats.updated++;
7299
+ for (const attrKey of Object.keys(updatePayload)) {
7300
+ const oldVal = existing?.[attrKey] ?? null;
7301
+ const newVal = updatePayload[attrKey];
7302
+ stats.diffs.push({
7303
+ uid,
7304
+ collectionName: ct.info?.displayName || uid,
7305
+ documentId: resolvedDocId,
7306
+ label: existing.title || existing.name || `Entry #${resolvedDocId}`,
7307
+ attribute: attrKey,
7308
+ oldValue: oldVal,
7309
+ newValue: newVal,
7310
+ status: "updated",
7311
+ message: `${actionLabel} "${attrKey}" via CSV import (row ${rowNumber})`
7312
+ });
6327
7313
  }
6328
- return payload2;
6329
7314
  }
6330
- function formatValueDisplay(val) {
6331
- if (val === null || val === void 0) return "(empty)";
6332
- if (typeof val === "object") {
7315
+ async function executeCreateMutation(strapi, ct, uid, docId, row, rowNumber, options, effectiveLocale, isEditing, isDraftAndPublish, stats) {
7316
+ const createPayload = await buildDocumentUpdatePayload(
7317
+ strapi,
7318
+ uid,
7319
+ null,
7320
+ row,
7321
+ {}
7322
+ );
7323
+ const valResultNew = await validateEntityQuotas(strapi, uid, createPayload);
7324
+ if (!valResultNew.isValid) {
7325
+ stats.skipped++;
7326
+ if (stats.failed !== void 0) stats.failed++;
7327
+ stats.errors.push({
7328
+ row: rowNumber,
7329
+ documentId: docId || "new",
7330
+ error: valResultNew.errorMessage
7331
+ });
7332
+ stats.diffs.push({
7333
+ uid,
7334
+ collectionName: ct.info?.displayName || uid,
7335
+ documentId: docId || "new",
7336
+ label: `Row ${rowNumber}`,
7337
+ attribute: valResultNew.targetField || "",
7338
+ oldValue: null,
7339
+ newValue: createPayload?.[valResultNew.targetField || ""] ?? null,
7340
+ status: "error",
7341
+ message: valResultNew.errorMessage
7342
+ });
7343
+ return;
7344
+ }
7345
+ const createArgs = { data: createPayload };
7346
+ if (effectiveLocale) createArgs.locale = effectiveLocale;
7347
+ const created = await strapi.documents(uid).create(createArgs);
7348
+ const newDocId = created?.documentId || docId;
7349
+ const shouldPublishNew = !isEditing && isDraftAndPublish && Boolean(options.publish) && (options.publishStrategy === "all" || options.unreviewedConsent ? true : false);
7350
+ if (shouldPublishNew && newDocId) {
6333
7351
  try {
6334
- return JSON.stringify(val);
6335
- } catch {
6336
- return String(val);
7352
+ const pubArgs = { documentId: newDocId };
7353
+ if (effectiveLocale) pubArgs.locale = effectiveLocale;
7354
+ await strapi.documents(uid).publish(pubArgs);
7355
+ } catch (pubErr) {
7356
+ strapi.log.warn(`[bulk-updater] Auto-publish failed for ${newDocId}:`, pubErr);
6337
7357
  }
6338
7358
  }
6339
- const s = String(val).trim();
6340
- return s === "" ? "(empty)" : s;
7359
+ try {
7360
+ await recordContentHistoryVersion(strapi, {
7361
+ uid,
7362
+ documentId: newDocId,
7363
+ userId: options.user?.id,
7364
+ statusOverride: shouldPublishNew ? "published" : isDraftAndPublish ? "draft" : void 0
7365
+ });
7366
+ } catch {
7367
+ }
7368
+ stats.created++;
7369
+ if (!docId) {
7370
+ stats.newWithoutDocId++;
7371
+ }
7372
+ for (const attrKey of Object.keys(createPayload)) {
7373
+ stats.diffs.push({
7374
+ uid,
7375
+ collectionName: ct.info?.displayName || uid,
7376
+ documentId: newDocId,
7377
+ label: created?.title || created?.name || `New Entry #${newDocId}`,
7378
+ attribute: attrKey,
7379
+ oldValue: null,
7380
+ newValue: createPayload[attrKey],
7381
+ status: "created",
7382
+ message: docId ? `Created "${attrKey}" via CSV import (row ${rowNumber})` : `Created "${attrKey}" as new entry (row ${rowNumber})`
7383
+ });
7384
+ }
6341
7385
  }
6342
7386
  async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6343
- const attrs = ct.attributes || {};
7387
+ ct.attributes || {};
6344
7388
  const { mode = "auto", publish = true, publishStrategy = "safe", user } = options;
6345
7389
  const isDraftAndPublish = Boolean(ct.options?.draftAndPublish);
6346
7390
  const docIdsInChunk = rows.map((r) => extractDocId(r)).filter(Boolean);
@@ -6384,323 +7428,84 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6384
7428
  if (ct.kind === "singleType" && !docId) {
6385
7429
  try {
6386
7430
  const findSingleArgs = {};
6387
- if (effectiveLocale) findSingleArgs.locale = effectiveLocale;
6388
- const singleDoc = await strapi.documents(uid).findFirst(findSingleArgs);
6389
- if (singleDoc?.documentId) {
6390
- docId = singleDoc.documentId;
6391
- }
6392
- } catch {
6393
- }
6394
- }
6395
- const payload2 = parseRowToPayload(strapi, attrs, row);
6396
- try {
6397
- if (mode === "update") {
6398
- if (!docId) {
6399
- stats.skipped++;
6400
- stats.errors.push({
6401
- row: rowNumber,
6402
- error: "Missing or invalid documentId for Update mode. (Tip: Use Smart Auto-Detect mode to auto-add entries without document IDs)."
6403
- });
6404
- continue;
6405
- }
6406
- const existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
6407
- if (!existing) {
6408
- stats.skipped++;
6409
- stats.errors.push({
6410
- row: rowNumber,
6411
- documentId: docId,
6412
- error: `Document with ID "${docId}" not found in database.`
6413
- });
6414
- continue;
6415
- }
6416
- const resolvedDocId = existing.documentId || docId;
6417
- const mergedPayload = { ...payload2 };
6418
- for (const key of Object.keys(payload2)) {
6419
- if (attrs[key]?.type === "component" && typeof payload2[key] === "object" && payload2[key] !== null) {
6420
- mergedPayload[key] = deepMergeComponent(existing[key], payload2[key]);
6421
- }
6422
- }
6423
- if (Object.keys(mergedPayload).length === 0) {
6424
- stats.skipped++;
6425
- stats.diffs.push({
6426
- uid,
6427
- collectionName: ct.info?.displayName || uid,
6428
- documentId: resolvedDocId,
6429
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6430
- attribute: "",
6431
- oldValue: existing,
6432
- newValue: {},
6433
- status: "skipped",
6434
- message: `Skipped (no editable attributes in row ${rowNumber})`
6435
- });
6436
- continue;
6437
- }
6438
- let pubRecord = effectiveLocale && publishedCounterparts.get(`${resolvedDocId}@@@${effectiveLocale}`) || publishedCounterparts.get(String(resolvedDocId));
6439
- if (!pubRecord && isDraftAndPublish && resolvedDocId) {
6440
- try {
6441
- const singlePub = await strapi.documents(uid).findMany({
6442
- status: "published",
6443
- filters: { documentId: resolvedDocId },
6444
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6445
- limit: 1
6446
- });
6447
- if (singlePub && singlePub.length > 0) {
6448
- pubRecord = singlePub[0];
6449
- publishedCounterparts.set(String(resolvedDocId), pubRecord);
6450
- }
6451
- } catch {
6452
- }
6453
- }
6454
- const rowStatus = row.status || row.Status || row.STATUS || row["Published Status"] || row["published_status"] || row["strapi_status"];
6455
- const rowPubAt = row.publishedAt || row.published_at || row.PublishedAt;
6456
- const inspectionExisting = rowStatus || rowPubAt ? { ...existing, ...rowStatus ? { status: rowStatus } : {}, ...rowPubAt ? { publishedAt: rowPubAt } : {} } : existing;
6457
- const { hadPublishedVersion } = resolveRecordPublicationStatus(
6458
- inspectionExisting,
6459
- pubRecord,
6460
- isDraftAndPublish
6461
- );
6462
- const shouldPublish = evaluateShouldPublish({
6463
- isDraftAndPublish,
6464
- hadPublishedVersion,
6465
- isEditing,
6466
- publishOnApproval: Boolean(publish),
6467
- publishStrategy,
6468
- unreviewedConsent: options.unreviewedConsent
6469
- });
6470
- const updateArgs = {
6471
- documentId: resolvedDocId,
6472
- data: mergedPayload
6473
- };
6474
- if (effectiveLocale) updateArgs.locale = effectiveLocale;
6475
- const proposedEntity = deepMergeEntities(existing, mergedPayload);
6476
- const valResult = await validateEntityQuotas(strapi, uid, proposedEntity);
6477
- if (!valResult.isValid) {
6478
- stats.skipped++;
6479
- if (stats.failed !== void 0) stats.failed++;
6480
- stats.errors.push({
6481
- row: rowNumber,
6482
- documentId: resolvedDocId,
6483
- error: valResult.errorMessage
6484
- });
6485
- stats.diffs.push({
6486
- uid,
6487
- collectionName: ct.info?.displayName || uid,
6488
- documentId: resolvedDocId,
6489
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6490
- attribute: valResult.targetField || "",
6491
- oldValue: existing?.[valResult.targetField || ""] ?? null,
6492
- newValue: mergedPayload?.[valResult.targetField || ""] ?? null,
6493
- status: "error",
6494
- message: valResult.errorMessage
6495
- });
6496
- continue;
6497
- }
6498
- await strapi.documents(uid).update(updateArgs);
6499
- if (shouldPublish) {
6500
- try {
6501
- const pubArgs = { documentId: resolvedDocId };
6502
- if (effectiveLocale) pubArgs.locale = effectiveLocale;
6503
- await strapi.documents(uid).publish(pubArgs);
6504
- } catch (pubErr) {
6505
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${resolvedDocId}:`, pubErr);
6506
- }
6507
- }
6508
- try {
6509
- await recordContentHistoryVersion(strapi, {
6510
- uid,
6511
- documentId: resolvedDocId,
6512
- userId: user?.id,
6513
- statusOverride: shouldPublish ? "published" : isDraftAndPublish ? hadPublishedVersion ? "modified" : "draft" : void 0
6514
- });
6515
- } catch {
6516
- }
6517
- stats.updated++;
6518
- for (const attrKey of Object.keys(payload2)) {
6519
- const oldVal = existing?.[attrKey] ?? null;
6520
- const newVal = payload2[attrKey];
6521
- stats.diffs.push({
6522
- uid,
6523
- collectionName: ct.info?.displayName || uid,
6524
- documentId: resolvedDocId,
6525
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6526
- attribute: attrKey,
6527
- oldValue: oldVal,
6528
- newValue: newVal,
6529
- status: "updated",
6530
- message: `Updated "${attrKey}" via CSV import (row ${rowNumber})`
6531
- });
6532
- }
6533
- } else if (mode === "create_or_override") {
6534
- let existing = null;
6535
- if (docId) {
6536
- existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
7431
+ if (effectiveLocale) findSingleArgs.locale = effectiveLocale;
7432
+ const singleDoc = await strapi.documents(uid).findFirst(findSingleArgs);
7433
+ if (singleDoc?.documentId) {
7434
+ docId = singleDoc.documentId;
6537
7435
  }
6538
- if (existing) {
6539
- const resolvedDocId = existing.documentId || docId;
6540
- const mergedPayload = { ...payload2 };
6541
- for (const key of Object.keys(payload2)) {
6542
- if (attrs[key]?.type === "component" && typeof payload2[key] === "object" && payload2[key] !== null) {
6543
- mergedPayload[key] = deepMergeComponent(existing[key], payload2[key]);
6544
- }
6545
- }
6546
- let pubRecord = effectiveLocale && publishedCounterparts.get(`${resolvedDocId}@@@${effectiveLocale}`) || publishedCounterparts.get(String(resolvedDocId));
6547
- if (!pubRecord && isDraftAndPublish && resolvedDocId) {
6548
- try {
6549
- const singlePub = await strapi.documents(uid).findMany({
6550
- status: "published",
6551
- filters: { documentId: resolvedDocId },
6552
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6553
- limit: 1
6554
- });
6555
- if (singlePub && singlePub.length > 0) {
6556
- pubRecord = singlePub[0];
6557
- publishedCounterparts.set(String(resolvedDocId), pubRecord);
6558
- }
6559
- } catch {
6560
- }
6561
- }
6562
- const rowStatus = row.status || row.Status || row.STATUS || row["Published Status"] || row["published_status"] || row["strapi_status"];
6563
- const rowPubAt = row.publishedAt || row.published_at || row.PublishedAt;
6564
- const inspectionExisting = rowStatus || rowPubAt ? { ...existing, ...rowStatus ? { status: rowStatus } : {}, ...rowPubAt ? { publishedAt: rowPubAt } : {} } : existing;
6565
- const { hadPublishedVersion } = resolveRecordPublicationStatus(
6566
- inspectionExisting,
6567
- pubRecord,
6568
- isDraftAndPublish
6569
- );
6570
- const shouldPublish = evaluateShouldPublish({
6571
- isDraftAndPublish,
6572
- hadPublishedVersion,
6573
- isEditing,
6574
- publishOnApproval: Boolean(publish),
6575
- publishStrategy,
6576
- unreviewedConsent: options.unreviewedConsent
7436
+ } catch {
7437
+ }
7438
+ }
7439
+ try {
7440
+ if (mode === "update") {
7441
+ if (!docId) {
7442
+ stats.skipped++;
7443
+ stats.errors.push({
7444
+ row: rowNumber,
7445
+ error: "Missing or invalid documentId for Update mode. (Tip: Use Smart Auto-Detect mode to auto-add entries without document IDs)."
6577
7446
  });
6578
- const updateArgs = {
6579
- documentId: resolvedDocId,
6580
- data: mergedPayload
6581
- };
6582
- if (effectiveLocale) updateArgs.locale = effectiveLocale;
6583
- const proposedEntity = deepMergeEntities(existing, mergedPayload);
6584
- const valResult = await validateEntityQuotas(strapi, uid, proposedEntity);
6585
- if (!valResult.isValid) {
6586
- stats.skipped++;
6587
- if (stats.failed !== void 0) stats.failed++;
6588
- stats.errors.push({
6589
- row: rowNumber,
6590
- documentId: resolvedDocId,
6591
- error: valResult.errorMessage
6592
- });
6593
- stats.diffs.push({
6594
- uid,
6595
- collectionName: ct.info?.displayName || uid,
6596
- documentId: resolvedDocId,
6597
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6598
- attribute: valResult.targetField || "",
6599
- oldValue: existing?.[valResult.targetField || ""] ?? null,
6600
- newValue: mergedPayload?.[valResult.targetField || ""] ?? null,
6601
- status: "error",
6602
- message: valResult.errorMessage
6603
- });
6604
- continue;
6605
- }
6606
- await strapi.documents(uid).update(updateArgs);
6607
- if (shouldPublish) {
6608
- try {
6609
- const pubArgs = { documentId: resolvedDocId };
6610
- if (effectiveLocale) pubArgs.locale = effectiveLocale;
6611
- await strapi.documents(uid).publish(pubArgs);
6612
- } catch (pubErr) {
6613
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${resolvedDocId}:`, pubErr);
6614
- }
6615
- }
6616
- try {
6617
- await recordContentHistoryVersion(strapi, {
6618
- uid,
6619
- documentId: resolvedDocId,
6620
- userId: user?.id,
6621
- statusOverride: shouldPublish ? "published" : isDraftAndPublish ? hadPublishedVersion ? "modified" : "draft" : void 0
6622
- });
6623
- } catch {
6624
- }
6625
- stats.updated++;
6626
- for (const attrKey of Object.keys(payload2)) {
6627
- const oldVal = existing?.[attrKey] ?? null;
6628
- const newVal = payload2[attrKey];
6629
- stats.diffs.push({
6630
- uid,
6631
- collectionName: ct.info?.displayName || uid,
6632
- documentId: resolvedDocId,
6633
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6634
- attribute: attrKey,
6635
- oldValue: oldVal,
6636
- newValue: newVal,
6637
- status: "updated",
6638
- message: `Overridden "${attrKey}" via CSV import (row ${rowNumber})`
6639
- });
6640
- }
6641
7447
  continue;
6642
7448
  }
6643
- const valResultNew = await validateEntityQuotas(strapi, uid, payload2);
6644
- if (!valResultNew.isValid) {
7449
+ const existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
7450
+ if (!existing) {
6645
7451
  stats.skipped++;
6646
- if (stats.failed !== void 0) stats.failed++;
6647
7452
  stats.errors.push({
6648
7453
  row: rowNumber,
6649
- documentId: docId || "new",
6650
- error: valResultNew.errorMessage
6651
- });
6652
- stats.diffs.push({
6653
- uid,
6654
- collectionName: ct.info?.displayName || uid,
6655
- documentId: docId || "new",
6656
- label: `Row ${rowNumber}`,
6657
- attribute: valResultNew.targetField || "",
6658
- oldValue: null,
6659
- newValue: payload2?.[valResultNew.targetField || ""] ?? null,
6660
- status: "error",
6661
- message: valResultNew.errorMessage
7454
+ documentId: docId,
7455
+ error: `Document with ID "${docId}" not found in database.`
6662
7456
  });
6663
7457
  continue;
6664
7458
  }
6665
- const createArgs = { data: payload2 };
6666
- if (effectiveLocale) createArgs.locale = effectiveLocale;
6667
- const created = await strapi.documents(uid).create(createArgs);
6668
- const newDocId = created?.documentId || docId;
6669
- const shouldPublishNew = !isEditing && isDraftAndPublish && Boolean(publish) && (publishStrategy === "all" || options.unreviewedConsent ? true : false);
6670
- if (shouldPublishNew && newDocId) {
6671
- try {
6672
- const pubArgs = { documentId: newDocId };
6673
- if (effectiveLocale) pubArgs.locale = effectiveLocale;
6674
- await strapi.documents(uid).publish(pubArgs);
6675
- } catch (pubErr) {
6676
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${newDocId}:`, pubErr);
6677
- }
7459
+ await executeUpdateMutation(
7460
+ strapi,
7461
+ ct,
7462
+ uid,
7463
+ existing,
7464
+ row,
7465
+ rowNumber,
7466
+ options,
7467
+ effectiveLocale,
7468
+ isEditing,
7469
+ isDraftAndPublish,
7470
+ publishedCounterparts,
7471
+ stats,
7472
+ "Updated"
7473
+ );
7474
+ } else if (mode === "create_or_override") {
7475
+ let existing = null;
7476
+ if (docId) {
7477
+ existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
6678
7478
  }
6679
- try {
6680
- await recordContentHistoryVersion(strapi, {
7479
+ if (existing) {
7480
+ await executeUpdateMutation(
7481
+ strapi,
7482
+ ct,
6681
7483
  uid,
6682
- documentId: newDocId,
6683
- userId: user?.id,
6684
- statusOverride: shouldPublishNew ? "published" : isDraftAndPublish ? "draft" : void 0
6685
- });
6686
- } catch {
6687
- }
6688
- stats.created++;
6689
- if (!docId) {
6690
- stats.newWithoutDocId++;
6691
- }
6692
- for (const attrKey of Object.keys(payload2)) {
6693
- stats.diffs.push({
7484
+ existing,
7485
+ row,
7486
+ rowNumber,
7487
+ options,
7488
+ effectiveLocale,
7489
+ isEditing,
7490
+ isDraftAndPublish,
7491
+ publishedCounterparts,
7492
+ stats,
7493
+ "Overridden"
7494
+ );
7495
+ } else {
7496
+ await executeCreateMutation(
7497
+ strapi,
7498
+ ct,
6694
7499
  uid,
6695
- collectionName: ct.info?.displayName || uid,
6696
- documentId: newDocId,
6697
- label: created?.title || created?.name || `New Entry #${newDocId}`,
6698
- attribute: attrKey,
6699
- oldValue: null,
6700
- newValue: payload2[attrKey],
6701
- status: "created",
6702
- message: docId ? `Created "${attrKey}" via CSV import (row ${rowNumber})` : `Created "${attrKey}" as new entry (row ${rowNumber})`
6703
- });
7500
+ docId,
7501
+ row,
7502
+ rowNumber,
7503
+ options,
7504
+ effectiveLocale,
7505
+ isEditing,
7506
+ isDraftAndPublish,
7507
+ stats
7508
+ );
6704
7509
  }
6705
7510
  } else {
6706
7511
  let existing = null;
@@ -6708,178 +7513,56 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6708
7513
  existing = await findExistingDocument(strapi, uid, docId, effectiveLocale);
6709
7514
  }
6710
7515
  if (existing) {
6711
- const resolvedDocId = existing.documentId || docId;
6712
- const mergedPayload = { ...payload2 };
6713
- for (const key of Object.keys(payload2)) {
6714
- if (attrs[key]?.type === "component" && typeof payload2[key] === "object" && payload2[key] !== null) {
6715
- mergedPayload[key] = deepMergeComponent(existing[key], payload2[key]);
6716
- }
6717
- }
6718
- let pubRecord = effectiveLocale && publishedCounterparts.get(`${resolvedDocId}@@@${effectiveLocale}`) || publishedCounterparts.get(String(resolvedDocId));
6719
- if (!pubRecord && isDraftAndPublish && resolvedDocId) {
6720
- try {
6721
- const singlePub = await strapi.documents(uid).findMany({
6722
- status: "published",
6723
- filters: { documentId: resolvedDocId },
6724
- fields: ["documentId", "updatedAt", "publishedAt", "locale"],
6725
- limit: 1
6726
- });
6727
- if (singlePub && singlePub.length > 0) {
6728
- pubRecord = singlePub[0];
6729
- publishedCounterparts.set(String(resolvedDocId), pubRecord);
6730
- }
6731
- } catch {
6732
- }
6733
- }
6734
- const rowStatus = row.status || row.Status || row.STATUS || row["Published Status"] || row["published_status"] || row["strapi_status"];
6735
- const rowPubAt = row.publishedAt || row.published_at || row.PublishedAt;
6736
- const inspectionExisting = rowStatus || rowPubAt ? { ...existing, ...rowStatus ? { status: rowStatus } : {}, ...rowPubAt ? { publishedAt: rowPubAt } : {} } : existing;
6737
- const { hadPublishedVersion } = resolveRecordPublicationStatus(
6738
- inspectionExisting,
6739
- pubRecord,
6740
- isDraftAndPublish
6741
- );
6742
- const shouldPublish = evaluateShouldPublish({
6743
- isDraftAndPublish,
6744
- hadPublishedVersion,
6745
- isEditing,
6746
- publishOnApproval: Boolean(publish),
6747
- publishStrategy,
6748
- unreviewedConsent: options.unreviewedConsent
6749
- });
6750
- const updateArgs = {
6751
- documentId: resolvedDocId,
6752
- data: mergedPayload
6753
- };
6754
- if (effectiveLocale) updateArgs.locale = effectiveLocale;
6755
- const proposedEntity = deepMergeEntities(existing, mergedPayload);
6756
- const valResult = await validateEntityQuotas(strapi, uid, proposedEntity);
6757
- if (!valResult.isValid) {
6758
- stats.skipped++;
6759
- if (stats.failed !== void 0) stats.failed++;
6760
- stats.errors.push({
6761
- row: rowNumber,
6762
- documentId: resolvedDocId,
6763
- error: valResult.errorMessage
6764
- });
6765
- stats.diffs.push({
6766
- uid,
6767
- collectionName: ct.info?.displayName || uid,
6768
- documentId: resolvedDocId,
6769
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6770
- attribute: valResult.targetField || "",
6771
- oldValue: existing?.[valResult.targetField || ""] ?? null,
6772
- newValue: mergedPayload?.[valResult.targetField || ""] ?? null,
6773
- status: "error",
6774
- message: valResult.errorMessage
6775
- });
6776
- continue;
6777
- }
6778
- await strapi.documents(uid).update(updateArgs);
6779
- if (shouldPublish) {
6780
- try {
6781
- const pubArgs = { documentId: resolvedDocId };
6782
- if (effectiveLocale) pubArgs.locale = effectiveLocale;
6783
- await strapi.documents(uid).publish(pubArgs);
6784
- } catch (pubErr) {
6785
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${resolvedDocId}:`, pubErr);
6786
- }
6787
- }
6788
- try {
6789
- await recordContentHistoryVersion(strapi, {
6790
- uid,
6791
- documentId: resolvedDocId,
6792
- userId: user?.id,
6793
- statusOverride: shouldPublish ? "published" : isDraftAndPublish ? hadPublishedVersion ? "modified" : "draft" : void 0
6794
- });
6795
- } catch {
6796
- }
6797
- stats.updated++;
6798
- for (const attrKey of Object.keys(payload2)) {
6799
- const oldVal = existing?.[attrKey] ?? null;
6800
- const newVal = payload2[attrKey];
6801
- stats.diffs.push({
6802
- uid,
6803
- collectionName: ct.info?.displayName || uid,
6804
- documentId: resolvedDocId,
6805
- label: existing.title || existing.name || `Entry #${resolvedDocId}`,
6806
- attribute: attrKey,
6807
- oldValue: oldVal,
6808
- newValue: newVal,
6809
- status: "updated",
6810
- message: `Updated "${attrKey}" via CSV import (row ${rowNumber})`
6811
- });
6812
- }
6813
- continue;
6814
- }
6815
- const valResultNew = await validateEntityQuotas(strapi, uid, payload2);
6816
- if (!valResultNew.isValid) {
6817
- stats.skipped++;
6818
- if (stats.failed !== void 0) stats.failed++;
6819
- stats.errors.push({
6820
- row: rowNumber,
6821
- documentId: docId || "new",
6822
- error: valResultNew.errorMessage
6823
- });
6824
- stats.diffs.push({
6825
- uid,
6826
- collectionName: ct.info?.displayName || uid,
6827
- documentId: docId || "new",
6828
- label: `Row ${rowNumber}`,
6829
- attribute: valResultNew.targetField || "",
6830
- oldValue: null,
6831
- newValue: payload2?.[valResultNew.targetField || ""] ?? null,
6832
- status: "error",
6833
- message: valResultNew.errorMessage
6834
- });
6835
- continue;
6836
- }
6837
- const createArgs = { data: payload2 };
6838
- if (effectiveLocale) createArgs.locale = effectiveLocale;
6839
- const created = await strapi.documents(uid).create(createArgs);
6840
- const newDocId = created?.documentId || docId;
6841
- const shouldPublishNew = !isEditing && isDraftAndPublish && Boolean(publish) && (publishStrategy === "all" || options.unreviewedConsent ? true : false);
6842
- if (shouldPublishNew && newDocId) {
6843
- try {
6844
- const pubArgs = { documentId: newDocId };
6845
- if (effectiveLocale) pubArgs.locale = effectiveLocale;
6846
- await strapi.documents(uid).publish(pubArgs);
6847
- } catch (pubErr) {
6848
- strapi.log.warn(`[bulk-updater] Auto-publish failed for ${newDocId}:`, pubErr);
6849
- }
6850
- }
6851
- try {
6852
- await recordContentHistoryVersion(strapi, {
7516
+ await executeUpdateMutation(
7517
+ strapi,
7518
+ ct,
6853
7519
  uid,
6854
- documentId: newDocId,
6855
- userId: user?.id,
6856
- statusOverride: shouldPublishNew ? "published" : isDraftAndPublish ? "draft" : void 0
6857
- });
6858
- } catch {
6859
- }
6860
- stats.created++;
6861
- if (!docId) {
6862
- stats.newWithoutDocId++;
6863
- }
6864
- for (const attrKey of Object.keys(payload2)) {
6865
- stats.diffs.push({
7520
+ existing,
7521
+ row,
7522
+ rowNumber,
7523
+ options,
7524
+ effectiveLocale,
7525
+ isEditing,
7526
+ isDraftAndPublish,
7527
+ publishedCounterparts,
7528
+ stats,
7529
+ "Updated"
7530
+ );
7531
+ } else {
7532
+ await executeCreateMutation(
7533
+ strapi,
7534
+ ct,
6866
7535
  uid,
6867
- collectionName: ct.info?.displayName || uid,
6868
- documentId: newDocId,
6869
- label: created?.title || created?.name || `New Entry #${newDocId}`,
6870
- attribute: attrKey,
6871
- oldValue: null,
6872
- newValue: payload2[attrKey],
6873
- status: "created",
6874
- message: docId ? `Created "${attrKey}" as new entry (documentId "${docId}" not found in database - row ${rowNumber})` : `Created "${attrKey}" as new entry (no documentId provided in CSV - row ${rowNumber})`
6875
- });
7536
+ docId,
7537
+ row,
7538
+ rowNumber,
7539
+ options,
7540
+ effectiveLocale,
7541
+ isEditing,
7542
+ isDraftAndPublish,
7543
+ stats
7544
+ );
6876
7545
  }
6877
7546
  }
6878
7547
  } catch (err) {
7548
+ stats.skipped++;
7549
+ if (stats.failed !== void 0) stats.failed++;
7550
+ const errMsg = extractDetailedErrorMessage(err);
6879
7551
  stats.errors.push({
6880
7552
  row: rowNumber,
6881
7553
  documentId: docId || void 0,
6882
- error: extractDetailedErrorMessage(err)
7554
+ error: errMsg
7555
+ });
7556
+ stats.diffs.push({
7557
+ uid,
7558
+ collectionName: ct.info?.displayName || uid,
7559
+ documentId: docId || `(Row #${rowNumber})`,
7560
+ label: `Row #${rowNumber}`,
7561
+ attribute: "(record)",
7562
+ oldValue: null,
7563
+ newValue: null,
7564
+ status: "error",
7565
+ message: `Failed to process row ${rowNumber}: ${errMsg}`
6883
7566
  });
6884
7567
  }
6885
7568
  }
@@ -6958,133 +7641,183 @@ const csvService = ({ strapi }) => ({
6958
7641
  if (!ct) {
6959
7642
  throw new Error(`Content type ${uid} not found`);
6960
7643
  }
6961
- const attrs = ct.attributes || {};
6962
- const excluded = ["createdAt", "updatedAt", "publishedAt", "createdBy", "updatedBy", "localizations"];
6963
- const headers = ["documentId"];
6964
- const sampleRow = ["(Leave empty to create new, or enter existing docId)"];
6965
- for (const [attrName, attrDef] of Object.entries(attrs)) {
6966
- if (excluded.includes(attrName)) continue;
6967
- if (attrDef.type === "relation") continue;
6968
- if (attrDef.type === "component" || attrDef.type === "dynamiczone") continue;
6969
- headers.push(attrName);
6970
- let sampleVal = "";
6971
- switch (attrDef.type) {
6972
- case "string":
6973
- case "text":
6974
- case "richtext":
6975
- sampleVal = `Sample ${attrName}`;
6976
- break;
6977
- case "integer":
6978
- case "biginteger":
6979
- case "float":
6980
- case "decimal":
6981
- sampleVal = "10";
6982
- break;
6983
- case "boolean":
6984
- sampleVal = "true";
6985
- break;
6986
- case "email":
6987
- sampleVal = "sample@example.com";
6988
- break;
6989
- case "enumeration":
6990
- sampleVal = attrDef.enum?.[0] || "option1";
6991
- break;
6992
- case "customField":
6993
- sampleVal = "value";
6994
- break;
6995
- default:
7644
+ const schema = discoverSchema(strapi, uid);
7645
+ const headers = [METADATA_COLUMN_KEY, ...schema.allExportKeys];
7646
+ const sampleRow = [
7647
+ JSON.stringify({
7648
+ schemaVersion: CURRENT_SCHEMA_VERSION,
7649
+ contentType: uid,
7650
+ documentId: "",
7651
+ locale: schema.isLocalized ? "en" : void 0,
7652
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString()
7653
+ })
7654
+ ];
7655
+ for (const key of schema.allExportKeys) {
7656
+ if (key === "documentId") {
7657
+ sampleRow.push("(Leave empty to create new, or enter existing docId)");
7658
+ } else if (key === "locale") {
7659
+ sampleRow.push("en");
7660
+ } else {
7661
+ const field = schema.fields[key];
7662
+ let sampleVal = "";
7663
+ if (field) {
7664
+ switch (field.category) {
7665
+ case "scalar":
7666
+ sampleVal = field.rawType === "boolean" ? "true" : field.rawType === "integer" ? "10" : `Sample ${key}`;
7667
+ break;
7668
+ case "blocks":
7669
+ sampleVal = JSON.stringify([{ type: "paragraph", children: [{ type: "text", text: `Sample ${key}` }] }]);
7670
+ break;
7671
+ case "component_single":
7672
+ sampleVal = JSON.stringify({ sampleField: "Sample value" });
7673
+ break;
7674
+ case "component_repeatable":
7675
+ sampleVal = JSON.stringify([{ label: "Sample item", url: "/" }]);
7676
+ break;
7677
+ case "dynamiczone":
7678
+ sampleVal = JSON.stringify(
7679
+ field.dzComponents && field.dzComponents.length > 0 ? [{ __component: field.dzComponents[0], title: "Sample" }] : []
7680
+ );
7681
+ break;
7682
+ case "relation_to_one":
7683
+ sampleVal = JSON.stringify({ documentId: "target-doc-id" });
7684
+ break;
7685
+ case "relation_to_many":
7686
+ sampleVal = JSON.stringify([{ documentId: "target-doc-id-1" }]);
7687
+ break;
7688
+ case "media_single":
7689
+ sampleVal = JSON.stringify({ id: 1, url: "/uploads/sample.png" });
7690
+ break;
7691
+ case "media_to_many":
7692
+ sampleVal = JSON.stringify([{ id: 1, url: "/uploads/sample.png" }]);
7693
+ break;
7694
+ default:
7695
+ sampleVal = "sample";
7696
+ }
7697
+ } else {
6996
7698
  sampleVal = "sample";
7699
+ }
7700
+ sampleRow.push(sampleVal);
6997
7701
  }
6998
- sampleRow.push(sampleVal);
6999
7702
  }
7000
- const csvContent = "\uFEFF" + headers.map(escapeCsvValue).join(",") + "\r\n" + sampleRow.map(escapeCsvValue).join(",") + "\r\n";
7703
+ const csvContent = "\uFEFF" + headers.map(escapeCsvCell).join(",") + "\r\n" + sampleRow.map(escapeCsvCell).join(",") + "\r\n";
7001
7704
  return {
7002
7705
  filename: `${ct.info?.singularName || "template"}_template.csv`,
7003
7706
  csvContent,
7004
7707
  headers
7005
7708
  };
7006
7709
  },
7007
- /**
7008
- * Exports entries of a collection to CSV with deep nested component support,
7009
- * RFC-4180 CRLF line endings, and UTF-8 BOM for 100% Microsoft Excel compatibility.
7010
- */
7011
7710
  async exportCollectionCsv(uid, options = {}) {
7012
7711
  const ct = strapi.contentTypes[uid];
7013
7712
  if (!ct) {
7014
7713
  throw new Error(`Content type ${uid} not found`);
7015
7714
  }
7016
- const allComponents = strapi.components || {};
7017
- const fields = discoverExportFields(ct, allComponents);
7018
- const filters = {};
7019
- const { attribute, filterOperator, filterQuery, search, documentIds } = options;
7020
- if (documentIds && Array.isArray(documentIds) && documentIds.length > 0) {
7021
- filters.documentId = { $in: documentIds };
7022
- }
7023
- if (attribute && filterOperator && filterOperator !== "none") {
7024
- const isNested = attribute.includes(".");
7025
- if (filterOperator === "empty") {
7026
- if (isNested) {
7027
- const [parent, child] = attribute.split(".");
7028
- filters[parent] = { [child]: { $null: true } };
7029
- } else {
7030
- filters[attribute] = { $null: true };
7031
- }
7032
- } else if (filterOperator === "not_empty") {
7033
- if (isNested) {
7034
- const [parent, child] = attribute.split(".");
7035
- filters[parent] = { [child]: { $notNull: true } };
7036
- } else {
7037
- filters[attribute] = { $notNull: true };
7038
- }
7039
- } else if (filterQuery !== void 0 && filterQuery !== "") {
7040
- const opMap = {
7041
- equals: "$eq",
7042
- notEquals: "$ne",
7043
- contains: "$containsi",
7044
- notContains: "$notContainsi",
7045
- startsWith: "$startsWith",
7046
- endsWith: "$endsWith"
7047
- };
7048
- const strapiOp = opMap[filterOperator] || "$eq";
7049
- if (isNested) {
7050
- const [parent, child] = attribute.split(".");
7051
- filters[parent] = { [child]: { [strapiOp]: filterQuery } };
7052
- } else {
7053
- filters[attribute] = { [strapiOp]: filterQuery };
7054
- }
7055
- }
7715
+ const schema = discoverSchema(strapi, uid);
7716
+ const deepPopulate = buildLosslessPopulate(strapi, uid);
7717
+ const headers = [METADATA_COLUMN_KEY, ...schema.allExportKeys];
7718
+ const lines = [];
7719
+ lines.push(headers.map(escapeCsvCell).join(","));
7720
+ const filterMeta = buildCollectionQueryFilters(strapi, ct, {
7721
+ attribute: options.attribute,
7722
+ searchAttribute: options.searchAttribute || options.attribute,
7723
+ filterOperator: options.filterOperator,
7724
+ filterQuery: options.filterQuery,
7725
+ search: options.search,
7726
+ documentIds: options.documentIds
7727
+ });
7728
+ if (!filterMeta.colHasAttribute && filterMeta.normOp && filterMeta.normOp !== "none") {
7729
+ return {
7730
+ filename: `${ct.info?.singularName || uid}_export_${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`,
7731
+ csvContent: "\uFEFF" + lines.join("\r\n") + "\r\n",
7732
+ count: 0,
7733
+ fields: headers
7734
+ };
7056
7735
  }
7057
- if (search && search.trim() !== "") {
7058
- const q = search.trim();
7059
- const searchConditions = [];
7060
- const searchFields = ["name", "title", "email", "slug", "description"].filter(
7061
- (f) => ct.attributes?.[f] && ["string", "text", "email"].includes(ct.attributes[f].type)
7062
- );
7063
- for (const field of searchFields) {
7064
- searchConditions.push({ [field]: { $containsi: q } });
7736
+ const filters = filterMeta.filters;
7737
+ const isRootDz = filterMeta.isRootDz;
7738
+ const normOp = filterMeta.normOp;
7739
+ const targetFilterAttr = filterMeta.targetFilterAttr;
7740
+ const passesDzFilter = (entry) => {
7741
+ if (!isRootDz || !normOp || normOp === "none") return true;
7742
+ const matches = getAllNestedValues(entry, targetFilterAttr);
7743
+ if (normOp === "empty") {
7744
+ return matches.length === 0 || matches.every((m) => {
7745
+ const v = m.value;
7746
+ if (v === void 0 || v === null) return true;
7747
+ if (Array.isArray(v)) return v.length === 0;
7748
+ if (typeof v === "object") return Object.keys(v).length === 0;
7749
+ return String(v).trim() === "";
7750
+ });
7065
7751
  }
7066
- if (searchConditions.length > 0) {
7067
- if (filters && Object.keys(filters).length > 0) {
7068
- filters.$and = [{ $or: searchConditions }];
7069
- } else {
7070
- filters.$or = searchConditions;
7071
- }
7752
+ if (normOp === "notempty") {
7753
+ return matches.some((m) => {
7754
+ const v = m.value;
7755
+ if (v === void 0 || v === null) return false;
7756
+ if (Array.isArray(v)) return v.length > 0;
7757
+ if (typeof v === "object") return Object.keys(v).length > 0;
7758
+ return String(v).trim() !== "";
7759
+ });
7072
7760
  }
7073
- }
7074
- const deepPopulate = buildDeepPopulate(ct.attributes || {}, allComponents);
7075
- const lines = [];
7076
- lines.push(fields.map((f) => escapeCsvValue(f.key)).join(","));
7761
+ const qVal = (filterMeta.filterQuery || "").trim().toLowerCase();
7762
+ const testSingleValue = (v) => {
7763
+ if (v === void 0 || v === null) return false;
7764
+ if (Array.isArray(v)) return v.some(testSingleValue);
7765
+ if (typeof v === "object") {
7766
+ return testSingleValue(v.name) || testSingleValue(v.title) || testSingleValue(v.email) || testSingleValue(v.username) || testSingleValue(v.documentId) || testSingleValue(v.id) || testSingleValue(v.slug);
7767
+ }
7768
+ const valStr = String(v).trim().toLowerCase();
7769
+ switch (normOp) {
7770
+ case "equals":
7771
+ return valStr === qVal;
7772
+ case "notequals":
7773
+ return valStr !== qVal;
7774
+ case "contains":
7775
+ return valStr.includes(qVal);
7776
+ case "notcontains":
7777
+ return !valStr.includes(qVal);
7778
+ case "startswith":
7779
+ return valStr.startsWith(qVal);
7780
+ case "endswith":
7781
+ return valStr.endsWith(qVal);
7782
+ default:
7783
+ return valStr.includes(qVal);
7784
+ }
7785
+ };
7786
+ return matches.some((m) => testSingleValue(m.value));
7787
+ };
7077
7788
  let totalExported = 0;
7078
7789
  const maxLimit = options.limit && options.limit > 0 ? options.limit : Infinity;
7079
7790
  const BATCH_SIZE = 200;
7791
+ const exportedAt = (/* @__PURE__ */ new Date()).toISOString();
7080
7792
  if (ct.kind === "singleType") {
7081
- const findFirstArgs = {};
7793
+ const findFirstArgs = {
7794
+ filters: Object.keys(filters).length > 0 ? filters : void 0
7795
+ };
7082
7796
  if (deepPopulate) {
7083
7797
  findFirstArgs.populate = deepPopulate;
7084
7798
  }
7085
7799
  const doc = await strapi.documents(uid).findFirst(findFirstArgs);
7086
- if (doc) {
7087
- const rowValues = fields.map((f) => escapeCsvValue(getNestedExportValue(doc, f.key)));
7800
+ if (doc && passesDzFilter(doc)) {
7801
+ const rowValues = [];
7802
+ const metadata = {
7803
+ schemaVersion: CURRENT_SCHEMA_VERSION,
7804
+ contentType: uid,
7805
+ documentId: String(doc.documentId || doc.id || ""),
7806
+ locale: doc.locale || void 0,
7807
+ exportedAt
7808
+ };
7809
+ rowValues.push(escapeCsvCell(metadata));
7810
+ for (const key of schema.allExportKeys) {
7811
+ if (key === "documentId") {
7812
+ rowValues.push(escapeCsvCell(doc.documentId || doc.id || ""));
7813
+ } else if (key === "locale") {
7814
+ rowValues.push(escapeCsvCell(doc.locale || ""));
7815
+ } else {
7816
+ const field = schema.fields[key];
7817
+ const rawVal = doc[key];
7818
+ rowValues.push(escapeCsvCell(field ? serializeFieldValue(rawVal, field) : rawVal));
7819
+ }
7820
+ }
7088
7821
  lines.push(rowValues.join(","));
7089
7822
  totalExported = 1;
7090
7823
  }
@@ -7112,7 +7845,29 @@ const csvService = ({ strapi }) => ({
7112
7845
  break;
7113
7846
  }
7114
7847
  for (const entry of chunkEntries) {
7115
- const rowValues = fields.map((f) => escapeCsvValue(getNestedExportValue(entry, f.key)));
7848
+ if (!passesDzFilter(entry)) {
7849
+ continue;
7850
+ }
7851
+ const rowValues = [];
7852
+ const metadata = {
7853
+ schemaVersion: CURRENT_SCHEMA_VERSION,
7854
+ contentType: uid,
7855
+ documentId: String(entry.documentId || entry.id || ""),
7856
+ locale: entry.locale || void 0,
7857
+ exportedAt
7858
+ };
7859
+ rowValues.push(escapeCsvCell(metadata));
7860
+ for (const key of schema.allExportKeys) {
7861
+ if (key === "documentId") {
7862
+ rowValues.push(escapeCsvCell(entry.documentId || entry.id || ""));
7863
+ } else if (key === "locale") {
7864
+ rowValues.push(escapeCsvCell(entry.locale || ""));
7865
+ } else {
7866
+ const field = schema.fields[key];
7867
+ const rawVal = entry[key];
7868
+ rowValues.push(escapeCsvCell(field ? serializeFieldValue(rawVal, field) : rawVal));
7869
+ }
7870
+ }
7116
7871
  lines.push(rowValues.join(","));
7117
7872
  totalExported++;
7118
7873
  if (totalExported >= maxLimit) {
@@ -7134,12 +7889,9 @@ const csvService = ({ strapi }) => ({
7134
7889
  filename,
7135
7890
  csvContent,
7136
7891
  count: totalExported,
7137
- fields: fields.map((f) => f.key)
7892
+ fields: headers
7138
7893
  };
7139
7894
  },
7140
- /**
7141
- * Exports violations of a specific rule directly into a CSV
7142
- */
7143
7895
  async exportViolationsCsv(ruleId) {
7144
7896
  const validationRulesService2 = strapi.plugin("bulk-updater").service("validationRules");
7145
7897
  const scanReport = await validationRulesService2.scanViolations(ruleId);
@@ -7615,7 +8367,18 @@ const csvService = ({ strapi }) => ({
7615
8367
  }
7616
8368
  }
7617
8369
  if (activeRules.length > 0) {
7618
- const proposedEntity = existing ? deepMergeEntities(existing, payload) : payload;
8370
+ let proposedPayload = {};
8371
+ try {
8372
+ proposedPayload = await buildDocumentUpdatePayload(
8373
+ strapi,
8374
+ uid,
8375
+ existing,
8376
+ row,
8377
+ { isPartialUpdate: mode === "update" }
8378
+ );
8379
+ } catch {
8380
+ }
8381
+ const proposedEntity = existing ? deepMergeEntities(existing, proposedPayload) : proposedPayload;
7619
8382
  const valResult = await validateEntityQuotas(strapi, uid, proposedEntity, activeRules);
7620
8383
  if (!valResult.isValid) {
7621
8384
  errors2.push({
@@ -7701,12 +8464,18 @@ const csvService = ({ strapi }) => ({
7701
8464
  });
7702
8465
  continue;
7703
8466
  }
7704
- const payload2 = parseRowToPayload(strapi, attrs, row);
8467
+ const payload = await buildDocumentUpdatePayload(
8468
+ strapi,
8469
+ uid,
8470
+ existing,
8471
+ row,
8472
+ {}
8473
+ );
7705
8474
  if (existing) {
7706
8475
  const resolvedDocId = existing.documentId || docId;
7707
8476
  const entryLabel = existing.title || existing.name || existing.slug || `Entry #${resolvedDocId}`;
7708
8477
  let rowHasChanges = false;
7709
- const payloadKeys = Object.keys(payload2);
8478
+ const payloadKeys = Object.keys(payload);
7710
8479
  if (payloadKeys.length === 0) {
7711
8480
  unchangedCount++;
7712
8481
  diffs.push({
@@ -7727,7 +8496,7 @@ const csvService = ({ strapi }) => ({
7727
8496
  } else {
7728
8497
  for (const attrKey of payloadKeys) {
7729
8498
  const oldVal = existing?.[attrKey] ?? null;
7730
- let newVal = payload2[attrKey];
8499
+ let newVal = payload[attrKey];
7731
8500
  if (attrs[attrKey]?.type === "component" && typeof newVal === "object" && newVal !== null) {
7732
8501
  newVal = deepMergeComponent(existing[attrKey], newVal);
7733
8502
  }
@@ -7762,8 +8531,8 @@ const csvService = ({ strapi }) => ({
7762
8531
  } else {
7763
8532
  willCreateCount++;
7764
8533
  const resolvedDocId = docId || `(Auto-generated)`;
7765
- const entryLabel = payload2.title || payload2.name || payload2.slug || `New Entry (Row #${rowNumber})`;
7766
- const payloadKeys = Object.keys(payload2);
8534
+ const entryLabel = payload.title || payload.name || payload.slug || `New Entry (Row #${rowNumber})`;
8535
+ const payloadKeys = Object.keys(payload);
7767
8536
  if (payloadKeys.length === 0) {
7768
8537
  diffs.push({
7769
8538
  uid,
@@ -7782,7 +8551,7 @@ const csvService = ({ strapi }) => ({
7782
8551
  });
7783
8552
  } else {
7784
8553
  for (const attrKey of payloadKeys) {
7785
- const newVal = payload2[attrKey];
8554
+ const newVal = payload[attrKey];
7786
8555
  diffs.push({
7787
8556
  uid,
7788
8557
  collectionName: ct.info?.displayName || uid,
@@ -8136,7 +8905,7 @@ const index = {
8136
8905
  if (context.uid && docId) {
8137
8906
  try {
8138
8907
  const ct = strapi.contentTypes[context.uid];
8139
- const populateDef = ct?.attributes ? buildDeepPopulate$1(ct.attributes, strapi.components) : void 0;
8908
+ const populateDef = ct?.attributes ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
8140
8909
  const existing = await strapi.documents(context.uid).findOne({
8141
8910
  documentId: docId,
8142
8911
  ...params?.locale ? { locale: params.locale } : {},
@@ -8280,6 +9049,35 @@ const index = {
8280
9049
  }
8281
9050
  };
8282
9051
  export {
8283
- index as default
9052
+ CURRENT_SCHEMA_VERSION,
9053
+ METADATA_COLUMN_KEY,
9054
+ SYSTEM_ATTRIBUTES,
9055
+ buildCollectionQueryFilters,
9056
+ buildDocumentUpdatePayload,
9057
+ buildLosslessPopulate,
9058
+ classifyAttribute,
9059
+ deepMergeEntities,
9060
+ index as default,
9061
+ discoverComponentFields,
9062
+ discoverSchema,
9063
+ escapeCsvCell,
9064
+ extractHeadingsFromRichText,
9065
+ extractMetadataFromRow,
9066
+ getAllNestedValues,
9067
+ isValidDocumentId,
9068
+ parseBoolean,
9069
+ parseCsvToMatrix,
9070
+ parseCsvToRecords,
9071
+ parseNumeric,
9072
+ resolveComponentPayload,
9073
+ resolveDynamicZonePayload,
9074
+ resolveMediaIds,
9075
+ resolveRelationPayload,
9076
+ serializeDocumentsToCsv,
9077
+ serializeFieldValue,
9078
+ sortAuditRecordsDesc,
9079
+ validateEntityQuotas,
9080
+ verifyDocumentIntegrity,
9081
+ withRollbackLock
8284
9082
  };
8285
9083
  //# sourceMappingURL=index.mjs.map