strapi-plugin-bulk-updater 1.5.11 → 1.5.13

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.
@@ -957,331 +957,931 @@ const contentHistoryService = {
957
957
  recordContentHistoryVersion,
958
958
  recordContentHistoryVersionsBatch
959
959
  };
960
- const queryCache = /* @__PURE__ */ new Map();
961
- const modelsCache = /* @__PURE__ */ new Map();
962
- const MAX_QUERY_CACHE_SIZE = 500;
963
- const CACHE_TTL_MS = 60 * 1e3;
964
- let staticSchemaCache = null;
965
- function formatEntryRecord(entry) {
966
- if (!entry || typeof entry !== "object") return entry;
967
- const formatted = {
968
- id: entry.id,
969
- documentId: entry.documentId,
970
- status: entry.status !== void 0 ? entry.status : void 0,
971
- ...entry
972
- };
973
- if (entry.updatedAt !== void 0 && formatted.updated_at === void 0) {
974
- formatted.updated_at = entry.updatedAt;
960
+ const DEFAULT_RULES = [
961
+ {
962
+ id: "rule_seo_heading_h1",
963
+ name: "SEO Single H1 Page Rule",
964
+ description: "Enforces that only one H1 heading tag can be selected across all dynamic zone heading blocks within an entry, combined with rich text HTML.",
965
+ collectionUid: "*",
966
+ targetField: "headingLevel",
967
+ quotas: {
968
+ h1: 1,
969
+ h2: 3
970
+ },
971
+ exceededAction: "disable",
972
+ enabled: true,
973
+ scope: "entry",
974
+ includeRichTextHtml: true,
975
+ richTextFields: [],
976
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
977
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
975
978
  }
976
- if (entry.updated_at !== void 0 && formatted.updatedAt === void 0) {
977
- formatted.updatedAt = entry.updated_at;
979
+ ];
980
+ function extractHeadingsFromRichText(content) {
981
+ const counts = { h1: 0, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 };
982
+ if (!content) return counts;
983
+ if (Array.isArray(content)) {
984
+ for (const node of content) {
985
+ if (node && typeof node === "object") {
986
+ if (node.type === "heading" && typeof node.level === "number") {
987
+ const tag = `h${node.level}`;
988
+ if (counts[tag] !== void 0) counts[tag]++;
989
+ }
990
+ if (Array.isArray(node.children)) {
991
+ const sub = extractHeadingsFromRichText(node.children);
992
+ for (const k of Object.keys(counts)) counts[k] += sub[k];
993
+ }
994
+ }
995
+ }
996
+ return counts;
978
997
  }
979
- if (entry.createdAt !== void 0 && formatted.created_at === void 0) {
980
- formatted.created_at = entry.createdAt;
998
+ if (typeof content === "string") {
999
+ for (let level = 1; level <= 6; level++) {
1000
+ const tag = `h${level}`;
1001
+ const htmlMatches = content.match(new RegExp(`<${tag}\\b[^>]*>`, "gi"));
1002
+ if (htmlMatches) {
1003
+ counts[tag] += htmlMatches.length;
1004
+ }
1005
+ const mdRegex = new RegExp(`(?:^|\\n)${"#".repeat(level)}\\s+[^\\n]+`, "g");
1006
+ const mdMatches = content.match(mdRegex);
1007
+ if (mdMatches) {
1008
+ counts[tag] += mdMatches.length;
1009
+ }
1010
+ }
981
1011
  }
982
- if (entry.created_at !== void 0 && formatted.createdAt === void 0) {
983
- formatted.createdAt = entry.created_at;
1012
+ return counts;
1013
+ }
1014
+ function cleanKey(str) {
1015
+ return (str || "").replace(/[-_]/g, "").toLowerCase().trim();
1016
+ }
1017
+ function matchesPath(normalizedPath, leafKey, targetField) {
1018
+ if (!targetField) return false;
1019
+ const pClean = cleanKey(normalizedPath);
1020
+ const kClean = cleanKey(leafKey);
1021
+ const tClean = cleanKey(targetField);
1022
+ if (kClean === tClean || pClean === tClean) return true;
1023
+ const targetSegments = targetField.replace(/^api::/i, "").split(".").map(cleanKey).filter(Boolean);
1024
+ const pathSegments = normalizedPath.split(".").map(cleanKey).filter(Boolean);
1025
+ if (targetSegments.length === 0 || pathSegments.length === 0) return false;
1026
+ if (targetSegments.length === 1) {
1027
+ const single = targetSegments[0];
1028
+ return kClean === single || pathSegments[pathSegments.length - 1] === single;
984
1029
  }
985
- if (entry.publishedAt !== void 0 && formatted.published_at === void 0) {
986
- formatted.published_at = entry.publishedAt;
1030
+ let isSuffix = true;
1031
+ for (let i = 0; i < targetSegments.length; i++) {
1032
+ const tSeg = targetSegments[targetSegments.length - 1 - i];
1033
+ const pSeg = pathSegments[pathSegments.length - 1 - i];
1034
+ if (tSeg !== "*" && tSeg !== pSeg) {
1035
+ isSuffix = false;
1036
+ break;
1037
+ }
987
1038
  }
988
- if (entry.published_at !== void 0 && formatted.publishedAt === void 0) {
989
- formatted.publishedAt = entry.published_at;
1039
+ if (isSuffix) return true;
1040
+ for (let startIdx = 1; startIdx < targetSegments.length; startIdx++) {
1041
+ const subTarget = targetSegments.slice(startIdx);
1042
+ if (subTarget.length > pathSegments.length) continue;
1043
+ let subSuffix = true;
1044
+ for (let i = 0; i < subTarget.length; i++) {
1045
+ const tSeg = subTarget[subTarget.length - 1 - i];
1046
+ const pSeg = pathSegments[pathSegments.length - 1 - i];
1047
+ if (tSeg !== "*" && tSeg !== pSeg) {
1048
+ subSuffix = false;
1049
+ break;
1050
+ }
1051
+ }
1052
+ if (subSuffix) return true;
990
1053
  }
991
- return formatted;
992
- }
993
- function isRowInEditingStage$1(row) {
994
- if (!row || typeof row !== "object") return false;
995
- const candidates = [
996
- row.strapi_stage,
997
- row["strapi_stage"],
998
- row.strapiStage,
999
- row["Strapi Stage"],
1000
- row["strapi-stage"],
1001
- row.stage,
1002
- row.Stage,
1003
- row.review_stage,
1004
- row.workflow_stage
1005
- ];
1006
- if (row.status && typeof row.status === "string") {
1007
- const s = row.status.trim().toLowerCase();
1008
- if (s === "editing" || s === "in review" || s === "in_review" || s === "pending review" || s === "pending_review") {
1009
- candidates.push(row.status);
1054
+ let pIdx = 0;
1055
+ let matchesInOrder = true;
1056
+ let tStart = 0;
1057
+ if (targetSegments.length > 2 && targetSegments[0] !== pathSegments[0] && targetSegments[0] !== "*") {
1058
+ tStart = 1;
1059
+ }
1060
+ for (let tIdx = tStart; tIdx < targetSegments.length; tIdx++) {
1061
+ const tSeg = targetSegments[tIdx];
1062
+ if (tSeg === "*") continue;
1063
+ let found = false;
1064
+ while (pIdx < pathSegments.length) {
1065
+ if (pathSegments[pIdx] === tSeg) {
1066
+ found = true;
1067
+ pIdx++;
1068
+ break;
1069
+ }
1070
+ pIdx++;
1071
+ }
1072
+ if (!found) {
1073
+ matchesInOrder = false;
1074
+ break;
1010
1075
  }
1011
1076
  }
1012
- for (const c of candidates) {
1013
- if (c !== void 0 && c !== null) {
1014
- let stageName = "";
1015
- if (typeof c === "object") {
1016
- stageName = String(c.name || c.title || c.status || c.documentId || c.id || "").trim();
1017
- } else if (typeof c === "string") {
1018
- const trimmed = c.trim();
1019
- if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
1020
- try {
1021
- const parsed = JSON.parse(trimmed);
1022
- if (typeof parsed === "object" && parsed !== null) {
1023
- stageName = String(parsed.name || parsed.title || parsed.status || parsed.documentId || parsed.id || "").trim();
1024
- }
1025
- } catch {
1026
- }
1027
- }
1028
- if (!stageName) {
1029
- stageName = trimmed;
1030
- }
1077
+ return matchesInOrder;
1078
+ }
1079
+ function deepMergeEntities(target, source) {
1080
+ if (!target || typeof target !== "object") {
1081
+ return source;
1082
+ }
1083
+ if (!source || typeof source !== "object") {
1084
+ return source !== void 0 ? source : target;
1085
+ }
1086
+ if (Array.isArray(source) || Array.isArray(target)) {
1087
+ return source;
1088
+ }
1089
+ const result = { ...target };
1090
+ for (const key of Object.keys(source)) {
1091
+ const sVal = source[key];
1092
+ const tVal = target[key];
1093
+ if (sVal === void 0) continue;
1094
+ if (sVal !== null && typeof sVal === "object" && !Array.isArray(sVal)) {
1095
+ if (tVal !== null && typeof tVal === "object" && !Array.isArray(tVal)) {
1096
+ result[key] = deepMergeEntities(tVal, sVal);
1031
1097
  } else {
1032
- stageName = String(c).trim();
1098
+ result[key] = sVal;
1033
1099
  }
1034
- if (stageName) {
1035
- const s = stageName.toLowerCase();
1036
- if (s === "editing" || s === "in review" || s === "in_review" || s === "pending review" || s === "pending_review") {
1037
- return true;
1100
+ } else {
1101
+ result[key] = sVal;
1102
+ }
1103
+ }
1104
+ return result;
1105
+ }
1106
+ function filterAndEnrichRules(strapi, collectionUid, activeRules) {
1107
+ const effectiveRules = [
1108
+ ...(activeRules || []).filter((r) => {
1109
+ if (!r.collectionUid || r.collectionUid === "*") return true;
1110
+ if (r.collectionUid === collectionUid) return true;
1111
+ const cleanRuleCol = cleanKey(r.collectionUid);
1112
+ const cleanCtxCol = cleanKey(collectionUid);
1113
+ return cleanCtxCol.includes(cleanRuleCol) || cleanRuleCol.includes(cleanCtxCol);
1114
+ }).map((r) => ({
1115
+ id: r.id || r.targetField,
1116
+ name: r.name || r.targetField,
1117
+ collectionUid: r.collectionUid || "*",
1118
+ targetField: r.targetField,
1119
+ quotas: r.quotas || {},
1120
+ includeRichTextHtml: Boolean(r.includeRichTextHtml),
1121
+ richTextFields: Array.isArray(r.richTextFields) ? r.richTextFields : []
1122
+ }))
1123
+ ];
1124
+ const allComponents = strapi?.components || {};
1125
+ const ct = strapi?.contentTypes?.[collectionUid];
1126
+ const schemasToInspect = [
1127
+ ...Object.values(allComponents),
1128
+ ...ct ? [ct] : []
1129
+ ];
1130
+ for (const schema of schemasToInspect) {
1131
+ const attrs = schema?.attributes || {};
1132
+ for (const [attrName, attrDef] of Object.entries(attrs)) {
1133
+ if (attrDef.type === "customField" && (attrDef.customField === "plugin::bulk-updater.scoped-select" || attrDef.customField === "global::scoped-select") && !effectiveRules.some((r) => matchesPath(attrName, attrName, r.targetField))) {
1134
+ const quotas = attrDef.options?.quotas || {};
1135
+ const items = attrDef.options?.items || [];
1136
+ const itemQuotas = {};
1137
+ for (const item of items) {
1138
+ if (typeof item.maxAllowed === "number" && item.maxAllowed > 0) {
1139
+ itemQuotas[item.value] = item.maxAllowed;
1140
+ }
1038
1141
  }
1142
+ effectiveRules.push({
1143
+ id: `schema_${attrName}`,
1144
+ name: `${attrName} quota rule`,
1145
+ collectionUid: "*",
1146
+ targetField: attrName,
1147
+ quotas: {
1148
+ h1: 1,
1149
+ h2: 3,
1150
+ ...itemQuotas,
1151
+ ...quotas
1152
+ },
1153
+ includeRichTextHtml: true,
1154
+ richTextFields: []
1155
+ });
1039
1156
  }
1040
1157
  }
1041
1158
  }
1042
- return false;
1159
+ return effectiveRules;
1043
1160
  }
1044
- function resolveRecordPublicationStatus(entry, publishedRecord, isDraftAndPublish) {
1045
- if (isDraftAndPublish === false) {
1046
- return { status: "published", hadPublishedVersion: true };
1047
- }
1048
- if (!entry || typeof entry !== "object") {
1049
- return { status: "unknown", hadPublishedVersion: false };
1161
+ async function validateEntityQuotas(strapi, collectionUid, entity, customRules) {
1162
+ if (!entity || typeof entity !== "object") {
1163
+ return { isValid: true };
1050
1164
  }
1051
- if (typeof entry.status === "string" && entry.status.trim()) {
1052
- const s = entry.status.trim().toLowerCase();
1053
- if (s === "published") {
1054
- return { status: "published", hadPublishedVersion: true };
1055
- }
1056
- if (s === "modified") {
1057
- return { status: "modified", hadPublishedVersion: true };
1058
- }
1059
- if (s === "draft") {
1060
- return { status: "draft", hadPublishedVersion: false };
1165
+ let effectiveRules = [];
1166
+ if (customRules && Array.isArray(customRules)) {
1167
+ effectiveRules = customRules;
1168
+ } else {
1169
+ try {
1170
+ const rulesService = strapi.plugin("bulk-updater").service("validationRules");
1171
+ if (rulesService) {
1172
+ const allRules = await rulesService.getRules();
1173
+ const activeUiRules = (allRules || []).filter((r) => r.enabled);
1174
+ effectiveRules = filterAndEnrichRules(strapi, collectionUid, activeUiRules);
1175
+ }
1176
+ } catch (err) {
1177
+ strapi.log?.warn?.("[bulk-updater] Failed to fetch validation rules for quota check:", err);
1061
1178
  }
1062
1179
  }
1063
- const pub = publishedRecord || (entry.publishedAt ? entry : null);
1064
- if (!pub) {
1065
- return { status: "draft", hadPublishedVersion: false };
1180
+ if (effectiveRules.length === 0) {
1181
+ return { isValid: true };
1066
1182
  }
1067
- const draftUpdatedTime = new Date(entry.updatedAt || entry.updated_at || 0).getTime();
1068
- const pubUpdatedTime = new Date(pub.updatedAt || pub.updated_at || 0).getTime();
1069
- const pubPublishedTime = new Date(pub.publishedAt || pub.published_at || 0).getTime();
1070
- const lastPublishedTime = Math.max(
1071
- isNaN(pubUpdatedTime) ? 0 : pubUpdatedTime,
1072
- isNaN(pubPublishedTime) ? 0 : pubPublishedTime
1073
- );
1074
- if (isNaN(draftUpdatedTime) || lastPublishedTime === 0) {
1075
- if (pub.publishedAt || pub.published_at) {
1076
- return { status: "published", hadPublishedVersion: true };
1183
+ const structuredCounts = {};
1184
+ const richTextCounts = {};
1185
+ for (const rule of effectiveRules) {
1186
+ structuredCounts[rule.id] = {};
1187
+ richTextCounts[rule.id] = { h1: 0, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 };
1188
+ }
1189
+ function scanDataTree(obj, currentPath = "", depth = 0) {
1190
+ if (!obj || typeof obj !== "object" || depth > 20) return;
1191
+ const compName = typeof obj.__component === "string" ? obj.__component : "";
1192
+ if (Array.isArray(obj)) {
1193
+ for (let i = 0; i < obj.length; i++) {
1194
+ const item = obj[i];
1195
+ if (item && typeof item === "object") {
1196
+ scanDataTree(item, currentPath ? `${currentPath}.${i}` : `${i}`, depth + 1);
1197
+ }
1198
+ }
1199
+ return;
1200
+ }
1201
+ for (const key of Object.keys(obj)) {
1202
+ if (key === "__component") continue;
1203
+ const val = obj[key];
1204
+ const newPath = currentPath ? `${currentPath}.${key}` : key;
1205
+ const normalizedPath = newPath.replace(/\.\d+/g, "");
1206
+ const compPath = compName ? (currentPath ? `${currentPath}.${compName}.${key}` : `${compName}.${key}`).replace(/\.\d+/g, "") : "";
1207
+ for (const rule of effectiveRules) {
1208
+ const isMatch = matchesPath(normalizedPath, key, rule.targetField) || (compPath ? matchesPath(compPath, key, rule.targetField) : false);
1209
+ if (isMatch && (typeof val === "string" || typeof val === "number") && String(val).trim()) {
1210
+ const lowerVal = String(val).toLowerCase().trim();
1211
+ structuredCounts[rule.id][lowerVal] = (structuredCounts[rule.id][lowerVal] || 0) + 1;
1212
+ }
1213
+ }
1214
+ const isRichTextString = typeof val === "string" && (/<h[1-6]\b/i.test(val) || val.includes("#"));
1215
+ const isBlocksArray = Array.isArray(val) && val.length > 0 && typeof val[0] === "object" && val[0]?.type;
1216
+ if (isRichTextString || isBlocksArray) {
1217
+ const headings = extractHeadingsFromRichText(val);
1218
+ for (const rule of effectiveRules) {
1219
+ if (!rule.includeRichTextHtml) continue;
1220
+ if (Array.isArray(rule.richTextFields) && rule.richTextFields.length > 0) {
1221
+ const matchesSpecificField = rule.richTextFields.some(
1222
+ (rf) => matchesPath(normalizedPath, key, rf) || (compPath ? matchesPath(compPath, key, rf) : false)
1223
+ );
1224
+ if (!matchesSpecificField) continue;
1225
+ }
1226
+ for (const [tag, count] of Object.entries(headings)) {
1227
+ if (count > 0) {
1228
+ richTextCounts[rule.id][tag] = (richTextCounts[rule.id][tag] || 0) + count;
1229
+ }
1230
+ }
1231
+ }
1232
+ if (isBlocksArray) {
1233
+ continue;
1234
+ }
1235
+ }
1236
+ if (typeof val === "object" && val !== null) {
1237
+ scanDataTree(val, newPath, depth + 1);
1238
+ }
1077
1239
  }
1078
- return { status: "unknown", hadPublishedVersion: false };
1079
1240
  }
1080
- if (draftUpdatedTime > lastPublishedTime) {
1081
- return { status: "modified", hadPublishedVersion: true };
1241
+ scanDataTree(entity);
1242
+ for (const rule of effectiveRules) {
1243
+ const ruleCounts = structuredCounts[rule.id] || {};
1244
+ const rtRuleCounts = richTextCounts[rule.id] || {};
1245
+ for (const [quotaKey, maxAllowed] of Object.entries(rule.quotas || {})) {
1246
+ const lowerVal = quotaKey.toLowerCase().trim();
1247
+ const structCount = ruleCounts[lowerVal] || 0;
1248
+ const rtCount = rule.includeRichTextHtml ? rtRuleCounts[lowerVal] || 0 : 0;
1249
+ const totalFound = structCount + rtCount;
1250
+ if (totalFound > maxAllowed) {
1251
+ let detailMsg = `Option "${quotaKey.toUpperCase()}" cannot appear more than ${maxAllowed} time(s) across this entry.`;
1252
+ if (rtCount > 0 && structCount > 0) {
1253
+ detailMsg += ` Found ${totalFound} occurrences combined: ${structCount} in structured component ('${rule.targetField}') and ${rtCount} in rich text HTML / Markdown.`;
1254
+ } else if (rtCount > 0) {
1255
+ detailMsg += ` Found ${totalFound} in rich text HTML / Markdown content.`;
1256
+ } else {
1257
+ detailMsg += ` Found ${totalFound} in structured field '${rule.targetField}'.`;
1258
+ }
1259
+ const fullErrorMessage = `Validation Error (${rule.name}): ${detailMsg}`;
1260
+ return {
1261
+ isValid: false,
1262
+ ruleId: rule.id,
1263
+ ruleName: rule.name,
1264
+ targetField: rule.targetField,
1265
+ violatingOption: quotaKey.toUpperCase(),
1266
+ foundCount: totalFound,
1267
+ maxAllowed,
1268
+ structuredCount: structCount,
1269
+ richTextCount: rtCount,
1270
+ errorMessage: fullErrorMessage
1271
+ };
1272
+ }
1273
+ }
1082
1274
  }
1083
- return { status: "published", hadPublishedVersion: true };
1275
+ return { isValid: true };
1084
1276
  }
1085
- function evaluateShouldPublish({
1086
- isDraftAndPublish,
1087
- hadPublishedVersion,
1088
- isEditing,
1089
- publishOnApproval = true,
1090
- publishStrategy = "safe",
1091
- unreviewedConsent = false
1092
- }) {
1093
- if (!isDraftAndPublish) return false;
1094
- if (!hadPublishedVersion) return false;
1095
- if (!publishOnApproval) return false;
1096
- if (isEditing) return false;
1097
- return true;
1098
- }
1099
- async function populateDocumentLifecycleStatus(strapi, uid, entries) {
1100
- if (!entries || !Array.isArray(entries) || entries.length === 0) {
1101
- return entries;
1102
- }
1103
- const contentType = strapi?.contentTypes?.[uid];
1104
- if (!contentType) {
1105
- return entries;
1106
- }
1107
- const hasDraftAndPublish = Boolean(contentType.options?.draftAndPublish);
1108
- if (!hasDraftAndPublish) {
1109
- for (const entry of entries) {
1110
- if (entry && typeof entry === "object") {
1111
- entry.status = "published";
1112
- }
1277
+ const validationRulesService = ({ strapi }) => ({
1278
+ async getStore() {
1279
+ return strapi.store({
1280
+ type: "plugin",
1281
+ name: "bulk-updater",
1282
+ key: "validation-rules"
1283
+ });
1284
+ },
1285
+ async getRules() {
1286
+ const store = await this.getStore();
1287
+ const stored = await store.get({});
1288
+ if (!stored || !Array.isArray(stored.rules)) {
1289
+ await store.set({ value: { rules: DEFAULT_RULES } });
1290
+ return DEFAULT_RULES;
1113
1291
  }
1114
- return entries;
1115
- }
1116
- const hasSlugInSchema = Boolean(contentType.attributes?.slug);
1117
- const docIds = [];
1118
- const slugs = [];
1119
- for (const entry of entries) {
1120
- if (!entry || typeof entry !== "object") continue;
1121
- if (entry.documentId) {
1122
- docIds.push(String(entry.documentId));
1123
- } else if (hasSlugInSchema && entry.slug) {
1124
- slugs.push(String(entry.slug));
1292
+ return stored.rules;
1293
+ },
1294
+ async saveRule(ruleData) {
1295
+ const store = await this.getStore();
1296
+ const rules = await this.getRules();
1297
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1298
+ let savedRule;
1299
+ if (ruleData.id) {
1300
+ const index2 = rules.findIndex((r) => r.id === ruleData.id);
1301
+ if (index2 !== -1) {
1302
+ savedRule = {
1303
+ ...rules[index2],
1304
+ ...ruleData,
1305
+ collectionUid: ruleData.collectionUid !== void 0 ? ruleData.collectionUid : rules[index2].collectionUid || "*",
1306
+ includeRichTextHtml: ruleData.includeRichTextHtml !== void 0 ? Boolean(ruleData.includeRichTextHtml) : Boolean(rules[index2].includeRichTextHtml),
1307
+ richTextFields: Array.isArray(ruleData.richTextFields) ? ruleData.richTextFields : rules[index2].richTextFields || [],
1308
+ updatedAt: now
1309
+ };
1310
+ rules[index2] = savedRule;
1311
+ } else {
1312
+ savedRule = {
1313
+ id: ruleData.id,
1314
+ name: ruleData.name || "New Rule",
1315
+ description: ruleData.description || "",
1316
+ collectionUid: ruleData.collectionUid || "*",
1317
+ targetField: ruleData.targetField || "headingLevel",
1318
+ quotas: ruleData.quotas || { h1: 1 },
1319
+ exceededAction: ruleData.exceededAction || "disable",
1320
+ enabled: ruleData.enabled ?? true,
1321
+ scope: ruleData.scope || "entry",
1322
+ includeRichTextHtml: Boolean(ruleData.includeRichTextHtml),
1323
+ richTextFields: Array.isArray(ruleData.richTextFields) ? ruleData.richTextFields : [],
1324
+ createdAt: now,
1325
+ updatedAt: now
1326
+ };
1327
+ rules.push(savedRule);
1328
+ }
1125
1329
  } else {
1126
- entry.status = "unknown";
1330
+ const id = `rule_${Date.now()}_${Math.random().toString(36).substring(2, 6)}`;
1331
+ savedRule = {
1332
+ id,
1333
+ name: ruleData.name || "Custom Quota Rule",
1334
+ description: ruleData.description || "",
1335
+ collectionUid: ruleData.collectionUid || "*",
1336
+ targetField: ruleData.targetField || "headingLevel",
1337
+ quotas: ruleData.quotas || { h1: 1 },
1338
+ exceededAction: ruleData.exceededAction || "disable",
1339
+ enabled: ruleData.enabled ?? true,
1340
+ scope: ruleData.scope || "entry",
1341
+ includeRichTextHtml: Boolean(ruleData.includeRichTextHtml),
1342
+ richTextFields: Array.isArray(ruleData.richTextFields) ? ruleData.richTextFields : [],
1343
+ createdAt: now,
1344
+ updatedAt: now
1345
+ };
1346
+ rules.push(savedRule);
1127
1347
  }
1128
- }
1129
- if (docIds.length === 0 && slugs.length === 0) {
1130
- return entries;
1131
- }
1132
- let filterClause;
1133
- if (docIds.length > 0 && slugs.length > 0) {
1134
- filterClause = {
1135
- $or: [
1136
- { documentId: { $in: docIds } },
1137
- { slug: { $in: slugs } }
1138
- ]
1348
+ await store.set({ value: { rules } });
1349
+ return savedRule;
1350
+ },
1351
+ async deleteRule(ruleId) {
1352
+ const store = await this.getStore();
1353
+ const rules = await this.getRules();
1354
+ const filtered = rules.filter((r) => r.id !== ruleId);
1355
+ await store.set({ value: { rules: filtered } });
1356
+ return true;
1357
+ },
1358
+ async toggleRule(ruleId, enabled) {
1359
+ const store = await this.getStore();
1360
+ const rules = await this.getRules();
1361
+ const index2 = rules.findIndex((r) => r.id === ruleId);
1362
+ if (index2 === -1) return null;
1363
+ const current = rules[index2];
1364
+ const newEnabled = typeof enabled === "boolean" ? enabled : !current.enabled;
1365
+ const updated = {
1366
+ ...current,
1367
+ enabled: newEnabled,
1368
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1139
1369
  };
1140
- } else if (docIds.length > 0) {
1141
- filterClause = { documentId: { $in: docIds } };
1142
- } else {
1143
- filterClause = { slug: { $in: slugs } };
1144
- }
1145
- const queryFields = ["documentId", "updatedAt", "publishedAt"];
1146
- if (hasSlugInSchema) {
1147
- queryFields.push("slug");
1148
- }
1149
- let publishedRecords = [];
1150
- try {
1151
- const docService = strapi?.documents?.(uid);
1152
- if (docService?.findMany) {
1153
- publishedRecords = await docService.findMany({
1154
- status: "published",
1155
- filters: filterClause,
1156
- fields: queryFields,
1157
- limit: Math.max(entries.length, 100)
1158
- });
1370
+ rules[index2] = updated;
1371
+ await store.set({ value: { rules } });
1372
+ return updated;
1373
+ },
1374
+ async scanViolations(ruleId) {
1375
+ const rules = await this.getRules();
1376
+ const rule = rules.find((r) => r.id === ruleId);
1377
+ if (!rule) {
1378
+ throw new Error(`Validation rule ${ruleId} not found`);
1159
1379
  }
1160
- } catch (err) {
1161
- strapi?.log?.warn?.(`[bulk-updater] Failed to fetch published status for ${uid}: ${err?.message || err}`);
1162
- for (const entry of entries) {
1163
- if (entry && typeof entry === "object" && entry.status !== "unknown") {
1164
- entry.status = "unknown";
1380
+ const targetField = rule.targetField;
1381
+ const quotas = rule.quotas || {};
1382
+ const violations = [];
1383
+ let totalScanned = 0;
1384
+ const allContentTypes = strapi.contentTypes || {};
1385
+ const allComponents = strapi.components || {};
1386
+ function componentHasField(compUid, targetField2) {
1387
+ const comp = allComponents[compUid];
1388
+ if (!comp?.attributes) return false;
1389
+ if (matchesPath(compUid, compUid, targetField2)) return true;
1390
+ for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
1391
+ if (matchesPath(attrName, attrName, targetField2) || matchesPath(`${compUid}.${attrName}`, attrName, targetField2)) return true;
1392
+ if (attrDef.type === "component" && attrDef.component) {
1393
+ if (componentHasField(attrDef.component, targetField2)) return true;
1394
+ } else if (attrDef.type === "dynamiczone" && Array.isArray(attrDef.components)) {
1395
+ if (attrDef.components.some((c) => componentHasField(c, targetField2))) return true;
1396
+ }
1165
1397
  }
1398
+ return false;
1166
1399
  }
1167
- return entries;
1168
- }
1169
- const publishedByDocId = /* @__PURE__ */ new Map();
1170
- const publishedBySlug = /* @__PURE__ */ new Map();
1171
- for (const pub of publishedRecords || []) {
1172
- if (pub?.documentId) {
1173
- publishedByDocId.set(String(pub.documentId), pub);
1174
- }
1175
- if (pub?.slug && hasSlugInSchema) {
1176
- publishedBySlug.set(String(pub.slug), pub);
1177
- }
1178
- }
1179
- for (const entry of entries) {
1180
- if (!entry || typeof entry !== "object") continue;
1181
- if (entry.status === "unknown") continue;
1182
- const pub = entry.documentId && publishedByDocId.get(String(entry.documentId)) || hasSlugInSchema && entry.slug && publishedBySlug.get(String(entry.slug));
1183
- if (!pub) {
1184
- entry.status = "draft";
1185
- entry.publishedAt = null;
1186
- entry.published_at = null;
1187
- } else {
1188
- entry.publishedAt = pub.publishedAt || pub.published_at || null;
1189
- entry.published_at = entry.publishedAt;
1190
- const draftUpdatedTime = new Date(entry.updatedAt || entry.updated_at || 0).getTime();
1191
- const pubUpdatedTime = new Date(pub.updatedAt || pub.updated_at || 0).getTime();
1192
- const pubPublishedTime = new Date(pub.publishedAt || pub.published_at || 0).getTime();
1193
- const lastPublishedTime = Math.max(
1194
- isNaN(pubUpdatedTime) ? 0 : pubUpdatedTime,
1195
- isNaN(pubPublishedTime) ? 0 : pubPublishedTime
1196
- );
1197
- if (isNaN(draftUpdatedTime) || lastPublishedTime === 0) {
1198
- if (pub.publishedAt) {
1199
- entry.status = "published";
1200
- } else {
1201
- entry.status = "unknown";
1400
+ function schemaHasField(ctSchema) {
1401
+ if (!ctSchema || !ctSchema.attributes) return { hasField: false, populateAttrs: {} };
1402
+ const rawAttrs = ctSchema.attributes;
1403
+ const populateAttrs = {};
1404
+ let hasField = false;
1405
+ for (const [attrKey, attrDef] of Object.entries(rawAttrs)) {
1406
+ if (matchesPath(attrKey, attrKey, targetField)) {
1407
+ hasField = true;
1408
+ }
1409
+ if (attrDef.type === "component" && attrDef.component) {
1410
+ if (componentHasField(attrDef.component, targetField)) {
1411
+ hasField = true;
1412
+ populateAttrs[attrKey] = { populate: "*" };
1413
+ }
1414
+ } else if (attrDef.type === "dynamiczone" && Array.isArray(attrDef.components)) {
1415
+ const matchingComp = attrDef.components.some(
1416
+ (compUid) => componentHasField(compUid, targetField) || matchesPath(`${attrKey}.${compUid}`, compUid, targetField)
1417
+ );
1418
+ if (matchingComp) {
1419
+ hasField = true;
1420
+ populateAttrs[attrKey] = { populate: "*" };
1421
+ }
1202
1422
  }
1203
- } else if (draftUpdatedTime > lastPublishedTime) {
1204
- entry.status = "modified";
1205
- } else {
1206
- entry.status = "published";
1207
1423
  }
1424
+ return { hasField, populateAttrs };
1208
1425
  }
1426
+ const candidateUids = Object.keys(allContentTypes).filter((uid) => {
1427
+ if (!uid.startsWith("api::") || uid.includes("bulk-updater")) return false;
1428
+ if (rule.collectionUid && rule.collectionUid !== "*") {
1429
+ if (rule.collectionUid === uid) return true;
1430
+ const cleanRuleCol = cleanKey(rule.collectionUid);
1431
+ const cleanUid = cleanKey(uid);
1432
+ if (cleanUid.includes(cleanRuleCol) || cleanRuleCol.includes(cleanUid)) return true;
1433
+ return false;
1434
+ }
1435
+ return true;
1436
+ });
1437
+ const relevantCollections = [];
1438
+ for (const uid of candidateUids) {
1439
+ const ct = allContentTypes[uid];
1440
+ if (!ct) continue;
1441
+ const { hasField, populateAttrs } = schemaHasField(ct);
1442
+ const isTargetCol = rule.collectionUid && (rule.collectionUid === uid || cleanKey(uid).includes(cleanKey(rule.collectionUid)));
1443
+ if (hasField || isTargetCol) {
1444
+ relevantCollections.push({
1445
+ uid,
1446
+ displayName: ct.info?.displayName || uid,
1447
+ populateOption: Object.keys(populateAttrs).length > 0 ? populateAttrs : "*"
1448
+ });
1449
+ }
1450
+ }
1451
+ const BATCH_SIZE = 250;
1452
+ await Promise.all(
1453
+ relevantCollections.map(async ({ uid, displayName, populateOption }) => {
1454
+ try {
1455
+ let page = 1;
1456
+ while (true) {
1457
+ const entries = await strapi.documents(uid).findMany({
1458
+ page,
1459
+ pageSize: BATCH_SIZE,
1460
+ populate: populateOption
1461
+ });
1462
+ if (!entries || entries.length === 0) break;
1463
+ for (const entry of entries) {
1464
+ let traverse = function(obj, currentPath = "") {
1465
+ if (!obj || typeof obj !== "object") return;
1466
+ const compName = typeof obj.__component === "string" ? obj.__component : "";
1467
+ for (const key of Object.keys(obj)) {
1468
+ if (key === "__component") continue;
1469
+ const val = obj[key];
1470
+ const newPath = currentPath ? `${currentPath}.${key}` : key;
1471
+ const normalizedPath = newPath.replace(/\.\d+/g, "");
1472
+ const compPath = compName ? (currentPath ? `${currentPath}.${compName}.${key}` : `${compName}.${key}`).replace(/\.\d+/g, "") : "";
1473
+ const isMatch = matchesPath(normalizedPath, key, targetField) || (compPath ? matchesPath(compPath, key, targetField) : false);
1474
+ if (isMatch && typeof val === "string" && val.trim()) {
1475
+ const lower = val.toLowerCase().trim();
1476
+ structuredCounts[lower] = (structuredCounts[lower] || 0) + 1;
1477
+ }
1478
+ if (rule.includeRichTextHtml) {
1479
+ if (typeof val === "string" && (val.includes("<h") || val.includes("#"))) {
1480
+ const headings = extractHeadingsFromRichText(val);
1481
+ for (const [tag, count] of Object.entries(headings)) {
1482
+ if (count > 0) {
1483
+ richTextCounts[tag] = (richTextCounts[tag] || 0) + count;
1484
+ }
1485
+ }
1486
+ } else if (Array.isArray(val) && val.length > 0 && typeof val[0] === "object" && val[0]?.type) {
1487
+ const headings = extractHeadingsFromRichText(val);
1488
+ for (const [tag, count] of Object.entries(headings)) {
1489
+ if (count > 0) {
1490
+ richTextCounts[tag] = (richTextCounts[tag] || 0) + count;
1491
+ }
1492
+ }
1493
+ continue;
1494
+ }
1495
+ }
1496
+ if (typeof val === "object" && val !== null) {
1497
+ traverse(val, newPath);
1498
+ }
1499
+ }
1500
+ };
1501
+ totalScanned++;
1502
+ const structuredCounts = {};
1503
+ const richTextCounts = { h1: 0, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 };
1504
+ traverse(entry);
1505
+ for (const [optKey, max] of Object.entries(quotas)) {
1506
+ const lowerOpt = optKey.toLowerCase().trim();
1507
+ const structCount = structuredCounts[lowerOpt] || 0;
1508
+ const rtCount = rule.includeRichTextHtml ? richTextCounts[lowerOpt] || 0 : 0;
1509
+ const combinedCount = structCount + rtCount;
1510
+ if (combinedCount > max) {
1511
+ const entryLabel = entry.title || entry.name || entry.email || `Entry #${entry.documentId}`;
1512
+ let detail = "";
1513
+ if (rtCount > 0 && structCount > 0) {
1514
+ detail = `${structCount} structured + ${rtCount} in rich text HTML`;
1515
+ } else if (rtCount > 0) {
1516
+ detail = `${rtCount} in rich text HTML / Markdown`;
1517
+ } else {
1518
+ detail = `${structCount} in structured component`;
1519
+ }
1520
+ violations.push({
1521
+ uid,
1522
+ collectionDisplayName: displayName,
1523
+ documentId: entry.documentId,
1524
+ entryLabel,
1525
+ violatingOption: optKey.toUpperCase(),
1526
+ foundCount: combinedCount,
1527
+ structuredCount: structCount,
1528
+ richTextCount: rtCount,
1529
+ maxAllowed: max,
1530
+ detail,
1531
+ editUrl: `/admin/content-manager/collection-types/${uid}/${entry.documentId}`
1532
+ });
1533
+ }
1534
+ }
1535
+ }
1536
+ if (entries.length < BATCH_SIZE) break;
1537
+ page++;
1538
+ }
1539
+ } catch (err) {
1540
+ strapi.log.warn(`[bulk-updater] Failed scanning ${uid} for rule ${ruleId}:`, err);
1541
+ }
1542
+ })
1543
+ );
1544
+ return {
1545
+ rule,
1546
+ totalScanned,
1547
+ totalViolations: violations.length,
1548
+ violations
1549
+ };
1550
+ },
1551
+ async getEffectiveRules(collectionUid) {
1552
+ const allRules = await this.getRules();
1553
+ const activeUiRules = (allRules || []).filter((r) => r.enabled);
1554
+ return filterAndEnrichRules(strapi, collectionUid, activeUiRules);
1555
+ },
1556
+ async validateEntity(entity, collectionUid, customRules) {
1557
+ return validateEntityQuotas(strapi, collectionUid, entity, customRules);
1209
1558
  }
1210
- return entries;
1211
- }
1212
- function resolveContentTypeField(contentType, field) {
1213
- if (!field) return null;
1214
- const attrs = contentType?.attributes || {};
1215
- if (attrs[field]) return field;
1216
- if (field === "updated_at" || field === "updatedAt") {
1217
- return attrs["updated_at"] ? "updated_at" : "updatedAt";
1218
- }
1219
- if (field === "created_at" || field === "createdAt") {
1220
- return attrs["created_at"] ? "created_at" : "createdAt";
1221
- }
1222
- if (field === "published_at" || field === "publishedAt") {
1223
- return attrs["published_at"] ? "published_at" : "publishedAt";
1559
+ });
1560
+ const queryCache = /* @__PURE__ */ new Map();
1561
+ const modelsCache = /* @__PURE__ */ new Map();
1562
+ const MAX_QUERY_CACHE_SIZE = 500;
1563
+ const CACHE_TTL_MS = 60 * 1e3;
1564
+ let staticSchemaCache = null;
1565
+ function formatEntryRecord(entry) {
1566
+ if (!entry || typeof entry !== "object") return entry;
1567
+ const formatted = {
1568
+ id: entry.id,
1569
+ documentId: entry.documentId,
1570
+ status: entry.status !== void 0 ? entry.status : void 0,
1571
+ ...entry
1572
+ };
1573
+ if (entry.updatedAt !== void 0 && formatted.updated_at === void 0) {
1574
+ formatted.updated_at = entry.updatedAt;
1224
1575
  }
1225
- if (field === "id" || field === "documentId") {
1226
- return field;
1576
+ if (entry.updated_at !== void 0 && formatted.updatedAt === void 0) {
1577
+ formatted.updatedAt = entry.updated_at;
1227
1578
  }
1228
- const camel = field.replace(/_([a-z0-9])/g, (_, l) => l.toUpperCase());
1229
- if (attrs[camel]) return camel;
1230
- const snake = field.replace(/([A-Z])/g, "_$1").toLowerCase();
1231
- if (attrs[snake]) return snake;
1232
- const lower = field.toLowerCase().replace(/_/g, "");
1233
- const matched = Object.keys(attrs).find(
1234
- (k) => k.toLowerCase().replace(/_/g, "") === lower
1235
- );
1236
- if (matched) return matched;
1237
- return null;
1579
+ if (entry.createdAt !== void 0 && formatted.created_at === void 0) {
1580
+ formatted.created_at = entry.createdAt;
1581
+ }
1582
+ if (entry.created_at !== void 0 && formatted.createdAt === void 0) {
1583
+ formatted.createdAt = entry.created_at;
1584
+ }
1585
+ if (entry.publishedAt !== void 0 && formatted.published_at === void 0) {
1586
+ formatted.published_at = entry.publishedAt;
1587
+ }
1588
+ if (entry.published_at !== void 0 && formatted.publishedAt === void 0) {
1589
+ formatted.publishedAt = entry.published_at;
1590
+ }
1591
+ return formatted;
1238
1592
  }
1239
- function buildDeepPopulate$1(attributes, allComponents, depth = 0) {
1240
- if (depth > 5) return void 0;
1241
- const populate = {};
1242
- for (const [key, def] of Object.entries(attributes || {})) {
1243
- if (def.type === "component" && def.component) {
1244
- const comp = allComponents[def.component];
1245
- if (comp?.attributes) {
1246
- const subPopulate = buildDeepPopulate$1(comp.attributes, allComponents, depth + 1);
1247
- if (subPopulate && Object.keys(subPopulate).length > 0) {
1248
- populate[key] = {
1249
- populate: subPopulate
1250
- };
1251
- } else {
1252
- populate[key] = true;
1593
+ function isRowInEditingStage$1(row) {
1594
+ if (!row || typeof row !== "object") return false;
1595
+ const candidates = [
1596
+ row.strapi_stage,
1597
+ row["strapi_stage"],
1598
+ row.strapiStage,
1599
+ row["Strapi Stage"],
1600
+ row["strapi-stage"],
1601
+ row.stage,
1602
+ row.Stage,
1603
+ row.review_stage,
1604
+ row.workflow_stage
1605
+ ];
1606
+ if (row.status && typeof row.status === "string") {
1607
+ const s = row.status.trim().toLowerCase();
1608
+ if (s === "editing" || s === "in review" || s === "in_review" || s === "pending review" || s === "pending_review") {
1609
+ candidates.push(row.status);
1610
+ }
1611
+ }
1612
+ for (const c of candidates) {
1613
+ if (c !== void 0 && c !== null) {
1614
+ let stageName = "";
1615
+ if (typeof c === "object") {
1616
+ stageName = String(c.name || c.title || c.status || c.documentId || c.id || "").trim();
1617
+ } else if (typeof c === "string") {
1618
+ const trimmed = c.trim();
1619
+ if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
1620
+ try {
1621
+ const parsed = JSON.parse(trimmed);
1622
+ if (typeof parsed === "object" && parsed !== null) {
1623
+ stageName = String(parsed.name || parsed.title || parsed.status || parsed.documentId || parsed.id || "").trim();
1624
+ }
1625
+ } catch {
1626
+ }
1627
+ }
1628
+ if (!stageName) {
1629
+ stageName = trimmed;
1253
1630
  }
1254
1631
  } else {
1255
- populate[key] = true;
1632
+ stageName = String(c).trim();
1633
+ }
1634
+ if (stageName) {
1635
+ const s = stageName.toLowerCase();
1636
+ if (s === "editing" || s === "in review" || s === "in_review" || s === "pending review" || s === "pending_review") {
1637
+ return true;
1638
+ }
1256
1639
  }
1257
- } else if (def.type === "dynamiczone") {
1258
- populate[key] = {
1259
- populate: "*"
1260
- };
1261
- } else if (def.type === "relation" || def.type === "media") {
1262
- populate[key] = true;
1263
1640
  }
1264
1641
  }
1265
- return Object.keys(populate).length > 0 ? populate : void 0;
1642
+ return false;
1266
1643
  }
1267
- function discoverComponentAttributes(strapi, compUid, prefix, currentDepth, maxDepth, systemFields, allContentTypes, relationsByAttr, allRelationsMeta, attributesMeta) {
1268
- if (currentDepth > maxDepth || !compUid) return [];
1269
- const compSchema = strapi.components[compUid];
1270
- if (!compSchema?.attributes) return [];
1271
- const discoveredAttrs = [];
1272
- for (const [subKey, subAttr] of Object.entries(compSchema.attributes)) {
1273
- if (systemFields.includes(subKey)) continue;
1274
- const fullPath = prefix ? `${prefix}.${subKey}` : subKey;
1275
- if (subAttr.type === "dynamiczone") {
1276
- const dzComps = Array.isArray(subAttr.components) ? subAttr.components : [];
1277
- for (const dzCompUid of dzComps) {
1278
- const deeper = discoverComponentAttributes(
1279
- strapi,
1280
- dzCompUid,
1281
- fullPath,
1282
- currentDepth + 1,
1283
- maxDepth,
1284
- systemFields,
1644
+ function resolveRecordPublicationStatus(entry, publishedRecord, isDraftAndPublish) {
1645
+ if (isDraftAndPublish === false) {
1646
+ return { status: "published", hadPublishedVersion: true };
1647
+ }
1648
+ if (!entry || typeof entry !== "object") {
1649
+ return { status: "unknown", hadPublishedVersion: false };
1650
+ }
1651
+ if (typeof entry.status === "string" && entry.status.trim()) {
1652
+ const s = entry.status.trim().toLowerCase();
1653
+ if (s === "published") {
1654
+ return { status: "published", hadPublishedVersion: true };
1655
+ }
1656
+ if (s === "modified") {
1657
+ return { status: "modified", hadPublishedVersion: true };
1658
+ }
1659
+ if (s === "draft") {
1660
+ return { status: "draft", hadPublishedVersion: false };
1661
+ }
1662
+ }
1663
+ const pub = publishedRecord || (entry.publishedAt ? entry : null);
1664
+ if (!pub) {
1665
+ return { status: "draft", hadPublishedVersion: false };
1666
+ }
1667
+ const draftUpdatedTime = new Date(entry.updatedAt || entry.updated_at || 0).getTime();
1668
+ const pubUpdatedTime = new Date(pub.updatedAt || pub.updated_at || 0).getTime();
1669
+ const pubPublishedTime = new Date(pub.publishedAt || pub.published_at || 0).getTime();
1670
+ const lastPublishedTime = Math.max(
1671
+ isNaN(pubUpdatedTime) ? 0 : pubUpdatedTime,
1672
+ isNaN(pubPublishedTime) ? 0 : pubPublishedTime
1673
+ );
1674
+ if (isNaN(draftUpdatedTime) || lastPublishedTime === 0) {
1675
+ if (pub.publishedAt || pub.published_at) {
1676
+ return { status: "published", hadPublishedVersion: true };
1677
+ }
1678
+ return { status: "unknown", hadPublishedVersion: false };
1679
+ }
1680
+ if (draftUpdatedTime > lastPublishedTime) {
1681
+ return { status: "modified", hadPublishedVersion: true };
1682
+ }
1683
+ return { status: "published", hadPublishedVersion: true };
1684
+ }
1685
+ function evaluateShouldPublish({
1686
+ isDraftAndPublish,
1687
+ hadPublishedVersion,
1688
+ isEditing,
1689
+ publishOnApproval = true,
1690
+ publishStrategy = "safe",
1691
+ unreviewedConsent = false
1692
+ }) {
1693
+ if (!isDraftAndPublish) return false;
1694
+ if (!hadPublishedVersion) return false;
1695
+ if (!publishOnApproval) return false;
1696
+ if (isEditing) return false;
1697
+ return true;
1698
+ }
1699
+ async function populateDocumentLifecycleStatus(strapi, uid, entries) {
1700
+ if (!entries || !Array.isArray(entries) || entries.length === 0) {
1701
+ return entries;
1702
+ }
1703
+ const contentType = strapi?.contentTypes?.[uid];
1704
+ if (!contentType) {
1705
+ return entries;
1706
+ }
1707
+ const hasDraftAndPublish = Boolean(contentType.options?.draftAndPublish);
1708
+ if (!hasDraftAndPublish) {
1709
+ for (const entry of entries) {
1710
+ if (entry && typeof entry === "object") {
1711
+ entry.status = "published";
1712
+ }
1713
+ }
1714
+ return entries;
1715
+ }
1716
+ const hasSlugInSchema = Boolean(contentType.attributes?.slug);
1717
+ const docIds = [];
1718
+ const slugs = [];
1719
+ for (const entry of entries) {
1720
+ if (!entry || typeof entry !== "object") continue;
1721
+ if (entry.documentId) {
1722
+ docIds.push(String(entry.documentId));
1723
+ } else if (hasSlugInSchema && entry.slug) {
1724
+ slugs.push(String(entry.slug));
1725
+ } else {
1726
+ entry.status = "unknown";
1727
+ }
1728
+ }
1729
+ if (docIds.length === 0 && slugs.length === 0) {
1730
+ return entries;
1731
+ }
1732
+ let filterClause;
1733
+ if (docIds.length > 0 && slugs.length > 0) {
1734
+ filterClause = {
1735
+ $or: [
1736
+ { documentId: { $in: docIds } },
1737
+ { slug: { $in: slugs } }
1738
+ ]
1739
+ };
1740
+ } else if (docIds.length > 0) {
1741
+ filterClause = { documentId: { $in: docIds } };
1742
+ } else {
1743
+ filterClause = { slug: { $in: slugs } };
1744
+ }
1745
+ const queryFields = ["documentId", "updatedAt", "publishedAt"];
1746
+ if (hasSlugInSchema) {
1747
+ queryFields.push("slug");
1748
+ }
1749
+ let publishedRecords = [];
1750
+ try {
1751
+ const docService = strapi?.documents?.(uid);
1752
+ if (docService?.findMany) {
1753
+ publishedRecords = await docService.findMany({
1754
+ status: "published",
1755
+ filters: filterClause,
1756
+ fields: queryFields,
1757
+ limit: Math.max(entries.length, 100)
1758
+ });
1759
+ }
1760
+ } catch (err) {
1761
+ strapi?.log?.warn?.(`[bulk-updater] Failed to fetch published status for ${uid}: ${err?.message || err}`);
1762
+ for (const entry of entries) {
1763
+ if (entry && typeof entry === "object" && entry.status !== "unknown") {
1764
+ entry.status = "unknown";
1765
+ }
1766
+ }
1767
+ return entries;
1768
+ }
1769
+ const publishedByDocId = /* @__PURE__ */ new Map();
1770
+ const publishedBySlug = /* @__PURE__ */ new Map();
1771
+ for (const pub of publishedRecords || []) {
1772
+ if (pub?.documentId) {
1773
+ publishedByDocId.set(String(pub.documentId), pub);
1774
+ }
1775
+ if (pub?.slug && hasSlugInSchema) {
1776
+ publishedBySlug.set(String(pub.slug), pub);
1777
+ }
1778
+ }
1779
+ for (const entry of entries) {
1780
+ if (!entry || typeof entry !== "object") continue;
1781
+ if (entry.status === "unknown") continue;
1782
+ const pub = entry.documentId && publishedByDocId.get(String(entry.documentId)) || hasSlugInSchema && entry.slug && publishedBySlug.get(String(entry.slug));
1783
+ if (!pub) {
1784
+ entry.status = "draft";
1785
+ entry.publishedAt = null;
1786
+ entry.published_at = null;
1787
+ } else {
1788
+ entry.publishedAt = pub.publishedAt || pub.published_at || null;
1789
+ entry.published_at = entry.publishedAt;
1790
+ const draftUpdatedTime = new Date(entry.updatedAt || entry.updated_at || 0).getTime();
1791
+ const pubUpdatedTime = new Date(pub.updatedAt || pub.updated_at || 0).getTime();
1792
+ const pubPublishedTime = new Date(pub.publishedAt || pub.published_at || 0).getTime();
1793
+ const lastPublishedTime = Math.max(
1794
+ isNaN(pubUpdatedTime) ? 0 : pubUpdatedTime,
1795
+ isNaN(pubPublishedTime) ? 0 : pubPublishedTime
1796
+ );
1797
+ if (isNaN(draftUpdatedTime) || lastPublishedTime === 0) {
1798
+ if (pub.publishedAt) {
1799
+ entry.status = "published";
1800
+ } else {
1801
+ entry.status = "unknown";
1802
+ }
1803
+ } else if (draftUpdatedTime > lastPublishedTime) {
1804
+ entry.status = "modified";
1805
+ } else {
1806
+ entry.status = "published";
1807
+ }
1808
+ }
1809
+ }
1810
+ return entries;
1811
+ }
1812
+ function resolveContentTypeField(contentType, field) {
1813
+ if (!field) return null;
1814
+ const attrs = contentType?.attributes || {};
1815
+ if (attrs[field]) return field;
1816
+ if (field === "updated_at" || field === "updatedAt") {
1817
+ return attrs["updated_at"] ? "updated_at" : "updatedAt";
1818
+ }
1819
+ if (field === "created_at" || field === "createdAt") {
1820
+ return attrs["created_at"] ? "created_at" : "createdAt";
1821
+ }
1822
+ if (field === "published_at" || field === "publishedAt") {
1823
+ return attrs["published_at"] ? "published_at" : "publishedAt";
1824
+ }
1825
+ if (field === "id" || field === "documentId") {
1826
+ return field;
1827
+ }
1828
+ const camel = field.replace(/_([a-z0-9])/g, (_, l) => l.toUpperCase());
1829
+ if (attrs[camel]) return camel;
1830
+ const snake = field.replace(/([A-Z])/g, "_$1").toLowerCase();
1831
+ if (attrs[snake]) return snake;
1832
+ const lower = field.toLowerCase().replace(/_/g, "");
1833
+ const matched = Object.keys(attrs).find(
1834
+ (k) => k.toLowerCase().replace(/_/g, "") === lower
1835
+ );
1836
+ if (matched) return matched;
1837
+ return null;
1838
+ }
1839
+ function buildDeepPopulate$1(attributes, allComponents, depth = 0) {
1840
+ if (depth > 5) return void 0;
1841
+ const populate = {};
1842
+ for (const [key, def] of Object.entries(attributes || {})) {
1843
+ if (def.type === "component" && def.component) {
1844
+ const comp = allComponents[def.component];
1845
+ if (comp?.attributes) {
1846
+ const subPopulate = buildDeepPopulate$1(comp.attributes, allComponents, depth + 1);
1847
+ if (subPopulate && Object.keys(subPopulate).length > 0) {
1848
+ populate[key] = {
1849
+ populate: subPopulate
1850
+ };
1851
+ } else {
1852
+ populate[key] = true;
1853
+ }
1854
+ } else {
1855
+ populate[key] = true;
1856
+ }
1857
+ } else if (def.type === "dynamiczone") {
1858
+ populate[key] = {
1859
+ populate: "*"
1860
+ };
1861
+ } else if (def.type === "relation" || def.type === "media") {
1862
+ populate[key] = true;
1863
+ }
1864
+ }
1865
+ return Object.keys(populate).length > 0 ? populate : void 0;
1866
+ }
1867
+ function discoverComponentAttributes(strapi, compUid, prefix, currentDepth, maxDepth, systemFields, allContentTypes, relationsByAttr, allRelationsMeta, attributesMeta) {
1868
+ if (currentDepth > maxDepth || !compUid) return [];
1869
+ const compSchema = strapi.components[compUid];
1870
+ if (!compSchema?.attributes) return [];
1871
+ const discoveredAttrs = [];
1872
+ for (const [subKey, subAttr] of Object.entries(compSchema.attributes)) {
1873
+ if (systemFields.includes(subKey)) continue;
1874
+ const fullPath = prefix ? `${prefix}.${subKey}` : subKey;
1875
+ if (subAttr.type === "dynamiczone") {
1876
+ const dzComps = Array.isArray(subAttr.components) ? subAttr.components : [];
1877
+ for (const dzCompUid of dzComps) {
1878
+ const deeper = discoverComponentAttributes(
1879
+ strapi,
1880
+ dzCompUid,
1881
+ fullPath,
1882
+ currentDepth + 1,
1883
+ maxDepth,
1884
+ systemFields,
1285
1885
  allContentTypes,
1286
1886
  relationsByAttr,
1287
1887
  allRelationsMeta,
@@ -1776,9 +2376,14 @@ async function executeBatchInternal(strapi, {
1776
2376
  const getDocumentDeduplicated = (uid, documentId) => {
1777
2377
  const loaderKey = `${uid}@@@${documentId}`;
1778
2378
  if (!documentLoader.has(loaderKey)) {
2379
+ const ct = strapi.contentTypes[uid];
2380
+ const populateDef = ct?.attributes ? buildDeepPopulate$1(ct.attributes, strapi.components) : void 0;
1779
2381
  documentLoader.set(
1780
2382
  loaderKey,
1781
- strapi.documents(uid).findOne({ documentId })
2383
+ strapi.documents(uid).findOne({
2384
+ documentId,
2385
+ ...populateDef ? { populate: populateDef } : { populate: "*" }
2386
+ })
1782
2387
  );
1783
2388
  }
1784
2389
  return documentLoader.get(loaderKey);
@@ -1862,6 +2467,21 @@ async function executeBatchInternal(strapi, {
1862
2467
  publishStrategy,
1863
2468
  unreviewedConsent
1864
2469
  });
2470
+ const proposedEntityComp = deepMergeEntities(currentEntryWithPopulate || currentEntry, { [rootKey]: updatedRoot });
2471
+ const valResultComp = await validateEntityQuotas(strapi, target.uid, proposedEntityComp);
2472
+ if (!valResultComp.isValid) {
2473
+ return {
2474
+ uid: target.uid,
2475
+ collectionName: displayName,
2476
+ documentId: target.documentId,
2477
+ label: entryLabel,
2478
+ attribute,
2479
+ oldValue: currentVal2 ?? null,
2480
+ newValue: newValue2,
2481
+ status: "error",
2482
+ message: valResultComp.errorMessage
2483
+ };
2484
+ }
1865
2485
  const updateArgsComp = {
1866
2486
  documentId: target.documentId,
1867
2487
  data: {
@@ -1999,6 +2619,21 @@ async function executeBatchInternal(strapi, {
1999
2619
  publishStrategy,
2000
2620
  unreviewedConsent
2001
2621
  });
2622
+ const proposedEntityRel = deepMergeEntities(currentEntry, { [attribute]: relationPayload });
2623
+ const valResultRel = await validateEntityQuotas(strapi, target.uid, proposedEntityRel);
2624
+ if (!valResultRel.isValid) {
2625
+ return {
2626
+ uid: target.uid,
2627
+ collectionName: displayName,
2628
+ documentId: target.documentId,
2629
+ label: entryLabel,
2630
+ attribute,
2631
+ oldValue: { isRelation: true, documentIds: oldDocIds, display: oldDisplay },
2632
+ newValue: { isRelation: true, mode, documentIds: targetDocIds, display: newDisplay },
2633
+ status: "error",
2634
+ message: valResultRel.errorMessage
2635
+ };
2636
+ }
2002
2637
  const updateArgsRel = {
2003
2638
  documentId: target.documentId,
2004
2639
  data: {
@@ -2082,13 +2717,28 @@ async function executeBatchInternal(strapi, {
2082
2717
  publishStrategy,
2083
2718
  unreviewedConsent
2084
2719
  });
2085
- const updateArgsScalar = {
2086
- documentId: target.documentId,
2087
- data: {
2088
- [attribute]: newValue
2089
- }
2090
- };
2091
- if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleScalar && candLocaleScalar !== "null" && candLocaleScalar !== "undefined") {
2720
+ const proposedEntityScalar = deepMergeEntities(currentEntry, { [attribute]: newValue });
2721
+ const valResultScalar = await validateEntityQuotas(strapi, target.uid, proposedEntityScalar);
2722
+ if (!valResultScalar.isValid) {
2723
+ return {
2724
+ uid: target.uid,
2725
+ collectionName: displayName,
2726
+ documentId: target.documentId,
2727
+ label: entryLabel,
2728
+ attribute,
2729
+ oldValue: currentVal ?? null,
2730
+ newValue,
2731
+ status: "error",
2732
+ message: valResultScalar.errorMessage
2733
+ };
2734
+ }
2735
+ const updateArgsScalar = {
2736
+ documentId: target.documentId,
2737
+ data: {
2738
+ [attribute]: newValue
2739
+ }
2740
+ };
2741
+ if (Boolean(contentType?.pluginOptions?.i18n?.localized) && candLocaleScalar && candLocaleScalar !== "null" && candLocaleScalar !== "undefined") {
2092
2742
  updateArgsScalar.locale = candLocaleScalar;
2093
2743
  }
2094
2744
  await strapi.documents(target.uid).update(updateArgsScalar);
@@ -4469,7 +5119,7 @@ const auditService = ({ strapi }) => ({
4469
5119
  /**
4470
5120
  * Optionally writes an audit event directly to Strapi Enterprise's native Audit Logs table.
4471
5121
  */
4472
- async recordToEnterpriseNative(action, payload, user) {
5122
+ async recordToEnterpriseNative(action, payload2, user) {
4473
5123
  try {
4474
5124
  const eeService = this.getEnterpriseAuditService();
4475
5125
  if (eeService && typeof eeService.save === "function") {
@@ -4477,7 +5127,7 @@ const auditService = ({ strapi }) => ({
4477
5127
  action,
4478
5128
  date: /* @__PURE__ */ new Date(),
4479
5129
  userId: user?.id,
4480
- payload
5130
+ payload: payload2
4481
5131
  });
4482
5132
  strapi.log.info(
4483
5133
  `[bulk-updater] Successfully dispatched event to Strapi Enterprise Audit Log: ${action}`
@@ -4722,562 +5372,168 @@ const auditService = ({ strapi }) => ({
4722
5372
  [rootKey]: restoredRoot
4723
5373
  }
4724
5374
  });
4725
- } else {
4726
- const currentDoc = await strapi.documents(item.uid).findOne({
4727
- documentId: item.documentId
4728
- });
4729
- wasPublished = Boolean(currentDoc?.publishedAt);
4730
- await strapi.documents(item.uid).update({
4731
- documentId: item.documentId,
4732
- data: {
4733
- [item.attribute]: rollbackPayload
4734
- }
4735
- });
4736
- }
4737
- if (ct?.options?.draftAndPublish && wasPublished) {
4738
- try {
4739
- await strapi.documents(item.uid).publish({
4740
- documentId: item.documentId
4741
- });
4742
- } catch (publishErr) {
4743
- strapi.log.warn(`[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`, publishErr?.message);
4744
- }
4745
- }
4746
- try {
4747
- await recordContentHistoryVersion(strapi, {
4748
- uid: item.uid,
4749
- documentId: item.documentId,
4750
- userId,
4751
- statusOverride: ct?.options?.draftAndPublish ? wasPublished ? "published" : "draft" : void 0
4752
- });
4753
- } catch {
4754
- }
4755
- try {
4756
- const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
4757
- if (bulkService?.invalidateCache) {
4758
- bulkService.invalidateCache(item.uid);
4759
- }
4760
- } catch {
4761
- }
4762
- revertedCount++;
4763
- rollbackDetails.push({
4764
- uid: item.uid,
4765
- documentId: item.documentId,
4766
- label: item.label,
4767
- attribute: item.attribute,
4768
- revertedTo: item.oldValue,
4769
- status: "reverted"
4770
- });
4771
- } catch (err) {
4772
- rollbackDetails.push({
4773
- uid: item.uid,
4774
- documentId: item.documentId,
4775
- label: item.label,
4776
- status: "error",
4777
- message: err.message
4778
- });
4779
- }
4780
- }
4781
- }
4782
- return { revertedCount, rollbackDetails };
4783
- },
4784
- /**
4785
- * Performs deterministic rollback of a batch
4786
- */
4787
- async rollbackBatch(batchId, currentUser) {
4788
- const config = this.getAuditConfig();
4789
- if (!config.enabled) {
4790
- throw new Error("Audit trail is not configured or disabled.");
4791
- }
4792
- if (config.mode === "store") {
4793
- const store = strapi.store({ type: "plugin", name: "bulk-updater", key: "audit-history" });
4794
- const stored = await store.get({}) || { history: [] };
4795
- const history = Array.isArray(stored.history) ? stored.history : [];
4796
- const recordIndex = history.findIndex((r) => r.batchId === batchId);
4797
- if (recordIndex === -1) {
4798
- throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
4799
- }
4800
- const record2 = history[recordIndex];
4801
- if (record2.isRolledBack) {
4802
- throw new Error(`Batch "${batchId}" has already been rolled back.`);
4803
- }
4804
- const diffs2 = Array.isArray(record2.diffs) ? record2.diffs : [];
4805
- const { revertedCount: revertedCount2, rollbackDetails: rollbackDetails2 } = await this.revertDiffItems(diffs2, currentUser?.id);
4806
- record2.isRolledBack = true;
4807
- record2.rolledBackAt = (/* @__PURE__ */ new Date()).toISOString();
4808
- record2.rolledBackBy = currentUser?.email || "Admin";
4809
- history[recordIndex] = record2;
4810
- await store.set({ value: { history } });
4811
- try {
4812
- const affectedUids = new Set(rollbackDetails2.map((d) => d.uid));
4813
- const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
4814
- affectedUids.forEach((uid) => {
4815
- if (uid && bulkService?.invalidateCache) {
4816
- bulkService.invalidateCache(uid);
4817
- }
4818
- });
4819
- } catch {
4820
- }
4821
- await this.recordToEnterpriseNative(
4822
- "bulk-updater.rollback",
4823
- {
4824
- batchId,
4825
- revertedCount: revertedCount2
4826
- },
4827
- currentUser
4828
- );
4829
- return {
4830
- success: true,
4831
- batchId,
4832
- revertedCount: revertedCount2,
4833
- details: rollbackDetails2
4834
- };
4835
- }
4836
- if (!config.contentType || !config.fields) {
4837
- throw new Error("Audit trail is not configured or disabled.");
4838
- }
4839
- const f = config.fields;
4840
- const records = await strapi.documents(config.contentType).findMany({
4841
- filters: {
4842
- [f.batchId]: { $eq: batchId }
4843
- }
4844
- });
4845
- const record = records?.[0];
4846
- if (!record) {
4847
- throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
4848
- }
4849
- if (record[f.isRolledBack]) {
4850
- throw new Error(`Batch "${batchId}" has already been rolled back.`);
4851
- }
4852
- const diffs = typeof record[f.diffs] === "string" ? JSON.parse(record[f.diffs]) : record[f.diffs] || [];
4853
- const { revertedCount, rollbackDetails } = await this.revertDiffItems(diffs, currentUser?.id);
4854
- const updateData = {};
4855
- if (f.isRolledBack) updateData[f.isRolledBack] = true;
4856
- if (f.rolledBackAt) updateData[f.rolledBackAt] = (/* @__PURE__ */ new Date()).toISOString();
4857
- if (f.rolledBackBy) {
4858
- updateData[f.rolledBackBy] = currentUser?.email || "Admin";
4859
- }
4860
- await strapi.documents(config.contentType).update({
4861
- documentId: record.documentId,
4862
- data: updateData
4863
- });
4864
- try {
4865
- const affectedUids = new Set(rollbackDetails.map((d) => d.uid));
4866
- const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
4867
- affectedUids.forEach((uid) => {
4868
- if (uid && bulkService?.invalidateCache) {
4869
- bulkService.invalidateCache(uid);
4870
- }
4871
- });
4872
- } catch {
4873
- }
4874
- await this.recordToEnterpriseNative(
4875
- "bulk-updater.rollback",
4876
- {
4877
- batchId,
4878
- revertedCount
4879
- },
4880
- currentUser
4881
- );
4882
- return {
4883
- success: true,
4884
- batchId,
4885
- revertedCount,
4886
- details: rollbackDetails
4887
- };
4888
- }
4889
- });
4890
- const DEFAULT_RULES = [
4891
- {
4892
- id: "rule_seo_heading_h1",
4893
- name: "SEO Single H1 Page Rule",
4894
- description: "Enforces that only one H1 heading tag can be selected across all dynamic zone heading blocks within an entry, combined with rich text HTML.",
4895
- collectionUid: "*",
4896
- targetField: "headingLevel",
4897
- quotas: {
4898
- h1: 1,
4899
- h2: 3
4900
- },
4901
- exceededAction: "disable",
4902
- enabled: true,
4903
- scope: "entry",
4904
- includeRichTextHtml: true,
4905
- richTextFields: [],
4906
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
4907
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
4908
- }
4909
- ];
4910
- function extractHeadingsFromRichText(content) {
4911
- const counts = { h1: 0, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 };
4912
- if (!content) return counts;
4913
- if (Array.isArray(content)) {
4914
- for (const node of content) {
4915
- if (node && typeof node === "object") {
4916
- if (node.type === "heading" && typeof node.level === "number") {
4917
- const tag = `h${node.level}`;
4918
- if (counts[tag] !== void 0) counts[tag]++;
4919
- }
4920
- if (Array.isArray(node.children)) {
4921
- const sub = extractHeadingsFromRichText(node.children);
4922
- for (const k of Object.keys(counts)) counts[k] += sub[k];
4923
- }
4924
- }
4925
- }
4926
- return counts;
4927
- }
4928
- if (typeof content === "string") {
4929
- for (let level = 1; level <= 6; level++) {
4930
- const tag = `h${level}`;
4931
- const htmlMatches = content.match(new RegExp(`<${tag}\\b[^>]*>`, "gi"));
4932
- if (htmlMatches) {
4933
- counts[tag] += htmlMatches.length;
4934
- }
4935
- const mdRegex = new RegExp(`(?:^|\\n)${"#".repeat(level)}\\s+[^\\n]+`, "g");
4936
- const mdMatches = content.match(mdRegex);
4937
- if (mdMatches) {
4938
- counts[tag] += mdMatches.length;
4939
- }
4940
- }
4941
- }
4942
- return counts;
4943
- }
4944
- function cleanKey(str) {
4945
- return (str || "").replace(/[-_]/g, "").toLowerCase().trim();
4946
- }
4947
- function matchesPath(normalizedPath, leafKey, targetField) {
4948
- if (!targetField) return false;
4949
- const pClean = cleanKey(normalizedPath);
4950
- const kClean = cleanKey(leafKey);
4951
- const tClean = cleanKey(targetField);
4952
- if (kClean === tClean || pClean === tClean) return true;
4953
- const targetSegments = targetField.replace(/^api::/i, "").split(".").map(cleanKey).filter(Boolean);
4954
- const pathSegments = normalizedPath.split(".").map(cleanKey).filter(Boolean);
4955
- if (targetSegments.length === 0 || pathSegments.length === 0) return false;
4956
- if (targetSegments.length === 1) {
4957
- const single = targetSegments[0];
4958
- return kClean === single || pathSegments[pathSegments.length - 1] === single;
4959
- }
4960
- let isSuffix = true;
4961
- for (let i = 0; i < targetSegments.length; i++) {
4962
- const tSeg = targetSegments[targetSegments.length - 1 - i];
4963
- const pSeg = pathSegments[pathSegments.length - 1 - i];
4964
- if (tSeg !== "*" && tSeg !== pSeg) {
4965
- isSuffix = false;
4966
- break;
4967
- }
4968
- }
4969
- if (isSuffix) return true;
4970
- for (let startIdx = 1; startIdx < targetSegments.length; startIdx++) {
4971
- const subTarget = targetSegments.slice(startIdx);
4972
- if (subTarget.length > pathSegments.length) continue;
4973
- let subSuffix = true;
4974
- for (let i = 0; i < subTarget.length; i++) {
4975
- const tSeg = subTarget[subTarget.length - 1 - i];
4976
- const pSeg = pathSegments[pathSegments.length - 1 - i];
4977
- if (tSeg !== "*" && tSeg !== pSeg) {
4978
- subSuffix = false;
4979
- break;
4980
- }
4981
- }
4982
- if (subSuffix) return true;
4983
- }
4984
- let pIdx = 0;
4985
- let matchesInOrder = true;
4986
- let tStart = 0;
4987
- if (targetSegments.length > 2 && targetSegments[0] !== pathSegments[0] && targetSegments[0] !== "*") {
4988
- tStart = 1;
4989
- }
4990
- for (let tIdx = tStart; tIdx < targetSegments.length; tIdx++) {
4991
- const tSeg = targetSegments[tIdx];
4992
- if (tSeg === "*") continue;
4993
- let found = false;
4994
- while (pIdx < pathSegments.length) {
4995
- if (pathSegments[pIdx] === tSeg) {
4996
- found = true;
4997
- pIdx++;
4998
- break;
4999
- }
5000
- pIdx++;
5001
- }
5002
- if (!found) {
5003
- matchesInOrder = false;
5004
- break;
5005
- }
5006
- }
5007
- return matchesInOrder;
5008
- }
5009
- const validationRulesService = ({ strapi }) => ({
5010
- async getStore() {
5011
- return strapi.store({
5012
- type: "plugin",
5013
- name: "bulk-updater",
5014
- key: "validation-rules"
5015
- });
5016
- },
5017
- async getRules() {
5018
- const store = await this.getStore();
5019
- const stored = await store.get({});
5020
- if (!stored || !Array.isArray(stored.rules)) {
5021
- await store.set({ value: { rules: DEFAULT_RULES } });
5022
- return DEFAULT_RULES;
5023
- }
5024
- return stored.rules;
5025
- },
5026
- async saveRule(ruleData) {
5027
- const store = await this.getStore();
5028
- const rules = await this.getRules();
5029
- const now = (/* @__PURE__ */ new Date()).toISOString();
5030
- let savedRule;
5031
- if (ruleData.id) {
5032
- const index2 = rules.findIndex((r) => r.id === ruleData.id);
5033
- if (index2 !== -1) {
5034
- savedRule = {
5035
- ...rules[index2],
5036
- ...ruleData,
5037
- collectionUid: ruleData.collectionUid !== void 0 ? ruleData.collectionUid : rules[index2].collectionUid || "*",
5038
- includeRichTextHtml: ruleData.includeRichTextHtml !== void 0 ? Boolean(ruleData.includeRichTextHtml) : Boolean(rules[index2].includeRichTextHtml),
5039
- richTextFields: Array.isArray(ruleData.richTextFields) ? ruleData.richTextFields : rules[index2].richTextFields || [],
5040
- updatedAt: now
5041
- };
5042
- rules[index2] = savedRule;
5043
- } else {
5044
- savedRule = {
5045
- id: ruleData.id,
5046
- name: ruleData.name || "New Rule",
5047
- description: ruleData.description || "",
5048
- collectionUid: ruleData.collectionUid || "*",
5049
- targetField: ruleData.targetField || "headingLevel",
5050
- quotas: ruleData.quotas || { h1: 1 },
5051
- exceededAction: ruleData.exceededAction || "disable",
5052
- enabled: ruleData.enabled ?? true,
5053
- scope: ruleData.scope || "entry",
5054
- includeRichTextHtml: Boolean(ruleData.includeRichTextHtml),
5055
- richTextFields: Array.isArray(ruleData.richTextFields) ? ruleData.richTextFields : [],
5056
- createdAt: now,
5057
- updatedAt: now
5058
- };
5059
- rules.push(savedRule);
5060
- }
5061
- } else {
5062
- const id = `rule_${Date.now()}_${Math.random().toString(36).substring(2, 6)}`;
5063
- savedRule = {
5064
- id,
5065
- name: ruleData.name || "Custom Quota Rule",
5066
- description: ruleData.description || "",
5067
- collectionUid: ruleData.collectionUid || "*",
5068
- targetField: ruleData.targetField || "headingLevel",
5069
- quotas: ruleData.quotas || { h1: 1 },
5070
- exceededAction: ruleData.exceededAction || "disable",
5071
- enabled: ruleData.enabled ?? true,
5072
- scope: ruleData.scope || "entry",
5073
- includeRichTextHtml: Boolean(ruleData.includeRichTextHtml),
5074
- richTextFields: Array.isArray(ruleData.richTextFields) ? ruleData.richTextFields : [],
5075
- createdAt: now,
5076
- updatedAt: now
5077
- };
5078
- rules.push(savedRule);
5079
- }
5080
- await store.set({ value: { rules } });
5081
- return savedRule;
5082
- },
5083
- async deleteRule(ruleId) {
5084
- const store = await this.getStore();
5085
- const rules = await this.getRules();
5086
- const filtered = rules.filter((r) => r.id !== ruleId);
5087
- await store.set({ value: { rules: filtered } });
5088
- return true;
5089
- },
5090
- async toggleRule(ruleId, enabled) {
5091
- const store = await this.getStore();
5092
- const rules = await this.getRules();
5093
- const index2 = rules.findIndex((r) => r.id === ruleId);
5094
- if (index2 === -1) return null;
5095
- const current = rules[index2];
5096
- const newEnabled = typeof enabled === "boolean" ? enabled : !current.enabled;
5097
- const updated = {
5098
- ...current,
5099
- enabled: newEnabled,
5100
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
5101
- };
5102
- rules[index2] = updated;
5103
- await store.set({ value: { rules } });
5104
- return updated;
5105
- },
5106
- async scanViolations(ruleId) {
5107
- const rules = await this.getRules();
5108
- const rule = rules.find((r) => r.id === ruleId);
5109
- if (!rule) {
5110
- throw new Error(`Validation rule ${ruleId} not found`);
5111
- }
5112
- const targetField = rule.targetField;
5113
- const quotas = rule.quotas || {};
5114
- const violations = [];
5115
- let totalScanned = 0;
5116
- const allContentTypes = strapi.contentTypes || {};
5117
- const allComponents = strapi.components || {};
5118
- function componentHasField(compUid, targetField2) {
5119
- const comp = allComponents[compUid];
5120
- if (!comp?.attributes) return false;
5121
- if (matchesPath(compUid, compUid, targetField2)) return true;
5122
- for (const [attrName, attrDef] of Object.entries(comp.attributes)) {
5123
- if (matchesPath(attrName, attrName, targetField2) || matchesPath(`${compUid}.${attrName}`, attrName, targetField2)) return true;
5124
- if (attrDef.type === "component" && attrDef.component) {
5125
- if (componentHasField(attrDef.component, targetField2)) return true;
5126
- } else if (attrDef.type === "dynamiczone" && Array.isArray(attrDef.components)) {
5127
- if (attrDef.components.some((c) => componentHasField(c, targetField2))) return true;
5128
- }
5129
- }
5130
- return false;
5131
- }
5132
- function schemaHasField(ctSchema) {
5133
- if (!ctSchema || !ctSchema.attributes) return { hasField: false, populateAttrs: {} };
5134
- const rawAttrs = ctSchema.attributes;
5135
- const populateAttrs = {};
5136
- let hasField = false;
5137
- for (const [attrKey, attrDef] of Object.entries(rawAttrs)) {
5138
- if (matchesPath(attrKey, attrKey, targetField)) {
5139
- hasField = true;
5140
- }
5141
- if (attrDef.type === "component" && attrDef.component) {
5142
- if (componentHasField(attrDef.component, targetField)) {
5143
- hasField = true;
5144
- populateAttrs[attrKey] = { populate: "*" };
5145
- }
5146
- } else if (attrDef.type === "dynamiczone" && Array.isArray(attrDef.components)) {
5147
- const matchingComp = attrDef.components.some(
5148
- (compUid) => componentHasField(compUid, targetField) || matchesPath(`${attrKey}.${compUid}`, compUid, targetField)
5149
- );
5150
- if (matchingComp) {
5151
- hasField = true;
5152
- populateAttrs[attrKey] = { populate: "*" };
5153
- }
5154
- }
5155
- }
5156
- return { hasField, populateAttrs };
5157
- }
5158
- const candidateUids = Object.keys(allContentTypes).filter((uid) => {
5159
- if (!uid.startsWith("api::") || uid.includes("bulk-updater")) return false;
5160
- if (rule.collectionUid && rule.collectionUid !== "*") {
5161
- if (rule.collectionUid === uid) return true;
5162
- const cleanRuleCol = cleanKey(rule.collectionUid);
5163
- const cleanUid = cleanKey(uid);
5164
- if (cleanUid.includes(cleanRuleCol) || cleanRuleCol.includes(cleanUid)) return true;
5165
- return false;
5166
- }
5167
- return true;
5168
- });
5169
- const relevantCollections = [];
5170
- for (const uid of candidateUids) {
5171
- const ct = allContentTypes[uid];
5172
- if (!ct) continue;
5173
- const { hasField, populateAttrs } = schemaHasField(ct);
5174
- const isTargetCol = rule.collectionUid && (rule.collectionUid === uid || cleanKey(uid).includes(cleanKey(rule.collectionUid)));
5175
- if (hasField || isTargetCol) {
5176
- relevantCollections.push({
5177
- uid,
5178
- displayName: ct.info?.displayName || uid,
5179
- populateOption: Object.keys(populateAttrs).length > 0 ? populateAttrs : "*"
5180
- });
5181
- }
5182
- }
5183
- const BATCH_SIZE = 250;
5184
- await Promise.all(
5185
- relevantCollections.map(async ({ uid, displayName, populateOption }) => {
5186
- try {
5187
- let page = 1;
5188
- while (true) {
5189
- const entries = await strapi.documents(uid).findMany({
5190
- page,
5191
- pageSize: BATCH_SIZE,
5192
- populate: populateOption
5193
- });
5194
- if (!entries || entries.length === 0) break;
5195
- for (const entry of entries) {
5196
- let traverse = function(obj, currentPath = "") {
5197
- if (!obj || typeof obj !== "object") return;
5198
- const compName = typeof obj.__component === "string" ? obj.__component : "";
5199
- for (const key of Object.keys(obj)) {
5200
- if (key === "__component") continue;
5201
- const val = obj[key];
5202
- const newPath = currentPath ? `${currentPath}.${key}` : key;
5203
- const normalizedPath = newPath.replace(/\.\d+/g, "");
5204
- const compPath = compName ? (currentPath ? `${currentPath}.${compName}.${key}` : `${compName}.${key}`).replace(/\.\d+/g, "") : "";
5205
- const isMatch = matchesPath(normalizedPath, key, targetField) || (compPath ? matchesPath(compPath, key, targetField) : false);
5206
- if (isMatch && typeof val === "string" && val.trim()) {
5207
- const lower = val.toLowerCase().trim();
5208
- structuredCounts[lower] = (structuredCounts[lower] || 0) + 1;
5209
- }
5210
- if (rule.includeRichTextHtml) {
5211
- if (typeof val === "string" && (val.includes("<h") || val.includes("#"))) {
5212
- const headings = extractHeadingsFromRichText(val);
5213
- for (const [tag, count] of Object.entries(headings)) {
5214
- if (count > 0) {
5215
- richTextCounts[tag] = (richTextCounts[tag] || 0) + count;
5216
- }
5217
- }
5218
- } else if (Array.isArray(val) && val.length > 0 && typeof val[0] === "object" && val[0]?.type) {
5219
- const headings = extractHeadingsFromRichText(val);
5220
- for (const [tag, count] of Object.entries(headings)) {
5221
- if (count > 0) {
5222
- richTextCounts[tag] = (richTextCounts[tag] || 0) + count;
5223
- }
5224
- }
5225
- continue;
5226
- }
5227
- }
5228
- if (typeof val === "object" && val !== null) {
5229
- traverse(val, newPath);
5230
- }
5231
- }
5232
- };
5233
- totalScanned++;
5234
- const structuredCounts = {};
5235
- const richTextCounts = { h1: 0, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 };
5236
- traverse(entry);
5237
- for (const [optKey, max] of Object.entries(quotas)) {
5238
- const lowerOpt = optKey.toLowerCase().trim();
5239
- const structCount = structuredCounts[lowerOpt] || 0;
5240
- const rtCount = rule.includeRichTextHtml ? richTextCounts[lowerOpt] || 0 : 0;
5241
- const combinedCount = structCount + rtCount;
5242
- if (combinedCount > max) {
5243
- const entryLabel = entry.title || entry.name || entry.email || `Entry #${entry.documentId}`;
5244
- let detail = "";
5245
- if (rtCount > 0 && structCount > 0) {
5246
- detail = `${structCount} structured + ${rtCount} in rich text HTML`;
5247
- } else if (rtCount > 0) {
5248
- detail = `${rtCount} in rich text HTML / Markdown`;
5249
- } else {
5250
- detail = `${structCount} in structured component`;
5251
- }
5252
- violations.push({
5253
- uid,
5254
- collectionDisplayName: displayName,
5255
- documentId: entry.documentId,
5256
- entryLabel,
5257
- violatingOption: optKey.toUpperCase(),
5258
- foundCount: combinedCount,
5259
- structuredCount: structCount,
5260
- richTextCount: rtCount,
5261
- maxAllowed: max,
5262
- detail,
5263
- editUrl: `/admin/content-manager/collection-types/${uid}/${entry.documentId}`
5264
- });
5265
- }
5375
+ } else {
5376
+ const currentDoc = await strapi.documents(item.uid).findOne({
5377
+ documentId: item.documentId
5378
+ });
5379
+ wasPublished = Boolean(currentDoc?.publishedAt);
5380
+ await strapi.documents(item.uid).update({
5381
+ documentId: item.documentId,
5382
+ data: {
5383
+ [item.attribute]: rollbackPayload
5266
5384
  }
5385
+ });
5386
+ }
5387
+ if (ct?.options?.draftAndPublish && wasPublished) {
5388
+ try {
5389
+ await strapi.documents(item.uid).publish({
5390
+ documentId: item.documentId
5391
+ });
5392
+ } catch (publishErr) {
5393
+ strapi.log.warn(`[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`, publishErr?.message);
5267
5394
  }
5268
- if (entries.length < BATCH_SIZE) break;
5269
- page++;
5270
5395
  }
5396
+ try {
5397
+ await recordContentHistoryVersion(strapi, {
5398
+ uid: item.uid,
5399
+ documentId: item.documentId,
5400
+ userId,
5401
+ statusOverride: ct?.options?.draftAndPublish ? wasPublished ? "published" : "draft" : void 0
5402
+ });
5403
+ } catch {
5404
+ }
5405
+ try {
5406
+ const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
5407
+ if (bulkService?.invalidateCache) {
5408
+ bulkService.invalidateCache(item.uid);
5409
+ }
5410
+ } catch {
5411
+ }
5412
+ revertedCount++;
5413
+ rollbackDetails.push({
5414
+ uid: item.uid,
5415
+ documentId: item.documentId,
5416
+ label: item.label,
5417
+ attribute: item.attribute,
5418
+ revertedTo: item.oldValue,
5419
+ status: "reverted"
5420
+ });
5271
5421
  } catch (err) {
5272
- strapi.log.warn(`[bulk-updater] Failed scanning ${uid} for rule ${ruleId}:`, err);
5422
+ rollbackDetails.push({
5423
+ uid: item.uid,
5424
+ documentId: item.documentId,
5425
+ label: item.label,
5426
+ status: "error",
5427
+ message: err.message
5428
+ });
5273
5429
  }
5274
- })
5430
+ }
5431
+ }
5432
+ return { revertedCount, rollbackDetails };
5433
+ },
5434
+ /**
5435
+ * Performs deterministic rollback of a batch
5436
+ */
5437
+ 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) {
5448
+ throw new Error(`Batch record with ID "${batchId}" was not found in audit trail.`);
5449
+ }
5450
+ const record2 = history[recordIndex];
5451
+ if (record2.isRolledBack) {
5452
+ throw new Error(`Batch "${batchId}" has already been rolled back.`);
5453
+ }
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 } });
5461
+ try {
5462
+ const affectedUids = new Set(rollbackDetails2.map((d) => d.uid));
5463
+ const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
5464
+ affectedUids.forEach((uid) => {
5465
+ if (uid && bulkService?.invalidateCache) {
5466
+ bulkService.invalidateCache(uid);
5467
+ }
5468
+ });
5469
+ } catch {
5470
+ }
5471
+ await this.recordToEnterpriseNative(
5472
+ "bulk-updater.rollback",
5473
+ {
5474
+ batchId,
5475
+ revertedCount: revertedCount2
5476
+ },
5477
+ currentUser
5478
+ );
5479
+ return {
5480
+ success: true,
5481
+ batchId,
5482
+ revertedCount: revertedCount2,
5483
+ details: rollbackDetails2
5484
+ };
5485
+ }
5486
+ if (!config.contentType || !config.fields) {
5487
+ throw new Error("Audit trail is not configured or disabled.");
5488
+ }
5489
+ const f = config.fields;
5490
+ const records = await strapi.documents(config.contentType).findMany({
5491
+ filters: {
5492
+ [f.batchId]: { $eq: batchId }
5493
+ }
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);
5520
+ }
5521
+ });
5522
+ } catch {
5523
+ }
5524
+ await this.recordToEnterpriseNative(
5525
+ "bulk-updater.rollback",
5526
+ {
5527
+ batchId,
5528
+ revertedCount
5529
+ },
5530
+ currentUser
5275
5531
  );
5276
5532
  return {
5277
- rule,
5278
- totalScanned,
5279
- totalViolations: violations.length,
5280
- violations
5533
+ success: true,
5534
+ batchId,
5535
+ revertedCount,
5536
+ details: rollbackDetails
5281
5537
  };
5282
5538
  }
5283
5539
  });
@@ -5710,8 +5966,12 @@ async function findExistingDocument(strapi, uid, targetDocId, docLocale) {
5710
5966
  if (!targetDocId) return null;
5711
5967
  const ct = strapi.contentTypes[uid];
5712
5968
  const effectiveLocale = getEffectiveLocale(ct, docLocale);
5969
+ const populateDef = ct?.attributes ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
5713
5970
  try {
5714
- const queryArgs = { documentId: targetDocId };
5971
+ const queryArgs = {
5972
+ documentId: targetDocId,
5973
+ ...populateDef ? { populate: populateDef } : { populate: "*" }
5974
+ };
5715
5975
  if (effectiveLocale) queryArgs.locale = effectiveLocale;
5716
5976
  const found = await strapi.documents(uid).findOne(queryArgs);
5717
5977
  if (found) return found;
@@ -5874,7 +6134,7 @@ function parseMediaValue(rawVal, isMultiple = false) {
5874
6134
  return isMultiple ? [] : null;
5875
6135
  }
5876
6136
  function parseRowToPayload(strapi, attrs, row) {
5877
- const payload = {};
6137
+ const payload2 = {};
5878
6138
  for (const [key, rawVal] of Object.entries(row)) {
5879
6139
  const normalizedKey = key.toLowerCase().replace(/[\s_-]/g, "");
5880
6140
  if (SYSTEM_FIELD_KEYS.has(normalizedKey)) continue;
@@ -5883,7 +6143,7 @@ function parseRowToPayload(strapi, attrs, row) {
5883
6143
  if (SYSTEM_FIELD_KEYS.has(topPart)) continue;
5884
6144
  const parts = key.split(".");
5885
6145
  let currentAttrs = attrs;
5886
- let currentTarget = payload;
6146
+ let currentTarget = payload2;
5887
6147
  for (let pIdx = 0; pIdx < parts.length; pIdx++) {
5888
6148
  const part = parts[pIdx];
5889
6149
  const isLeaf = pIdx === parts.length - 1;
@@ -5981,61 +6241,61 @@ function parseRowToPayload(strapi, attrs, row) {
5981
6241
  }
5982
6242
  if (rawVal === "" || rawVal === null || rawVal === void 0) {
5983
6243
  if (attrDef.type !== "dynamiczone" && !(attrDef.type === "component" && attrDef.repeatable) && attrDef.type !== "relation" && attrDef.type !== "password") {
5984
- payload[key] = null;
6244
+ payload2[key] = null;
5985
6245
  }
5986
6246
  continue;
5987
6247
  }
5988
6248
  switch (attrDef.type) {
5989
6249
  case "integer":
5990
6250
  case "biginteger":
5991
- payload[key] = parseNumberValue(rawVal, true);
6251
+ payload2[key] = parseNumberValue(rawVal, true);
5992
6252
  break;
5993
6253
  case "float":
5994
6254
  case "decimal":
5995
- payload[key] = parseNumberValue(rawVal, false);
6255
+ payload2[key] = parseNumberValue(rawVal, false);
5996
6256
  break;
5997
6257
  case "boolean":
5998
- payload[key] = parseBooleanValue(rawVal);
6258
+ payload2[key] = parseBooleanValue(rawVal);
5999
6259
  break;
6000
6260
  case "blocks":
6001
- payload[key] = parseBlocksValue(rawVal);
6261
+ payload2[key] = parseBlocksValue(rawVal);
6002
6262
  break;
6003
6263
  case "enumeration":
6004
- payload[key] = parseEnumValue(rawVal, attrDef.enum);
6264
+ payload2[key] = parseEnumValue(rawVal, attrDef.enum);
6005
6265
  break;
6006
6266
  case "relation":
6007
- payload[key] = parseRelationValue(rawVal, attrDef.relation);
6267
+ payload2[key] = parseRelationValue(rawVal, attrDef.relation);
6008
6268
  break;
6009
6269
  case "media":
6010
- payload[key] = parseMediaValue(rawVal, Boolean(attrDef.multiple));
6270
+ payload2[key] = parseMediaValue(rawVal, Boolean(attrDef.multiple));
6011
6271
  break;
6012
6272
  case "date":
6013
6273
  case "time":
6014
6274
  case "datetime":
6015
6275
  case "timestamp":
6016
- payload[key] = String(rawVal).trim() || null;
6276
+ payload2[key] = String(rawVal).trim() || null;
6017
6277
  break;
6018
6278
  case "email":
6019
6279
  case "uid":
6020
- payload[key] = String(rawVal).trim();
6280
+ payload2[key] = String(rawVal).trim();
6021
6281
  break;
6022
6282
  case "password":
6023
6283
  if (String(rawVal).trim()) {
6024
- payload[key] = String(rawVal).trim();
6284
+ payload2[key] = String(rawVal).trim();
6025
6285
  }
6026
6286
  break;
6027
6287
  case "json":
6028
6288
  try {
6029
- payload[key] = JSON.parse(rawVal);
6289
+ payload2[key] = JSON.parse(rawVal);
6030
6290
  } catch {
6031
- payload[key] = rawVal;
6291
+ payload2[key] = rawVal;
6032
6292
  }
6033
6293
  break;
6034
6294
  case "dynamiczone": {
6035
6295
  try {
6036
6296
  const parsed = JSON.parse(rawVal);
6037
6297
  if (Array.isArray(parsed) && parsed.every((item) => item && typeof item === "object" && typeof item.__component === "string")) {
6038
- payload[key] = parsed;
6298
+ payload2[key] = parsed;
6039
6299
  }
6040
6300
  } catch {
6041
6301
  }
@@ -6046,7 +6306,7 @@ function parseRowToPayload(strapi, attrs, row) {
6046
6306
  try {
6047
6307
  const parsed = JSON.parse(rawVal);
6048
6308
  if (Array.isArray(parsed) && parsed.every((item) => item && typeof item === "object")) {
6049
- payload[key] = parsed;
6309
+ payload2[key] = parsed;
6050
6310
  }
6051
6311
  } catch {
6052
6312
  }
@@ -6054,7 +6314,7 @@ function parseRowToPayload(strapi, attrs, row) {
6054
6314
  try {
6055
6315
  const parsed = JSON.parse(rawVal);
6056
6316
  if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
6057
- payload[key] = parsed;
6317
+ payload2[key] = parsed;
6058
6318
  }
6059
6319
  } catch {
6060
6320
  }
@@ -6062,10 +6322,10 @@ function parseRowToPayload(strapi, attrs, row) {
6062
6322
  break;
6063
6323
  }
6064
6324
  default:
6065
- payload[key] = rawVal;
6325
+ payload2[key] = rawVal;
6066
6326
  }
6067
6327
  }
6068
- return payload;
6328
+ return payload2;
6069
6329
  }
6070
6330
  function formatValueDisplay(val) {
6071
6331
  if (val === null || val === void 0) return "(empty)";
@@ -6109,6 +6369,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6109
6369
  created: 0,
6110
6370
  updated: 0,
6111
6371
  skipped: 0,
6372
+ failed: 0,
6112
6373
  newWithoutDocId: 0,
6113
6374
  errors: [],
6114
6375
  diffs: []
@@ -6131,7 +6392,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6131
6392
  } catch {
6132
6393
  }
6133
6394
  }
6134
- const payload = parseRowToPayload(strapi, attrs, row);
6395
+ const payload2 = parseRowToPayload(strapi, attrs, row);
6135
6396
  try {
6136
6397
  if (mode === "update") {
6137
6398
  if (!docId) {
@@ -6153,10 +6414,10 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6153
6414
  continue;
6154
6415
  }
6155
6416
  const resolvedDocId = existing.documentId || docId;
6156
- const mergedPayload = { ...payload };
6157
- for (const key of Object.keys(payload)) {
6158
- if (attrs[key]?.type === "component" && typeof payload[key] === "object" && payload[key] !== null) {
6159
- mergedPayload[key] = deepMergeComponent(existing[key], payload[key]);
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]);
6160
6421
  }
6161
6422
  }
6162
6423
  if (Object.keys(mergedPayload).length === 0) {
@@ -6211,6 +6472,29 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6211
6472
  data: mergedPayload
6212
6473
  };
6213
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
+ }
6214
6498
  await strapi.documents(uid).update(updateArgs);
6215
6499
  if (shouldPublish) {
6216
6500
  try {
@@ -6231,9 +6515,9 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6231
6515
  } catch {
6232
6516
  }
6233
6517
  stats.updated++;
6234
- for (const attrKey of Object.keys(payload)) {
6518
+ for (const attrKey of Object.keys(payload2)) {
6235
6519
  const oldVal = existing?.[attrKey] ?? null;
6236
- const newVal = payload[attrKey];
6520
+ const newVal = payload2[attrKey];
6237
6521
  stats.diffs.push({
6238
6522
  uid,
6239
6523
  collectionName: ct.info?.displayName || uid,
@@ -6253,10 +6537,10 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6253
6537
  }
6254
6538
  if (existing) {
6255
6539
  const resolvedDocId = existing.documentId || docId;
6256
- const mergedPayload = { ...payload };
6257
- for (const key of Object.keys(payload)) {
6258
- if (attrs[key]?.type === "component" && typeof payload[key] === "object" && payload[key] !== null) {
6259
- mergedPayload[key] = deepMergeComponent(existing[key], payload[key]);
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]);
6260
6544
  }
6261
6545
  }
6262
6546
  let pubRecord = effectiveLocale && publishedCounterparts.get(`${resolvedDocId}@@@${effectiveLocale}`) || publishedCounterparts.get(String(resolvedDocId));
@@ -6296,6 +6580,29 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6296
6580
  data: mergedPayload
6297
6581
  };
6298
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
+ }
6299
6606
  await strapi.documents(uid).update(updateArgs);
6300
6607
  if (shouldPublish) {
6301
6608
  try {
@@ -6316,9 +6623,9 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6316
6623
  } catch {
6317
6624
  }
6318
6625
  stats.updated++;
6319
- for (const attrKey of Object.keys(payload)) {
6626
+ for (const attrKey of Object.keys(payload2)) {
6320
6627
  const oldVal = existing?.[attrKey] ?? null;
6321
- const newVal = payload[attrKey];
6628
+ const newVal = payload2[attrKey];
6322
6629
  stats.diffs.push({
6323
6630
  uid,
6324
6631
  collectionName: ct.info?.displayName || uid,
@@ -6333,7 +6640,29 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6333
6640
  }
6334
6641
  continue;
6335
6642
  }
6336
- const createArgs = { data: payload };
6643
+ const valResultNew = await validateEntityQuotas(strapi, uid, payload2);
6644
+ if (!valResultNew.isValid) {
6645
+ stats.skipped++;
6646
+ if (stats.failed !== void 0) stats.failed++;
6647
+ stats.errors.push({
6648
+ row: rowNumber,
6649
+ documentId: docId || "new",
6650
+ error: valResultNew.errorMessage
6651
+ });
6652
+ stats.diffs.push({
6653
+ uid,
6654
+ collectionName: ct.info?.displayName || uid,
6655
+ documentId: docId || "new",
6656
+ label: `Row ${rowNumber}`,
6657
+ attribute: valResultNew.targetField || "",
6658
+ oldValue: null,
6659
+ newValue: payload2?.[valResultNew.targetField || ""] ?? null,
6660
+ status: "error",
6661
+ message: valResultNew.errorMessage
6662
+ });
6663
+ continue;
6664
+ }
6665
+ const createArgs = { data: payload2 };
6337
6666
  if (effectiveLocale) createArgs.locale = effectiveLocale;
6338
6667
  const created = await strapi.documents(uid).create(createArgs);
6339
6668
  const newDocId = created?.documentId || docId;
@@ -6360,7 +6689,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6360
6689
  if (!docId) {
6361
6690
  stats.newWithoutDocId++;
6362
6691
  }
6363
- for (const attrKey of Object.keys(payload)) {
6692
+ for (const attrKey of Object.keys(payload2)) {
6364
6693
  stats.diffs.push({
6365
6694
  uid,
6366
6695
  collectionName: ct.info?.displayName || uid,
@@ -6368,7 +6697,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6368
6697
  label: created?.title || created?.name || `New Entry #${newDocId}`,
6369
6698
  attribute: attrKey,
6370
6699
  oldValue: null,
6371
- newValue: payload[attrKey],
6700
+ newValue: payload2[attrKey],
6372
6701
  status: "created",
6373
6702
  message: docId ? `Created "${attrKey}" via CSV import (row ${rowNumber})` : `Created "${attrKey}" as new entry (row ${rowNumber})`
6374
6703
  });
@@ -6380,10 +6709,10 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6380
6709
  }
6381
6710
  if (existing) {
6382
6711
  const resolvedDocId = existing.documentId || docId;
6383
- const mergedPayload = { ...payload };
6384
- for (const key of Object.keys(payload)) {
6385
- if (attrs[key]?.type === "component" && typeof payload[key] === "object" && payload[key] !== null) {
6386
- mergedPayload[key] = deepMergeComponent(existing[key], payload[key]);
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]);
6387
6716
  }
6388
6717
  }
6389
6718
  let pubRecord = effectiveLocale && publishedCounterparts.get(`${resolvedDocId}@@@${effectiveLocale}`) || publishedCounterparts.get(String(resolvedDocId));
@@ -6423,6 +6752,29 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6423
6752
  data: mergedPayload
6424
6753
  };
6425
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
+ }
6426
6778
  await strapi.documents(uid).update(updateArgs);
6427
6779
  if (shouldPublish) {
6428
6780
  try {
@@ -6443,9 +6795,9 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6443
6795
  } catch {
6444
6796
  }
6445
6797
  stats.updated++;
6446
- for (const attrKey of Object.keys(payload)) {
6798
+ for (const attrKey of Object.keys(payload2)) {
6447
6799
  const oldVal = existing?.[attrKey] ?? null;
6448
- const newVal = payload[attrKey];
6800
+ const newVal = payload2[attrKey];
6449
6801
  stats.diffs.push({
6450
6802
  uid,
6451
6803
  collectionName: ct.info?.displayName || uid,
@@ -6460,7 +6812,29 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6460
6812
  }
6461
6813
  continue;
6462
6814
  }
6463
- const createArgs = { data: payload };
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 };
6464
6838
  if (effectiveLocale) createArgs.locale = effectiveLocale;
6465
6839
  const created = await strapi.documents(uid).create(createArgs);
6466
6840
  const newDocId = created?.documentId || docId;
@@ -6487,7 +6861,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6487
6861
  if (!docId) {
6488
6862
  stats.newWithoutDocId++;
6489
6863
  }
6490
- for (const attrKey of Object.keys(payload)) {
6864
+ for (const attrKey of Object.keys(payload2)) {
6491
6865
  stats.diffs.push({
6492
6866
  uid,
6493
6867
  collectionName: ct.info?.displayName || uid,
@@ -6495,7 +6869,7 @@ async function processCsvRows(strapi, ct, uid, rows, startRowNumber, options) {
6495
6869
  label: created?.title || created?.name || `New Entry #${newDocId}`,
6496
6870
  attribute: attrKey,
6497
6871
  oldValue: null,
6498
- newValue: payload[attrKey],
6872
+ newValue: payload2[attrKey],
6499
6873
  status: "created",
6500
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})`
6501
6875
  });
@@ -6904,6 +7278,7 @@ const csvService = ({ strapi }) => ({
6904
7278
  created: 0,
6905
7279
  updated: 0,
6906
7280
  skipped: 0,
7281
+ failed: 0,
6907
7282
  newWithoutDocId: 0,
6908
7283
  errors: [],
6909
7284
  diffs: [],
@@ -6918,6 +7293,7 @@ const csvService = ({ strapi }) => ({
6918
7293
  session.created += chunkStats.created;
6919
7294
  session.updated += chunkStats.updated;
6920
7295
  session.skipped += chunkStats.skipped;
7296
+ session.failed = (session.failed || 0) + (chunkStats.failed || 0);
6921
7297
  session.newWithoutDocId += chunkStats.newWithoutDocId;
6922
7298
  session.errors.push(...chunkStats.errors);
6923
7299
  session.diffs.push(...chunkStats.diffs);
@@ -6945,6 +7321,7 @@ const csvService = ({ strapi }) => ({
6945
7321
  created: session.created,
6946
7322
  updated: session.updated,
6947
7323
  skipped: session.skipped,
7324
+ failed: session.failed || 0,
6948
7325
  newWithoutDocId: session.newWithoutDocId,
6949
7326
  errors: session.errors,
6950
7327
  diffs: session.diffs
@@ -7221,7 +7598,7 @@ const csvService = ({ strapi }) => ({
7221
7598
  if (activeRules.length > 0) {
7222
7599
  for (const rule of activeRules) {
7223
7600
  if (rule.collectionUid && rule.collectionUid !== "*" && rule.collectionUid !== uid) continue;
7224
- if (rule.includeRichTextHtml && (rawVal.includes("<h") || rawVal.includes("# "))) {
7601
+ if (rule.includeRichTextHtml && (/<h[1-6]\b/i.test(rawVal) || rawVal.includes("# "))) {
7225
7602
  const headings = extractHeadingsFromRichText(rawVal);
7226
7603
  for (const [tag, count] of Object.entries(headings)) {
7227
7604
  const max = rule.quotas?.[tag.toLowerCase()];
@@ -7237,6 +7614,18 @@ const csvService = ({ strapi }) => ({
7237
7614
  }
7238
7615
  }
7239
7616
  }
7617
+ if (activeRules.length > 0) {
7618
+ const proposedEntity = existing ? deepMergeEntities(existing, payload) : payload;
7619
+ const valResult = await validateEntityQuotas(strapi, uid, proposedEntity, activeRules);
7620
+ if (!valResult.isValid) {
7621
+ errors2.push({
7622
+ row: rowNumber,
7623
+ documentId: docId || void 0,
7624
+ error: valResult.errorMessage
7625
+ });
7626
+ rowHasError = true;
7627
+ }
7628
+ }
7240
7629
  if (!rowHasError) {
7241
7630
  validRows++;
7242
7631
  }
@@ -7312,12 +7701,12 @@ const csvService = ({ strapi }) => ({
7312
7701
  });
7313
7702
  continue;
7314
7703
  }
7315
- const payload = parseRowToPayload(strapi, attrs, row);
7704
+ const payload2 = parseRowToPayload(strapi, attrs, row);
7316
7705
  if (existing) {
7317
7706
  const resolvedDocId = existing.documentId || docId;
7318
7707
  const entryLabel = existing.title || existing.name || existing.slug || `Entry #${resolvedDocId}`;
7319
7708
  let rowHasChanges = false;
7320
- const payloadKeys = Object.keys(payload);
7709
+ const payloadKeys = Object.keys(payload2);
7321
7710
  if (payloadKeys.length === 0) {
7322
7711
  unchangedCount++;
7323
7712
  diffs.push({
@@ -7338,7 +7727,7 @@ const csvService = ({ strapi }) => ({
7338
7727
  } else {
7339
7728
  for (const attrKey of payloadKeys) {
7340
7729
  const oldVal = existing?.[attrKey] ?? null;
7341
- let newVal = payload[attrKey];
7730
+ let newVal = payload2[attrKey];
7342
7731
  if (attrs[attrKey]?.type === "component" && typeof newVal === "object" && newVal !== null) {
7343
7732
  newVal = deepMergeComponent(existing[attrKey], newVal);
7344
7733
  }
@@ -7373,8 +7762,8 @@ const csvService = ({ strapi }) => ({
7373
7762
  } else {
7374
7763
  willCreateCount++;
7375
7764
  const resolvedDocId = docId || `(Auto-generated)`;
7376
- const entryLabel = payload.title || payload.name || payload.slug || `New Entry (Row #${rowNumber})`;
7377
- const payloadKeys = Object.keys(payload);
7765
+ const entryLabel = payload2.title || payload2.name || payload2.slug || `New Entry (Row #${rowNumber})`;
7766
+ const payloadKeys = Object.keys(payload2);
7378
7767
  if (payloadKeys.length === 0) {
7379
7768
  diffs.push({
7380
7769
  uid,
@@ -7393,7 +7782,7 @@ const csvService = ({ strapi }) => ({
7393
7782
  });
7394
7783
  } else {
7395
7784
  for (const attrKey of payloadKeys) {
7396
- const newVal = payload[attrKey];
7785
+ const newVal = payload2[attrKey];
7397
7786
  diffs.push({
7398
7787
  uid,
7399
7788
  collectionName: ct.info?.displayName || uid,
@@ -7741,139 +8130,28 @@ const index = {
7741
8130
  if (["create", "update"].includes(context.action)) {
7742
8131
  const data = params?.data;
7743
8132
  if (data && typeof data === "object") {
7744
- let scanDataTree = function(obj, currentPath = "") {
7745
- if (!obj || typeof obj !== "object") return;
7746
- const compName = typeof obj.__component === "string" ? obj.__component : "";
7747
- for (const key of Object.keys(obj)) {
7748
- if (key === "__component") continue;
7749
- const val = obj[key];
7750
- const newPath = currentPath ? `${currentPath}.${key}` : key;
7751
- const normalizedPath = newPath.replace(/\.\d+/g, "");
7752
- const compPath = compName ? (currentPath ? `${currentPath}.${compName}.${key}` : `${compName}.${key}`).replace(/\.\d+/g, "") : "";
7753
- for (const rule of effectiveRules) {
7754
- const isMatch = matchesPath(normalizedPath, key, rule.targetField) || (compPath ? matchesPath(compPath, key, rule.targetField) : false);
7755
- if (isMatch && typeof val === "string" && val.trim()) {
7756
- const lowerVal = val.toLowerCase().trim();
7757
- structuredCounts[rule.id] = structuredCounts[rule.id] || {};
7758
- structuredCounts[rule.id][lowerVal] = (structuredCounts[rule.id][lowerVal] || 0) + 1;
7759
- }
7760
- }
7761
- if (typeof val === "string" && (val.includes("<h") || val.includes("#"))) {
7762
- const headings = extractHeadingsFromRichText(val);
7763
- for (const [tag, count] of Object.entries(headings)) {
7764
- if (count > 0) {
7765
- richTextCounts[tag] = (richTextCounts[tag] || 0) + count;
7766
- }
7767
- }
7768
- } else if (Array.isArray(val) && val.length > 0 && typeof val[0] === "object" && val[0]?.type) {
7769
- const headings = extractHeadingsFromRichText(val);
7770
- for (const [tag, count] of Object.entries(headings)) {
7771
- if (count > 0) {
7772
- richTextCounts[tag] = (richTextCounts[tag] || 0) + count;
7773
- }
7774
- }
7775
- continue;
7776
- }
7777
- if (typeof val === "object" && val !== null) {
7778
- scanDataTree(val, newPath);
7779
- }
7780
- }
7781
- };
7782
- let activeUiRules = [];
7783
- try {
7784
- const rulesService = strapi.plugin("bulk-updater").service("validationRules");
7785
- if (rulesService) {
7786
- const allRules = await rulesService.getRules();
7787
- activeUiRules = allRules.filter((r) => r.enabled);
7788
- }
7789
- } catch (err) {
7790
- strapi.log.warn("[bulk-updater] Failed to fetch active UI validation rules:", err);
7791
- }
7792
- const effectiveRules = [
7793
- ...activeUiRules.filter((r) => {
7794
- if (!r.collectionUid || r.collectionUid === "*") return true;
7795
- if (r.collectionUid === context.uid) return true;
7796
- const cleanRuleCol = cleanKey(r.collectionUid);
7797
- const cleanCtxCol = cleanKey(context.uid);
7798
- return cleanCtxCol.includes(cleanRuleCol) || cleanRuleCol.includes(cleanCtxCol);
7799
- }).map((r) => ({
7800
- id: r.id || r.targetField,
7801
- name: r.name || r.targetField,
7802
- collectionUid: r.collectionUid || "*",
7803
- targetField: r.targetField,
7804
- quotas: r.quotas || {},
7805
- includeRichTextHtml: Boolean(r.includeRichTextHtml),
7806
- richTextFields: r.richTextFields || []
7807
- }))
7808
- ];
7809
- const allComponents = strapi.components || {};
7810
- for (const comp of Object.values(allComponents)) {
7811
- const attrs = comp.attributes || {};
7812
- for (const [attrName, attrDef] of Object.entries(attrs)) {
7813
- if (attrDef.type === "customField" && (attrDef.customField === "plugin::bulk-updater.scoped-select" || attrDef.customField === "global::scoped-select") && !effectiveRules.some((r) => matchesPath(attrName, attrName, r.targetField))) {
7814
- const quotas = attrDef.options?.quotas || {};
7815
- const items = attrDef.options?.items || [];
7816
- const itemQuotas = {};
7817
- for (const item of items) {
7818
- if (typeof item.maxAllowed === "number" && item.maxAllowed > 0) {
7819
- itemQuotas[item.value] = item.maxAllowed;
7820
- }
7821
- }
7822
- effectiveRules.push({
7823
- id: `schema_${attrName}`,
7824
- name: `${attrName} quota rule`,
7825
- collectionUid: "*",
7826
- targetField: attrName,
7827
- quotas: {
7828
- h1: 1,
7829
- h2: 3,
7830
- ...itemQuotas,
7831
- ...quotas
7832
- },
7833
- includeRichTextHtml: true,
7834
- richTextFields: []
7835
- });
7836
- }
7837
- }
7838
- }
7839
- const structuredCounts = {};
7840
- const richTextCounts = { h1: 0, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 };
7841
- let dataToScan = data;
8133
+ let fullEntity = data;
7842
8134
  if (context.action === "update" && (params?.documentId || params?.where?.documentId)) {
7843
8135
  const docId = params?.documentId || params?.where?.documentId;
7844
8136
  if (context.uid && docId) {
7845
8137
  try {
7846
- const existing = await strapi.db?.query?.(context.uid)?.findOne?.({
7847
- where: { documentId: docId },
7848
- populate: true
8138
+ const ct = strapi.contentTypes[context.uid];
8139
+ const populateDef = ct?.attributes ? buildDeepPopulate$1(ct.attributes, strapi.components) : void 0;
8140
+ const existing = await strapi.documents(context.uid).findOne({
8141
+ documentId: docId,
8142
+ ...params?.locale ? { locale: params.locale } : {},
8143
+ ...populateDef ? { populate: populateDef } : { populate: "*" }
7849
8144
  });
7850
8145
  if (existing) {
7851
- dataToScan = { ...existing, ...data };
8146
+ fullEntity = deepMergeEntities(existing, data);
7852
8147
  }
7853
8148
  } catch {
7854
8149
  }
7855
8150
  }
7856
8151
  }
7857
- scanDataTree(dataToScan);
7858
- for (const rule of effectiveRules) {
7859
- const ruleCounts = structuredCounts[rule.id] || {};
7860
- for (const [quotaKey, maxAllowed] of Object.entries(rule.quotas || {})) {
7861
- const lowerVal = quotaKey.toLowerCase().trim();
7862
- const structCount = ruleCounts[lowerVal] || 0;
7863
- const rtCount = rule.includeRichTextHtml ? richTextCounts[lowerVal] || 0 : 0;
7864
- const totalFound = structCount + rtCount;
7865
- if (totalFound > maxAllowed) {
7866
- let detailMsg = `Option "${quotaKey.toUpperCase()}" cannot appear more than ${maxAllowed} time(s) across this entry.`;
7867
- if (rtCount > 0 && structCount > 0) {
7868
- detailMsg += ` Found ${totalFound} occurrences combined: ${structCount} in structured component ('${rule.targetField}') and ${rtCount} in rich text HTML / Markdown.`;
7869
- } else if (rtCount > 0) {
7870
- detailMsg += ` Found ${totalFound} in rich text HTML / Markdown content.`;
7871
- } else {
7872
- detailMsg += ` Found ${totalFound} in structured field '${rule.targetField}'.`;
7873
- }
7874
- throw createValidationError(rule.name, detailMsg, rule.targetField);
7875
- }
7876
- }
8152
+ const valResult = await validateEntityQuotas(strapi, context.uid, fullEntity);
8153
+ if (!valResult.isValid) {
8154
+ throw createValidationError(valResult.ruleName, valResult.errorMessage, valResult.targetField);
7877
8155
  }
7878
8156
  }
7879
8157
  }