@zachariaz/strapi-plugin-experience-context 0.0.0-stage → 0.1.0-dev.0

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.
Files changed (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +78 -2
  3. package/dist/_chunks/en-8ms9Hfxr.mjs +27 -0
  4. package/dist/_chunks/en-yERKDiB0.js +27 -0
  5. package/dist/admin/index.js +464 -0
  6. package/dist/admin/index.mjs +448 -0
  7. package/dist/admin/src/api/client.d.ts +13 -0
  8. package/dist/admin/src/api/types.d.ts +93 -0
  9. package/dist/admin/src/api/useInspect.d.ts +3 -0
  10. package/dist/admin/src/components/BlockMarkers.d.ts +12 -0
  11. package/dist/admin/src/components/ExperienceModal.d.ts +28 -0
  12. package/dist/admin/src/components/HeaderBadge.d.ts +19 -0
  13. package/dist/admin/src/components/Initializer.d.ts +5 -0
  14. package/dist/admin/src/components/ModalTrigger.d.ts +10 -0
  15. package/dist/admin/src/contentManagerHooks/editView.d.ts +7 -0
  16. package/dist/admin/src/index.d.ts +17 -0
  17. package/dist/admin/src/pluginId.d.ts +2 -0
  18. package/dist/admin/src/utils/dzSlots.d.ts +16 -0
  19. package/dist/admin/src/utils/labels.d.ts +30 -0
  20. package/dist/admin/src/utils/markers.d.ts +12 -0
  21. package/dist/admin/src/utils/modal.d.ts +10 -0
  22. package/dist/admin/src/utils/targets.d.ts +12 -0
  23. package/dist/server/index.js +3694 -0
  24. package/dist/server/index.mjs +3695 -0
  25. package/dist/server/src/admin-api/access.d.ts +40 -0
  26. package/dist/server/src/admin-api/inspect.d.ts +132 -0
  27. package/dist/server/src/admin-api/mark.d.ts +9 -0
  28. package/dist/server/src/block-keys/index.d.ts +16 -0
  29. package/dist/server/src/block-keys/middleware.d.ts +17 -0
  30. package/dist/server/src/block-keys/stamp.d.ts +55 -0
  31. package/dist/server/src/block-keys/store.d.ts +33 -0
  32. package/dist/server/src/block-keys/targets.d.ts +43 -0
  33. package/dist/server/src/bootstrap.d.ts +16 -0
  34. package/dist/server/src/changes.d.ts +80 -0
  35. package/dist/server/src/config/index.d.ts +67 -0
  36. package/dist/server/src/constants.d.ts +18 -0
  37. package/dist/server/src/content-types/index.d.ts +309 -0
  38. package/dist/server/src/controllers/admin.d.ts +10 -0
  39. package/dist/server/src/controllers/experience.d.ts +15 -0
  40. package/dist/server/src/controllers/index.d.ts +16 -0
  41. package/dist/server/src/destroy.d.ts +5 -0
  42. package/dist/server/src/index.d.ts +441 -0
  43. package/dist/server/src/integrity/index.d.ts +34 -0
  44. package/dist/server/src/integrity/orphans.d.ts +40 -0
  45. package/dist/server/src/mcp/index.d.ts +2 -0
  46. package/dist/server/src/mcp/operations.d.ts +765 -0
  47. package/dist/server/src/mcp/permissions.d.ts +56 -0
  48. package/dist/server/src/mcp/tools.d.ts +59 -0
  49. package/dist/server/src/model/content.d.ts +32 -0
  50. package/dist/server/src/model/mapping.d.ts +90 -0
  51. package/dist/server/src/model/records.d.ts +132 -0
  52. package/dist/server/src/model/store.d.ts +44 -0
  53. package/dist/server/src/model/target.d.ts +40 -0
  54. package/dist/server/src/policies/index.d.ts +4 -0
  55. package/dist/server/src/rbac/index.d.ts +24 -0
  56. package/dist/server/src/read-path/editor.d.ts +28 -0
  57. package/dist/server/src/read-path/gate.d.ts +26 -0
  58. package/dist/server/src/read-path/index.d.ts +12 -0
  59. package/dist/server/src/read-path/loader.d.ts +31 -0
  60. package/dist/server/src/read-path/middleware.d.ts +32 -0
  61. package/dist/server/src/read-path/payload.d.ts +34 -0
  62. package/dist/server/src/read-path/populate.d.ts +6 -0
  63. package/dist/server/src/register.d.ts +14 -0
  64. package/dist/server/src/registry/index.d.ts +29 -0
  65. package/dist/server/src/registry/unomi.d.ts +53 -0
  66. package/dist/server/src/routes/index.d.ts +25 -0
  67. package/dist/server/src/services/index.d.ts +79 -0
  68. package/package.json +140 -4
  69. package/scripts/experience-smoke.mjs +430 -0
@@ -0,0 +1,3695 @@
1
+ import { validateExperienceMapping, parseConcept, parseTrait, parseAudience, parseAffinity, CONTRACT_VERSION, fromSegmentName, isSlug, formatAudience, resolvePage, explainResolution, sanitizeContext, effectiveContext, sanitizePreviewContext, isExperimentKey, describeSplit } from "@zachariaz/experience-context-core";
2
+ import { randomUUID } from "node:crypto";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
4
+ import { z } from "@strapi/utils";
5
+ const PLUGIN_ID = "experience-context";
6
+ const LOG_PREFIX = `[${PLUGIN_ID}]`;
7
+ const ANNOTATION_UID = `plugin::${PLUGIN_ID}.annotation`;
8
+ const VARIATION_UID = `plugin::${PLUGIN_ID}.variation`;
9
+ const EXPERIMENT_UID = `plugin::${PLUGIN_ID}.experiment`;
10
+ const CHANGE_UID = `plugin::${PLUGIN_ID}.change`;
11
+ const CONTENT_ZONE = "content";
12
+ const EXPERIENCE_KEY = "_experience";
13
+ const FLAG = "withExperience";
14
+ const AGENT_INSTRUCTION = "Strapi MCP creates and maps content alternatives. If the customer context you need (audience, trait, affinity, experiment) does not exist, find or create it with Unomi MCP first, then reference its id in Strapi. Never describe customer conditions in Strapi.";
15
+ const DEFAULT_CONTENT_TYPES = [
16
+ "api::home.home",
17
+ "api::landing-page.landing-page",
18
+ "api::pdp.pdp",
19
+ "api::product.product",
20
+ "api::category.category",
21
+ "api::collection.collection",
22
+ "api::category-listing.category-listing"
23
+ ];
24
+ const defaultConfig = {};
25
+ function resolveContentTypes(value) {
26
+ return value === void 0 ? [...DEFAULT_CONTENT_TYPES] : value;
27
+ }
28
+ const rawOption = (strapi, key) => strapi.config.get(`plugin::${PLUGIN_ID}.${key}`);
29
+ const configuredContentTypes = (strapi) => resolveContentTypes(rawOption(strapi, "contentTypes")).slice();
30
+ const configuredRegistry = (strapi) => rawOption(strapi, "registry") ?? {};
31
+ const configuredUnomi = (strapi) => rawOption(strapi, "unomi") ?? void 0;
32
+ const configuredRoles = (strapi) => rawOption(strapi, "roles") === true;
33
+ const configuredPresets = (strapi) => {
34
+ const presets = rawOption(strapi, "presets");
35
+ return Array.isArray(presets) ? presets : [];
36
+ };
37
+ const UID_PATTERN = /^api::[a-z0-9-]+\.[a-z0-9-]+$/;
38
+ const REGISTRY_PARSERS = {
39
+ audiences: parseAudience,
40
+ traits: parseTrait,
41
+ // Affinity entries name a concept (`<vocabulary>/<slug>`), `affinity/<concept>` or a banded affinity id.
42
+ affinities: (id) => parseConcept(id) ?? parseAffinity(id) ?? (typeof id === "string" && id.startsWith("affinity/") ? parseConcept(id.slice("affinity/".length)) : null),
43
+ concepts: parseConcept
44
+ };
45
+ function registryProblems(registry2) {
46
+ if (registry2 === void 0) return [];
47
+ if (!registry2 || typeof registry2 !== "object" || Array.isArray(registry2)) return ["`registry` must be an object"];
48
+ const problems = [];
49
+ for (const [kind2, list] of Object.entries(registry2)) {
50
+ const parse = REGISTRY_PARSERS[kind2];
51
+ if (!parse) {
52
+ problems.push(`\`registry.${kind2}\` is not a registry list (audiences, traits, affinities, concepts)`);
53
+ continue;
54
+ }
55
+ if (!Array.isArray(list)) {
56
+ problems.push(`\`registry.${kind2}\` must be an array of { id, label, description? }`);
57
+ continue;
58
+ }
59
+ list.forEach((entry, i) => {
60
+ const id = entry?.id;
61
+ if (!parse(id)) problems.push(`\`registry.${kind2}[${i}].id\` ${JSON.stringify(id)} is not a valid ${kind2.replace(/s$/, "")} id`);
62
+ });
63
+ }
64
+ return problems;
65
+ }
66
+ function unomiProblems(unomi) {
67
+ if (unomi === void 0) return [];
68
+ if (!unomi || typeof unomi !== "object" || Array.isArray(unomi)) return ["`unomi` must be an object"];
69
+ const u = unomi;
70
+ const problems = [];
71
+ if (u.url !== void 0 && (typeof u.url !== "string" || u.url !== "" && !/^https?:\/\/\S+$/.test(u.url))) {
72
+ problems.push("`unomi.url` must be an http(s) URL (or empty to turn the source off)");
73
+ }
74
+ for (const k of ["username", "password", "scope"]) {
75
+ if (u[k] !== void 0 && typeof u[k] !== "string") problems.push(`\`unomi.${k}\` must be a string`);
76
+ }
77
+ for (const k of ["ttlSeconds", "timeoutMs"]) {
78
+ if (u[k] !== void 0 && !(typeof u[k] === "number" && u[k] > 0)) problems.push(`\`unomi.${k}\` must be a positive number`);
79
+ }
80
+ return problems;
81
+ }
82
+ function presetProblems(presets) {
83
+ if (presets === void 0) return [];
84
+ if (!Array.isArray(presets)) return ["`presets` must be an array of { name, context }"];
85
+ const problems = [];
86
+ presets.forEach((p, i) => {
87
+ if (!p || typeof p !== "object" || typeof p.name !== "string" || !p.name) {
88
+ problems.push(`\`presets[${i}]\` needs a name`);
89
+ }
90
+ });
91
+ const result2 = validateExperienceMapping({ variations: [], presets });
92
+ for (const e of result2.errors) problems.push(`${e.path}: ${e.message}`);
93
+ return problems;
94
+ }
95
+ const config = {
96
+ default: defaultConfig,
97
+ validator(config2) {
98
+ const contentTypes2 = resolveContentTypes(config2.contentTypes);
99
+ if (!Array.isArray(contentTypes2)) {
100
+ throw new Error(`${PLUGIN_ID}: \`contentTypes\` must be an array of content type UIDs`);
101
+ }
102
+ for (const uid of contentTypes2) {
103
+ if (typeof uid !== "string" || !UID_PATTERN.test(uid)) {
104
+ throw new Error(`${PLUGIN_ID}: \`contentTypes\` entry ${JSON.stringify(uid)} is not an api:: content type UID`);
105
+ }
106
+ }
107
+ const problems = [...registryProblems(config2.registry), ...presetProblems(config2.presets), ...unomiProblems(config2.unomi)];
108
+ if (config2.roles !== void 0 && typeof config2.roles !== "boolean") problems.push("`roles` must be true or false");
109
+ if (problems.length > 0) throw new Error(`${PLUGIN_ID}: invalid config:
110
+ - ${problems.join("\n- ")}`);
111
+ }
112
+ };
113
+ const BLOCK_KEY = "blockKey";
114
+ const TARGET_DYNAMIC_ZONES = ["content"];
115
+ const TARGET_COMPONENT_PREFIX = "zone.";
116
+ const BLOCK_KEY_ATTRIBUTE = Object.freeze({
117
+ type: "string",
118
+ visible: false,
119
+ configurable: false
120
+ });
121
+ function resolveTargets(contentTypes2, configured) {
122
+ const zonesByUid = /* @__PURE__ */ new Map();
123
+ const keyedComponents = /* @__PURE__ */ new Set();
124
+ for (const uid of configured) {
125
+ const attributes2 = contentTypes2[uid]?.attributes;
126
+ if (!attributes2) continue;
127
+ const zones = [];
128
+ for (const name of TARGET_DYNAMIC_ZONES) {
129
+ const attr = attributes2[name];
130
+ if (attr?.type !== "dynamiczone") continue;
131
+ const keyed = (attr.components ?? []).filter((c) => c.startsWith(TARGET_COMPONENT_PREFIX));
132
+ if (keyed.length === 0) continue;
133
+ zones.push(name);
134
+ keyed.forEach((c) => keyedComponents.add(c));
135
+ }
136
+ if (zones.length > 0) zonesByUid.set(uid, zones);
137
+ }
138
+ return { zonesByUid, keyedComponents };
139
+ }
140
+ function getTargets(strapi, configured) {
141
+ return resolveTargets(strapi.contentTypes, configured);
142
+ }
143
+ function injectBlockKeyAttribute(strapi, targets) {
144
+ const added = [];
145
+ const components = strapi.components;
146
+ for (const uid of targets.keyedComponents) {
147
+ const component = components[uid];
148
+ if (!component?.attributes) continue;
149
+ if (component.attributes[BLOCK_KEY]) continue;
150
+ component.attributes[BLOCK_KEY] = { ...BLOCK_KEY_ATTRIBUTE };
151
+ added.push(uid);
152
+ }
153
+ return added;
154
+ }
155
+ const hasKey = (value) => typeof value === "string" && value.trim() !== "";
156
+ const idOf = (block) => typeof block.id === "number" || typeof block.id === "string" && block.id !== "" ? String(block.id) : void 0;
157
+ const keyedBlock = (block, isKeyed) => Boolean(block) && typeof block === "object" && typeof block.__component === "string" && isKeyed(block.__component);
158
+ function lookupsFor(blocks, isKeyed) {
159
+ const out = /* @__PURE__ */ new Map();
160
+ if (!Array.isArray(blocks)) return out;
161
+ for (const block of blocks) {
162
+ if (!keyedBlock(block, isKeyed) || hasKey(block[BLOCK_KEY])) continue;
163
+ const id = idOf(block);
164
+ if (id === void 0) continue;
165
+ const ids = out.get(block.__component) ?? [];
166
+ if (!ids.includes(id)) ids.push(id);
167
+ out.set(block.__component, ids);
168
+ }
169
+ return out;
170
+ }
171
+ function stampBlocks(blocks, options2) {
172
+ const events = [];
173
+ if (!Array.isArray(blocks)) return events;
174
+ const newKey = options2.newKey ?? randomUUID;
175
+ const seenIds = /* @__PURE__ */ new Set();
176
+ const seenKeys = /* @__PURE__ */ new Set();
177
+ blocks.forEach((block, index2) => {
178
+ if (!keyedBlock(block, options2.isKeyed)) return;
179
+ const component = block.__component;
180
+ let droppedId = false;
181
+ let id = idOf(block);
182
+ if (id !== void 0) {
183
+ const rowRef = `${component}:${id}`;
184
+ if (seenIds.has(rowRef)) {
185
+ delete block.id;
186
+ droppedId = true;
187
+ id = void 0;
188
+ } else {
189
+ seenIds.add(rowRef);
190
+ }
191
+ }
192
+ const current = block[BLOCK_KEY];
193
+ let kind2;
194
+ let key;
195
+ if (hasKey(current) && !seenKeys.has(current)) {
196
+ kind2 = "kept";
197
+ key = current;
198
+ } else if (hasKey(current)) {
199
+ kind2 = "regenerated";
200
+ key = newKey();
201
+ } else {
202
+ const stored = id !== void 0 ? options2.storedKey?.(component, id) : void 0;
203
+ if (hasKey(stored) && !seenKeys.has(stored)) {
204
+ kind2 = "reused";
205
+ key = stored;
206
+ } else {
207
+ kind2 = "stamped";
208
+ key = newKey();
209
+ }
210
+ }
211
+ block[BLOCK_KEY] = key;
212
+ seenKeys.add(key);
213
+ events.push(droppedId ? { index: index2, component, kind: kind2, key, droppedId } : { index: index2, component, kind: kind2, key });
214
+ });
215
+ return events;
216
+ }
217
+ function pairKeys(blocks, partner, isKeyed, newKey = randomUUID) {
218
+ const seen = /* @__PURE__ */ new Set();
219
+ return blocks.map((block, index2) => {
220
+ if (!keyedBlock(block, isKeyed)) return void 0;
221
+ const current = block[BLOCK_KEY];
222
+ if (hasKey(current) && !seen.has(current)) {
223
+ seen.add(current);
224
+ return void 0;
225
+ }
226
+ const other = partner[index2];
227
+ const candidate = other && other.__component === block.__component && hasKey(other[BLOCK_KEY]) ? other[BLOCK_KEY] : void 0;
228
+ const key = candidate !== void 0 && !seen.has(candidate) ? candidate : newKey();
229
+ seen.add(key);
230
+ return key;
231
+ });
232
+ }
233
+ const db = (strapi, uid) => strapi.db.query(uid);
234
+ async function storedKeys(strapi, lookups) {
235
+ const out = /* @__PURE__ */ new Map();
236
+ for (const [component, ids] of lookups) {
237
+ const numeric = ids.map((id) => /^\d+$/.test(id) ? Number(id) : id);
238
+ const rows = await db(strapi, component).findMany({
239
+ where: { id: { $in: numeric } },
240
+ select: ["id", BLOCK_KEY]
241
+ });
242
+ for (const row of rows) {
243
+ if (hasKey(row[BLOCK_KEY])) out.set(`${component}:${row.id}`, row[BLOCK_KEY]);
244
+ }
245
+ }
246
+ return out;
247
+ }
248
+ async function stampPayload(strapi, targets, uid, data) {
249
+ const zones = targets.zonesByUid.get(uid);
250
+ if (!zones || !data || typeof data !== "object") return [];
251
+ const isKeyed = (c) => targets.keyedComponents.has(c);
252
+ const events = [];
253
+ for (const zone of zones) {
254
+ const blocks = data[zone];
255
+ if (!Array.isArray(blocks)) continue;
256
+ const lookups = lookupsFor(blocks, isKeyed);
257
+ const stored = lookups.size > 0 ? await storedKeys(strapi, lookups) : /* @__PURE__ */ new Map();
258
+ events.push(...stampBlocks(blocks, { isKeyed, storedKey: (c, id) => stored.get(`${c}:${id}`) }));
259
+ }
260
+ return events;
261
+ }
262
+ const isPublished = (row) => row.publishedAt !== null && row.publishedAt !== void 0;
263
+ const chunk = (items, size) => {
264
+ const out = [];
265
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
266
+ return out;
267
+ };
268
+ async function backfill(strapi, targets, options2 = {}) {
269
+ const dryRun2 = options2.dryRun === true;
270
+ const batchSize = Math.max(1, options2.batchSize ?? 50);
271
+ const isKeyed = (c) => targets.keyedComponents.has(c);
272
+ const report2 = { dryRun: dryRun2, updated: 0, contentTypes: {} };
273
+ const uids = [...targets.zonesByUid.keys()].filter(
274
+ (uid) => !options2.contentTypes || options2.contentTypes.includes(uid)
275
+ );
276
+ for (const uid of uids) {
277
+ const zones = targets.zonesByUid.get(uid);
278
+ const typeReport = { rows: 0, documents: 0, blocks: 0, updated: 0 };
279
+ report2.contentTypes[uid] = typeReport;
280
+ const where = {};
281
+ if (options2.documentId) where.documentId = options2.documentId;
282
+ if (options2.locales && options2.locales.length > 0) where.locale = { $in: options2.locales };
283
+ const index2 = await db(strapi, uid).findMany({
284
+ where,
285
+ select: ["id", "documentId"],
286
+ orderBy: { id: "asc" }
287
+ });
288
+ const documentIds = [...new Set(index2.map((r) => r.documentId))];
289
+ typeReport.documents = documentIds.length;
290
+ for (const ids of chunk(documentIds, batchSize)) {
291
+ const rows = await db(strapi, uid).findMany({
292
+ where: { ...where, documentId: { $in: ids } },
293
+ select: ["id", "documentId", "locale", "publishedAt"],
294
+ populate: Object.fromEntries(zones.map((z2) => [z2, true])),
295
+ orderBy: { id: "asc" }
296
+ });
297
+ typeReport.rows += rows.length;
298
+ const groups = /* @__PURE__ */ new Map();
299
+ for (const row of rows) {
300
+ const key = `${row.documentId}\0${row.locale ?? ""}`;
301
+ const group = groups.get(key) ?? { other: [] };
302
+ if (isPublished(row)) {
303
+ if (group.published) group.other.push(row);
304
+ else group.published = row;
305
+ } else if (group.draft) group.other.push(row);
306
+ else group.draft = row;
307
+ groups.set(key, group);
308
+ }
309
+ for (const group of groups.values()) {
310
+ for (const zone of zones) {
311
+ const blocksOf2 = (row) => Array.isArray(row?.[zone]) ? row[zone] : [];
312
+ const draft = blocksOf2(group.draft);
313
+ const published = blocksOf2(group.published);
314
+ typeReport.blocks += [draft, published, ...group.other.map(blocksOf2)].flat().filter((b) => typeof b.__component === "string" && isKeyed(b.__component)).length;
315
+ const plans = [
316
+ [draft, published],
317
+ [published, draft],
318
+ ...group.other.map((row) => [blocksOf2(row), draft])
319
+ ];
320
+ for (const [blocks, partner] of plans) {
321
+ const keys = pairKeys(blocks, partner, isKeyed);
322
+ for (let i = 0; i < blocks.length; i++) {
323
+ const key = keys[i];
324
+ if (key === void 0) continue;
325
+ const block = blocks[i];
326
+ block[BLOCK_KEY] = key;
327
+ typeReport.updated++;
328
+ if (!dryRun2) {
329
+ await db(strapi, block.__component).update({
330
+ where: { id: block.id },
331
+ data: { [BLOCK_KEY]: key }
332
+ });
333
+ }
334
+ }
335
+ }
336
+ }
337
+ }
338
+ }
339
+ report2.updated += typeReport.updated;
340
+ }
341
+ return report2;
342
+ }
343
+ const WRITE_ACTIONS$1 = /* @__PURE__ */ new Set(["create", "update", "clone"]);
344
+ function publishLocales(locale2) {
345
+ if (typeof locale2 === "string" && locale2 !== "" && locale2 !== "*") return [locale2];
346
+ if (Array.isArray(locale2)) {
347
+ const list = locale2.filter((l) => typeof l === "string" && l !== "" && l !== "*");
348
+ return list.length === locale2.length && list.length > 0 ? list : void 0;
349
+ }
350
+ return void 0;
351
+ }
352
+ function registerBlockKeyMiddleware(strapi, targets) {
353
+ strapi.documents.use(async (ctx, next) => {
354
+ const uid = ctx?.uid;
355
+ if (typeof uid !== "string" || !targets.zonesByUid.has(uid)) return next();
356
+ const params = ctx.params ?? {};
357
+ if (WRITE_ACTIONS$1.has(ctx.action) && params.data) {
358
+ await stampPayload(strapi, targets, uid, params.data);
359
+ } else if (ctx.action === "publish" && typeof params.documentId === "string") {
360
+ try {
361
+ await backfill(strapi, targets, {
362
+ contentTypes: [uid],
363
+ documentId: params.documentId,
364
+ locales: publishLocales(params.locale)
365
+ });
366
+ } catch (err) {
367
+ strapi.log.warn(`${LOG_PREFIX} could not key blocks before publish of ${uid} ${params.documentId}: ${err.message}`);
368
+ }
369
+ }
370
+ return next();
371
+ });
372
+ }
373
+ const configuredTypes = (strapi) => configuredContentTypes(strapi);
374
+ const blockKeyTargets = (strapi) => getTargets(strapi, configuredTypes(strapi));
375
+ function registerBlockKeys(strapi) {
376
+ const targets = blockKeyTargets(strapi);
377
+ const added = injectBlockKeyAttribute(strapi, targets);
378
+ if (added.length > 0) strapi.log.debug?.(`${LOG_PREFIX} blockKey added to ${added.join(", ")}`);
379
+ }
380
+ const BACKFILL_STORE_KEY = "block-key-backfill";
381
+ const targetsSignature = (targets) => JSON.stringify({
382
+ zones: [...targets.zonesByUid.entries()].sort(([a], [b]) => a.localeCompare(b)),
383
+ components: [...targets.keyedComponents].sort()
384
+ });
385
+ async function bootstrapBlockKeys(strapi) {
386
+ const targets = blockKeyTargets(strapi);
387
+ if (targets.zonesByUid.size === 0) return;
388
+ registerBlockKeyMiddleware(strapi, targets);
389
+ const store2 = strapi.store?.({ type: "plugin", name: PLUGIN_ID });
390
+ if (!store2) return;
391
+ const signature = targetsSignature(targets);
392
+ try {
393
+ const done = await store2.get({ key: BACKFILL_STORE_KEY });
394
+ if (done?.signature === signature) return;
395
+ const report2 = await backfill(strapi, targets);
396
+ await store2.set({ key: BACKFILL_STORE_KEY, value: { signature, at: (/* @__PURE__ */ new Date()).toISOString(), updated: report2.updated } });
397
+ strapi.log.info(`${LOG_PREFIX} blockKey backfill: ${report2.updated} block(s) keyed`);
398
+ } catch (err) {
399
+ strapi.log.warn(`${LOG_PREFIX} blockKey backfill failed: ${err.message}`);
400
+ }
401
+ }
402
+ const READ_ACTION = `plugin::${PLUGIN_ID}.experience.read`;
403
+ function currentRequest(strapi) {
404
+ try {
405
+ return strapi.requestContext?.get?.();
406
+ } catch {
407
+ return void 0;
408
+ }
409
+ }
410
+ const isTruthyFlag = (v) => v === true || v === "true" || v === "1";
411
+ function flagRequested(params, req) {
412
+ return isTruthyFlag(params?.[FLAG]) || isTruthyFlag(req?.query?.[FLAG]);
413
+ }
414
+ async function checkGate(strapi, req) {
415
+ if (!req) return { ok: false, why: "no request" };
416
+ const auth = req.state?.auth;
417
+ if (!auth?.strategy) return { ok: false, why: "unauthenticated" };
418
+ if (auth.credentials === null || auth.credentials === void 0) return { ok: false, why: "public role" };
419
+ if (auth.strategy.name === "admin" || typeof auth.strategy.verify !== "function") {
420
+ return { ok: false, why: `strategy ${auth.strategy.name} is not a content-API strategy` };
421
+ }
422
+ try {
423
+ await strapi.auth.verify(auth, { scope: [READ_ACTION] });
424
+ return { ok: true, why: `${auth.strategy.name} holds ${READ_ACTION}` };
425
+ } catch {
426
+ return { ok: false, why: `${auth.strategy.name} lacks ${READ_ACTION}` };
427
+ }
428
+ }
429
+ const strings = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string" && v !== "") : [];
430
+ const isRecord = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
431
+ const validityOf = (v) => {
432
+ if (!isRecord(v)) return null;
433
+ const startsAt = typeof v.startsAt === "string" && v.startsAt ? v.startsAt : null;
434
+ const endsAt = typeof v.endsAt === "string" && v.endsAt ? v.endsAt : null;
435
+ return startsAt || endsAt ? { startsAt, endsAt } : null;
436
+ };
437
+ const experimentRefOf = (v) => isRecord(v) && typeof v.key === "string" && v.key && typeof v.outcome === "string" && v.outcome ? { key: v.key, outcome: v.outcome } : null;
438
+ const time = (v) => v instanceof Date ? v.toISOString() : typeof v === "string" ? v : null;
439
+ const toVariationRecord = (row) => ({
440
+ documentId: row?.documentId ?? null,
441
+ targetUid: row?.targetUid,
442
+ targetDocumentId: row?.targetDocumentId,
443
+ locale: row?.targetLocale ?? row?.locale ?? null,
444
+ blockKey: row?.blockKey,
445
+ sectionKey: row?.sectionKey,
446
+ variantKey: row?.variantKey,
447
+ displayName: row?.displayName ?? null,
448
+ description: row?.description ?? null,
449
+ isDefault: row?.isDefault === true,
450
+ status: row?.status === "inactive" ? "inactive" : "active",
451
+ orphaned: row?.orphaned === true,
452
+ targetAudiences: strings(row?.targetAudiences),
453
+ traits: strings(row?.traits),
454
+ affinities: strings(row?.affinities),
455
+ experiment: experimentRefOf(row?.experiment),
456
+ priority: Number.isFinite(Number(row?.priority)) ? Number(row?.priority) : 0,
457
+ validity: validityOf(row?.validity),
458
+ componentUid: row?.componentUid ?? null,
459
+ source: row?.source ?? null,
460
+ createdBy: row?.createdByActor ?? row?.createdBy ?? null,
461
+ correlationId: row?.correlationId ?? null,
462
+ createdAt: time(row?.createdAt),
463
+ updatedAt: time(row?.updatedAt)
464
+ });
465
+ const toAnnotationRecord = (row) => ({
466
+ documentId: row?.documentId ?? null,
467
+ targetUid: row?.targetUid,
468
+ targetDocumentId: row?.targetDocumentId,
469
+ locale: row?.targetLocale ?? row?.locale ?? null,
470
+ blockKey: row?.blockKey ?? null,
471
+ concepts: strings(row?.concepts),
472
+ orphaned: row?.orphaned === true,
473
+ source: row?.source ?? null,
474
+ createdBy: row?.createdByActor ?? row?.createdBy ?? null,
475
+ correlationId: row?.correlationId ?? null,
476
+ createdAt: time(row?.createdAt),
477
+ updatedAt: time(row?.updatedAt)
478
+ });
479
+ const outcomesOf = (v) => Array.isArray(v) ? v.filter((o) => isRecord(o) && typeof o.key === "string").map((o) => ({
480
+ key: o.key,
481
+ label: typeof o.label === "string" ? o.label : null,
482
+ ...o.intentionallyEmpty === true ? { intentionallyEmpty: true } : {},
483
+ // Stored as given; validation (V8) rejects bad weights on write, assignment ignores an invalid set.
484
+ ...o.weight !== void 0 && o.weight !== null ? { weight: o.weight } : {}
485
+ })) : [];
486
+ const toExperimentRecord = (row) => ({
487
+ documentId: row?.documentId ?? null,
488
+ key: row?.key,
489
+ name: row?.name ?? null,
490
+ description: row?.description ?? null,
491
+ outcomes: outcomesOf(row?.outcomes),
492
+ controlOutcome: row?.controlOutcome ?? "",
493
+ status: ["draft", "running", "paused", "concluded"].includes(row?.status) ? row.status : "draft",
494
+ validity: validityOf(row?.validity),
495
+ winner: row?.winner ?? null,
496
+ externalId: row?.externalId ?? null,
497
+ source: row?.source ?? null,
498
+ createdBy: row?.createdByActor ?? row?.createdBy ?? null,
499
+ correlationId: row?.correlationId ?? null,
500
+ createdAt: time(row?.createdAt),
501
+ updatedAt: time(row?.updatedAt)
502
+ });
503
+ const toVariation = (r) => ({
504
+ sectionKey: r.sectionKey,
505
+ variantKey: r.variantKey,
506
+ blockKey: r.blockKey,
507
+ isDefault: r.isDefault,
508
+ displayName: r.displayName,
509
+ description: r.description,
510
+ status: r.orphaned ? "orphaned" : r.status,
511
+ targetAudiences: r.targetAudiences,
512
+ traits: r.traits,
513
+ affinities: r.affinities,
514
+ experiment: r.experiment,
515
+ priority: r.priority,
516
+ validity: r.validity,
517
+ componentUid: r.componentUid
518
+ });
519
+ const toExperiment = (r) => ({
520
+ key: r.key,
521
+ name: r.name ?? null,
522
+ description: r.description ?? null,
523
+ outcomes: r.outcomes,
524
+ controlOutcome: r.controlOutcome,
525
+ status: r.status,
526
+ validity: r.validity ?? null,
527
+ winner: r.winner ?? null,
528
+ externalId: r.externalId ?? null
529
+ });
530
+ const annotationData = (r) => ({
531
+ targetUid: r.targetUid,
532
+ targetDocumentId: r.targetDocumentId,
533
+ targetLocale: r.locale,
534
+ blockKey: r.blockKey,
535
+ concepts: r.concepts,
536
+ orphaned: r.orphaned,
537
+ source: r.source,
538
+ createdByActor: r.createdBy,
539
+ correlationId: r.correlationId
540
+ });
541
+ const experimentData = (r) => ({
542
+ key: r.key,
543
+ name: r.name ?? null,
544
+ description: r.description ?? null,
545
+ outcomes: r.outcomes,
546
+ controlOutcome: r.controlOutcome,
547
+ status: r.status,
548
+ validity: r.validity ?? null,
549
+ winner: r.winner ?? null,
550
+ externalId: r.externalId ?? null,
551
+ source: r.source,
552
+ createdByActor: r.createdBy,
553
+ correlationId: r.correlationId
554
+ });
555
+ function forLocale(rows, locale2) {
556
+ const specific = rows.filter((r) => locale2 !== null && r.locale === locale2);
557
+ const taken = new Set(specific.map((r) => r.blockKey ?? ""));
558
+ const shared = rows.filter((r) => r.locale === null && !taken.has(r.blockKey ?? ""));
559
+ return [...specific, ...shared];
560
+ }
561
+ function liveRows(rows, locale2) {
562
+ return {
563
+ variations: forLocale(rows.variations, locale2).filter((v) => v.status === "active" && !v.orphaned),
564
+ annotations: forLocale(rows.annotations, locale2).filter((a) => !a.orphaned && a.concepts.length > 0)
565
+ };
566
+ }
567
+ const blocksOf$1 = (doc, zones) => zones.flatMap((zone) => Array.isArray(doc?.[zone]) ? doc[zone] : []).filter((b) => b && typeof b === "object");
568
+ function experimentKeysOf(doc, zones, rows, locale2) {
569
+ const live = liveRows(rows, locale2);
570
+ const present = new Set(blocksOf$1(doc, zones).map((b) => b.blockKey).filter((k) => typeof k === "string" && k));
571
+ return [...new Set(live.variations.filter((v) => present.has(v.blockKey) && v.experiment).map((v) => v.experiment.key))];
572
+ }
573
+ function attachToDocument(doc, zones, rows, experiments2, fallbackLocale) {
574
+ if (!doc || typeof doc !== "object" || typeof doc.documentId !== "string") return doc;
575
+ const locale2 = (typeof doc.locale === "string" ? doc.locale : fallbackLocale) ?? null;
576
+ const live = liveRows(rows, locale2);
577
+ const byBlock = new Map(live.variations.map((v) => [v.blockKey, v]));
578
+ const conceptsOf = new Map(live.annotations.map((a) => [a.blockKey ?? "", a.concepts]));
579
+ const referenced = {};
580
+ for (const block of blocksOf$1(doc, zones)) {
581
+ const key = block.blockKey;
582
+ if (typeof key !== "string" || !key) continue;
583
+ const variation = byBlock.get(key);
584
+ const concepts = conceptsOf.get(key);
585
+ if (!variation && !concepts) continue;
586
+ const payload = { v: CONTRACT_VERSION };
587
+ if (concepts) payload.concepts = [...concepts];
588
+ if (variation) payload.variation = toVariation(variation);
589
+ block[EXPERIENCE_KEY] = payload;
590
+ const ref = variation?.experiment;
591
+ const exp = ref ? experiments2.get(ref.key) : void 0;
592
+ if (ref && exp) {
593
+ const declared = referenced[ref.key] ??= {
594
+ ...toExperiment(exp),
595
+ blockKeys: Object.fromEntries(exp.outcomes.map((o) => [o.key, []]))
596
+ };
597
+ (declared.blockKeys[ref.outcome] ??= []).push(key);
598
+ }
599
+ }
600
+ const root = { v: CONTRACT_VERSION, concepts: [...conceptsOf.get("") ?? []], experiments: referenced };
601
+ doc[EXPERIENCE_KEY] = root;
602
+ return doc;
603
+ }
604
+ function documentsOf(result2) {
605
+ if (!result2) return [];
606
+ if (Array.isArray(result2)) return result2;
607
+ const results = result2.results;
608
+ if (Array.isArray(results)) return results;
609
+ return [result2];
610
+ }
611
+ function stripExperience(data) {
612
+ const removed = [];
613
+ if (!data || typeof data !== "object" || Array.isArray(data)) return removed;
614
+ const record = data;
615
+ if (EXPERIENCE_KEY in record) {
616
+ delete record[EXPERIENCE_KEY];
617
+ removed.push("root");
618
+ }
619
+ for (const [field, value] of Object.entries(record)) {
620
+ if (!Array.isArray(value)) continue;
621
+ value.forEach((entry, i) => {
622
+ if (entry && typeof entry === "object" && !Array.isArray(entry) && EXPERIENCE_KEY in entry) {
623
+ delete entry[EXPERIENCE_KEY];
624
+ removed.push(`${field}[${i}]`);
625
+ }
626
+ });
627
+ }
628
+ return removed;
629
+ }
630
+ const VARIATION_SELECT = [
631
+ "documentId",
632
+ "targetUid",
633
+ "targetDocumentId",
634
+ "targetLocale",
635
+ "blockKey",
636
+ "sectionKey",
637
+ "variantKey",
638
+ "displayName",
639
+ "description",
640
+ "isDefault",
641
+ "status",
642
+ "orphaned",
643
+ "targetAudiences",
644
+ "traits",
645
+ "affinities",
646
+ "experiment",
647
+ "priority",
648
+ "validity",
649
+ "componentUid"
650
+ ];
651
+ const ANNOTATION_SELECT = ["documentId", "targetUid", "targetDocumentId", "targetLocale", "blockKey", "concepts", "orphaned"];
652
+ const CHUNK = 500;
653
+ const indexKey = (uid, documentId) => `${uid}\0${documentId}`;
654
+ class RequestLoader {
655
+ constructor(strapi) {
656
+ this.strapi = strapi;
657
+ this.loaded = /* @__PURE__ */ new Map();
658
+ this.experiments = /* @__PURE__ */ new Map();
659
+ this.pending = [];
660
+ this.scheduled = false;
661
+ }
662
+ /** Rows of one document (after `load`). */
663
+ rowsOf(uid, documentId) {
664
+ return this.loaded.get(indexKey(uid, documentId)) ?? { variations: [], annotations: [] };
665
+ }
666
+ async load(uid, documentIds) {
667
+ const missing = [...new Set(documentIds)].filter((id) => !this.loaded.has(indexKey(uid, id)));
668
+ if (missing.length === 0) return;
669
+ await new Promise((resolve, reject) => {
670
+ this.pending.push({ uid, ids: missing, resolve, reject });
671
+ if (!this.scheduled) {
672
+ this.scheduled = true;
673
+ setImmediate(() => void this.flush());
674
+ }
675
+ });
676
+ }
677
+ /** Experiment declarations by key; one query per call for keys not loaded yet. */
678
+ async loadExperiments(keys) {
679
+ const missing = [...new Set(keys)].filter((k) => !this.experiments.has(k));
680
+ if (missing.length > 0) {
681
+ missing.forEach((k) => this.experiments.set(k, null));
682
+ for (let i = 0; i < missing.length; i += CHUNK) {
683
+ const rows = await this.strapi.db.query(EXPERIMENT_UID).findMany({ where: { key: { $in: missing.slice(i, i + CHUNK) } } });
684
+ for (const row of rows ?? []) this.experiments.set(row.key, toExperimentRecord(row));
685
+ }
686
+ }
687
+ return new Map(keys.map((k) => [k, this.experiments.get(k) ?? void 0]));
688
+ }
689
+ async flush() {
690
+ const batch = this.pending;
691
+ this.pending = [];
692
+ this.scheduled = false;
693
+ try {
694
+ const byUid = /* @__PURE__ */ new Map();
695
+ for (const p of batch) {
696
+ const ids = byUid.get(p.uid) ?? /* @__PURE__ */ new Set();
697
+ p.ids.forEach((id) => ids.add(id));
698
+ byUid.set(p.uid, ids);
699
+ }
700
+ const where = this.where(byUid);
701
+ const [variations2, annotations] = where ? await Promise.all([
702
+ this.strapi.db.query(VARIATION_UID).findMany({ where, select: VARIATION_SELECT, orderBy: { id: "asc" } }),
703
+ this.strapi.db.query(ANNOTATION_UID).findMany({ where, select: ANNOTATION_SELECT, orderBy: { id: "asc" } })
704
+ ]) : [[], []];
705
+ for (const [uid, ids] of byUid) for (const id of ids) this.loaded.set(indexKey(uid, id), { variations: [], annotations: [] });
706
+ for (const row of variations2 ?? []) this.loaded.get(indexKey(row.targetUid, row.targetDocumentId))?.variations.push(toVariationRecord(row));
707
+ for (const row of annotations ?? []) this.loaded.get(indexKey(row.targetUid, row.targetDocumentId))?.annotations.push(toAnnotationRecord(row));
708
+ batch.forEach((p) => p.resolve());
709
+ } catch (err) {
710
+ batch.forEach((p) => p.reject(err));
711
+ }
712
+ }
713
+ where(byUid) {
714
+ const clauses = [];
715
+ for (const [uid, ids] of byUid) {
716
+ const list = [...ids];
717
+ for (let i = 0; i < list.length; i += CHUNK) clauses.push({ targetUid: uid, targetDocumentId: { $in: list.slice(i, i + CHUNK) } });
718
+ }
719
+ if (clauses.length === 0) return null;
720
+ return clauses.length === 1 ? clauses[0] : { $or: clauses };
721
+ }
722
+ }
723
+ const loaders = /* @__PURE__ */ new WeakMap();
724
+ function loaderFor(strapi, req) {
725
+ let loader = loaders.get(req);
726
+ if (!loader) loaders.set(req, loader = new RequestLoader(strapi));
727
+ return loader;
728
+ }
729
+ async function enrich(loader, uid, docs, zones, locale2) {
730
+ await loader.load(
731
+ uid,
732
+ docs.map((d) => d.documentId)
733
+ );
734
+ const docLocale = (d) => typeof d.locale === "string" ? d.locale : locale2;
735
+ const keys = [...new Set(docs.flatMap((d) => experimentKeysOf(d, zones, loader.rowsOf(uid, d.documentId), docLocale(d))))];
736
+ const experiments2 = keys.length ? await loader.loadExperiments(keys) : /* @__PURE__ */ new Map();
737
+ for (const doc of docs) attachToDocument(doc, zones, loader.rowsOf(uid, doc.documentId), experiments2, locale2);
738
+ }
739
+ const asFieldList = (fields) => {
740
+ if (typeof fields === "string") return fields.split(",").map((f) => f.trim()).filter(Boolean);
741
+ if (Array.isArray(fields)) return fields.filter((f) => typeof f === "string");
742
+ return void 0;
743
+ };
744
+ function withBlockKey(entry) {
745
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return entry;
746
+ const fields = asFieldList(entry.fields);
747
+ if (!fields || fields.includes("*") || fields.includes(BLOCK_KEY)) return entry;
748
+ return { ...entry, fields: [...fields, BLOCK_KEY] };
749
+ }
750
+ function ensureBlockKeyFields(populate, zones, keyedComponents) {
751
+ if (!populate || typeof populate !== "object" || Array.isArray(populate)) return populate;
752
+ let out;
753
+ for (const zone of zones) {
754
+ const zonePopulate2 = populate[zone];
755
+ if (!zonePopulate2 || typeof zonePopulate2 !== "object" || Array.isArray(zonePopulate2)) continue;
756
+ const on = zonePopulate2.on;
757
+ if (!on || typeof on !== "object" || Array.isArray(on)) continue;
758
+ let newOn;
759
+ for (const [component, entry] of Object.entries(on)) {
760
+ if (!keyedComponents.has(component)) continue;
761
+ const updated = withBlockKey(entry);
762
+ if (updated !== entry) (newOn ??= { ...on })[component] = updated;
763
+ }
764
+ if (newOn) (out ??= { ...populate })[zone] = { ...zonePopulate2, on: newOn };
765
+ }
766
+ return out ?? populate;
767
+ }
768
+ const READ_ACTIONS = /* @__PURE__ */ new Set(["findOne", "findFirst", "findMany"]);
769
+ const WRITE_ACTIONS = /* @__PURE__ */ new Set(["create", "update", "clone"]);
770
+ const PRIVATE_CACHE_CONTROL = "private, no-store";
771
+ const insideRead = new AsyncLocalStorage();
772
+ function readPathOptions(configured, targets) {
773
+ const zonesByUid = /* @__PURE__ */ new Map();
774
+ for (const uid of configured) zonesByUid.set(uid, targets.zonesByUid.get(uid) ?? []);
775
+ return { zonesByUid, keyedComponents: targets.keyedComponents };
776
+ }
777
+ function registerReadPathMiddleware(strapi, options2) {
778
+ strapi.documents.use(async (ctx, next) => {
779
+ const uid = ctx?.uid;
780
+ const action = ctx?.action;
781
+ if (WRITE_ACTIONS.has(action)) {
782
+ if (typeof uid === "string" && options2.zonesByUid.has(uid)) {
783
+ const removed = stripExperience(ctx.params?.data);
784
+ if (removed.length > 0) strapi.log.debug?.(`${LOG_PREFIX} stripped ${EXPERIENCE_KEY} on ${action} ${uid}: ${removed.join(", ")}`);
785
+ }
786
+ return next();
787
+ }
788
+ if (!READ_ACTIONS.has(action)) return next();
789
+ const nested = insideRead.getStore() === true;
790
+ const run = () => insideRead.run(true, next);
791
+ if (nested || typeof uid !== "string" || !options2.zonesByUid.has(uid)) return run();
792
+ const params = ctx.params ?? {};
793
+ const req = currentRequest(strapi);
794
+ if (!flagRequested(params, req)) return run();
795
+ const gate = await checkGate(strapi, req);
796
+ if (!gate.ok) return run();
797
+ const zones = options2.zonesByUid.get(uid) ?? [];
798
+ if (params.populate) {
799
+ const populate = ensureBlockKeyFields(params.populate, zones, options2.keyedComponents);
800
+ if (populate !== params.populate) ctx.params = { ...params, populate };
801
+ }
802
+ const result2 = await run();
803
+ const docs = documentsOf(result2).filter((d) => d && typeof d.documentId === "string");
804
+ if (docs.length === 0) return result2;
805
+ const locale2 = typeof params.locale === "string" ? params.locale : null;
806
+ await enrich(loaderFor(strapi, req), uid, docs, zones, locale2);
807
+ try {
808
+ req.set?.("Cache-Control", PRIVATE_CACHE_CONTROL);
809
+ } catch {
810
+ }
811
+ return result2;
812
+ });
813
+ }
814
+ function registerReadPathParams(strapi) {
815
+ const contentAPI = strapi.contentAPI;
816
+ if (typeof contentAPI?.addQueryParams !== "function") return;
817
+ try {
818
+ contentAPI.addQueryParams({
819
+ [FLAG]: { schema: (z2) => z2.enum(["true", "false", "1", "0"]).optional() }
820
+ });
821
+ } catch (err) {
822
+ strapi.log.warn(`${LOG_PREFIX} could not register the ${FLAG} query param: ${err.message}`);
823
+ }
824
+ }
825
+ const WRITE_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
826
+ function registerWriteBackStrip(strapi) {
827
+ const prefix = `${(strapi.config.get("api.rest.prefix", "/api") ?? "/api").replace(/\/$/, "")}/`;
828
+ strapi.server.use(async (ctx, next) => {
829
+ if (WRITE_METHODS.has(ctx.method) && typeof ctx.path === "string" && ctx.path.startsWith(prefix)) {
830
+ const removed = stripExperience(ctx.request?.body?.data);
831
+ if (removed.length > 0) strapi.log.debug?.(`${LOG_PREFIX} stripped ${EXPERIENCE_KEY} from ${ctx.method} ${ctx.path}: ${removed.join(", ")}`);
832
+ }
833
+ await next();
834
+ });
835
+ }
836
+ function bootstrapReadPath(strapi, targets) {
837
+ const configured = configuredContentTypes(strapi).filter((uid) => Boolean(strapi.contentTypes[uid]));
838
+ if (configured.length === 0) return;
839
+ registerReadPathMiddleware(strapi, readPathOptions(configured, targets));
840
+ registerWriteBackStrip(strapi);
841
+ }
842
+ const ACTIONS = {
843
+ read: `plugin::${PLUGIN_ID}.read`,
844
+ variationsWrite: `plugin::${PLUGIN_ID}.variations.write`,
845
+ experimentsWrite: `plugin::${PLUGIN_ID}.experiments.write`,
846
+ maintenance: `plugin::${PLUGIN_ID}.maintenance`
847
+ };
848
+ const policies$1 = (...actions) => actions.map((action) => ({ action }));
849
+ const READ_POLICIES = policies$1(ACTIONS.read, ACTIONS.variationsWrite, ACTIONS.experimentsWrite, ACTIONS.maintenance);
850
+ const VARIATIONS_POLICIES = policies$1(ACTIONS.variationsWrite);
851
+ const EXPERIMENTS_POLICIES = policies$1(ACTIONS.experimentsWrite);
852
+ const REMOVE_POLICIES = policies$1(ACTIONS.variationsWrite, ACTIONS.experimentsWrite);
853
+ const MAINTENANCE_POLICIES = policies$1(ACTIONS.maintenance);
854
+ const canRead$1 = (ability) => Boolean(ability && typeof ability.can === "function" && READ_POLICIES.some((p) => ability.can(p.action)));
855
+ const PERMISSION_ACTIONS = [
856
+ {
857
+ section: "plugins",
858
+ displayName: "Read experience mappings (inspection, simulator, MCP read tools)",
859
+ uid: "read",
860
+ pluginName: PLUGIN_ID
861
+ },
862
+ {
863
+ section: "plugins",
864
+ displayName: "Manage audience variations and concepts (MCP)",
865
+ uid: "variations.write",
866
+ pluginName: PLUGIN_ID
867
+ },
868
+ {
869
+ section: "plugins",
870
+ displayName: "Manage experiments: declare, start, pause, conclude (MCP)",
871
+ uid: "experiments.write",
872
+ pluginName: PLUGIN_ID
873
+ },
874
+ {
875
+ section: "plugins",
876
+ displayName: "Maintenance: backfill block keys (MCP)",
877
+ uid: "maintenance",
878
+ pluginName: PLUGIN_ID
879
+ }
880
+ ];
881
+ const registerPermissionActions = async (strapi) => {
882
+ const permission = strapi.service?.("admin::permission") ?? strapi.admin?.services?.permission;
883
+ if (!permission?.actionProvider?.registerMany) return;
884
+ await permission.actionProvider.registerMany(PERMISSION_ACTIONS);
885
+ };
886
+ class ToolError extends Error {
887
+ }
888
+ function didYouMean(input, candidates) {
889
+ const a = String(input ?? "");
890
+ let best;
891
+ let bestScore = Infinity;
892
+ for (const c of candidates) {
893
+ const d = distance(a.toLowerCase(), c.toLowerCase());
894
+ if (d < bestScore) {
895
+ bestScore = d;
896
+ best = c;
897
+ }
898
+ }
899
+ return best !== void 0 && bestScore <= Math.max(2, Math.floor(a.length / 3)) ? ` Did you mean ${JSON.stringify(best)}?` : "";
900
+ }
901
+ function distance(a, b) {
902
+ const dp = Array.from({ length: a.length + 1 }, (_, i) => [i, ...new Array(b.length).fill(0)]);
903
+ for (let j = 1; j <= b.length; j++) dp[0][j] = j;
904
+ for (let i = 1; i <= a.length; i++) {
905
+ for (let j = 1; j <= b.length; j++) {
906
+ dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
907
+ }
908
+ }
909
+ return dp[a.length][b.length];
910
+ }
911
+ const localeCodes = async (strapi) => {
912
+ const locales = await strapi.plugin("i18n")?.service("locales")?.find() ?? [];
913
+ return locales.map((l) => l.code);
914
+ };
915
+ const resolveTarget = async (strapi, targetUid2, targetDocumentId2) => {
916
+ const contentTypes2 = configuredContentTypes(strapi);
917
+ if (!contentTypes2.includes(targetUid2)) {
918
+ throw new ToolError(`${JSON.stringify(targetUid2)} is not an experience target.${didYouMean(targetUid2, contentTypes2)} Targets: ${contentTypes2.join(", ")}.`);
919
+ }
920
+ const contentType = strapi.contentTypes[targetUid2];
921
+ if (!contentType) throw new ToolError(`Content type ${targetUid2} does not exist in this app.`);
922
+ const kind2 = contentType.kind === "singleType" ? "singleType" : "collectionType";
923
+ const localized = Boolean(contentType.pluginOptions?.i18n?.localized);
924
+ let documentId = targetDocumentId2 ?? void 0;
925
+ if (!documentId) {
926
+ if (kind2 !== "singleType") throw new ToolError(`targetDocumentId is required for collection type ${targetUid2}.`);
927
+ const doc = await strapi.documents(targetUid2).findFirst({ status: "draft" });
928
+ const any = doc ?? (localized ? (await Promise.all((await localeCodes(strapi)).map((locale2) => strapi.documents(targetUid2).findFirst({ status: "draft", locale: locale2 })))).find(Boolean) : void 0);
929
+ if (!any?.documentId) throw new ToolError(`Single type ${targetUid2} has no document yet.`);
930
+ documentId = any.documentId;
931
+ }
932
+ return { uid: targetUid2, documentId, kind: kind2, localized };
933
+ };
934
+ const pickLocale = async (strapi, target, locale2) => {
935
+ if (!target.localized) return null;
936
+ const codes = await localeCodes(strapi);
937
+ if (locale2) {
938
+ if (codes.length && !codes.includes(locale2)) {
939
+ throw new ToolError(`Unknown locale ${JSON.stringify(locale2)}.${didYouMean(locale2, codes)} Locales: ${codes.join(", ")}.`);
940
+ }
941
+ return locale2;
942
+ }
943
+ for (const code of codes) {
944
+ const doc = await strapi.documents(target.uid).findOne({ documentId: target.documentId, status: "draft", locale: code, fields: ["documentId"] });
945
+ if (doc) return code;
946
+ }
947
+ return codes[0] ?? null;
948
+ };
949
+ const SUMMARY_FIELDS = ["heading", "title", "Title", "sectionLabel", "eyebrow", "quote", "name", "label", "searchTerm", "variant", "layout", "source"];
950
+ const TITLE_FIELDS = ["title", "Title", "heading", "name", "label", "quote", "sectionLabel"];
951
+ const short = (s, n = 60) => s.length > n ? `${s.slice(0, n - 1)}…` : s;
952
+ const titleOfValue = (value) => {
953
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
954
+ for (const f of TITLE_FIELDS) {
955
+ const v = value[f];
956
+ if (typeof v === "string" && v.trim()) return v.trim();
957
+ }
958
+ return void 0;
959
+ };
960
+ const blockTitle = (block) => {
961
+ const own = titleOfValue(block);
962
+ if (own) return short(own, 80);
963
+ for (const [k, v] of Object.entries(block)) {
964
+ if (k.startsWith("_") || k === "__component") continue;
965
+ const t = titleOfValue(v) ?? (Array.isArray(v) ? titleOfValue(v[0]) : void 0);
966
+ if (t) return short(t, 80);
967
+ }
968
+ return null;
969
+ };
970
+ const summarizeBlock = (block) => {
971
+ const parts = [];
972
+ for (const f of SUMMARY_FIELDS) {
973
+ const v = block[f];
974
+ if (typeof v === "string" && v.trim()) parts.push(`${f}: ${JSON.stringify(short(v.trim()))}`);
975
+ if (parts.length >= 2) break;
976
+ }
977
+ for (const [k, v] of Object.entries(block)) {
978
+ if (parts.length >= 3) break;
979
+ if (k.startsWith("_") || k === "__component") continue;
980
+ const t = titleOfValue(v);
981
+ if (t) parts.push(`${k}: ${JSON.stringify(short(t))}`);
982
+ else if (Array.isArray(v) && v.length) parts.push(`${k}: ${v.length} item(s)`);
983
+ }
984
+ return `${String(block.__component)}${parts.length ? ` (${parts.join(", ")})` : ""}`;
985
+ };
986
+ const loadDocument = async (strapi, target, locale2, status) => {
987
+ const base = { documentId: target.documentId, status, ...target.localized && locale2 ? { locale: locale2 } : {} };
988
+ try {
989
+ return await strapi.documents(target.uid).findOne({ ...base, populate: { [CONTENT_ZONE]: { populate: "*" } } });
990
+ } catch {
991
+ return strapi.documents(target.uid).findOne({ ...base, populate: [CONTENT_ZONE] });
992
+ }
993
+ };
994
+ const blocksOf = (doc) => (doc?.[CONTENT_ZONE] ?? []).map((block, index2) => ({
995
+ index: index2,
996
+ blockKey: typeof block?.blockKey === "string" && block.blockKey ? block.blockKey : null,
997
+ componentUid: String(block?.__component),
998
+ summary: summarizeBlock(block ?? {}),
999
+ title: blockTitle(block ?? {})
1000
+ }));
1001
+ const displayTitle = (doc) => titleOfValue(doc) ?? (typeof doc?.slug === "string" ? doc.slug : null);
1002
+ const componentLabel = (uid) => {
1003
+ const name = String(uid ?? "").split(".").pop() ?? "";
1004
+ const words = name.replace(/[-_]+/g, " ").trim();
1005
+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : "Block";
1006
+ };
1007
+ const PAGE_SIZE = 500;
1008
+ const EMPTY = { audiences: [], affinities: [] };
1009
+ function definitionsFromSegments(segments, scope) {
1010
+ const audiences2 = /* @__PURE__ */ new Map();
1011
+ const affinities2 = /* @__PURE__ */ new Map();
1012
+ for (const s of segments ?? []) {
1013
+ const seg = s ?? {};
1014
+ const meta = seg.metadata && typeof seg.metadata === "object" ? seg.metadata : seg;
1015
+ if (meta.enabled === false) continue;
1016
+ if (scope && meta.scope !== scope) continue;
1017
+ const id = fromSegmentName(meta.id);
1018
+ if (!id) continue;
1019
+ if (parseAudience(id) && !audiences2.has(id)) {
1020
+ const entry = { id };
1021
+ if (typeof meta.name === "string" && meta.name) entry.label = meta.name;
1022
+ if (typeof meta.description === "string" && meta.description) entry.description = meta.description;
1023
+ audiences2.set(id, entry);
1024
+ continue;
1025
+ }
1026
+ const affinity = parseAffinity(id);
1027
+ if (affinity && !affinities2.has(affinity.concept)) affinities2.set(affinity.concept, { id: affinity.concept });
1028
+ }
1029
+ return { audiences: [...audiences2.values()], affinities: [...affinities2.values()] };
1030
+ }
1031
+ async function fetchSegments(config2, fetchImpl = fetch) {
1032
+ const base = (config2.url ?? "").replace(/\/+$/, "");
1033
+ const headers = { accept: "application/json" };
1034
+ if (config2.username) headers.authorization = `Basic ${Buffer.from(`${config2.username}:${config2.password ?? ""}`).toString("base64")}`;
1035
+ const all = [];
1036
+ for (let offset = 0; ; offset += PAGE_SIZE) {
1037
+ const res = await fetchImpl(`${base}/segments?offset=${offset}&size=${PAGE_SIZE}`, {
1038
+ headers,
1039
+ signal: AbortSignal.timeout(config2.timeoutMs ?? 3e3)
1040
+ });
1041
+ if (!res.ok) throw new Error(`GET /segments answered ${res.status}`);
1042
+ const page = await res.json();
1043
+ if (!Array.isArray(page)) throw new Error("GET /segments did not answer a list");
1044
+ all.push(...page);
1045
+ if (page.length < PAGE_SIZE) return all;
1046
+ }
1047
+ }
1048
+ const cache = /* @__PURE__ */ new Map();
1049
+ const unomiEnabled = (config2) => Boolean(config2 && typeof config2.url === "string" && config2.url.trim());
1050
+ async function loadUnomiDefinitions(config2, log, fetchImpl = fetch, now = Date.now) {
1051
+ if (!unomiEnabled(config2)) return EMPTY;
1052
+ const key = `${config2.url}|${config2.scope ?? ""}`;
1053
+ const hit = cache.get(key);
1054
+ const ttl = (config2.ttlSeconds ?? 300) * 1e3;
1055
+ if (hit && now() - hit.at < ttl) return hit.value;
1056
+ if (hit?.pending) return hit.pending;
1057
+ const entry = hit ?? { at: 0, value: EMPTY, failing: false };
1058
+ entry.pending = fetchSegments(config2, fetchImpl).then((segments) => {
1059
+ entry.value = definitionsFromSegments(segments, config2.scope);
1060
+ if (entry.failing || entry.at === 0) {
1061
+ log.info(`registry: ${entry.value.audiences.length} audience(s), ${entry.value.affinities.length} affinity concept(s) from Unomi ${config2.url}`);
1062
+ }
1063
+ entry.failing = false;
1064
+ return entry.value;
1065
+ }).catch((e) => {
1066
+ if (!entry.failing) log.warn(`registry: Unomi ${config2.url} unavailable (${e.message}); using the last known definitions`);
1067
+ entry.failing = true;
1068
+ return entry.value;
1069
+ }).finally(() => {
1070
+ entry.at = now();
1071
+ entry.pending = void 0;
1072
+ });
1073
+ cache.set(key, entry);
1074
+ return entry.pending;
1075
+ }
1076
+ const SEGMENT_UID = "plugin::content-variants.segment";
1077
+ const REGISTRY_KINDS = ["audiences", "traits", "affinities", "concepts", "experiments"];
1078
+ function sanitizeEntry(e) {
1079
+ if (!e || typeof e !== "object") return null;
1080
+ const { id, label, description } = e;
1081
+ if (typeof id !== "string" || !id) return null;
1082
+ const out = { id };
1083
+ if (typeof label === "string" && label) out.label = label;
1084
+ if (typeof description === "string" && description) out.description = description;
1085
+ return out;
1086
+ }
1087
+ const dedupe = (entries) => {
1088
+ const seen = /* @__PURE__ */ new Map();
1089
+ for (const e of entries) if (e && !seen.has(e.id)) seen.set(e.id, e);
1090
+ return [...seen.values()];
1091
+ };
1092
+ function segmentAudiences(segments) {
1093
+ const out = [];
1094
+ for (const s of segments ?? []) {
1095
+ const seg = s;
1096
+ if (typeof seg?.externalId !== "string" || !seg.externalId || !isSlug(seg.slug)) continue;
1097
+ const id = formatAudience(seg.slug);
1098
+ if (!parseAudience(id)) continue;
1099
+ out.push(sanitizeEntry({ id, label: seg.name, description: seg.description }));
1100
+ }
1101
+ return dedupe(out);
1102
+ }
1103
+ function buildRegistry(config2, segments, experiments2, unomi = { audiences: [], affinities: [] }) {
1104
+ const list = (kind2) => (Array.isArray(config2?.[kind2]) ? config2[kind2] : []).map(sanitizeEntry);
1105
+ return {
1106
+ audiences: dedupe([...list("audiences"), ...segmentAudiences(segments), ...unomi.audiences.map(sanitizeEntry)]),
1107
+ traits: dedupe(list("traits")),
1108
+ affinities: dedupe([...list("affinities"), ...unomi.affinities.map(sanitizeEntry)]),
1109
+ concepts: dedupe(list("concepts")),
1110
+ experiments: dedupe(experiments2.map((e) => sanitizeEntry({ id: e.key, label: e.name ?? e.key, description: e.description })))
1111
+ };
1112
+ }
1113
+ async function loadRegistry(strapi) {
1114
+ let segments = [];
1115
+ if (strapi.contentTypes[SEGMENT_UID]) {
1116
+ try {
1117
+ segments = await strapi.db.query(SEGMENT_UID).findMany({
1118
+ where: { externalId: { $notNull: true } },
1119
+ select: ["slug", "name", "description", "externalId"]
1120
+ });
1121
+ } catch (e) {
1122
+ strapi.log.warn(`${LOG_PREFIX} registry: could not read content-variants segments: ${e.message}`);
1123
+ }
1124
+ }
1125
+ let experiments2 = [];
1126
+ try {
1127
+ experiments2 = await strapi.db.query(EXPERIMENT_UID).findMany({ select: ["key", "name", "description"], orderBy: { id: "asc" } });
1128
+ } catch (e) {
1129
+ strapi.log.warn(`${LOG_PREFIX} registry: could not read experiments: ${e.message}`);
1130
+ }
1131
+ const log = { info: (m) => strapi.log.info(`${LOG_PREFIX} ${m}`), warn: (m) => strapi.log.warn(`${LOG_PREFIX} ${m}`) };
1132
+ const unomi = await loadUnomiDefinitions(configuredUnomi(strapi), log);
1133
+ return buildRegistry(configuredRegistry(strapi), segments, experiments2, unomi);
1134
+ }
1135
+ const WEBHOOK_EVENT = "experience.update";
1136
+ const WEBHOOK_EVENT_KEY = "EXPERIENCE_UPDATE";
1137
+ const SYSTEM_ACTOR = "system";
1138
+ const AUDIT_FIELDS = {
1139
+ annotation: ["documentId", "targetUid", "targetDocumentId", "locale", "blockKey", "concepts", "orphaned", "source", "createdBy", "correlationId"],
1140
+ variation: [
1141
+ "documentId",
1142
+ "targetUid",
1143
+ "targetDocumentId",
1144
+ "locale",
1145
+ "blockKey",
1146
+ "sectionKey",
1147
+ "variantKey",
1148
+ "displayName",
1149
+ "description",
1150
+ "isDefault",
1151
+ "status",
1152
+ "orphaned",
1153
+ "targetAudiences",
1154
+ "traits",
1155
+ "affinities",
1156
+ "experiment",
1157
+ "priority",
1158
+ "validity",
1159
+ "componentUid",
1160
+ "source",
1161
+ "createdBy",
1162
+ "correlationId"
1163
+ ],
1164
+ experiment: [
1165
+ "documentId",
1166
+ "key",
1167
+ "name",
1168
+ "description",
1169
+ "outcomes",
1170
+ "controlOutcome",
1171
+ "status",
1172
+ "validity",
1173
+ "winner",
1174
+ "externalId",
1175
+ "source",
1176
+ "createdBy",
1177
+ "correlationId"
1178
+ ],
1179
+ // A content block an MCP tool copied into or removed from a page: where it is, not its content.
1180
+ block: ["targetUid", "targetDocumentId", "locale", "blockKey", "componentUid", "index", "copiedFrom"]
1181
+ };
1182
+ function auditRecord(entity, record) {
1183
+ if (!record) return null;
1184
+ const out = {};
1185
+ for (const f of AUDIT_FIELDS[entity]) if (record[f] !== void 0) out[f] = record[f];
1186
+ return out;
1187
+ }
1188
+ class ChangeBatch {
1189
+ constructor() {
1190
+ this.targets = /* @__PURE__ */ new Map();
1191
+ this.experiments = /* @__PURE__ */ new Set();
1192
+ this.count = 0;
1193
+ }
1194
+ addTarget(uid, documentId, locale2) {
1195
+ if (!uid || !documentId) return;
1196
+ this.targets.set(`${uid}\0${documentId}\0${locale2 ?? ""}`, { uid, documentId, locale: locale2 ?? null });
1197
+ }
1198
+ addExperiment(key) {
1199
+ if (key) this.experiments.add(key);
1200
+ }
1201
+ get empty() {
1202
+ return this.targets.size === 0 && this.experiments.size === 0;
1203
+ }
1204
+ payload() {
1205
+ return { targets: [...this.targets.values()], experiments: [...this.experiments].sort() };
1206
+ }
1207
+ /** Emits one `experience.update` after commit (nothing when the batch is empty). */
1208
+ async flush(strapi) {
1209
+ if (this.empty) return;
1210
+ await emitAfterCommit(strapi, this.payload());
1211
+ }
1212
+ }
1213
+ const experimentKeyOf = (entry) => {
1214
+ for (const r of [entry.after, entry.before]) {
1215
+ if (!r) continue;
1216
+ if (entry.entity === "experiment" && typeof r.key === "string") return r.key;
1217
+ const key = r.experiment?.key;
1218
+ if (typeof key === "string" && key) return key;
1219
+ }
1220
+ return null;
1221
+ };
1222
+ const emitNow = async (strapi, payload) => {
1223
+ try {
1224
+ await strapi.eventHub?.emit?.(WEBHOOK_EVENT, payload);
1225
+ } catch (err) {
1226
+ strapi.log.warn(`${LOG_PREFIX} could not emit ${WEBHOOK_EVENT}: ${err.message}`);
1227
+ }
1228
+ };
1229
+ async function emitAfterCommit(strapi, payload) {
1230
+ const db2 = strapi.db;
1231
+ if (typeof db2?.inTransaction === "function" && db2.inTransaction() && typeof db2.transaction === "function") {
1232
+ await db2.transaction(({ onCommit }) => {
1233
+ onCommit(() => {
1234
+ void emitNow(strapi, payload);
1235
+ });
1236
+ });
1237
+ return;
1238
+ }
1239
+ await emitNow(strapi, payload);
1240
+ }
1241
+ async function recordChange(strapi, entry, batch) {
1242
+ const before = auditRecord(entry.entity, entry.before);
1243
+ const after = auditRecord(entry.entity, entry.after);
1244
+ const record = after ?? before ?? {};
1245
+ const experimentKey = experimentKeyOf({ entity: entry.entity, before, after });
1246
+ const targetUid2 = entry.entity === "experiment" ? null : record.targetUid ?? null;
1247
+ const targetDocumentId2 = entry.entity === "experiment" ? null : record.targetDocumentId ?? null;
1248
+ await strapi.documents(CHANGE_UID).create({
1249
+ data: {
1250
+ action: entry.action,
1251
+ entity: entry.entity,
1252
+ entityDocumentId: entry.entityDocumentId ?? record.documentId ?? null,
1253
+ targetUid: targetUid2,
1254
+ targetDocumentId: targetDocumentId2,
1255
+ targetLocale: entry.entity === "experiment" ? null : record.locale ?? null,
1256
+ blockKey: record.blockKey ?? null,
1257
+ componentUid: record.componentUid ?? null,
1258
+ sectionKey: record.sectionKey ?? null,
1259
+ variantKey: record.variantKey ?? null,
1260
+ experimentKey,
1261
+ actor: entry.actor ?? null,
1262
+ source: entry.source,
1263
+ reason: entry.reason ?? null,
1264
+ correlationId: entry.correlationId ?? null,
1265
+ before,
1266
+ after
1267
+ }
1268
+ });
1269
+ const own = batch ?? new ChangeBatch();
1270
+ own.count++;
1271
+ if (targetUid2) own.addTarget(targetUid2, targetDocumentId2, record.locale ?? null);
1272
+ own.addExperiment(experimentKey);
1273
+ if (!batch) await own.flush(strapi);
1274
+ }
1275
+ function registerWebhookEvent(strapi) {
1276
+ try {
1277
+ strapi.get?.("webhookStore")?.addAllowedEvent?.(WEBHOOK_EVENT_KEY, WEBHOOK_EVENT);
1278
+ } catch (err) {
1279
+ strapi.log.warn(`${LOG_PREFIX} could not register the ${WEBHOOK_EVENT} webhook event: ${err.message}`);
1280
+ }
1281
+ }
1282
+ async function changeHistory(strapi, filters, limit = 20) {
1283
+ return await strapi.documents(CHANGE_UID).findMany({
1284
+ filters: Object.fromEntries(Object.entries(filters).filter(([, v]) => v !== void 0)),
1285
+ sort: [{ createdAt: "desc" }, { id: "desc" }],
1286
+ pagination: { limit }
1287
+ });
1288
+ }
1289
+ const MAX_DEPTH = 5;
1290
+ const schemaOf = (strapi, uid) => strapi.components[uid];
1291
+ function populateFor(strapi, componentUid, depth = 0) {
1292
+ const schema = schemaOf(strapi, componentUid);
1293
+ if (!schema?.attributes || depth >= MAX_DEPTH) return "*";
1294
+ const populate = {};
1295
+ for (const [name, attr] of Object.entries(schema.attributes)) {
1296
+ if (attr?.type === "component") populate[name] = { populate: populateFor(strapi, attr.component, depth + 1) };
1297
+ else if (attr?.type === "relation" || attr?.type === "media") populate[name] = true;
1298
+ }
1299
+ return Object.keys(populate).length ? populate : "*";
1300
+ }
1301
+ function zonePopulate(strapi, uid) {
1302
+ const zone = strapi.contentTypes[uid]?.attributes?.[CONTENT_ZONE];
1303
+ const on = {};
1304
+ for (const c of zone?.components ?? []) on[c] = { populate: populateFor(strapi, c) };
1305
+ return { [CONTENT_ZONE]: { on } };
1306
+ }
1307
+ const relationRef = (v) => {
1308
+ if (!v || typeof v !== "object" || typeof v.documentId !== "string") return null;
1309
+ return { documentId: v.documentId, ...typeof v.locale === "string" ? { locale: v.locale } : {} };
1310
+ };
1311
+ function toCopyInput(strapi, componentUid, value, depth = 0) {
1312
+ if (value === null || value === void 0) return value;
1313
+ const schema = schemaOf(strapi, componentUid);
1314
+ if (!schema?.attributes || depth > MAX_DEPTH) {
1315
+ const { id: _id, ...rest } = value ?? {};
1316
+ return rest;
1317
+ }
1318
+ const out = {};
1319
+ for (const [name, attr] of Object.entries(schema.attributes)) {
1320
+ if (!(name in value)) continue;
1321
+ const v = value[name];
1322
+ switch (attr?.type) {
1323
+ case "component":
1324
+ out[name] = attr.repeatable ? (Array.isArray(v) ? v : []).map((x) => toCopyInput(strapi, attr.component, x, depth + 1)) : toCopyInput(strapi, attr.component, v, depth + 1);
1325
+ break;
1326
+ case "relation": {
1327
+ const list = (Array.isArray(v) ? v : v ? [v] : []).map(relationRef).filter(Boolean);
1328
+ out[name] = { set: list };
1329
+ break;
1330
+ }
1331
+ case "media":
1332
+ out[name] = Array.isArray(v) ? v.map((f) => f?.id).filter((id) => id !== void 0) : v?.id ?? null;
1333
+ break;
1334
+ default:
1335
+ out[name] = v;
1336
+ }
1337
+ }
1338
+ return out;
1339
+ }
1340
+ async function loadDraftZone(strapi, target, locale2) {
1341
+ const doc = await strapi.documents(target.uid).findOne({
1342
+ documentId: target.documentId,
1343
+ status: "draft",
1344
+ ...target.localized && locale2 ? { locale: locale2 } : {},
1345
+ populate: zonePopulate(strapi, target.uid)
1346
+ });
1347
+ if (!doc) {
1348
+ throw new ToolError(`No draft of ${target.uid} ${target.documentId}${locale2 ? ` in locale ${locale2}` : ""}.`);
1349
+ }
1350
+ return { doc, blocks: Array.isArray(doc[CONTENT_ZONE]) ? doc[CONTENT_ZONE] : [] };
1351
+ }
1352
+ function newBlock(strapi, source, content, blockKey = randomUUID()) {
1353
+ if (source) {
1354
+ const copy = toCopyInput(strapi, source.__component, source);
1355
+ return { ...copy, __component: source.__component, blockKey };
1356
+ }
1357
+ const component = content?.__component;
1358
+ if (typeof component !== "string" || !schemaOf(strapi, component)) {
1359
+ throw new ToolError(`content.__component ${JSON.stringify(component)} is not a component of this app.`);
1360
+ }
1361
+ const { id: _id, blockKey: _k, _experience: _x, ...rest } = content;
1362
+ return { ...rest, __component: component, blockKey };
1363
+ }
1364
+ async function writeZone(strapi, target, locale2, entries) {
1365
+ const data = {
1366
+ [CONTENT_ZONE]: entries.map((b) => b.id !== void 0 && b.id !== null ? { __component: b.__component, id: b.id } : b)
1367
+ };
1368
+ await strapi.documents(target.uid).update({
1369
+ documentId: target.documentId,
1370
+ ...target.localized && locale2 ? { locale: locale2 } : {},
1371
+ data
1372
+ });
1373
+ }
1374
+ function zoneAccepts(strapi, uid, componentUid) {
1375
+ const zone = strapi.contentTypes[uid]?.attributes?.[CONTENT_ZONE];
1376
+ return Array.isArray(zone?.components) && zone.components.includes(componentUid);
1377
+ }
1378
+ async function loadSnapshot(strapi, store2, target, locale2, status = "draft") {
1379
+ const doc = await loadDocument(strapi, target, locale2, status);
1380
+ const allVariations = await store2.listVariations({ targetUid: target.uid, targetDocumentId: target.documentId });
1381
+ const allAnnotations = await store2.listAnnotations({ targetUid: target.uid, targetDocumentId: target.documentId });
1382
+ const variations2 = forLocale(allVariations, locale2);
1383
+ const annotations = forLocale(allAnnotations, locale2);
1384
+ const keys = [...new Set(variations2.filter((v) => v.experiment).map((v) => v.experiment.key))];
1385
+ const experiments2 = new Map((await store2.listExperiments(keys)).map((e) => [e.key, e]));
1386
+ return { target, locale: locale2, status, doc, blocks: blocksOf(doc), allVariations, allAnnotations, variations: variations2, annotations, experiments: experiments2 };
1387
+ }
1388
+ async function contentOutcomesElsewhere(store2, snap, keys) {
1389
+ const mine = new Set(snap.variations.map((v) => v.documentId));
1390
+ const out = {};
1391
+ for (const key of keys) {
1392
+ const outcomes = /* @__PURE__ */ new Set();
1393
+ for (const v of await store2.variationsOfExperiment(key)) {
1394
+ if (mine.has(v.documentId) || v.status !== "active" || v.orphaned) continue;
1395
+ outcomes.add(v.experiment.outcome);
1396
+ }
1397
+ if (outcomes.size) out[key] = [...outcomes];
1398
+ }
1399
+ return out;
1400
+ }
1401
+ function mappingInput(state, presets = []) {
1402
+ return {
1403
+ v: CONTRACT_VERSION,
1404
+ variations: state.variations.map(toVariation),
1405
+ experiments: state.experiments.map(toExperiment),
1406
+ annotations: state.annotations.filter((a) => !a.orphaned).map((a) => ({ blockKey: a.blockKey, concepts: a.concepts })),
1407
+ blockKeys: state.blockKeys,
1408
+ presets,
1409
+ contentOutcomes: state.contentOutcomes
1410
+ };
1411
+ }
1412
+ async function validationContext(strapi) {
1413
+ return { registry: await loadRegistry(strapi), presets: configuredPresets(strapi) };
1414
+ }
1415
+ function validateState(state, vctx) {
1416
+ return validateExperienceMapping(mappingInput(state, vctx.presets), vctx.registry);
1417
+ }
1418
+ async function snapshotState(store2, snap) {
1419
+ const experiments2 = [...snap.experiments.values()];
1420
+ return {
1421
+ variations: snap.variations,
1422
+ annotations: snap.annotations,
1423
+ experiments: experiments2,
1424
+ blockKeys: snap.doc ? snap.blocks.map((b) => b.blockKey).filter((k) => Boolean(k)) : void 0,
1425
+ contentOutcomes: await contentOutcomesElsewhere(store2, snap, experiments2.map((e) => e.key))
1426
+ };
1427
+ }
1428
+ const MARK = { ok: "✓", warning: "⚠", error: "✗" };
1429
+ const checklistLine = (i) => `${MARK[i.status]} ${i.text}`;
1430
+ const issueAt = (issues, path) => issues.some((i) => i.path === path || i.path.startsWith(`${path}.`) || i.path.startsWith(`${path}[`));
1431
+ function checklist(state, result2) {
1432
+ const items = [];
1433
+ const all = [...result2.errors, ...result2.warnings];
1434
+ const sections = [...new Set(state.variations.map((v) => v.sectionKey))];
1435
+ for (const s of sections) {
1436
+ const path = `sections.${s}`;
1437
+ if (!all.some((i) => i.path === path && i.code === "V1")) items.push({ status: "ok", path, text: `${s}: default exists` });
1438
+ }
1439
+ for (const v of state.variations) {
1440
+ if (v.isDefault) continue;
1441
+ const base = `sections.${v.sectionKey}.variations.${v.variantKey}`;
1442
+ const refs = [
1443
+ ["targetAudiences", v.targetAudiences],
1444
+ ["traits", v.traits],
1445
+ ["affinities", v.affinities]
1446
+ ];
1447
+ for (const [field, ids] of refs) {
1448
+ ids.forEach((id, i) => {
1449
+ const path = `${base}.${field}[${i}]`;
1450
+ if (!issueAt(all, path)) items.push({ status: "ok", path, text: `${v.sectionKey} / ${v.variantKey}: ${id} valid` });
1451
+ });
1452
+ }
1453
+ }
1454
+ for (const e of state.experiments) {
1455
+ const mapped = /* @__PURE__ */ new Set([
1456
+ ...state.variations.filter((v) => v.experiment?.key === e.key && v.status === "active" && !v.orphaned).map((v) => v.experiment.outcome),
1457
+ ...state.contentOutcomes?.[e.key] ?? []
1458
+ ]);
1459
+ for (const o of e.outcomes) {
1460
+ const path = `experiments.${e.key}.outcomes.${o.key}`;
1461
+ if (mapped.has(o.key) && !issueAt(all, path)) items.push({ status: "ok", path, text: `${e.key}: outcome ${o.key} mapped` });
1462
+ }
1463
+ }
1464
+ for (const e of result2.errors) items.push({ status: "error", code: e.code, path: e.path, text: `${e.code} ${e.path}: ${e.message}` });
1465
+ for (const w of result2.warnings) items.push({ status: "warning", code: w.code, path: w.path, text: `${w.code} ${w.path}: ${w.message}` });
1466
+ return items;
1467
+ }
1468
+ function report(state, result2) {
1469
+ const items = checklist(state, result2);
1470
+ return { ok: result2.ok, errors: result2.errors, warnings: result2.warnings, checklist: items.map(checklistLine), items };
1471
+ }
1472
+ function explainContext(input, preview) {
1473
+ const raw = typeof input === "object" && input !== null && !Array.isArray(input) ? input : {};
1474
+ const previewing = preview ?? raw.preview !== false;
1475
+ const real = sanitizeContext(raw);
1476
+ const now = typeof raw.now === "string" && !Number.isNaN(Date.parse(raw.now)) ? raw.now : void 0;
1477
+ if (!previewing) return now ? { ...effectiveContext(real, null), now } : effectiveContext(real, null);
1478
+ const overrides = sanitizePreviewContext({ experiments: raw.experiments, now }, "experience-builder");
1479
+ return effectiveContext({ ...real, experiments: {} }, overrides);
1480
+ }
1481
+ function explainSnapshot(snap, context, preview) {
1482
+ const doc = snap.doc ? structuredClone(snap.doc) : { documentId: snap.target.documentId, content: [] };
1483
+ attachToDocument(doc, ["content"], { variations: snap.allVariations, annotations: snap.allAnnotations }, snap.experiments, snap.locale);
1484
+ const ctx = explainContext(context, preview);
1485
+ const result2 = resolvePage(doc[EXPERIENCE_KEY], doc.content ?? [], ctx);
1486
+ const explanation = explainResolution(result2);
1487
+ return {
1488
+ context: ctx,
1489
+ rendered: result2.blocks.map((b) => typeof b.blockKey === "string" ? b.blockKey : null),
1490
+ sections: result2.sections,
1491
+ experiments: result2.experiments,
1492
+ explanation
1493
+ };
1494
+ }
1495
+ const ALL = { pagination: { limit: -1 } };
1496
+ const localeFilter = (locale2) => locale2 === void 0 ? {} : { targetLocale: locale2 === null ? { $null: true } : locale2 };
1497
+ function createStore(strapi) {
1498
+ const docs = (uid) => strapi.documents(uid);
1499
+ const log = (ctx, entry) => recordChange(strapi, entry, ctx.batch);
1500
+ async function listVariations(filters = {}) {
1501
+ const where = {};
1502
+ if (filters.targetUid) where.targetUid = filters.targetUid;
1503
+ if (Array.isArray(filters.targetDocumentId)) where.targetDocumentId = { $in: filters.targetDocumentId };
1504
+ else if (filters.targetDocumentId) where.targetDocumentId = filters.targetDocumentId;
1505
+ if (filters.sectionKey) where.sectionKey = filters.sectionKey;
1506
+ if (filters.blockKey) where.blockKey = filters.blockKey;
1507
+ Object.assign(where, localeFilter(filters.locale));
1508
+ const rows = await docs(VARIATION_UID).findMany({ ...ALL, filters: where, sort: [{ id: "asc" }] });
1509
+ return rows.map(toVariationRecord);
1510
+ }
1511
+ async function createVariation(record, ctx) {
1512
+ const data = { ...variationDataOf(record), source: ctx.source, createdByActor: ctx.actor, correlationId: ctx.correlationId ?? null };
1513
+ const stored = toVariationRecord(await docs(VARIATION_UID).create({ data }));
1514
+ await log(ctx, { action: "create", entity: "variation", entityDocumentId: stored.documentId, before: null, after: stored, actor: ctx.actor, source: ctx.source, reason: ctx.reason, correlationId: ctx.correlationId });
1515
+ return stored;
1516
+ }
1517
+ async function updateVariation(before, patch, ctx) {
1518
+ const next = { ...before, ...patch };
1519
+ const data = { ...variationDataOf(next), correlationId: ctx.correlationId ?? before.correlationId ?? null };
1520
+ const stored = toVariationRecord(await docs(VARIATION_UID).update({ documentId: before.documentId, data }));
1521
+ await log(ctx, { action: "update", entity: "variation", entityDocumentId: before.documentId, before, after: stored, actor: ctx.actor, source: ctx.source, reason: ctx.reason, correlationId: ctx.correlationId });
1522
+ return stored;
1523
+ }
1524
+ async function deleteVariation(before, ctx) {
1525
+ await docs(VARIATION_UID).delete({ documentId: before.documentId });
1526
+ await log(ctx, { action: "delete", entity: "variation", entityDocumentId: before.documentId, before, after: null, actor: ctx.actor, source: ctx.source, reason: ctx.reason, correlationId: ctx.correlationId });
1527
+ }
1528
+ async function listAnnotations(filters = {}) {
1529
+ const where = {};
1530
+ if (filters.targetUid) where.targetUid = filters.targetUid;
1531
+ if (Array.isArray(filters.targetDocumentId)) where.targetDocumentId = { $in: filters.targetDocumentId };
1532
+ else if (filters.targetDocumentId) where.targetDocumentId = filters.targetDocumentId;
1533
+ if (filters.blockKey !== void 0) where.blockKey = filters.blockKey === null ? { $null: true } : filters.blockKey;
1534
+ Object.assign(where, localeFilter(filters.locale));
1535
+ const rows = await docs(ANNOTATION_UID).findMany({ ...ALL, filters: where, sort: [{ id: "asc" }] });
1536
+ return rows.map(toAnnotationRecord);
1537
+ }
1538
+ async function setAnnotation(existing, record, ctx) {
1539
+ if (record.concepts.length === 0) {
1540
+ if (existing) await deleteAnnotation(existing, ctx);
1541
+ return null;
1542
+ }
1543
+ const data = annotationData({
1544
+ ...record,
1545
+ orphaned: record.orphaned ?? existing?.orphaned ?? false,
1546
+ source: existing?.source ?? ctx.source,
1547
+ createdBy: existing?.createdBy ?? ctx.actor,
1548
+ correlationId: ctx.correlationId ?? existing?.correlationId ?? null
1549
+ });
1550
+ if (existing) {
1551
+ const stored2 = toAnnotationRecord(await docs(ANNOTATION_UID).update({ documentId: existing.documentId, data }));
1552
+ await log(ctx, { action: "update", entity: "annotation", entityDocumentId: existing.documentId, before: existing, after: stored2, actor: ctx.actor, source: ctx.source, reason: ctx.reason, correlationId: ctx.correlationId });
1553
+ return stored2;
1554
+ }
1555
+ const stored = toAnnotationRecord(await docs(ANNOTATION_UID).create({ data }));
1556
+ await log(ctx, { action: "create", entity: "annotation", entityDocumentId: stored.documentId, before: null, after: stored, actor: ctx.actor, source: ctx.source, reason: ctx.reason, correlationId: ctx.correlationId });
1557
+ return stored;
1558
+ }
1559
+ async function deleteAnnotation(before, ctx) {
1560
+ await docs(ANNOTATION_UID).delete({ documentId: before.documentId });
1561
+ await log(ctx, { action: "delete", entity: "annotation", entityDocumentId: before.documentId, before, after: null, actor: ctx.actor, source: ctx.source, reason: ctx.reason, correlationId: ctx.correlationId });
1562
+ }
1563
+ async function listExperiments(keys) {
1564
+ if (keys && keys.length === 0) return [];
1565
+ const rows = await docs(EXPERIMENT_UID).findMany({
1566
+ ...ALL,
1567
+ ...keys ? { filters: { key: { $in: [...new Set(keys)] } } } : {},
1568
+ sort: [{ id: "asc" }]
1569
+ });
1570
+ return rows.map(toExperimentRecord);
1571
+ }
1572
+ async function getExperiment(key) {
1573
+ return (await listExperiments([key]))[0];
1574
+ }
1575
+ async function saveExperiment(existing, record, ctx) {
1576
+ const data = experimentData({
1577
+ ...record,
1578
+ source: existing?.source ?? ctx.source,
1579
+ createdBy: existing?.createdBy ?? ctx.actor,
1580
+ correlationId: ctx.correlationId ?? existing?.correlationId ?? null
1581
+ });
1582
+ if (existing) {
1583
+ const stored2 = toExperimentRecord(await docs(EXPERIMENT_UID).update({ documentId: existing.documentId, data }));
1584
+ await log(ctx, { action: "update", entity: "experiment", entityDocumentId: existing.documentId, before: existing, after: stored2, actor: ctx.actor, source: ctx.source, reason: ctx.reason, correlationId: ctx.correlationId });
1585
+ return stored2;
1586
+ }
1587
+ const stored = toExperimentRecord(await docs(EXPERIMENT_UID).create({ data }));
1588
+ await log(ctx, { action: "create", entity: "experiment", entityDocumentId: stored.documentId, before: null, after: stored, actor: ctx.actor, source: ctx.source, reason: ctx.reason, correlationId: ctx.correlationId });
1589
+ return stored;
1590
+ }
1591
+ async function deleteExperiment(before, ctx) {
1592
+ await docs(EXPERIMENT_UID).delete({ documentId: before.documentId });
1593
+ await log(ctx, { action: "delete", entity: "experiment", entityDocumentId: before.documentId, before, after: null, actor: ctx.actor, source: ctx.source, reason: ctx.reason, correlationId: ctx.correlationId });
1594
+ }
1595
+ async function variationsOfExperiment(key) {
1596
+ return (await listVariations()).filter((v) => v.experiment?.key === key);
1597
+ }
1598
+ async function logBlock(action, block, ctx) {
1599
+ await log(ctx, {
1600
+ action,
1601
+ entity: "block",
1602
+ entityDocumentId: null,
1603
+ before: action === "delete" ? block : null,
1604
+ after: action === "create" ? block : null,
1605
+ actor: ctx.actor,
1606
+ source: ctx.source,
1607
+ reason: ctx.reason,
1608
+ correlationId: ctx.correlationId
1609
+ });
1610
+ }
1611
+ return {
1612
+ listVariations,
1613
+ createVariation,
1614
+ updateVariation,
1615
+ deleteVariation,
1616
+ listAnnotations,
1617
+ setAnnotation,
1618
+ deleteAnnotation,
1619
+ listExperiments,
1620
+ getExperiment,
1621
+ saveExperiment,
1622
+ deleteExperiment,
1623
+ variationsOfExperiment,
1624
+ logBlock
1625
+ };
1626
+ }
1627
+ const variationDataOf = (r) => {
1628
+ const { targetUid: targetUid2, targetDocumentId: targetDocumentId2, locale: locale2, blockKey, sectionKey: sectionKey2, variantKey: variantKey2, displayName, description, isDefault, status, orphaned, targetAudiences, traits: traits2, affinities: affinities2, experiment, priority, validity: validity2, componentUid, source, createdBy } = r;
1629
+ return {
1630
+ targetUid: targetUid2,
1631
+ targetDocumentId: targetDocumentId2,
1632
+ targetLocale: locale2,
1633
+ blockKey,
1634
+ sectionKey: sectionKey2,
1635
+ variantKey: variantKey2,
1636
+ displayName,
1637
+ description,
1638
+ isDefault,
1639
+ status,
1640
+ orphaned,
1641
+ targetAudiences,
1642
+ traits: traits2,
1643
+ affinities: affinities2,
1644
+ experiment,
1645
+ priority,
1646
+ validity: validity2,
1647
+ componentUid,
1648
+ source,
1649
+ createdByActor: createdBy
1650
+ };
1651
+ };
1652
+ const ALLOWED_STATUS = ["active", "inactive"];
1653
+ const issueLines = (issues) => issues.map((i) => `- ${i.code} ${i.path}: ${i.message}`).join("\n");
1654
+ function assertValid(result2, where = "") {
1655
+ if (result2.errors.length === 0) return;
1656
+ const warnings = result2.warnings.length ? `
1657
+ Warnings:
1658
+ ${issueLines(result2.warnings)}` : "";
1659
+ throw new ToolError(`Rejected${where ? ` (${where})` : ""}, nothing was written:
1660
+ ${issueLines(result2.errors)}${warnings}`);
1661
+ }
1662
+ async function inTransaction(strapi, run) {
1663
+ const db2 = strapi.db;
1664
+ return typeof db2?.transaction === "function" ? db2.transaction(run) : run();
1665
+ }
1666
+ async function write(strapi, caller, args, run) {
1667
+ const batch = new ChangeBatch();
1668
+ const ctx = { actor: caller.actor, source: "mcp", correlationId: args.correlationId ?? null, reason: args.reason ?? null, batch };
1669
+ const out = await inTransaction(strapi, () => run(ctx));
1670
+ await batch.flush(strapi);
1671
+ return out;
1672
+ }
1673
+ const store$1 = (strapi) => createStore(strapi);
1674
+ const keysOfBlocks = (blocks) => blocks.map((b) => b.blockKey).filter((k) => typeof k === "string" && k !== "");
1675
+ async function targetAndLocale(strapi, args) {
1676
+ const target = await resolveTarget(strapi, args.targetUid, args.targetDocumentId);
1677
+ const locale2 = await pickLocale(strapi, target, args.locale ?? void 0);
1678
+ return { target, locale: locale2 };
1679
+ }
1680
+ const variationView = (v) => ({
1681
+ ...toVariation(v),
1682
+ id: v.documentId,
1683
+ locale: v.locale,
1684
+ orphaned: v.orphaned,
1685
+ source: v.source,
1686
+ createdBy: v.createdBy,
1687
+ correlationId: v.correlationId,
1688
+ createdAt: v.createdAt ?? null,
1689
+ updatedAt: v.updatedAt ?? null
1690
+ });
1691
+ const sectionViews = (variations2) => {
1692
+ const sections = /* @__PURE__ */ new Map();
1693
+ for (const v of variations2) {
1694
+ const s = sections.get(v.sectionKey) ?? { sectionKey: v.sectionKey, default: null, variations: [] };
1695
+ if (v.isDefault && !s.default) s.default = variationView(v);
1696
+ else s.variations.push(variationView(v));
1697
+ sections.set(v.sectionKey, s);
1698
+ }
1699
+ return [...sections.values()];
1700
+ };
1701
+ function findVariation(snap, args) {
1702
+ const rows = snap.variations;
1703
+ let row;
1704
+ if (args.blockKey) row = rows.find((v) => v.blockKey === args.blockKey);
1705
+ else if (args.sectionKey && args.variantKey) row = rows.find((v) => v.sectionKey === args.sectionKey && v.variantKey === args.variantKey);
1706
+ else throw new ToolError("Name the variation with sectionKey + variantKey, or blockKey.");
1707
+ if (row) return row;
1708
+ const sectionKeys = [...new Set(rows.map((v) => v.sectionKey))];
1709
+ if (args.sectionKey && !sectionKeys.includes(args.sectionKey)) {
1710
+ throw new ToolError(
1711
+ `No section ${JSON.stringify(args.sectionKey)} on ${snap.target.uid} ${snap.target.documentId}${snap.locale ? ` (${snap.locale})` : ""}.${didYouMean(args.sectionKey, sectionKeys)} Sections: ${sectionKeys.join(", ") || "none"}.`
1712
+ );
1713
+ }
1714
+ const keys = rows.filter((v) => !args.sectionKey || v.sectionKey === args.sectionKey).map((v) => v.variantKey);
1715
+ const what = args.blockKey ? `block ${args.blockKey}` : `variant ${JSON.stringify(args.variantKey)} in section ${args.sectionKey}`;
1716
+ throw new ToolError(`No mapping for ${what}.${args.variantKey ? didYouMean(args.variantKey, keys) : ""} Variants: ${keys.join(", ") || "none"}.`);
1717
+ }
1718
+ async function experimentsFor(s, variations2, extra = []) {
1719
+ const keys = [...new Set(variations2.filter((v) => v.experiment).map((v) => v.experiment.key))];
1720
+ const map = new Map(extra.map((e) => [e.key, e]));
1721
+ for (const e of await s.listExperiments(keys.filter((k) => !map.has(k)))) map.set(e.key, e);
1722
+ return keys.map((k) => map.get(k)).filter((e) => Boolean(e));
1723
+ }
1724
+ async function validateFinal(s, snap, vctx, next) {
1725
+ const experiments2 = await experimentsFor(s, next.variations, next.experiments);
1726
+ const state = {
1727
+ variations: next.variations,
1728
+ annotations: next.annotations ?? snap.annotations,
1729
+ experiments: experiments2,
1730
+ blockKeys: next.blockKeys ?? (snap.doc ? keysOfBlocks(snap.blocks) : void 0),
1731
+ contentOutcomes: await contentOutcomesElsewhere(s, { target: snap.target, variations: snap.variations }, experiments2.map((e) => e.key))
1732
+ };
1733
+ const result2 = validateState(state, vctx);
1734
+ return { state, result: result2, report: report(state, result2) };
1735
+ }
1736
+ const blankVariation = (snap) => ({
1737
+ targetUid: snap.target.uid,
1738
+ targetDocumentId: snap.target.documentId,
1739
+ locale: snap.locale,
1740
+ displayName: null,
1741
+ description: null,
1742
+ status: "active",
1743
+ orphaned: false,
1744
+ targetAudiences: [],
1745
+ traits: [],
1746
+ affinities: [],
1747
+ experiment: null,
1748
+ priority: 0,
1749
+ validity: null,
1750
+ componentUid: null,
1751
+ source: "mcp",
1752
+ createdBy: null,
1753
+ correlationId: null
1754
+ });
1755
+ const checkKey = (value, name) => {
1756
+ if (!isSlug(value)) throw new ToolError(`${name} ${JSON.stringify(value)} must be lowercase [a-z0-9-] (e.g. "home-hero").`);
1757
+ };
1758
+ const targetView = (snap) => ({
1759
+ uid: snap.target.uid,
1760
+ documentId: snap.target.documentId,
1761
+ kind: snap.target.kind,
1762
+ localized: snap.target.localized,
1763
+ locale: snap.locale
1764
+ });
1765
+ async function describeTarget(strapi, args) {
1766
+ const s = store$1(strapi);
1767
+ const { target, locale: locale2 } = await targetAndLocale(strapi, args);
1768
+ const status = args.status ?? "draft";
1769
+ const snap = await loadSnapshot(strapi, s, target, locale2, status);
1770
+ const vctx = await validationContext(strapi);
1771
+ const state = await snapshotState(s, snap);
1772
+ const validation = report(state, validateState(state, vctx));
1773
+ const warnings = [];
1774
+ const coverage = [];
1775
+ const locales = target.localized ? await localeCodes(strapi) : [null];
1776
+ for (const loc of locales) {
1777
+ const doc = loc === locale2 ? snap.doc : await loadDocument(strapi, target, loc, status);
1778
+ const blocks = blocksOf(doc);
1779
+ const keys = new Set(keysOfBlocks(blocks));
1780
+ const rows = forLocale(snap.allVariations, loc);
1781
+ coverage.push({
1782
+ locale: loc,
1783
+ exists: Boolean(doc),
1784
+ blocks: blocks.length,
1785
+ unkeyedBlocks: blocks.filter((b) => !b.blockKey).length,
1786
+ mappedBlocks: rows.filter((v) => keys.has(v.blockKey)).length,
1787
+ mappingsWithoutBlock: rows.filter((v) => !keys.has(v.blockKey)).map((v) => ({ sectionKey: v.sectionKey, variantKey: v.variantKey, blockKey: v.blockKey }))
1788
+ });
1789
+ }
1790
+ if (!snap.doc) warnings.push(`No ${status} version of ${target.uid} ${target.documentId}${locale2 ? ` in locale ${locale2}` : ""}.`);
1791
+ const unkeyed = snap.blocks.filter((b) => !b.blockKey).length;
1792
+ if (unkeyed) warnings.push(`${unkeyed} block(s) have no blockKey and cannot be mapped yet; run experience_backfill_block_keys.`);
1793
+ const orphaned = snap.variations.filter((v) => v.orphaned).length + snap.annotations.filter((a) => a.orphaned).length;
1794
+ if (orphaned) warnings.push(`${orphaned} mapping(s) are orphaned: their block is no longer in the draft. They are not sent until the block comes back.`);
1795
+ const byBlock = new Map(snap.variations.map((v) => [v.blockKey, v]));
1796
+ const concepts = new Map(snap.annotations.filter((a) => !a.orphaned).map((a) => [a.blockKey ?? "", a.concepts]));
1797
+ return {
1798
+ target: { ...targetView(snap), title: displayTitle(snap.doc) },
1799
+ locale: locale2,
1800
+ status,
1801
+ page: { concepts: concepts.get("") ?? [] },
1802
+ blocks: snap.blocks.map((b) => {
1803
+ const v = b.blockKey ? byBlock.get(b.blockKey) : void 0;
1804
+ return {
1805
+ ...b,
1806
+ concepts: b.blockKey && concepts.get(b.blockKey) || [],
1807
+ section: v ? {
1808
+ sectionKey: v.sectionKey,
1809
+ variantKey: v.variantKey,
1810
+ isDefault: v.isDefault,
1811
+ displayName: v.displayName,
1812
+ status: v.orphaned ? "orphaned" : v.status,
1813
+ targetAudiences: v.targetAudiences,
1814
+ traits: v.traits,
1815
+ affinities: v.affinities,
1816
+ priority: v.priority,
1817
+ validity: v.validity
1818
+ } : null,
1819
+ experiment: v?.experiment ?? null
1820
+ };
1821
+ }),
1822
+ sections: sectionViews(snap.variations),
1823
+ experiments: [...snap.experiments.values()].map(toExperiment),
1824
+ coverage,
1825
+ validation,
1826
+ warnings
1827
+ };
1828
+ }
1829
+ async function listRegistry(strapi, args) {
1830
+ const registry2 = await loadRegistry(strapi);
1831
+ const kinds = args.kind ? [args.kind] : [...REGISTRY_KINDS];
1832
+ const out = {};
1833
+ for (const k of kinds) out[k] = registry2[k];
1834
+ return { ...out, counts: Object.fromEntries(kinds.map((k) => [k, registry2[k].length])) };
1835
+ }
1836
+ async function listContentVariants(strapi, args) {
1837
+ const s = store$1(strapi);
1838
+ let rows;
1839
+ if (args.targetUid) {
1840
+ const target = await resolveTarget(strapi, args.targetUid, args.targetDocumentId);
1841
+ rows = await s.listVariations({ targetUid: target.uid, targetDocumentId: target.documentId });
1842
+ } else {
1843
+ rows = await s.listVariations();
1844
+ }
1845
+ rows = rows.filter(
1846
+ (v) => (args.locale === void 0 || v.locale === args.locale) && (!args.sectionKey || v.sectionKey === args.sectionKey) && (!args.audience || v.targetAudiences.includes(args.audience)) && (!args.experimentKey || v.experiment?.key === args.experimentKey) && (args.includeInactive === true || v.status === "active" && !v.orphaned)
1847
+ );
1848
+ const groups = /* @__PURE__ */ new Map();
1849
+ for (const v of rows) {
1850
+ const k = `${v.targetUid}\0${v.targetDocumentId}\0${v.locale ?? ""}`;
1851
+ groups.set(k, [...groups.get(k) ?? [], v]);
1852
+ }
1853
+ const targets = [...groups.values()].map((list) => ({
1854
+ targetUid: list[0].targetUid,
1855
+ targetDocumentId: list[0].targetDocumentId,
1856
+ locale: list[0].locale,
1857
+ sections: sectionViews(list)
1858
+ }));
1859
+ return { count: rows.length, targets };
1860
+ }
1861
+ async function validateMapping(strapi, args) {
1862
+ const s = store$1(strapi);
1863
+ const vctx = await validationContext(strapi);
1864
+ const results = [];
1865
+ let groups;
1866
+ if (args.targetUid) {
1867
+ groups = [await targetAndLocale(strapi, args)];
1868
+ } else {
1869
+ const seen = /* @__PURE__ */ new Map();
1870
+ for (const r of [...await s.listVariations(), ...await s.listAnnotations()]) {
1871
+ seen.set(`${r.targetUid}\0${r.targetDocumentId}\0${r.locale ?? ""}`, { uid: r.targetUid, documentId: r.targetDocumentId, locale: r.locale });
1872
+ }
1873
+ groups = [];
1874
+ for (const g of seen.values()) {
1875
+ if (!configuredContentTypes(strapi).includes(g.uid)) continue;
1876
+ const target = await resolveTarget(strapi, g.uid, g.documentId).catch(() => null);
1877
+ if (target) groups.push({ target, locale: g.locale });
1878
+ }
1879
+ }
1880
+ for (const g of groups) {
1881
+ const snap = await loadSnapshot(strapi, s, g.target, g.locale);
1882
+ const state = await snapshotState(s, snap);
1883
+ results.push({ target: targetView(snap), ...report(state, validateState(state, vctx)) });
1884
+ }
1885
+ const experiments2 = [];
1886
+ for (const e of await s.listExperiments()) {
1887
+ const coverage = [...new Set((await s.variationsOfExperiment(e.key)).filter((v) => v.status === "active" && !v.orphaned).map((v) => v.experiment.outcome))];
1888
+ const state = { variations: [], experiments: [e], contentOutcomes: { [e.key]: coverage } };
1889
+ experiments2.push({ key: e.key, status: e.status, ...report(state, validateExperienceMapping({ v: 2, variations: [], experiments: [toExperiment(e)], contentOutcomes: state.contentOutcomes }, vctx.registry)) });
1890
+ }
1891
+ const ok = results.every((r) => r.ok) && experiments2.every((e) => e.ok);
1892
+ return { ok, targets: results, experiments: experiments2 };
1893
+ }
1894
+ async function explainVariantResolution(strapi, args) {
1895
+ const s = store$1(strapi);
1896
+ const { target, locale: locale2 } = await targetAndLocale(strapi, args);
1897
+ const snap = await loadSnapshot(strapi, s, target, locale2, args.status ?? "draft");
1898
+ if (!snap.doc) throw new ToolError(`No ${args.status ?? "draft"} version of ${target.uid} ${target.documentId}${locale2 ? ` in locale ${locale2}` : ""}.`);
1899
+ const out = explainSnapshot(snap, args.context, args.preview);
1900
+ return { target: targetView(snap), status: snap.status, ...out };
1901
+ }
1902
+ async function createContentVariant(strapi, args, caller) {
1903
+ checkKey(args.sectionKey, "sectionKey");
1904
+ checkKey(args.variantKey, "variantKey");
1905
+ const s = store$1(strapi);
1906
+ const { target, locale: locale2 } = await targetAndLocale(strapi, args);
1907
+ const snap = await loadSnapshot(strapi, s, target, locale2);
1908
+ const { blocks } = await loadDraftZone(strapi, target, locale2);
1909
+ const keys = keysOfBlocks(blocks);
1910
+ const section = snap.variations.filter((v) => v.sectionKey === args.sectionKey);
1911
+ const existingDefault = section.find((v) => v.isDefault);
1912
+ const findBlock = (key, what) => {
1913
+ const b = blocks.find((x) => x.blockKey === key);
1914
+ if (!b) throw new ToolError(`${what} ${JSON.stringify(key)} is not a block of the draft${locale2 ? ` (${locale2})` : ""}.${didYouMean(key, keys)} Use experience_describe_target for block keys.`);
1915
+ return b;
1916
+ };
1917
+ let defaultRow = null;
1918
+ if (!existingDefault) {
1919
+ if (section.length) throw new ToolError(`Section ${args.sectionKey} has variations but no default; fix it with experience_remove_mapping or experience_validate_mapping first.`);
1920
+ const key = args.defaultBlockKey ?? args.sourceBlockKey;
1921
+ if (!key) throw new ToolError(`Section ${args.sectionKey} does not exist yet: pass sourceBlockKey (or defaultBlockKey with content or existingBlockKey) to make that block its default.`);
1922
+ const block2 = findBlock(key, "defaultBlockKey");
1923
+ defaultRow = {
1924
+ ...blankVariation(snap),
1925
+ sectionKey: args.sectionKey,
1926
+ variantKey: args.defaultVariantKey ?? "default",
1927
+ blockKey: key,
1928
+ isDefault: true,
1929
+ displayName: args.defaultDisplayName ?? blocksOf({ content: [block2] })[0]?.title ?? null,
1930
+ componentUid: block2.__component,
1931
+ experiment: args.defaultOutcome && args.experiment ? { key: args.experiment.key, outcome: args.defaultOutcome } : null
1932
+ };
1933
+ } else if (args.defaultOutcome) {
1934
+ throw new ToolError(`defaultOutcome only applies when the section is created; map the existing default with experience_associate_variant_with_experiment.`);
1935
+ }
1936
+ const adopt = args.existingBlockKey ?? null;
1937
+ if (adopt && (args.sourceBlockKey || args.content)) {
1938
+ throw new ToolError("Pass existingBlockKey, sourceBlockKey or content, not several.");
1939
+ }
1940
+ if (adopt && adopt === defaultRow?.blockKey) {
1941
+ throw new ToolError(`existingBlockKey ${adopt} is the section's default; pick another block for the variation.`);
1942
+ }
1943
+ const sourceKey = adopt ? null : args.sourceBlockKey ?? (args.content ? null : existingDefault?.blockKey ?? null);
1944
+ const source = sourceKey ? findBlock(sourceKey, "sourceBlockKey") : null;
1945
+ const block = adopt ? findBlock(adopt, "existingBlockKey") : newBlock(strapi, source, source ? null : args.content ?? null);
1946
+ if (!adopt && !zoneAccepts(strapi, target.uid, block.__component)) {
1947
+ throw new ToolError(`${block.__component} is not allowed in the content zone of ${target.uid}.`);
1948
+ }
1949
+ const members = /* @__PURE__ */ new Set([...section.map((v) => v.blockKey), ...defaultRow ? [defaultRow.blockKey] : []]);
1950
+ const lastIndex = Math.max(-1, ...blocks.map((b, i) => b.blockKey && members.has(b.blockKey) ? i : -1));
1951
+ const index2 = adopt ? blocks.indexOf(block) : lastIndex >= 0 ? lastIndex + 1 : blocks.length;
1952
+ const entries = adopt ? blocks : [...blocks.slice(0, index2), block, ...blocks.slice(index2)];
1953
+ const variantRow = {
1954
+ ...blankVariation(snap),
1955
+ sectionKey: args.sectionKey,
1956
+ variantKey: args.variantKey,
1957
+ blockKey: block.blockKey,
1958
+ isDefault: false,
1959
+ displayName: args.displayName ?? null,
1960
+ description: args.description ?? null,
1961
+ status: args.status ?? "active",
1962
+ targetAudiences: args.targetAudiences ?? [],
1963
+ traits: args.traits ?? [],
1964
+ affinities: args.affinities ?? [],
1965
+ experiment: args.experiment ?? null,
1966
+ priority: args.priority ?? 0,
1967
+ validity: args.validity ?? null,
1968
+ componentUid: block.__component
1969
+ };
1970
+ const planned = [...defaultRow ? [defaultRow] : [], variantRow].map((r) => ({ ...r, documentId: null }));
1971
+ const vctx = await validationContext(strapi);
1972
+ const { result: result2, report: validation } = await validateFinal(s, snap, vctx, {
1973
+ variations: [...snap.variations, ...planned],
1974
+ blockKeys: keysOfBlocks(entries)
1975
+ });
1976
+ if (result2.errors.some((e) => e.code === "V5")) {
1977
+ assertValid(
1978
+ {
1979
+ errors: result2.errors.map(
1980
+ (e) => e.code === "V5" ? { ...e, message: `${e.message}. Pass targetAudiences, traits or affinities (or experiment) when creating it.` } : e
1981
+ ),
1982
+ warnings: result2.warnings
1983
+ },
1984
+ `${target.uid} ${target.documentId}`
1985
+ );
1986
+ }
1987
+ assertValid(result2, `${target.uid} ${target.documentId}`);
1988
+ const plan = {
1989
+ section: { sectionKey: args.sectionKey, created: Boolean(defaultRow), default: defaultRow ? defaultRow.blockKey : existingDefault.blockKey },
1990
+ block: { blockKey: block.blockKey, componentUid: block.__component, index: index2, copiedFrom: source?.blockKey ?? null, adopted: Boolean(adopt) },
1991
+ variation: toVariation({ ...variantRow })
1992
+ };
1993
+ if (args.dryRun) return { dryRun: true, target: targetView(snap), ...plan, validation };
1994
+ await write(strapi, caller, args, async (ctx) => {
1995
+ if (!adopt) {
1996
+ await writeZone(strapi, target, locale2, entries);
1997
+ await s.logBlock("create", { targetUid: target.uid, targetDocumentId: target.documentId, locale: locale2, blockKey: block.blockKey, componentUid: block.__component, index: index2, copiedFrom: source?.blockKey ?? null }, ctx);
1998
+ }
1999
+ if (defaultRow) await s.createVariation(defaultRow, ctx);
2000
+ await s.createVariation(variantRow, ctx);
2001
+ });
2002
+ return {
2003
+ dryRun: false,
2004
+ target: targetView(snap),
2005
+ ...plan,
2006
+ validation,
2007
+ next: [
2008
+ adopt ? `Check the mapping with experience_validate_mapping and experience_explain_variant_resolution, then publish the page.` : `Edit the copied block (blockKey ${block.blockKey}) in the draft, then check it with experience_validate_mapping and experience_explain_variant_resolution.`
2009
+ ]
2010
+ };
2011
+ }
2012
+ async function patchVariation(strapi, caller, args, pick, patch) {
2013
+ const s = store$1(strapi);
2014
+ const { target, locale: locale2 } = await targetAndLocale(strapi, args);
2015
+ const snap = await loadSnapshot(strapi, s, target, locale2);
2016
+ const before = pick(snap);
2017
+ const changes = patch(before);
2018
+ const after = { ...before, ...changes };
2019
+ const vctx = await validationContext(strapi);
2020
+ const { result: result2, report: validation } = await validateFinal(s, snap, vctx, { variations: snap.variations.map((v) => v === before ? after : v) });
2021
+ assertValid(result2, `${target.uid} ${target.documentId}`);
2022
+ if (args.dryRun) return { dryRun: true, target: targetView(snap), before: variationView(before), after: variationView(after), validation };
2023
+ const stored = await write(strapi, caller, args, (ctx) => s.updateVariation(before, changes, ctx));
2024
+ return { dryRun: false, target: targetView(snap), before: variationView(before), after: variationView(stored), validation };
2025
+ }
2026
+ async function updateContentVariant(strapi, args, caller) {
2027
+ if (args.newVariantKey !== void 0) checkKey(args.newVariantKey, "newVariantKey");
2028
+ if (args.status !== void 0 && !ALLOWED_STATUS.includes(args.status)) throw new ToolError("status must be active or inactive.");
2029
+ return patchVariation(
2030
+ strapi,
2031
+ caller,
2032
+ args,
2033
+ (snap) => {
2034
+ const v = findVariation(snap, args);
2035
+ if (v.experiment) caller.require?.(ACTIONS.experimentsWrite, `Changing ${v.sectionKey}/${v.variantKey}, content of experiment ${v.experiment.key}`);
2036
+ return v;
2037
+ },
2038
+ () => {
2039
+ const p = {};
2040
+ if (args.newVariantKey !== void 0) p.variantKey = args.newVariantKey;
2041
+ if (args.displayName !== void 0) p.displayName = args.displayName;
2042
+ if (args.description !== void 0) p.description = args.description;
2043
+ if (args.status !== void 0) p.status = args.status;
2044
+ if (args.priority !== void 0) p.priority = args.priority;
2045
+ if (args.validity !== void 0) p.validity = args.validity;
2046
+ if (Object.keys(p).length === 0) throw new ToolError("Nothing to update: pass newVariantKey, displayName, description, status, priority or validity.");
2047
+ return p;
2048
+ }
2049
+ );
2050
+ }
2051
+ async function associateVariantWithAudience(strapi, args, caller) {
2052
+ if (args.targetAudiences === void 0 && args.traits === void 0 && args.affinities === void 0) {
2053
+ throw new ToolError("Pass targetAudiences, traits and/or affinities.");
2054
+ }
2055
+ return patchVariation(
2056
+ strapi,
2057
+ caller,
2058
+ args,
2059
+ (snap) => findVariation(snap, args),
2060
+ (v) => {
2061
+ if (v.isDefault) throw new ToolError(`${v.sectionKey} / ${v.variantKey} is the section's default (the fallback); it carries no audiences. Map a variation instead.`);
2062
+ if (v.experiment) {
2063
+ throw new ToolError(
2064
+ `${v.sectionKey} / ${v.variantKey} is content of experiment outcome ${v.experiment.key} / ${v.experiment.outcome}. Audience variations and experiment outcomes don't mix in one section until OD-1 is decided (X1).`
2065
+ );
2066
+ }
2067
+ const merge = (current, given) => given === void 0 ? current : args.mode === "add" ? [.../* @__PURE__ */ new Set([...current, ...given])] : [...new Set(given)];
2068
+ return {
2069
+ targetAudiences: merge(v.targetAudiences, args.targetAudiences),
2070
+ traits: merge(v.traits, args.traits),
2071
+ affinities: merge(v.affinities, args.affinities)
2072
+ };
2073
+ }
2074
+ );
2075
+ }
2076
+ async function associateVariantWithExperiment(strapi, args, caller) {
2077
+ if (args.experimentKey && !args.outcome) throw new ToolError("outcome is required with experimentKey (null experimentKey removes the mapping).");
2078
+ const s = store$1(strapi);
2079
+ const { target, locale: locale2 } = await targetAndLocale(strapi, args);
2080
+ const snap = await loadSnapshot(strapi, s, target, locale2);
2081
+ const existing = args.blockKey ? snap.variations.find((v) => v.blockKey === args.blockKey) : args.sectionKey && args.variantKey ? snap.variations.find((v) => v.sectionKey === args.sectionKey && v.variantKey === args.variantKey) : void 0;
2082
+ const ref = args.experimentKey ? { key: args.experimentKey, outcome: args.outcome } : null;
2083
+ const vctx = await validationContext(strapi);
2084
+ if (existing) {
2085
+ if (ref && (existing.targetAudiences.length || existing.traits.length || existing.affinities.length)) {
2086
+ throw new ToolError(
2087
+ `${existing.sectionKey} / ${existing.variantKey} is an audience variation. Audience variations and experiment outcomes don't mix in one section until OD-1 is decided (X1); use a separate section.`
2088
+ );
2089
+ }
2090
+ const after = { ...existing, experiment: ref };
2091
+ const { result: result22, report: validation2 } = await validateFinal(s, snap, vctx, { variations: snap.variations.map((v) => v === existing ? after : v) });
2092
+ assertValid(result22, `${target.uid} ${target.documentId}`);
2093
+ if (args.dryRun) return { dryRun: true, target: targetView(snap), before: variationView(existing), after: variationView(after), validation: validation2 };
2094
+ const stored2 = await write(strapi, caller, args, (ctx) => s.updateVariation(existing, { experiment: ref }, ctx));
2095
+ return { dryRun: false, target: targetView(snap), before: variationView(existing), after: variationView(stored2), validation: validation2 };
2096
+ }
2097
+ if (!args.blockKey || !args.sectionKey) {
2098
+ if (args.sectionKey && args.variantKey) findVariation(snap, args);
2099
+ throw new ToolError("To add a block that is not in a section yet, pass blockKey and sectionKey (variantKey defaults to the outcome).");
2100
+ }
2101
+ if (!ref) throw new ToolError(`Block ${args.blockKey} has no mapping to remove.`);
2102
+ checkKey(args.sectionKey, "sectionKey");
2103
+ const block = snap.blocks.find((b) => b.blockKey === args.blockKey);
2104
+ if (!block) throw new ToolError(`blockKey ${JSON.stringify(args.blockKey)} is not a block of the draft.${didYouMean(args.blockKey, keysOfBlocks(snap.blocks))}`);
2105
+ const isDefault = !snap.variations.some((v) => v.sectionKey === args.sectionKey);
2106
+ const row = {
2107
+ ...blankVariation(snap),
2108
+ documentId: null,
2109
+ sectionKey: args.sectionKey,
2110
+ variantKey: args.variantKey ?? ref.outcome,
2111
+ blockKey: args.blockKey,
2112
+ isDefault,
2113
+ displayName: block.title,
2114
+ componentUid: block.componentUid,
2115
+ experiment: ref
2116
+ };
2117
+ const { result: result2, report: validation } = await validateFinal(s, snap, vctx, { variations: [...snap.variations, row] });
2118
+ assertValid(result2, `${target.uid} ${target.documentId}`);
2119
+ if (args.dryRun) return { dryRun: true, target: targetView(snap), before: null, after: variationView(row), validation };
2120
+ const { documentId: _id, ...data } = row;
2121
+ const stored = await write(strapi, caller, args, (ctx) => s.createVariation(data, ctx));
2122
+ return { dryRun: false, target: targetView(snap), before: null, after: variationView(stored), validation };
2123
+ }
2124
+ const groupsOf = (rows) => {
2125
+ const groups = /* @__PURE__ */ new Map();
2126
+ for (const v of rows) groups.set(`${v.targetUid}\0${v.targetDocumentId}\0${v.locale ?? ""}`, { uid: v.targetUid, documentId: v.targetDocumentId, locale: v.locale });
2127
+ return [...groups.values()];
2128
+ };
2129
+ async function validateExperimentEverywhere(strapi, s, vctx, exp, mapped, rewrite, previous) {
2130
+ const coverage = [...new Set(mapped.filter((v) => v.status === "active" && !v.orphaned).map((v) => (rewrite ? rewrite(v) : v).experiment?.outcome).filter((o) => Boolean(o)))];
2131
+ const own = validateExperienceMapping(
2132
+ {
2133
+ v: 2,
2134
+ variations: [],
2135
+ experiments: [toExperiment(exp)],
2136
+ contentOutcomes: { [exp.key]: coverage },
2137
+ // W7: the split of a running experiment changes (compared under the new key after a rename).
2138
+ ...previous ? { previousExperiments: [{ ...toExperiment(previous), key: exp.key }] } : {}
2139
+ },
2140
+ vctx.registry
2141
+ );
2142
+ const errors = [...own.errors];
2143
+ const warnings = [...own.warnings];
2144
+ for (const g of groupsOf(mapped)) {
2145
+ const target = await resolveTarget(strapi, g.uid, g.documentId).catch(() => null);
2146
+ if (!target) continue;
2147
+ const snap = await loadSnapshot(strapi, s, target, g.locale);
2148
+ const variations2 = snap.variations.map((v) => rewrite ? rewrite(v) : v);
2149
+ const { result: result2 } = await validateFinal(s, snap, vctx, { variations: variations2, experiments: [exp] });
2150
+ const where = `${g.uid} ${g.documentId}${g.locale ? ` (${g.locale})` : ""}`;
2151
+ errors.push(...result2.errors.map((e) => ({ ...e, path: `${where}: ${e.path}` })));
2152
+ }
2153
+ return { ok: errors.length === 0, errors, warnings };
2154
+ }
2155
+ async function setExperiment(strapi, args, caller) {
2156
+ if (!isExperimentKey(args.key)) throw new ToolError(`key ${JSON.stringify(args.key)} must be lowercase [a-z0-9-], at most 40 characters.`);
2157
+ const s = store$1(strapi);
2158
+ const existing = await s.getExperiment(args.key);
2159
+ if (!existing && !args.outcomes) throw new ToolError(`Experiment ${args.key} does not exist yet: pass outcomes (at least two, e.g. [{"key":"a","label":"A (control)"},{"key":"b"}]).`);
2160
+ let key = args.key;
2161
+ const mapped = existing ? await s.variationsOfExperiment(existing.key) : [];
2162
+ if (args.newKey !== void 0 && args.newKey !== args.key) {
2163
+ if (!isExperimentKey(args.newKey)) throw new ToolError(`newKey ${JSON.stringify(args.newKey)} must be lowercase [a-z0-9-], at most 40 characters.`);
2164
+ if (!existing) throw new ToolError(`Experiment ${args.key} does not exist, so it cannot be renamed.`);
2165
+ if (existing.status === "running") throw new ToolError(`Experiment ${args.key} is running: its key is part of the assignment hash, so it cannot be renamed. Pause or conclude it first, or create a new experiment.`);
2166
+ if (await s.getExperiment(args.newKey)) throw new ToolError(`An experiment ${args.newKey} already exists.`);
2167
+ key = args.newKey;
2168
+ }
2169
+ const outcomes = (args.outcomes ?? existing?.outcomes ?? []).map((o) => ({
2170
+ key: o.key,
2171
+ label: o.label ?? null,
2172
+ ...o.intentionallyEmpty ? { intentionallyEmpty: true } : {},
2173
+ ...o.weight !== void 0 && o.weight !== null ? { weight: o.weight } : {}
2174
+ }));
2175
+ const final = {
2176
+ documentId: existing?.documentId ?? null,
2177
+ key,
2178
+ name: args.name !== void 0 ? args.name : existing?.name ?? null,
2179
+ description: args.description !== void 0 ? args.description : existing?.description ?? null,
2180
+ outcomes,
2181
+ controlOutcome: args.controlOutcome ?? existing?.controlOutcome ?? outcomes[0]?.key ?? "",
2182
+ status: args.status ?? existing?.status ?? "draft",
2183
+ validity: args.validity !== void 0 ? args.validity : existing?.validity ?? null,
2184
+ winner: existing?.winner ?? null,
2185
+ externalId: args.externalId !== void 0 ? args.externalId : existing?.externalId ?? null,
2186
+ source: existing?.source ?? "mcp",
2187
+ createdBy: existing?.createdBy ?? null,
2188
+ correlationId: existing?.correlationId ?? null
2189
+ };
2190
+ if (existing?.status === "concluded" && final.status !== "concluded") {
2191
+ throw new ToolError(`Experiment ${args.key} is concluded (winner ${existing.winner ?? "none"}); it cannot be restarted. Create a new experiment key.`);
2192
+ }
2193
+ const rewrite = key !== args.key ? (v) => v.experiment?.key === args.key ? { ...v, experiment: { key, outcome: v.experiment.outcome } } : v : void 0;
2194
+ const vctx = await validationContext(strapi);
2195
+ const validation = await validateExperimentEverywhere(strapi, s, vctx, final, mapped, rewrite, existing);
2196
+ assertValid(validation, `experiment ${args.key}`);
2197
+ const warnings = [];
2198
+ if (existing?.status === "running" && JSON.stringify(existing.outcomes.map((o) => o.key)) !== JSON.stringify(outcomes.map((o) => o.key))) {
2199
+ warnings.push("Changing the outcomes of a running experiment reshuffles visitors (assignment is HMAC(key, visitor) over the outcomes and their weights).");
2200
+ }
2201
+ for (const w of validation.warnings) if (w.code === "W7") warnings.push(w.message);
2202
+ const view = toExperiment(final);
2203
+ if (args.dryRun) return { dryRun: true, action: existing ? "update" : "create", experiment: view, previous: existing ? toExperiment(existing) : null, mappedBlocks: mapped.length, validation, warnings };
2204
+ await write(strapi, caller, args, async (ctx) => {
2205
+ const { documentId: _d, source: _s, createdBy: _c, correlationId: _k, ...record } = final;
2206
+ await s.saveExperiment(existing, record, ctx);
2207
+ for (const g of groupsOf(mapped)) ctx.batch.addTarget(g.uid, g.documentId, g.locale);
2208
+ if (rewrite) for (const v of mapped) await s.updateVariation(v, { experiment: rewrite(v).experiment }, ctx);
2209
+ });
2210
+ return {
2211
+ dryRun: false,
2212
+ action: existing ? "update" : "create",
2213
+ experiment: view,
2214
+ previous: existing ? toExperiment(existing) : null,
2215
+ mappedBlocks: mapped.length,
2216
+ validation,
2217
+ warnings,
2218
+ next: final.status === "draft" ? ['Map blocks to each outcome with experience_associate_variant_with_experiment, explain each outcome, then set status "running".'] : []
2219
+ };
2220
+ }
2221
+ async function concludeExperiment(strapi, args, caller) {
2222
+ const s = store$1(strapi);
2223
+ const existing = await s.getExperiment(args.key);
2224
+ if (!existing) {
2225
+ const keys = (await s.listExperiments()).map((e) => e.key);
2226
+ throw new ToolError(`No experiment ${JSON.stringify(args.key)}.${didYouMean(args.key, keys)}`);
2227
+ }
2228
+ const final = { ...existing, status: "concluded", winner: args.winner };
2229
+ const vctx = await validationContext(strapi);
2230
+ const mapped = await s.variationsOfExperiment(args.key);
2231
+ const plans = [];
2232
+ const errors = [];
2233
+ if (args.cleanup) {
2234
+ for (const g of groupsOf(mapped)) {
2235
+ const target = await resolveTarget(strapi, g.uid, g.documentId).catch(() => null);
2236
+ if (!target) continue;
2237
+ const snap = await loadSnapshot(strapi, s, target, g.locale);
2238
+ const mine = snap.variations.filter((v) => v.experiment?.key === args.key);
2239
+ const losers = mine.filter((v) => v.experiment.outcome !== args.winner);
2240
+ const winners = mine.filter((v) => v.experiment.outcome === args.winner);
2241
+ const loserKeys = new Set(losers.map((v) => v.blockKey));
2242
+ const zone = snap.doc ? (await loadDraftZone(strapi, target, g.locale)).blocks : null;
2243
+ const entries = zone ? zone.filter((b) => !b.blockKey || !loserKeys.has(b.blockKey)) : null;
2244
+ const promoted = /* @__PURE__ */ new Set();
2245
+ const remaining = snap.variations.filter((v) => !loserKeys.has(v.blockKey)).map((v) => {
2246
+ if (v.experiment?.key !== args.key) return v;
2247
+ const needsDefault = !snap.variations.some((x) => x.sectionKey === v.sectionKey && x.isDefault && !loserKeys.has(x.blockKey)) && !promoted.has(v.sectionKey);
2248
+ if (needsDefault) promoted.add(v.sectionKey);
2249
+ return { ...v, experiment: null, isDefault: v.isDefault || needsDefault };
2250
+ });
2251
+ const { result: result2 } = await validateFinal(s, snap, vctx, { variations: remaining, blockKeys: entries ? keysOfBlocks(entries) : void 0, experiments: [final] });
2252
+ errors.push(...result2.errors.map((e) => ({ ...e, path: `${g.uid} ${g.documentId}${g.locale ? ` (${g.locale})` : ""}: ${e.path}` })));
2253
+ plans.push({ target, locale: g.locale, snap, losers, winners: remaining.filter((v) => winners.some((w) => w.documentId === v.documentId)), entries });
2254
+ }
2255
+ }
2256
+ const own = validateExperienceMapping({ v: 2, variations: [], experiments: [toExperiment(final)] }, vctx.registry);
2257
+ assertValid({ errors: [...own.errors, ...errors], warnings: own.warnings }, `experiment ${args.key}`);
2258
+ const cleanup = plans.map((p) => ({
2259
+ targetUid: p.target.uid,
2260
+ targetDocumentId: p.target.documentId,
2261
+ locale: p.locale,
2262
+ removedBlocks: p.losers.map((v) => ({ sectionKey: v.sectionKey, variantKey: v.variantKey, blockKey: v.blockKey, outcome: v.experiment.outcome })),
2263
+ keptBlocks: p.winners.map((v) => ({ sectionKey: v.sectionKey, variantKey: v.variantKey, blockKey: v.blockKey, isDefault: v.isDefault }))
2264
+ }));
2265
+ if (args.dryRun) return { dryRun: true, experiment: toExperiment(final), previous: toExperiment(existing), cleanup, warnings: own.warnings };
2266
+ await write(strapi, caller, args, async (ctx) => {
2267
+ const { documentId: _d, source: _s, createdBy: _c, correlationId: _k, ...record } = final;
2268
+ await s.saveExperiment(existing, record, ctx);
2269
+ for (const g of groupsOf(mapped)) ctx.batch.addTarget(g.uid, g.documentId, g.locale);
2270
+ for (const p of plans) {
2271
+ if (p.entries && p.losers.length) {
2272
+ await writeZone(strapi, p.target, p.locale, p.entries);
2273
+ for (const v of p.losers) {
2274
+ await s.logBlock("delete", { targetUid: v.targetUid, targetDocumentId: v.targetDocumentId, locale: v.locale, blockKey: v.blockKey, componentUid: v.componentUid }, ctx);
2275
+ }
2276
+ }
2277
+ for (const v of p.losers) await s.deleteVariation(v, ctx);
2278
+ for (const w of p.winners) {
2279
+ const before = p.snap.variations.find((v) => v.documentId === w.documentId);
2280
+ await s.updateVariation(before, { experiment: null, isDefault: w.isDefault }, ctx);
2281
+ }
2282
+ }
2283
+ });
2284
+ return { dryRun: false, experiment: toExperiment(final), previous: toExperiment(existing), cleanup, warnings: own.warnings };
2285
+ }
2286
+ async function annotateContentWithConcepts(strapi, args, caller) {
2287
+ const s = store$1(strapi);
2288
+ const target = await resolveTarget(strapi, args.targetUid, args.targetDocumentId);
2289
+ const blockKey = args.blockKey ?? null;
2290
+ const locale2 = blockKey ? await pickLocale(strapi, target, args.locale ?? void 0) : args.locale ? await pickLocale(strapi, target, args.locale) : null;
2291
+ const viewLocale = locale2 ?? await pickLocale(strapi, target, void 0);
2292
+ const snap = await loadSnapshot(strapi, s, target, viewLocale);
2293
+ const existing = snap.allAnnotations.find((a) => (a.locale ?? null) === locale2 && (a.blockKey ?? null) === blockKey);
2294
+ const current = existing?.concepts ?? [];
2295
+ const given = [...new Set(args.concepts ?? [])];
2296
+ const concepts = args.mode === "add" ? [.../* @__PURE__ */ new Set([...current, ...given])] : args.mode === "remove" ? current.filter((c) => !given.includes(c)) : given;
2297
+ const next = {
2298
+ documentId: existing?.documentId ?? null,
2299
+ targetUid: target.uid,
2300
+ targetDocumentId: target.documentId,
2301
+ locale: locale2,
2302
+ blockKey,
2303
+ concepts,
2304
+ orphaned: existing?.orphaned ?? false,
2305
+ source: existing?.source ?? "mcp",
2306
+ createdBy: existing?.createdBy ?? null,
2307
+ correlationId: existing?.correlationId ?? null
2308
+ };
2309
+ const annotations = forLocale(
2310
+ [...snap.allAnnotations.filter((a) => a !== existing), ...concepts.length ? [next] : []],
2311
+ viewLocale
2312
+ );
2313
+ const vctx = await validationContext(strapi);
2314
+ const { result: result2, report: validation } = await validateFinal(s, snap, vctx, { variations: snap.variations, annotations });
2315
+ assertValid(result2, `${target.uid} ${target.documentId}`);
2316
+ const out = { target: targetView(snap), locale: locale2, blockKey, before: current, concepts, validation };
2317
+ if (args.dryRun) return { dryRun: true, ...out };
2318
+ await write(
2319
+ strapi,
2320
+ caller,
2321
+ args,
2322
+ (ctx) => s.setAnnotation(existing, { targetUid: target.uid, targetDocumentId: target.documentId, locale: locale2, blockKey, concepts }, ctx)
2323
+ );
2324
+ return { dryRun: false, ...out };
2325
+ }
2326
+ async function removeMapping(strapi, args, caller) {
2327
+ const s = store$1(strapi);
2328
+ const vctx = await validationContext(strapi);
2329
+ if (args.kind === "experiment") {
2330
+ if (!args.experimentKey) throw new ToolError('experimentKey is required for kind "experiment".');
2331
+ const existing = await s.getExperiment(args.experimentKey);
2332
+ if (!existing) throw new ToolError(`No experiment ${JSON.stringify(args.experimentKey)}.${didYouMean(args.experimentKey, (await s.listExperiments()).map((e) => e.key))}`);
2333
+ const mapped = await s.variationsOfExperiment(existing.key);
2334
+ if (mapped.length) {
2335
+ throw new ToolError(
2336
+ `Rejected, nothing was written:
2337
+ - V6 experiments.${existing.key}: ${mapped.length} block(s) still map to it (${mapped.map((v) => `${v.targetUid} ${v.targetDocumentId} ${v.sectionKey}/${v.variantKey}`).join("; ")}). Remove those mappings (or conclude it) first.`
2338
+ );
2339
+ }
2340
+ if (args.dryRun) return { dryRun: true, removed: { experiment: toExperiment(existing) } };
2341
+ await write(strapi, caller, args, (ctx) => s.deleteExperiment(existing, ctx));
2342
+ return { dryRun: false, removed: { experiment: toExperiment(existing) } };
2343
+ }
2344
+ if (!args.targetUid) throw new ToolError(`targetUid is required for kind "${args.kind}".`);
2345
+ const target = await resolveTarget(strapi, args.targetUid, args.targetDocumentId);
2346
+ if (args.kind === "annotation") {
2347
+ const blockKey = args.blockKey ?? null;
2348
+ const locale22 = blockKey ? await pickLocale(strapi, target, args.locale ?? void 0) : args.locale ? await pickLocale(strapi, target, args.locale) : null;
2349
+ const rows2 = await s.listAnnotations({ targetUid: target.uid, targetDocumentId: target.documentId });
2350
+ const existing = rows2.find((a) => (a.locale ?? null) === locale22 && (a.blockKey ?? null) === blockKey);
2351
+ if (!existing) throw new ToolError(`No concepts on ${blockKey ? `block ${blockKey}` : "the page"}${locale22 ? ` (${locale22})` : ""}.`);
2352
+ if (args.dryRun) return { dryRun: true, removed: { annotation: { blockKey, locale: locale22, concepts: existing.concepts } } };
2353
+ await write(strapi, caller, args, (ctx) => s.deleteAnnotation(existing, ctx));
2354
+ return { dryRun: false, removed: { annotation: { blockKey, locale: locale22, concepts: existing.concepts } } };
2355
+ }
2356
+ const locale2 = await pickLocale(strapi, target, args.locale ?? void 0);
2357
+ const snap = await loadSnapshot(strapi, s, target, locale2);
2358
+ let rows;
2359
+ if (args.kind === "section") {
2360
+ if (!args.sectionKey) throw new ToolError('sectionKey is required for kind "section".');
2361
+ rows = snap.variations.filter((v) => v.sectionKey === args.sectionKey);
2362
+ if (!rows.length) {
2363
+ const keys = [...new Set(snap.variations.map((v) => v.sectionKey))];
2364
+ throw new ToolError(`No section ${JSON.stringify(args.sectionKey)}.${didYouMean(args.sectionKey, keys)} Sections: ${keys.join(", ") || "none"}.`);
2365
+ }
2366
+ } else {
2367
+ rows = [findVariation(snap, { sectionKey: args.sectionKey, variantKey: args.variantKey, blockKey: args.blockKey ?? void 0 })];
2368
+ }
2369
+ const experimentKeys = [...new Set(rows.flatMap((v) => v.experiment ? [v.experiment.key] : []))];
2370
+ if (experimentKeys.length) caller.require?.(ACTIONS.experimentsWrite, `Removing content of experiment ${experimentKeys.join(", ")}`);
2371
+ const deleteKeys = new Set(args.deleteBlocks ? rows.filter((v) => args.kind === "variation" || !v.isDefault).map((v) => v.blockKey) : []);
2372
+ const removed = new Set(rows.map((v) => v.documentId));
2373
+ const zone = deleteKeys.size ? (await loadDraftZone(strapi, target, locale2)).blocks : null;
2374
+ const entries = zone ? zone.filter((b) => !b.blockKey || !deleteKeys.has(b.blockKey)) : null;
2375
+ const { result: result2, report: validation } = await validateFinal(s, snap, vctx, {
2376
+ variations: snap.variations.filter((v) => !removed.has(v.documentId)),
2377
+ blockKeys: entries ? keysOfBlocks(entries) : void 0
2378
+ });
2379
+ if (result2.errors.some((e) => e.code === "V1")) {
2380
+ assertValid(
2381
+ { errors: result2.errors.map((e) => e.code === "V1" ? { ...e, message: `${e.message}. To drop a whole section, use kind "section".` } : e), warnings: result2.warnings },
2382
+ `${target.uid} ${target.documentId}`
2383
+ );
2384
+ }
2385
+ assertValid(result2, `${target.uid} ${target.documentId}`);
2386
+ const out = {
2387
+ target: targetView(snap),
2388
+ removed: { variations: rows.map(variationView), blocks: [...deleteKeys] },
2389
+ keptBlocks: rows.filter((v) => !deleteKeys.has(v.blockKey)).map((v) => v.blockKey),
2390
+ validation
2391
+ };
2392
+ if (args.dryRun) return { dryRun: true, ...out };
2393
+ await write(strapi, caller, args, async (ctx) => {
2394
+ if (entries) {
2395
+ await writeZone(strapi, target, locale2, entries);
2396
+ for (const v of rows.filter((r) => deleteKeys.has(r.blockKey))) {
2397
+ await s.logBlock("delete", { targetUid: v.targetUid, targetDocumentId: v.targetDocumentId, locale: v.locale, blockKey: v.blockKey, componentUid: v.componentUid }, ctx);
2398
+ }
2399
+ }
2400
+ for (const v of rows) await s.deleteVariation(v, ctx);
2401
+ });
2402
+ return { dryRun: false, ...out };
2403
+ }
2404
+ async function backfillBlockKeys(strapi, args) {
2405
+ return backfill(strapi, blockKeyTargets(strapi), {
2406
+ dryRun: args.dryRun === true,
2407
+ contentTypes: args.contentTypes,
2408
+ documentId: args.documentId,
2409
+ locales: args.locales
2410
+ });
2411
+ }
2412
+ const loose = (shape = {}) => z.looseObject(shape);
2413
+ const targetUid = z.string().describe('Content type UID of the page, e.g. "api::home.home" or "api::landing-page.landing-page".');
2414
+ const targetDocumentId = z.string().optional().describe("documentId of the page. May be omitted for single types (home, pdp, category-listing).");
2415
+ const locale = z.string().nullable().optional().describe('Locale of the page version to work on, e.g. "en". Default: the first locale the page exists in.');
2416
+ const sectionKey = z.string().describe('Section (mapping set) key, lowercase [a-z0-9-], unique per page + locale, e.g. "home-hero".');
2417
+ const variantKey = z.string().describe('Variant key, lowercase [a-z0-9-], unique within the section; "default" for the default.');
2418
+ const dryRun = z.boolean().optional().describe("Validate and report what would change; write nothing.");
2419
+ const correlationId = z.string().max(200).optional().describe("Optional id of your orchestration run; stored in the change log with every change this call makes.");
2420
+ const reason = z.string().max(500).optional().describe("Why, for the change log.");
2421
+ const audiences = z.array(z.string()).describe('Audience ids "audience/<slug>" (ANY must match), e.g. ["audience/loyalty-gold"]. Unknown ids are warnings.');
2422
+ const traits = z.array(z.string()).describe('Declared trait ids "trait/<trait>/<value>" (ALL must match), e.g. ["trait/trade/electrician"].');
2423
+ const affinities = z.array(z.string()).describe('Affinity ids "affinity/<vocabulary>/<slug>/<low|medium|high>" (ALL must match; a band matches that band or higher), e.g. ["affinity/application/power-drills/medium"].');
2424
+ const validity = z.object({ startsAt: z.string().nullable().optional(), endsAt: z.string().nullable().optional() }).nullable().describe("Validity window, ISO 8601. Outside it the variation is not selected (the resolver applies the request time; preview can time-travel).");
2425
+ const experimentRef = z.object({ key: z.string(), outcome: z.string() }).describe("Experiment key and outcome this block is content of.");
2426
+ const outcome = z.object({
2427
+ key: z.string().describe('Outcome key, lowercase [a-z0-9-], e.g. "a".'),
2428
+ label: z.string().nullable().optional(),
2429
+ intentionallyEmpty: z.boolean().optional().describe("The outcome deliberately has no content (it hides its sections)."),
2430
+ weight: z.number().optional().describe("Relative traffic weight, a positive integer (e.g. 90 and 10). Give every outcome a weight or none (equal split); only the ratio matters (V8).")
2431
+ });
2432
+ const writeOut = (shape = {}) => loose({ dryRun: z.boolean(), ...shape });
2433
+ const actorOf = async (strapi, context) => {
2434
+ const user = `user:${context.user?.id ?? "unknown"}`;
2435
+ try {
2436
+ const header = strapi.requestContext?.get?.()?.request?.header?.authorization;
2437
+ const key = typeof header === "string" ? /^Bearer\s+(.+)$/i.exec(header.trim())?.[1] : void 0;
2438
+ const tokens = strapi.admin?.services?.["api-token"];
2439
+ if (key && typeof tokens?.hash === "function" && typeof tokens?.getByAccessKey === "function") {
2440
+ const token = await tokens.getByAccessKey(tokens.hash(key));
2441
+ if (token?.id !== void 0 && token?.id !== null) return `mcp:token:${token.id}/${user}`;
2442
+ }
2443
+ } catch {
2444
+ }
2445
+ return `mcp:${user}`;
2446
+ };
2447
+ const result = (structured) => ({
2448
+ content: [{ type: "text", text: JSON.stringify(structured, null, 2) }],
2449
+ structuredContent: structured
2450
+ });
2451
+ const failure = (message) => ({
2452
+ content: [{ type: "text", text: message }],
2453
+ isError: true
2454
+ });
2455
+ const ACTION_LABELS = {
2456
+ [ACTIONS.read]: "Experience Context: read",
2457
+ [ACTIONS.variationsWrite]: "Experience Context: Manage audience variations and concepts",
2458
+ [ACTIONS.experimentsWrite]: "Experience Context: Manage experiments",
2459
+ [ACTIONS.maintenance]: "Experience Context: Maintenance"
2460
+ };
2461
+ const requireAction = (context, action, why) => {
2462
+ const ability = context.userAbility;
2463
+ if (ability && typeof ability.can === "function" && ability.can(action)) return;
2464
+ throw new ToolError(
2465
+ `Forbidden, nothing was written: ${why} needs the permission "${ACTION_LABELS[action]}" (${action}), which this API token (or its owner's role) does not hold. Ask an administrator; do not retry with another token.`
2466
+ );
2467
+ };
2468
+ const handler = (strapi, context, run, requires) => async ({ args }) => {
2469
+ try {
2470
+ const a = args ?? {};
2471
+ for (const [action, why] of requires?.(a) ?? []) requireAction(context, action, why);
2472
+ const caller = {
2473
+ actor: await actorOf(strapi, context),
2474
+ require: (action, why) => requireAction(context, action, why)
2475
+ };
2476
+ return result(await run(a, caller));
2477
+ } catch (e) {
2478
+ if (e instanceof ToolError) return failure(e.message);
2479
+ throw e;
2480
+ }
2481
+ };
2482
+ const read = { policies: READ_POLICIES };
2483
+ const variations = { policies: VARIATIONS_POLICIES };
2484
+ const experiments = { policies: EXPERIMENTS_POLICIES };
2485
+ const telemetry = (name) => ({ source: "experience-context", name });
2486
+ const WRITE_NOTE = `Validated with the shared validateExperienceMapping (errors block the write and name the path; registry misses are warnings), audited with your correlationId, dryRun supported. ${AGENT_INSTRUCTION}`;
2487
+ const EXPERIENCE_TOOLS = [
2488
+ {
2489
+ name: "experience_describe_target",
2490
+ title: "Experience: describe a page (start here)",
2491
+ description: `A page's blocks in one locale with blockKey, component, summary, concepts, section/variant membership, experiment outcome, per-locale coverage, warnings and the validation checklist (✓/⚠/✗). Start here to find block keys. ${AGENT_INSTRUCTION}`,
2492
+ auth: read,
2493
+ telemetry: telemetry("describe_target"),
2494
+ resolveInputSchema: () => z.object({ targetUid, targetDocumentId, locale, status: z.enum(["draft", "published"]).optional().describe("Version to read (default draft).") }),
2495
+ resolveOutputSchema: () => loose({ target: loose(), locale: z.string().nullable(), status: z.string(), page: loose(), blocks: z.array(loose()), sections: z.array(loose()), experiments: z.array(loose()), coverage: z.array(loose()), validation: loose(), warnings: z.array(z.string()) }),
2496
+ createHandler: (strapi, context) => handler(strapi, context, (args) => describeTarget(strapi, args))
2497
+ },
2498
+ {
2499
+ name: "experience_list_registry",
2500
+ title: "Experience: list known context ids",
2501
+ description: `Known audience, trait, affinity, experiment and concept ids with labels (ids and labels only, never profile data). Audiences come from app config and content-variants segments with an externalId; experiments from this plugin. An id missing here is only a warning. ${AGENT_INSTRUCTION}`,
2502
+ auth: read,
2503
+ telemetry: telemetry("list_registry"),
2504
+ resolveInputSchema: () => z.object({ kind: z.enum(REGISTRY_KINDS).optional().describe("Only this list.") }),
2505
+ resolveOutputSchema: () => loose({ counts: loose() }),
2506
+ createHandler: (strapi, context) => handler(strapi, context, (args) => listRegistry(strapi, args))
2507
+ },
2508
+ {
2509
+ name: "experience_list_content_variants",
2510
+ title: "Experience: list sections and variations",
2511
+ description: "Sections and their variations for one page, or across pages filtered by audience id, experiment key or section key. Inactive and orphaned mappings are left out unless includeInactive is true.",
2512
+ auth: read,
2513
+ telemetry: telemetry("list_content_variants"),
2514
+ resolveInputSchema: () => z.object({
2515
+ targetUid: z.string().optional(),
2516
+ targetDocumentId: z.string().optional(),
2517
+ locale: z.string().nullable().optional(),
2518
+ sectionKey: z.string().optional(),
2519
+ audience: z.string().optional().describe("Only variations that name this audience id."),
2520
+ experimentKey: z.string().optional().describe("Only blocks mapped to this experiment."),
2521
+ includeInactive: z.boolean().optional()
2522
+ }),
2523
+ resolveOutputSchema: () => loose({ count: z.number(), targets: z.array(loose()) }),
2524
+ createHandler: (strapi, context) => handler(strapi, context, (args) => listContentVariants(strapi, args))
2525
+ },
2526
+ {
2527
+ name: "experience_create_content_variant",
2528
+ title: "Experience: create a content variant (copy a block into a section)",
2529
+ description: `Copies a block (sourceBlockKey, default: the section's default), creates one from content, or adopts a block already on the page (existingBlockKey) ({ "__component": "zone.hero", ...fields }) into the page's draft right after the section, gives it a new blockKey and registers it in the section with variantKey, displayName and description. Creates the section if needed, with the source block (or defaultBlockKey) as its default. A variation needs targetAudiences, traits or affinities, or an experiment outcome (V5): pass them here, change them later with experience_associate_variant_with_audience / _with_experiment. Then edit the copied block's content and publish the page. ${WRITE_NOTE}`,
2530
+ auth: variations,
2531
+ telemetry: telemetry("create_content_variant"),
2532
+ resolveInputSchema: () => z.object({
2533
+ targetUid,
2534
+ targetDocumentId,
2535
+ locale,
2536
+ sectionKey,
2537
+ variantKey,
2538
+ displayName: z.string().nullable().optional().describe('Readable name for inspection, e.g. "Gold loyalty hero". Never an identifier.'),
2539
+ description: z.string().nullable().optional().describe("Who it is for and why (warning W5 without it)."),
2540
+ sourceBlockKey: z.string().optional().describe("Block to copy. Default: the section's default block."),
2541
+ content: z.record(z.string(), z.unknown()).optional().describe('Create from content instead of copying: { "__component": "zone.text", ...fields } in Strapi input format.'),
2542
+ existingBlockKey: z.string().optional().describe("Register a block that is already in the draft as this variation (no copy, the page content is not changed). Use it to map existing alternatives."),
2543
+ defaultBlockKey: z.string().optional().describe("New section only: the default block (default: sourceBlockKey)."),
2544
+ defaultVariantKey: z.string().optional().describe('New section only: variant key of the default (default "default").'),
2545
+ defaultDisplayName: z.string().nullable().optional(),
2546
+ defaultOutcome: z.string().optional().describe('New experiment section only: the outcome the default block is content of (usually the control, "a").'),
2547
+ targetAudiences: audiences.optional(),
2548
+ traits: traits.optional(),
2549
+ affinities: affinities.optional(),
2550
+ experiment: experimentRef.nullable().optional(),
2551
+ status: z.enum(["active", "inactive"]).optional(),
2552
+ priority: z.number().int().optional().describe("Tie-break only: higher wins among matching variations."),
2553
+ validity: validity.optional(),
2554
+ dryRun,
2555
+ correlationId,
2556
+ reason
2557
+ }),
2558
+ resolveOutputSchema: () => writeOut({ section: loose(), block: loose(), variation: loose(), validation: loose() }),
2559
+ createHandler: (strapi, context) => handler(
2560
+ strapi,
2561
+ context,
2562
+ (args, caller) => createContentVariant(strapi, args, caller),
2563
+ (args) => args.experiment || args.defaultOutcome ? [[ACTIONS.experimentsWrite, "Mapping a block to an experiment outcome"]] : []
2564
+ )
2565
+ },
2566
+ {
2567
+ name: "experience_update_content_variant",
2568
+ title: "Experience: update a variation",
2569
+ description: `Renames (newVariantKey), describes (displayName, description), activates or deactivates (status active/inactive: inactive is kept but never resolved), and sets priority or validity of a variation. ${WRITE_NOTE}`,
2570
+ auth: variations,
2571
+ telemetry: telemetry("update_content_variant"),
2572
+ resolveInputSchema: () => z.object({
2573
+ targetUid,
2574
+ targetDocumentId,
2575
+ locale,
2576
+ sectionKey,
2577
+ variantKey,
2578
+ newVariantKey: z.string().optional(),
2579
+ displayName: z.string().nullable().optional(),
2580
+ description: z.string().nullable().optional(),
2581
+ status: z.enum(["active", "inactive"]).optional(),
2582
+ priority: z.number().int().optional(),
2583
+ validity: validity.optional(),
2584
+ dryRun,
2585
+ correlationId,
2586
+ reason
2587
+ }),
2588
+ resolveOutputSchema: () => writeOut({ before: loose(), after: loose(), validation: loose() }),
2589
+ createHandler: (strapi, context) => handler(strapi, context, (args, caller) => updateContentVariant(strapi, args, caller))
2590
+ },
2591
+ {
2592
+ name: "experience_associate_variant_with_audience",
2593
+ title: "Experience: set the audiences, traits and affinities of a variation",
2594
+ description: `Sets (mode "replace", default) or adds to (mode "add") the targetAudiences (ANY), traits (ALL) and affinities (ALL, band or higher) of a variation. Groups you leave out are kept. These are references to context that Unomi computes; Strapi never evaluates customer data. Malformed ids are rejected (V3); ids not in the registry are warnings. ${WRITE_NOTE}`,
2595
+ auth: variations,
2596
+ telemetry: telemetry("associate_variant_with_audience"),
2597
+ resolveInputSchema: () => z.object({
2598
+ targetUid,
2599
+ targetDocumentId,
2600
+ locale,
2601
+ sectionKey,
2602
+ variantKey,
2603
+ targetAudiences: audiences.optional(),
2604
+ traits: traits.optional(),
2605
+ affinities: affinities.optional(),
2606
+ mode: z.enum(["replace", "add"]).optional(),
2607
+ dryRun,
2608
+ correlationId,
2609
+ reason
2610
+ }),
2611
+ resolveOutputSchema: () => writeOut({ before: loose(), after: loose(), validation: loose() }),
2612
+ createHandler: (strapi, context) => handler(strapi, context, (args, caller) => associateVariantWithAudience(strapi, args, caller))
2613
+ },
2614
+ {
2615
+ name: "experience_set_experiment",
2616
+ title: "Experience: create or update an experiment declaration",
2617
+ description: `Creates or updates an experiment: key (lowercase [a-z0-9-], part of the assignment hash: never renamed while running), name, description, outcomes [{key,label,weight?}] (stable order; equal split unless every outcome has a positive integer weight, e.g. 90/10; equal weights keep the unweighted assignment), controlOutcome (default: the first), status draft|running|paused, validity, externalId (the Unomi experiment id, for reporting). Strapi declares the experiment; the storefront assigns (HMAC) and Unomi measures. Changing the split of a running experiment reshuffles visitors (warning W7). Setting status "running" is rejected while an outcome has no content and isn't intentionallyEmpty (V6). Workflow: create as draft → map blocks to each outcome (experience_associate_variant_with_experiment) → explain each outcome → set running. ${WRITE_NOTE}`,
2618
+ auth: experiments,
2619
+ telemetry: telemetry("set_experiment"),
2620
+ resolveInputSchema: () => z.object({
2621
+ key: z.string().describe('Experiment key, e.g. "homepage-category-lift-v2".'),
2622
+ newKey: z.string().optional().describe("Rename (not while running)."),
2623
+ name: z.string().nullable().optional(),
2624
+ description: z.string().nullable().optional(),
2625
+ outcomes: z.array(outcome).optional().describe('Required for a new experiment, at least two, e.g. [{"key":"a","label":"A (control)"},{"key":"b","label":"B"}].'),
2626
+ controlOutcome: z.string().optional(),
2627
+ status: z.enum(["draft", "running", "paused"]).optional().describe("Conclude with experience_conclude_experiment."),
2628
+ validity: validity.optional(),
2629
+ externalId: z.string().nullable().optional(),
2630
+ dryRun,
2631
+ correlationId,
2632
+ reason
2633
+ }),
2634
+ resolveOutputSchema: () => writeOut({ action: z.string(), experiment: loose(), previous: loose().nullable(), validation: loose(), warnings: z.array(z.string()) }),
2635
+ createHandler: (strapi, context) => handler(strapi, context, (args, caller) => setExperiment(strapi, args, caller))
2636
+ },
2637
+ {
2638
+ name: "experience_associate_variant_with_experiment",
2639
+ title: "Experience: map a block to an experiment outcome",
2640
+ description: `Maps a section member (sectionKey + variantKey, or blockKey) to { experimentKey, outcome }; experimentKey null removes the mapping. A block that is not in a section yet joins sectionKey (as the default when the section is new). An outcome may have no block in a section, which hides that section for the outcome. A section is either audience variations or experiment outcomes, not both (X1, until OD-1 is decided). ${WRITE_NOTE}`,
2641
+ auth: experiments,
2642
+ telemetry: telemetry("associate_variant_with_experiment"),
2643
+ resolveInputSchema: () => z.object({
2644
+ targetUid,
2645
+ targetDocumentId,
2646
+ locale,
2647
+ sectionKey: z.string().optional(),
2648
+ variantKey: z.string().optional(),
2649
+ blockKey: z.string().optional(),
2650
+ experimentKey: z.string().nullable(),
2651
+ outcome: z.string().optional(),
2652
+ dryRun,
2653
+ correlationId,
2654
+ reason
2655
+ }),
2656
+ resolveOutputSchema: () => writeOut({ before: loose().nullable(), after: loose(), validation: loose() }),
2657
+ createHandler: (strapi, context) => handler(strapi, context, (args, caller) => associateVariantWithExperiment(strapi, args, caller))
2658
+ },
2659
+ {
2660
+ name: "experience_conclude_experiment",
2661
+ title: "Experience: conclude an experiment (set the winner)",
2662
+ description: `Sets the winner (status concluded): from then on everyone sees the winning outcome and the storefront sends no exposure. With cleanup: the losing outcome blocks are removed from the page drafts and their mappings deleted; the winning blocks keep their content as the section's default without an experiment mapping. Publish the pages afterwards. A concluded experiment cannot be restarted. ${WRITE_NOTE}`,
2663
+ auth: experiments,
2664
+ telemetry: telemetry("conclude_experiment"),
2665
+ resolveInputSchema: () => z.object({
2666
+ key: z.string(),
2667
+ winner: z.string().describe("The winning outcome key (as reported by Unomi)."),
2668
+ cleanup: z.boolean().optional().describe("Remove losing outcome blocks from the drafts (default false)."),
2669
+ dryRun,
2670
+ correlationId,
2671
+ reason
2672
+ }),
2673
+ resolveOutputSchema: () => writeOut({ experiment: loose(), previous: loose(), cleanup: z.array(loose()) }),
2674
+ createHandler: (strapi, context) => handler(strapi, context, (args, caller) => concludeExperiment(strapi, args, caller))
2675
+ },
2676
+ {
2677
+ name: "experience_annotate_content_with_concepts",
2678
+ title: "Experience: set the concepts of a page or block",
2679
+ description: `Sets (mode "replace", default), adds or removes the concepts a page (no blockKey) or block is about: Reactionary concept ids "<vocabulary>/<slug>", e.g. "application/power-drills". Concepts are descriptive only and never imply an audience; the storefront sends the page's concepts with contentViewed. Page concepts apply to every locale unless locale is given; block concepts live in the block's locale. An empty list removes the annotation. ${WRITE_NOTE}`,
2680
+ auth: variations,
2681
+ telemetry: telemetry("annotate_content_with_concepts"),
2682
+ resolveInputSchema: () => z.object({
2683
+ targetUid,
2684
+ targetDocumentId,
2685
+ locale,
2686
+ blockKey: z.string().nullable().optional().describe("Block to annotate; omit or null for the page."),
2687
+ concepts: z.array(z.string()),
2688
+ mode: z.enum(["replace", "add", "remove"]).optional(),
2689
+ dryRun,
2690
+ correlationId,
2691
+ reason
2692
+ }),
2693
+ resolveOutputSchema: () => writeOut({ concepts: z.array(z.string()), validation: loose() }),
2694
+ createHandler: (strapi, context) => handler(strapi, context, (args, caller) => annotateContentWithConcepts(strapi, args, caller))
2695
+ },
2696
+ {
2697
+ name: "experience_validate_mapping",
2698
+ title: "Experience: validate mappings",
2699
+ description: "Runs the shared validation (plan §6) for one page and locale, or for every page with mappings plus every experiment: errors (V1 default count, V2 duplicates, V3 malformed id, V4 missing block, V5 untargeted variation, V6 experiment/outcome, V8 outcome weights, X1 audience + experiment in one section, V7 version) and warnings (W1 not in the registry, W2 validity, W3 tie, W4 no preset shows it, W5 no description, W6 orphaned, W7 split of a running experiment changed), as a ✓/⚠/✗ checklist.",
2700
+ auth: read,
2701
+ telemetry: telemetry("validate_mapping"),
2702
+ resolveInputSchema: () => z.object({ targetUid: z.string().optional(), targetDocumentId: z.string().optional(), locale: z.string().nullable().optional() }),
2703
+ resolveOutputSchema: () => loose({ ok: z.boolean(), targets: z.array(loose()), experiments: z.array(loose()) }),
2704
+ createHandler: (strapi, context) => handler(strapi, context, (args) => validateMapping(strapi, args))
2705
+ },
2706
+ {
2707
+ name: "experience_explain_variant_resolution",
2708
+ title: "Experience: explain which variant a context selects",
2709
+ description: `Resolves the page (draft by default) for a synthetic ExperienceContext with the same package as the storefront and the Experience Builder simulator: per section the selected variant, the reasons (✓/✗) and the fallback, the experiments with their outcome, and the rendered blockKeys. Context: { visitorId, audiences: ["audience/…"], traits: ["trait/…/…"], affinities: { "<vocabulary>/<slug>": "low|medium|high" }, experiments: { "<key>": "<outcome>" }, consent, locale, market, channel, now }. preview defaults to true: experiments and now become preview overrides (forced outcomes apply even to draft experiments, now time-travels validity windows, nothing is exposable); preview false treats experiments as the storefront's assignment. Experiments show their traffic split. Use an empty context to check the fallback. Never loads a real profile.`,
2710
+ auth: read,
2711
+ telemetry: telemetry("explain_variant_resolution"),
2712
+ resolveInputSchema: () => z.object({
2713
+ targetUid,
2714
+ targetDocumentId,
2715
+ locale,
2716
+ status: z.enum(["draft", "published"]).optional(),
2717
+ context: z.record(z.string(), z.unknown()).optional().describe("Synthetic ExperienceContext (partial is fine; missing parts are empty)."),
2718
+ preview: z.boolean().optional().describe("Default true. false: resolve as a storefront request (experiments = assignment, exposure computed).")
2719
+ }),
2720
+ resolveOutputSchema: () => loose({ target: loose(), rendered: z.array(z.string().nullable()), explanation: loose() }),
2721
+ createHandler: (strapi, context) => handler(strapi, context, (args) => explainVariantResolution(strapi, args))
2722
+ },
2723
+ {
2724
+ name: "experience_remove_mapping",
2725
+ title: "Experience: remove a mapping",
2726
+ description: `Removes a variation's mapping (kind "variation": sectionKey + variantKey or blockKey), a whole section ("section"), a page or block concept annotation ("annotation", blockKey null = page) or an experiment declaration ("experiment", only when no block maps to it). Never deletes content blocks unless deleteBlocks is true; even then a section's default block stays as plain content. ${WRITE_NOTE}`,
2727
+ auth: { policies: REMOVE_POLICIES },
2728
+ telemetry: telemetry("remove_mapping"),
2729
+ resolveInputSchema: () => z.object({
2730
+ kind: z.enum(["variation", "section", "annotation", "experiment"]),
2731
+ targetUid: z.string().optional(),
2732
+ targetDocumentId: z.string().optional(),
2733
+ locale: z.string().nullable().optional(),
2734
+ sectionKey: z.string().optional(),
2735
+ variantKey: z.string().optional(),
2736
+ blockKey: z.string().nullable().optional(),
2737
+ experimentKey: z.string().optional(),
2738
+ deleteBlocks: z.boolean().optional().describe("Also delete the removed variations' blocks from the draft (default false)."),
2739
+ dryRun,
2740
+ correlationId,
2741
+ reason
2742
+ }),
2743
+ resolveOutputSchema: () => writeOut({ removed: loose() }),
2744
+ createHandler: (strapi, context) => handler(
2745
+ strapi,
2746
+ context,
2747
+ (args, caller) => removeMapping(strapi, args, caller),
2748
+ (args) => [args.kind === "experiment" ? [ACTIONS.experimentsWrite, "Removing an experiment"] : [ACTIONS.variationsWrite, `Removing a ${args.kind ?? "mapping"}`]]
2749
+ )
2750
+ },
2751
+ {
2752
+ name: "experience_backfill_block_keys",
2753
+ title: "Experience: backfill block keys",
2754
+ description: "Gives every targeted zone.* block without a blockKey a new key (component rows only: no document update, no history version). Idempotent. Use dryRun to count first.",
2755
+ auth: { policies: MAINTENANCE_POLICIES },
2756
+ telemetry: telemetry("backfill_block_keys"),
2757
+ resolveInputSchema: () => z.object({
2758
+ dryRun,
2759
+ contentTypes: z.array(z.string()).optional().describe("Limit to these content types."),
2760
+ documentId: z.string().optional().describe("Limit to one document."),
2761
+ locales: z.array(z.string()).optional().describe("Limit to these locales.")
2762
+ }),
2763
+ resolveOutputSchema: () => loose({ dryRun: z.boolean(), updated: z.number() }),
2764
+ createHandler: (strapi, context) => handler(strapi, context, (args) => backfillBlockKeys(strapi, args))
2765
+ }
2766
+ ];
2767
+ const registerMcpTools = (strapi) => {
2768
+ const mcp = strapi.ai?.mcp;
2769
+ if (!mcp?.registerTool) return 0;
2770
+ for (const tool of EXPERIENCE_TOOLS) mcp.registerTool(tool);
2771
+ return EXPERIENCE_TOOLS.length;
2772
+ };
2773
+ function markTargetTypes(strapi) {
2774
+ const marked = [];
2775
+ for (const uid of configuredContentTypes(strapi)) {
2776
+ const contentType = strapi.contentTypes[uid];
2777
+ if (!contentType) continue;
2778
+ contentType.pluginOptions = {
2779
+ ...contentType.pluginOptions ?? {},
2780
+ [PLUGIN_ID]: { target: true }
2781
+ };
2782
+ marked.push(uid);
2783
+ }
2784
+ return marked;
2785
+ }
2786
+ const register = ({ strapi }) => {
2787
+ registerBlockKeys(strapi);
2788
+ registerMcpTools(strapi);
2789
+ registerReadPathParams(strapi);
2790
+ markTargetTypes(strapi);
2791
+ };
2792
+ function presentKeys(rows, zones, draftAndPublish) {
2793
+ const byLocale = /* @__PURE__ */ new Map();
2794
+ for (const row of rows) {
2795
+ if (draftAndPublish && row.publishedAt) continue;
2796
+ const locale2 = typeof row.locale === "string" ? row.locale : "";
2797
+ const keys = byLocale.get(locale2) ?? /* @__PURE__ */ new Set();
2798
+ for (const zone of zones) {
2799
+ const blocks = row[zone];
2800
+ if (!Array.isArray(blocks)) continue;
2801
+ for (const b of blocks) {
2802
+ const key = b?.blockKey;
2803
+ if (typeof key === "string" && key) keys.add(key);
2804
+ }
2805
+ }
2806
+ byLocale.set(locale2, keys);
2807
+ }
2808
+ return { byLocale };
2809
+ }
2810
+ function isOrphaned(row, present) {
2811
+ const locale2 = row.locale ?? null;
2812
+ const key = row.blockKey ?? null;
2813
+ if (key === null) {
2814
+ if (locale2 === null) return present.byLocale.size === 0;
2815
+ return !(present.byLocale.has(locale2) || present.byLocale.size === 1 && present.byLocale.has(""));
2816
+ }
2817
+ if (locale2 === null) {
2818
+ for (const keys2 of present.byLocale.values()) if (keys2.has(key)) return false;
2819
+ return true;
2820
+ }
2821
+ const keys = present.byLocale.get(locale2) ?? (present.byLocale.size === 1 ? present.byLocale.get("") : void 0);
2822
+ return !keys?.has(key);
2823
+ }
2824
+ function statusChanges(rows, present) {
2825
+ const changes = [];
2826
+ for (const row of rows) {
2827
+ const orphaned = isOrphaned(row, present);
2828
+ if (row.orphaned === true !== orphaned) changes.push({ row, orphaned });
2829
+ }
2830
+ return changes;
2831
+ }
2832
+ const RECOMPUTE_ACTIONS = /* @__PURE__ */ new Set(["update", "publish", "discardDraft"]);
2833
+ function createIntegrity(strapi, getTargets2) {
2834
+ const store2 = createStore(strapi);
2835
+ async function currentKeys(uid, documentId) {
2836
+ const zones = getTargets2().zonesByUid.get(uid) ?? [];
2837
+ const contentType = strapi.contentTypes[uid];
2838
+ const draftAndPublish = contentType?.options?.draftAndPublish !== false;
2839
+ const versions = await strapi.db.query(uid).findMany({
2840
+ where: { documentId },
2841
+ select: ["id", "locale", "publishedAt"],
2842
+ ...zones.length ? { populate: Object.fromEntries(zones.map((z2) => [z2, true])) } : {}
2843
+ });
2844
+ if (versions.length === 0) return null;
2845
+ return presentKeys(versions, zones, draftAndPublish);
2846
+ }
2847
+ async function orphanedNow(uid, documentId, target) {
2848
+ const present = await currentKeys(uid, documentId);
2849
+ if (!present) return true;
2850
+ return isOrphaned({ locale: target.locale ?? null, blockKey: target.blockKey ?? null }, present);
2851
+ }
2852
+ const mappingsOf = async (uid, documentId) => ({
2853
+ variations: await store2.listVariations({ targetUid: uid, targetDocumentId: documentId }),
2854
+ annotations: await store2.listAnnotations({ targetUid: uid, targetDocumentId: documentId })
2855
+ });
2856
+ async function recompute(uid, documentId, reason2 = "content-update") {
2857
+ const { variations: variations2, annotations } = await mappingsOf(uid, documentId);
2858
+ if (variations2.length + annotations.length === 0) return [];
2859
+ const present = await currentKeys(uid, documentId);
2860
+ if (!present) return [];
2861
+ const batch = new ChangeBatch();
2862
+ const out = [];
2863
+ const apply = async (entity, row, orphaned) => {
2864
+ const table = entity === "variation" ? VARIATION_UID : ANNOTATION_UID;
2865
+ await strapi.db.query(table).update({ where: { documentId: row.documentId }, data: { orphaned } });
2866
+ await recordChange(
2867
+ strapi,
2868
+ {
2869
+ action: orphaned ? "orphaned" : "reactivated",
2870
+ entity,
2871
+ entityDocumentId: row.documentId,
2872
+ before: row,
2873
+ after: { ...row, orphaned },
2874
+ actor: SYSTEM_ACTOR,
2875
+ source: "system",
2876
+ reason: reason2
2877
+ },
2878
+ batch
2879
+ );
2880
+ out.push({ entity, documentId: row.documentId, blockKey: row.blockKey ?? null, locale: row.locale ?? null, orphaned });
2881
+ };
2882
+ for (const { row, orphaned } of statusChanges(variations2, present)) await apply("variation", row, orphaned);
2883
+ for (const { row, orphaned } of statusChanges(annotations, present)) await apply("annotation", row, orphaned);
2884
+ if (out.length > 0) {
2885
+ strapi.log.info(`${LOG_PREFIX} ${uid} ${documentId}: ${out.map((c) => `${c.entity} ${c.blockKey ?? "page"} ${c.orphaned ? "orphaned" : "reactivated"}`).join(", ")}`);
2886
+ await batch.flush(strapi);
2887
+ }
2888
+ return out;
2889
+ }
2890
+ async function cascadeDelete(uid, documentId) {
2891
+ const { variations: variations2, annotations } = await mappingsOf(uid, documentId);
2892
+ const batch = new ChangeBatch();
2893
+ const ctx = { actor: SYSTEM_ACTOR, source: "system", reason: "document-deleted", batch };
2894
+ for (const v of variations2) await store2.deleteVariation(v, ctx);
2895
+ for (const a of annotations) await store2.deleteAnnotation(a, ctx);
2896
+ const removed = variations2.length + annotations.length;
2897
+ if (removed > 0) {
2898
+ strapi.log.info(`${LOG_PREFIX} ${uid} ${documentId} deleted: removed ${removed} experience mapping(s)`);
2899
+ await batch.flush(strapi);
2900
+ }
2901
+ return { variations: variations2.map((v) => v.documentId), annotations: annotations.map((a) => a.documentId) };
2902
+ }
2903
+ return { recompute, cascadeDelete, currentKeys, orphanedNow };
2904
+ }
2905
+ function registerIntegrityMiddleware(strapi, integrity2, configured) {
2906
+ const targets = new Set(configured);
2907
+ strapi.documents.use(async (ctx, next) => {
2908
+ const uid = ctx?.uid;
2909
+ const action = ctx?.action;
2910
+ if (typeof uid !== "string" || !targets.has(uid)) return next();
2911
+ const params = ctx.params ?? {};
2912
+ const result2 = await next();
2913
+ try {
2914
+ const documentId = params.documentId ?? result2?.documentId;
2915
+ if (typeof documentId === "string") {
2916
+ if (action === "delete") {
2917
+ const remaining = await strapi.db.query(uid).count({ where: { documentId } });
2918
+ if (remaining === 0) await integrity2.cascadeDelete(uid, documentId);
2919
+ else await integrity2.recompute(uid, documentId, "locale-deleted");
2920
+ } else if (RECOMPUTE_ACTIONS.has(action)) {
2921
+ await integrity2.recompute(uid, documentId, action === "update" ? "content-update" : action);
2922
+ }
2923
+ }
2924
+ } catch (err) {
2925
+ strapi.log.warn(`${LOG_PREFIX} integrity check after ${action} ${uid} failed: ${err.message}`);
2926
+ }
2927
+ return result2;
2928
+ });
2929
+ }
2930
+ function bootstrapIntegrity(strapi, integrity2) {
2931
+ registerWebhookEvent(strapi);
2932
+ const configured = configuredContentTypes(strapi).filter((uid) => Boolean(strapi.contentTypes[uid]));
2933
+ registerIntegrityMiddleware(strapi, integrity2, configured);
2934
+ }
2935
+ const ROLE_PRESETS = [
2936
+ {
2937
+ code: "experience-context-viewer",
2938
+ name: "Experience Viewer",
2939
+ description: "Add-on role: sees experience mappings (Content Manager badge, Experience Builder simulator, MCP read tools). Writes nothing.",
2940
+ actions: [ACTIONS.read]
2941
+ },
2942
+ {
2943
+ code: "experience-context-editor",
2944
+ name: "Experience Editor",
2945
+ description: "Add-on role: owns agent tokens that map audience variations and concepts. No experiments.",
2946
+ actions: [ACTIONS.read, ACTIONS.variationsWrite]
2947
+ },
2948
+ {
2949
+ code: "experience-context-manager",
2950
+ name: "Experience Manager",
2951
+ description: "Add-on role: owns agent tokens that also declare, start, pause and conclude experiments, and run block-key maintenance.",
2952
+ actions: [ACTIONS.read, ACTIONS.variationsWrite, ACTIONS.experimentsWrite, ACTIONS.maintenance]
2953
+ }
2954
+ ];
2955
+ const permissionOf = (action) => ({ action, subject: null, properties: {}, conditions: [] });
2956
+ async function provisionRoles(strapi, presets = ROLE_PRESETS) {
2957
+ const roles = strapi.admin?.services?.role;
2958
+ const permissions = strapi.admin?.services?.permission;
2959
+ if (!roles?.findOne || !roles?.create || !roles?.addPermissions || !permissions?.findMany) return [];
2960
+ const changes = [];
2961
+ for (const preset of presets) {
2962
+ let role = await roles.findOne({ code: preset.code });
2963
+ if (!role) {
2964
+ role = await roles.create({ name: preset.name, code: preset.code, description: preset.description });
2965
+ changes.push(`created role "${preset.name}" (${preset.code})`);
2966
+ }
2967
+ const held = new Set(
2968
+ (await permissions.findMany({ where: { role: { id: role.id } } }) ?? []).map((p) => p.action)
2969
+ );
2970
+ const missing = preset.actions.filter((a) => !held.has(a));
2971
+ if (missing.length) {
2972
+ await roles.addPermissions(role.id, missing.map(permissionOf));
2973
+ changes.push(`"${preset.name}": added ${missing.join(", ")}`);
2974
+ }
2975
+ }
2976
+ return changes;
2977
+ }
2978
+ async function bootstrapRoles(strapi, enabled) {
2979
+ if (!enabled) return;
2980
+ try {
2981
+ const changes = await provisionRoles(strapi);
2982
+ strapi.log.info(`${LOG_PREFIX} roles: ${changes.length ? changes.join("; ") : `${ROLE_PRESETS.length} add-on role(s) up to date`}`);
2983
+ } catch (e) {
2984
+ strapi.log.error(`${LOG_PREFIX} roles: provisioning failed: ${e instanceof Error ? e.message : String(e)}`);
2985
+ }
2986
+ }
2987
+ const bootstrap = async ({ strapi }) => {
2988
+ const configured = configuredContentTypes(strapi);
2989
+ const present = configured.filter((uid) => Boolean(strapi.contentTypes[uid]));
2990
+ const missing = configured.filter((uid) => !strapi.contentTypes[uid]);
2991
+ const registry2 = configuredRegistry(strapi);
2992
+ const counts = ["audiences", "traits", "affinities", "concepts"].map((k) => `${(registry2[k] ?? []).length} ${k}`).join(", ");
2993
+ strapi.log.info(`${LOG_PREFIX} registered; targeting ${present.length} content type(s): ${present.join(", ") || "none"}`);
2994
+ strapi.log.info(`${LOG_PREFIX} registry: ${counts}; ${configuredPresets(strapi).length} preset(s)`);
2995
+ if (missing.length > 0) strapi.log.warn(`${LOG_PREFIX} configured content types not found in this app: ${missing.join(", ")}`);
2996
+ const unomi = configuredUnomi(strapi);
2997
+ if (unomiEnabled(unomi)) {
2998
+ void loadUnomiDefinitions(unomi, {
2999
+ info: (m) => strapi.log.info(`${LOG_PREFIX} ${m}`),
3000
+ warn: (m) => strapi.log.warn(`${LOG_PREFIX} ${m}`)
3001
+ });
3002
+ }
3003
+ await registerPermissionActions(strapi);
3004
+ await bootstrapRoles(strapi, configuredRoles(strapi));
3005
+ await bootstrapBlockKeys(strapi);
3006
+ bootstrapReadPath(strapi, blockKeyTargets(strapi));
3007
+ bootstrapIntegrity(strapi, strapi.plugin(PLUGIN_ID).service("integrity"));
3008
+ };
3009
+ const destroy = (_ctx) => {
3010
+ };
3011
+ const kind$3 = "collectionType";
3012
+ const collectionName$3 = "experience_annotations";
3013
+ const info$3 = {
3014
+ singularName: "annotation",
3015
+ pluralName: "annotations",
3016
+ displayName: "Experience annotation",
3017
+ description: "Concepts a page (blockKey null) or a zone.* block is about. Descriptive only: never an audience or a condition. Written through the plugin's MCP tools only."
3018
+ };
3019
+ const options$3 = {
3020
+ draftAndPublish: false
3021
+ };
3022
+ const pluginOptions$3 = {
3023
+ "content-manager": {
3024
+ visible: false
3025
+ },
3026
+ "content-type-builder": {
3027
+ visible: false
3028
+ }
3029
+ };
3030
+ const attributes$3 = {
3031
+ targetUid: {
3032
+ type: "string",
3033
+ required: true
3034
+ },
3035
+ targetDocumentId: {
3036
+ type: "string",
3037
+ required: true
3038
+ },
3039
+ targetLocale: {
3040
+ type: "string"
3041
+ },
3042
+ blockKey: {
3043
+ type: "string"
3044
+ },
3045
+ concepts: {
3046
+ type: "json",
3047
+ required: true
3048
+ },
3049
+ orphaned: {
3050
+ type: "boolean",
3051
+ "default": false
3052
+ },
3053
+ source: {
3054
+ type: "string"
3055
+ },
3056
+ createdByActor: {
3057
+ type: "string"
3058
+ },
3059
+ correlationId: {
3060
+ type: "string"
3061
+ }
3062
+ };
3063
+ const annotationSchema = {
3064
+ kind: kind$3,
3065
+ collectionName: collectionName$3,
3066
+ info: info$3,
3067
+ options: options$3,
3068
+ pluginOptions: pluginOptions$3,
3069
+ attributes: attributes$3
3070
+ };
3071
+ const kind$2 = "collectionType";
3072
+ const collectionName$2 = "experience_changes";
3073
+ const info$2 = {
3074
+ singularName: "change",
3075
+ pluralName: "changes",
3076
+ displayName: "Experience change",
3077
+ description: "Append-only change log of annotations, variations, experiments and the content blocks the MCP tools add or remove: who, when (createdAt), before/after, source and correlationId. Never stores visitor context or profile data."
3078
+ };
3079
+ const options$2 = {
3080
+ draftAndPublish: false
3081
+ };
3082
+ const pluginOptions$2 = {
3083
+ "content-manager": {
3084
+ visible: false
3085
+ },
3086
+ "content-type-builder": {
3087
+ visible: false
3088
+ }
3089
+ };
3090
+ const attributes$2 = {
3091
+ action: {
3092
+ type: "enumeration",
3093
+ "enum": [
3094
+ "create",
3095
+ "update",
3096
+ "delete",
3097
+ "orphaned",
3098
+ "reactivated"
3099
+ ],
3100
+ required: true
3101
+ },
3102
+ entity: {
3103
+ type: "enumeration",
3104
+ "enum": [
3105
+ "annotation",
3106
+ "variation",
3107
+ "experiment",
3108
+ "block"
3109
+ ],
3110
+ required: true
3111
+ },
3112
+ entityDocumentId: {
3113
+ type: "string"
3114
+ },
3115
+ targetUid: {
3116
+ type: "string"
3117
+ },
3118
+ targetDocumentId: {
3119
+ type: "string"
3120
+ },
3121
+ targetLocale: {
3122
+ type: "string"
3123
+ },
3124
+ blockKey: {
3125
+ type: "string"
3126
+ },
3127
+ componentUid: {
3128
+ type: "string"
3129
+ },
3130
+ sectionKey: {
3131
+ type: "string"
3132
+ },
3133
+ variantKey: {
3134
+ type: "string"
3135
+ },
3136
+ experimentKey: {
3137
+ type: "string"
3138
+ },
3139
+ actor: {
3140
+ type: "string"
3141
+ },
3142
+ source: {
3143
+ type: "enumeration",
3144
+ "enum": [
3145
+ "mcp",
3146
+ "api",
3147
+ "system"
3148
+ ],
3149
+ required: true
3150
+ },
3151
+ reason: {
3152
+ type: "string"
3153
+ },
3154
+ correlationId: {
3155
+ type: "string"
3156
+ },
3157
+ before: {
3158
+ type: "json"
3159
+ },
3160
+ after: {
3161
+ type: "json"
3162
+ }
3163
+ };
3164
+ const changeSchema = {
3165
+ kind: kind$2,
3166
+ collectionName: collectionName$2,
3167
+ info: info$2,
3168
+ options: options$2,
3169
+ pluginOptions: pluginOptions$2,
3170
+ attributes: attributes$2
3171
+ };
3172
+ const kind$1 = "collectionType";
3173
+ const collectionName$1 = "experience_experiments";
3174
+ const info$1 = {
3175
+ singularName: "experiment",
3176
+ pluralName: "experiments",
3177
+ displayName: "Experience experiment",
3178
+ description: "Declares an experiment and its outcomes. It does not assign (the storefront does, by HMAC) or measure (Unomi does). Blocks join an outcome through their variation's `experiment`. `outcomes` is `[{ key, label?, intentionallyEmpty?, weight? }]` in stable order; `weight` is an optional positive integer (all outcomes or none; equal split without). Written through the plugin's MCP tools only."
3179
+ };
3180
+ const options$1 = {
3181
+ draftAndPublish: false
3182
+ };
3183
+ const pluginOptions$1 = {
3184
+ "content-manager": {
3185
+ visible: false
3186
+ },
3187
+ "content-type-builder": {
3188
+ visible: false
3189
+ }
3190
+ };
3191
+ const attributes$1 = {
3192
+ key: {
3193
+ type: "string",
3194
+ required: true,
3195
+ unique: true
3196
+ },
3197
+ name: {
3198
+ type: "string"
3199
+ },
3200
+ description: {
3201
+ type: "text"
3202
+ },
3203
+ outcomes: {
3204
+ type: "json",
3205
+ required: true
3206
+ },
3207
+ controlOutcome: {
3208
+ type: "string",
3209
+ required: true
3210
+ },
3211
+ status: {
3212
+ type: "enumeration",
3213
+ "enum": [
3214
+ "draft",
3215
+ "running",
3216
+ "paused",
3217
+ "concluded"
3218
+ ],
3219
+ "default": "draft",
3220
+ required: true
3221
+ },
3222
+ validity: {
3223
+ type: "json"
3224
+ },
3225
+ winner: {
3226
+ type: "string"
3227
+ },
3228
+ externalId: {
3229
+ type: "string"
3230
+ },
3231
+ source: {
3232
+ type: "string"
3233
+ },
3234
+ createdByActor: {
3235
+ type: "string"
3236
+ },
3237
+ correlationId: {
3238
+ type: "string"
3239
+ }
3240
+ };
3241
+ const experimentSchema = {
3242
+ kind: kind$1,
3243
+ collectionName: collectionName$1,
3244
+ info: info$1,
3245
+ options: options$1,
3246
+ pluginOptions: pluginOptions$1,
3247
+ attributes: attributes$1
3248
+ };
3249
+ const kind = "collectionType";
3250
+ const collectionName = "experience_variations";
3251
+ const info = {
3252
+ singularName: "variation",
3253
+ pluralName: "variations",
3254
+ displayName: "Experience variation",
3255
+ description: "One block's membership in a section (mapping set): the default or a variation with audience/trait/affinity references or an experiment outcome. Written through the plugin's MCP tools only."
3256
+ };
3257
+ const options = {
3258
+ draftAndPublish: false
3259
+ };
3260
+ const pluginOptions = {
3261
+ "content-manager": {
3262
+ visible: false
3263
+ },
3264
+ "content-type-builder": {
3265
+ visible: false
3266
+ }
3267
+ };
3268
+ const attributes = {
3269
+ targetUid: {
3270
+ type: "string",
3271
+ required: true
3272
+ },
3273
+ targetDocumentId: {
3274
+ type: "string",
3275
+ required: true
3276
+ },
3277
+ targetLocale: {
3278
+ type: "string"
3279
+ },
3280
+ blockKey: {
3281
+ type: "string",
3282
+ required: true
3283
+ },
3284
+ sectionKey: {
3285
+ type: "string",
3286
+ required: true
3287
+ },
3288
+ variantKey: {
3289
+ type: "string",
3290
+ required: true
3291
+ },
3292
+ displayName: {
3293
+ type: "string"
3294
+ },
3295
+ description: {
3296
+ type: "text"
3297
+ },
3298
+ isDefault: {
3299
+ type: "boolean",
3300
+ "default": false,
3301
+ required: true
3302
+ },
3303
+ status: {
3304
+ type: "enumeration",
3305
+ "enum": [
3306
+ "active",
3307
+ "inactive"
3308
+ ],
3309
+ "default": "active",
3310
+ required: true
3311
+ },
3312
+ orphaned: {
3313
+ type: "boolean",
3314
+ "default": false
3315
+ },
3316
+ targetAudiences: {
3317
+ type: "json"
3318
+ },
3319
+ traits: {
3320
+ type: "json"
3321
+ },
3322
+ affinities: {
3323
+ type: "json"
3324
+ },
3325
+ experiment: {
3326
+ type: "json"
3327
+ },
3328
+ priority: {
3329
+ type: "integer",
3330
+ "default": 0
3331
+ },
3332
+ validity: {
3333
+ type: "json"
3334
+ },
3335
+ componentUid: {
3336
+ type: "string"
3337
+ },
3338
+ source: {
3339
+ type: "string"
3340
+ },
3341
+ createdByActor: {
3342
+ type: "string"
3343
+ },
3344
+ correlationId: {
3345
+ type: "string"
3346
+ }
3347
+ };
3348
+ const variationSchema = {
3349
+ kind,
3350
+ collectionName,
3351
+ info,
3352
+ options,
3353
+ pluginOptions,
3354
+ attributes
3355
+ };
3356
+ const contentTypes = {
3357
+ annotation: { schema: annotationSchema },
3358
+ variation: { schema: variationSchema },
3359
+ experiment: { schema: experimentSchema },
3360
+ change: { schema: changeSchema }
3361
+ };
3362
+ const CM_READ_ACTION = "plugin::content-manager.explorer.read";
3363
+ class AdminApiError extends Error {
3364
+ constructor(status, message) {
3365
+ super(message);
3366
+ this.status = status;
3367
+ }
3368
+ }
3369
+ const UID = /^api::[a-z0-9-]+\.[a-z0-9-]+$/;
3370
+ const LOCALE = /^[A-Za-z0-9-]{1,35}$/;
3371
+ const checkUid = (strapi, uid) => {
3372
+ if (typeof uid !== "string" || !UID.test(uid)) throw new AdminApiError(400, "uid must be an api:: content type UID.");
3373
+ return { uid, target: configuredContentTypes(strapi).includes(uid) && Boolean(strapi.contentTypes[uid]) };
3374
+ };
3375
+ const checkLocale = (locale2) => {
3376
+ if (locale2 === void 0 || locale2 === null || locale2 === "") return null;
3377
+ if (typeof locale2 !== "string" || !LOCALE.test(locale2)) throw new AdminApiError(400, "locale is not a locale code.");
3378
+ return locale2;
3379
+ };
3380
+ const canRead = (ability, uid) => {
3381
+ if (!ability || typeof ability.can !== "function") return false;
3382
+ return Boolean(ability.can(CM_READ_ACTION, uid));
3383
+ };
3384
+ const OPEN_GUARD = { needsDocument: false, canReadDocument: () => true };
3385
+ const CONDITION_POPULATE = ["createdBy", "updatedBy"];
3386
+ const documentReadGuard = (strapi, ability, uid) => {
3387
+ let checker;
3388
+ try {
3389
+ checker = ability ? strapi.plugin("content-manager")?.service("permission-checker")?.create({ userAbility: ability, model: uid }) : void 0;
3390
+ } catch {
3391
+ checker = void 0;
3392
+ }
3393
+ if (!checker?.can?.read || !checker?.requiresEntity?.read) return { needsDocument: true, canReadDocument: () => false };
3394
+ const needsDocument = Boolean(checker.requiresEntity.read());
3395
+ return {
3396
+ needsDocument,
3397
+ canReadDocument: (version) => needsDocument ? Boolean(version) && Boolean(checker.can.read(version)) : true
3398
+ };
3399
+ };
3400
+ const permissionVersion = async (strapi, uid, documentId, locale2) => {
3401
+ try {
3402
+ return await strapi.documents(uid).findOne({
3403
+ documentId,
3404
+ status: "draft",
3405
+ ...locale2 ? { locale: locale2 } : {},
3406
+ populate: CONDITION_POPULATE
3407
+ });
3408
+ } catch {
3409
+ return null;
3410
+ }
3411
+ };
3412
+ const resolveLocale = async (strapi, uid, locale2) => {
3413
+ const localized = Boolean(strapi.contentTypes[uid]?.pluginOptions?.i18n?.localized);
3414
+ if (!localized) return null;
3415
+ if (locale2) return locale2;
3416
+ const i18n = strapi.plugin("i18n")?.service("locales");
3417
+ return await i18n?.getDefaultLocale?.() ?? null;
3418
+ };
3419
+ const HISTORY_LIMIT = 10;
3420
+ const SOURCE_LABELS = { mcp: "Agent / Strapi MCP", api: "API", system: "System" };
3421
+ const createdVia = (row) => row ? {
3422
+ label: SOURCE_LABELS[row.source ?? ""] ?? row.source ?? "unknown",
3423
+ source: row.source ?? null,
3424
+ actor: row.createdBy ?? null,
3425
+ date: row.createdAt ? String(row.createdAt).slice(0, 10) : null,
3426
+ correlationId: row.correlationId ?? null
3427
+ } : null;
3428
+ const roleOf = (v) => !v ? "concepts" : v.experiment ? "outcome" : v.isDefault ? "default" : "variation";
3429
+ const itemsForBlock = (items, v, blockKey) => items.filter((i) => {
3430
+ if (i.path === `annotations.${blockKey}` || i.path.startsWith(`annotations.${blockKey}.`)) return true;
3431
+ if (!v) return false;
3432
+ const section = `sections.${v.sectionKey}`;
3433
+ const own = `${section}.variations.${v.variantKey}`;
3434
+ if (i.path === section) return true;
3435
+ if (i.path === own || i.path.startsWith(`${own}.`) || i.path.startsWith(`${own}[`)) return true;
3436
+ return Boolean(v.experiment && (i.path === `experiments.${v.experiment.key}` || i.path.startsWith(`experiments.${v.experiment.key}.`)));
3437
+ }).map((i) => `${i.status === "ok" ? "✓" : i.status === "warning" ? "⚠" : "✗"} ${i.text}`);
3438
+ function blockCard(snap, items, blockKey, block) {
3439
+ const v = snap.variations.find((x) => x.blockKey === blockKey);
3440
+ const annotation = snap.annotations.find((a) => a.blockKey === blockKey && !a.orphaned);
3441
+ const pageConcepts = snap.annotations.find((a) => !a.blockKey && !a.orphaned)?.concepts ?? [];
3442
+ const def = v ? snap.variations.find((x) => x.sectionKey === v.sectionKey && x.isDefault) : void 0;
3443
+ const defBlock = def ? snap.blocks.find((b) => b.blockKey === def.blockKey) : void 0;
3444
+ const exp = v?.experiment ? snap.experiments.get(v.experiment.key) : void 0;
3445
+ const component = componentLabel(block?.componentUid ?? v?.componentUid);
3446
+ const role = roleOf(v);
3447
+ const roleText = role === "default" ? `Default "${v.variantKey}"` : role === "variation" ? `Variation "${v.variantKey}"` : role === "outcome" ? `Outcome ${v.experiment.outcome} "${v.variantKey}"` : "Concepts";
3448
+ return {
3449
+ blockKey,
3450
+ index: block?.index ?? null,
3451
+ componentUid: block?.componentUid ?? v?.componentUid ?? null,
3452
+ title: block?.title ?? null,
3453
+ heading: `${component} · ${roleText}`,
3454
+ role,
3455
+ sectionKey: v?.sectionKey ?? null,
3456
+ variantKey: v?.variantKey ?? null,
3457
+ status: v ? v.orphaned ? "orphaned" : v.status : null,
3458
+ about: annotation?.concepts?.length ? annotation.concepts : pageConcepts.map((c) => `${c} (page)`),
3459
+ intendedFor: v ? v.isDefault && !v.experiment ? ["Everyone (default)"] : [...v.targetAudiences, ...v.traits, ...v.affinities] : [],
3460
+ experiment: v?.experiment ? { ...v.experiment, name: exp?.name ?? null, status: exp?.status ?? null, split: exp ? describeSplit(toExperiment(exp)) || null : null } : null,
3461
+ fallback: def ? { blockKey: def.blockKey, label: `${def.variantKey}${defBlock?.title ? ` (${defBlock.title})` : def.displayName ? ` (${def.displayName})` : ""}` } : null,
3462
+ createdVia: createdVia(v ?? annotation),
3463
+ validation: itemsForBlock(items, v, blockKey)
3464
+ };
3465
+ }
3466
+ async function inspect(strapi, query, guard = OPEN_GUARD) {
3467
+ const { uid, target: isTarget } = checkUid(strapi, query.uid);
3468
+ if (!isTarget) return { target: null };
3469
+ const documentId = typeof query.documentId === "string" && query.documentId && query.documentId !== "create" ? query.documentId : void 0;
3470
+ let target;
3471
+ try {
3472
+ target = await resolveTarget(strapi, uid, documentId);
3473
+ } catch (e) {
3474
+ if (e instanceof ToolError) throw new AdminApiError(404, e.message);
3475
+ throw e;
3476
+ }
3477
+ const locale2 = await resolveLocale(strapi, uid, checkLocale(query.locale));
3478
+ if (guard.needsDocument && !guard.canReadDocument(await permissionVersion(strapi, uid, target.documentId, locale2))) {
3479
+ throw new AdminApiError(403, "You cannot read this document in this locale.");
3480
+ }
3481
+ const store2 = createStore(strapi);
3482
+ const snap = await loadSnapshot(strapi, store2, target, locale2);
3483
+ const state = await snapshotState(store2, snap);
3484
+ const validation = report(state, validateState(state, await validationContext(strapi)));
3485
+ const keys = /* @__PURE__ */ new Set();
3486
+ for (const v of snap.variations) keys.add(v.blockKey);
3487
+ for (const a of snap.annotations) if (a.blockKey) keys.add(a.blockKey);
3488
+ const byBlockKey = {};
3489
+ const orphaned = [];
3490
+ for (const key of keys) {
3491
+ const block = snap.blocks.find((b) => b.blockKey === key);
3492
+ const card = blockCard(snap, validation.items, key, block);
3493
+ if (block) byBlockKey[key] = card;
3494
+ else orphaned.push(card);
3495
+ }
3496
+ const history = await changeHistory(strapi, { targetUid: uid, targetDocumentId: target.documentId }, HISTORY_LIMIT);
3497
+ const experiments2 = [...snap.experiments.values()].map(toExperiment);
3498
+ const live = snap.variations.filter((v) => v.status === "active" && !v.orphaned);
3499
+ return {
3500
+ target: { uid: target.uid, documentId: target.documentId, kind: target.kind, localized: target.localized },
3501
+ locale: locale2,
3502
+ summary: {
3503
+ sections: new Set(live.map((v) => v.sectionKey)).size,
3504
+ variations: live.filter((v) => !v.isDefault).length,
3505
+ concepts: (snap.annotations.find((a) => !a.blockKey)?.concepts ?? []).length,
3506
+ annotatedBlocks: snap.annotations.filter((a) => a.blockKey && !a.orphaned).length,
3507
+ experiments: experiments2.map((e) => ({ key: e.key, name: e.name ?? null, status: e.status, running: e.status === "running" && !e.winner })),
3508
+ inactive: snap.variations.filter((v) => v.status === "inactive" && !v.orphaned).length,
3509
+ orphaned: orphaned.length,
3510
+ errors: validation.errors.length,
3511
+ warnings: validation.warnings.length
3512
+ },
3513
+ page: { concepts: snap.annotations.find((a) => !a.blockKey && !a.orphaned)?.concepts ?? [] },
3514
+ blocks: snap.blocks.map((b) => ({ index: b.index, blockKey: b.blockKey, componentUid: b.componentUid, summary: b.summary, title: b.title })),
3515
+ byBlockKey,
3516
+ orphaned,
3517
+ experiments: experiments2,
3518
+ validation: { ok: validation.ok, errors: validation.errors, warnings: validation.warnings, checklist: validation.checklist },
3519
+ changes: history.map((h) => ({
3520
+ createdAt: h.createdAt ?? null,
3521
+ action: h.action,
3522
+ entity: h.entity,
3523
+ actor: h.actor ?? null,
3524
+ source: h.source ?? null,
3525
+ sectionKey: h.sectionKey ?? null,
3526
+ variantKey: h.variantKey ?? null,
3527
+ blockKey: h.blockKey ?? null,
3528
+ experimentKey: h.experimentKey ?? null,
3529
+ correlationId: h.correlationId ?? null
3530
+ }))
3531
+ };
3532
+ }
3533
+ async function explain(strapi, body, guard = OPEN_GUARD) {
3534
+ const { uid, target: isTarget } = checkUid(strapi, body?.uid);
3535
+ if (!isTarget) throw new AdminApiError(404, `${uid} is not an experience target.`);
3536
+ const documentId = typeof body.documentId === "string" && body.documentId ? body.documentId : void 0;
3537
+ let target;
3538
+ try {
3539
+ target = await resolveTarget(strapi, uid, documentId);
3540
+ } catch (e) {
3541
+ if (e instanceof ToolError) throw new AdminApiError(404, e.message);
3542
+ throw e;
3543
+ }
3544
+ const locale2 = await resolveLocale(strapi, uid, checkLocale(body.locale));
3545
+ if (guard.needsDocument && !guard.canReadDocument(await permissionVersion(strapi, uid, target.documentId, locale2))) {
3546
+ throw new AdminApiError(403, "You cannot read this document in this locale.");
3547
+ }
3548
+ if (body.context !== void 0 && (typeof body.context !== "object" || body.context === null || Array.isArray(body.context))) {
3549
+ throw new AdminApiError(400, "context must be an ExperienceContext object.");
3550
+ }
3551
+ const snap = await loadSnapshot(strapi, createStore(strapi), target, locale2);
3552
+ return explainSnapshot(snap, body.context).explanation;
3553
+ }
3554
+ const errorName = (status) => status === 404 ? "NotFoundError" : status === 403 ? "ForbiddenError" : "ValidationError";
3555
+ const adminController = ({ strapi }) => {
3556
+ const send = async (ctx, run) => {
3557
+ try {
3558
+ ctx.set("Cache-Control", "private, no-store");
3559
+ ctx.body = { data: await run() };
3560
+ } catch (e) {
3561
+ if (e instanceof AdminApiError) {
3562
+ ctx.status = e.status;
3563
+ ctx.body = { error: { status: e.status, name: errorName(e.status), message: e.message } };
3564
+ return;
3565
+ }
3566
+ throw e;
3567
+ }
3568
+ };
3569
+ const guarded = (ctx, uidValue, handler2) => send(ctx, async () => {
3570
+ const { uid } = checkUid(strapi, uidValue);
3571
+ if (!canRead(ctx.state?.userAbility, uid)) throw new AdminApiError(403, "You cannot read this content type.");
3572
+ return handler2(documentReadGuard(strapi, ctx.state?.userAbility, uid));
3573
+ });
3574
+ return {
3575
+ async registry(ctx) {
3576
+ await send(ctx, () => loadRegistry(strapi));
3577
+ },
3578
+ async presets(ctx) {
3579
+ await send(ctx, async () => configuredPresets(strapi));
3580
+ },
3581
+ async inspect(ctx) {
3582
+ const { uid, documentId } = ctx.params ?? {};
3583
+ await guarded(ctx, uid, (guard) => inspect(strapi, { uid, documentId, locale: ctx.query?.locale }, guard));
3584
+ },
3585
+ async explain(ctx) {
3586
+ const body = ctx.request?.body ?? {};
3587
+ await guarded(ctx, body.uid, (guard) => explain(strapi, body, guard));
3588
+ }
3589
+ };
3590
+ };
3591
+ const experienceController = (_) => ({
3592
+ async read(ctx) {
3593
+ ctx.set("Cache-Control", "private, no-store");
3594
+ ctx.body = { data: { [FLAG]: true, contract: CONTRACT_VERSION } };
3595
+ }
3596
+ });
3597
+ const controllers = {
3598
+ admin: adminController,
3599
+ experience: experienceController
3600
+ };
3601
+ const canReadPolicy = (policyContext) => canRead$1(policyContext?.state?.userAbility);
3602
+ const policies = {
3603
+ "can-read": canReadPolicy
3604
+ };
3605
+ const adminPolicies = ["admin::isAuthenticatedAdmin", "plugin::experience-context.can-read"];
3606
+ const routes = {
3607
+ "content-api": {
3608
+ type: "content-api",
3609
+ routes: [
3610
+ {
3611
+ // Grants `plugin::experience-context.experience.read`, the
3612
+ // permission `?withExperience=true` is gated on.
3613
+ method: "GET",
3614
+ path: "/access",
3615
+ handler: "experience.read",
3616
+ config: { policies: [] }
3617
+ }
3618
+ ]
3619
+ },
3620
+ admin: {
3621
+ type: "admin",
3622
+ // Read-only, for the Content Manager inspection and the Experience Builder
3623
+ // simulator. POST /explain computes an explanation; it writes nothing.
3624
+ routes: [
3625
+ { method: "GET", path: "/registry", handler: "admin.registry", config: { policies: adminPolicies } },
3626
+ { method: "GET", path: "/presets", handler: "admin.presets", config: { policies: adminPolicies } },
3627
+ { method: "GET", path: "/inspect/:uid", handler: "admin.inspect", config: { policies: adminPolicies } },
3628
+ { method: "GET", path: "/inspect/:uid/:documentId", handler: "admin.inspect", config: { policies: adminPolicies } },
3629
+ { method: "POST", path: "/explain", handler: "admin.explain", config: { policies: adminPolicies } }
3630
+ ]
3631
+ }
3632
+ };
3633
+ async function attachForEditor(strapi, opts) {
3634
+ const { uid, userAbility } = opts;
3635
+ const docs = (opts.documents ?? []).filter((d) => d && typeof d === "object" && typeof d.documentId === "string");
3636
+ if (docs.length === 0) return { attached: false, why: "no documents" };
3637
+ if (!configuredContentTypes(strapi).includes(uid) || !strapi.contentTypes[uid]) {
3638
+ return { attached: false, why: `${uid} is not an experience target` };
3639
+ }
3640
+ if (!canRead(userAbility, uid)) return { attached: false, why: `the user cannot read ${uid}` };
3641
+ const guard = documentReadGuard(strapi, userAbility, uid);
3642
+ const readable = [];
3643
+ for (const doc of docs) {
3644
+ if (!guard.needsDocument) {
3645
+ readable.push(doc);
3646
+ continue;
3647
+ }
3648
+ const locale2 = typeof doc.locale === "string" ? doc.locale : opts.locale ?? void 0;
3649
+ const version = await strapi.documents(uid).findOne({ documentId: doc.documentId, status: "draft", ...locale2 ? { locale: locale2 } : {}, populate: CONDITION_POPULATE }).catch(() => null);
3650
+ if (guard.canReadDocument(version)) readable.push(doc);
3651
+ }
3652
+ if (readable.length === 0) return { attached: false, why: "the user cannot read these documents" };
3653
+ const zones = blockKeyTargets(strapi).zonesByUid.get(uid) ?? [];
3654
+ await enrich(new RequestLoader(strapi), uid, readable, zones, opts.locale ?? null);
3655
+ const refused = docs.length - readable.length;
3656
+ return refused > 0 ? { attached: true, why: `${refused} document(s) not readable by the user` } : { attached: true };
3657
+ }
3658
+ const blockKeys = ({ strapi }) => ({
3659
+ targets() {
3660
+ const t = blockKeyTargets(strapi);
3661
+ return { contentTypes: Object.fromEntries(t.zonesByUid), components: [...t.keyedComponents].sort() };
3662
+ },
3663
+ backfill(options2 = {}) {
3664
+ return backfill(strapi, blockKeyTargets(strapi), options2);
3665
+ },
3666
+ stamp(uid, data) {
3667
+ return stampPayload(strapi, blockKeyTargets(strapi), uid, data);
3668
+ }
3669
+ });
3670
+ const editor = ({ strapi }) => ({
3671
+ attach(options2) {
3672
+ return attachForEditor(strapi, options2);
3673
+ }
3674
+ });
3675
+ const integrity = ({ strapi }) => createIntegrity(strapi, () => blockKeyTargets(strapi));
3676
+ const registry = ({ strapi }) => ({
3677
+ get: () => loadRegistry(strapi),
3678
+ presets: () => configuredPresets(strapi)
3679
+ });
3680
+ const store = ({ strapi }) => createStore(strapi);
3681
+ const services = { blockKeys, editor, integrity, registry, store };
3682
+ const index = {
3683
+ register,
3684
+ bootstrap,
3685
+ destroy,
3686
+ config,
3687
+ contentTypes,
3688
+ controllers,
3689
+ policies,
3690
+ routes,
3691
+ services
3692
+ };
3693
+ export {
3694
+ index as default
3695
+ };