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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +86 -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 +3780 -0
  24. package/dist/server/index.mjs +3781 -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 +815 -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,448 @@
1
+ import * as React from "react";
2
+ import { useRef, useEffect } from "react";
3
+ import { jsx, jsxs, Fragment } from "react/jsx-runtime";
4
+ import { Modal, Typography, Button, Tabs, Flex, Box, Badge, Tooltip } from "@strapi/design-system";
5
+ import { Eye, ChartPie, PriceTag } from "@strapi/icons";
6
+ import { unstable_useDocumentLayout } from "@strapi/content-manager/strapi-admin";
7
+ import { useIntl } from "react-intl";
8
+ import { useFetchClient, useForm } from "@strapi/strapi/admin";
9
+ import { createPortal } from "react-dom";
10
+ import { useLocation } from "react-router-dom";
11
+ const pluginId = "experience-context";
12
+ const Initializer = ({ setPlugin }) => {
13
+ const ref = useRef(setPlugin);
14
+ useEffect(() => {
15
+ ref.current(pluginId);
16
+ }, []);
17
+ return null;
18
+ };
19
+ const cache = /* @__PURE__ */ new Map();
20
+ const INSPECT_TTL_MS = 5e3;
21
+ const inspectUrl = (uid, documentId) => `/${pluginId}/inspect/${encodeURIComponent(uid)}${documentId ? `/${encodeURIComponent(documentId)}` : ""}`;
22
+ function fetchInspect(get, uid, documentId, locale, now = Date.now()) {
23
+ const key = `${uid}\0${documentId ?? ""}\0${locale ?? ""}`;
24
+ const hit = cache.get(key);
25
+ if (hit && now - hit.at < INSPECT_TTL_MS) return hit.promise;
26
+ const promise = get(inspectUrl(uid, documentId), locale ? { params: { locale } } : void 0).then(({ data }) => data?.data);
27
+ promise.catch(() => cache.delete(key));
28
+ cache.set(key, { at: now, promise });
29
+ return promise;
30
+ }
31
+ function useInspect(uid, documentId, locale, skip = false) {
32
+ const { get } = useFetchClient();
33
+ const [data, setData] = React.useState(void 0);
34
+ React.useEffect(() => {
35
+ if (skip || !uid) {
36
+ setData(null);
37
+ return;
38
+ }
39
+ let cancelled = false;
40
+ fetchInspect(get, uid, documentId, locale).then((view) => !cancelled && setData(view)).catch(() => !cancelled && setData(null));
41
+ return () => {
42
+ cancelled = true;
43
+ };
44
+ }, [get, uid, documentId, locale, skip]);
45
+ return data;
46
+ }
47
+ const hasAnything = (s) => Boolean(s && (s.sections || s.concepts || s.annotatedBlocks || s.orphaned || s.experiments.length));
48
+ function headerParts(s, pluginId2) {
49
+ const parts = [];
50
+ if (s.sections) {
51
+ parts.push({ id: `${pluginId2}.header.sections`, defaultMessage: "{count, plural, one {# section} other {# sections}}", values: { count: s.sections } });
52
+ }
53
+ if (s.variations) {
54
+ parts.push({ id: `${pluginId2}.header.variations`, defaultMessage: "{count, plural, one {# variation} other {# variations}}", values: { count: s.variations } });
55
+ }
56
+ const running = s.experiments.filter((e) => e.running).length;
57
+ if (running) {
58
+ parts.push({ id: `${pluginId2}.header.experiments.running`, defaultMessage: "{count, plural, one {# experiment running} other {# experiments running}}", values: { count: running } });
59
+ } else if (s.experiments.length) {
60
+ parts.push({ id: `${pluginId2}.header.experiments`, defaultMessage: "{count, plural, one {# experiment (not running)} other {# experiments (not running)}}", values: { count: s.experiments.length } });
61
+ }
62
+ if (s.concepts) {
63
+ parts.push({ id: `${pluginId2}.header.concepts`, defaultMessage: "{count, plural, one {# concept} other {# concepts}}", values: { count: s.concepts } });
64
+ }
65
+ if (s.orphaned) parts.push({ id: `${pluginId2}.header.orphaned`, defaultMessage: "{count} orphaned", values: { count: s.orphaned } });
66
+ if (s.errors) {
67
+ parts.push({ id: `${pluginId2}.header.errors`, defaultMessage: "{count, plural, one {# validation error} other {# validation errors}}", values: { count: s.errors } });
68
+ }
69
+ return parts;
70
+ }
71
+ function markerText(card) {
72
+ switch (card.role) {
73
+ case "default":
74
+ return "Default";
75
+ case "variation":
76
+ return "Variation";
77
+ case "outcome":
78
+ return `Outcome ${card.experiment?.outcome ?? ""}`.trim();
79
+ default:
80
+ return "Concepts";
81
+ }
82
+ }
83
+ function markerLabel(card) {
84
+ const parts = [card.heading];
85
+ if (card.sectionKey) parts.push(`section ${card.sectionKey}`);
86
+ if (card.intendedFor.length) parts.push(`intended for ${card.intendedFor.join(", ")}`);
87
+ if (card.experiment) parts.push(`experiment ${card.experiment.key} / ${card.experiment.outcome}`);
88
+ if (card.status && card.status !== "active") parts.push(card.status);
89
+ return parts.join(" · ");
90
+ }
91
+ function cardRows(card) {
92
+ return [
93
+ { label: "About", value: card.about.length ? card.about.join(" · ") : "–" },
94
+ { label: "Intended for", value: card.intendedFor.length ? card.intendedFor.join(" · ") : "–" },
95
+ {
96
+ label: "Experiment",
97
+ value: card.experiment ? [`${card.experiment.key} · outcome ${card.experiment.outcome}`, card.experiment.split ? `split ${card.experiment.split}` : null].filter(Boolean).join(" · ") : "–"
98
+ },
99
+ { label: "Fallback", value: card.fallback ? card.fallback.label : "–" },
100
+ {
101
+ label: "Created via",
102
+ value: card.createdVia ? [card.createdVia.label, card.createdVia.date, card.createdVia.correlationId ? `correlation ${card.createdVia.correlationId}` : null].filter(Boolean).join(" · ") : "–"
103
+ },
104
+ { label: "Validation", value: card.validation.length ? card.validation.join(" ") : "–" }
105
+ ];
106
+ }
107
+ function isTargetType(options) {
108
+ return Boolean(options?.[pluginId]?.target);
109
+ }
110
+ const CONTENT_ZONE = "content";
111
+ const UID = /^api::[a-z0-9-]+\.[a-z0-9-]+$/;
112
+ function parseCmPath(pathname) {
113
+ const m = pathname.match(/\/content-manager\/(collection-types|single-types)\/([^/?#]+)(?:\/([^/?#]+))?/);
114
+ if (!m) return null;
115
+ const uid = decodeURIComponent(m[2]);
116
+ if (!UID.test(uid)) return null;
117
+ const documentId = m[3] && m[3] !== "create" ? decodeURIComponent(m[3]) : null;
118
+ return { collectionType: m[1], uid, documentId };
119
+ }
120
+ function localeFromSearch(search) {
121
+ const params = new URLSearchParams(search);
122
+ const locale = params.get("plugins[i18n][locale]");
123
+ return locale && /^[A-Za-z0-9-]{1,35}$/.test(locale) ? locale : null;
124
+ }
125
+ function modalCards(view, focusKey) {
126
+ const byKey = view.byBlockKey ?? {};
127
+ if (focusKey) {
128
+ const card = byKey[focusKey];
129
+ return { cards: card ? [card] : [], orphaned: [], raw: card ?? null };
130
+ }
131
+ const cards = Object.values(byKey).sort((a, b) => (a.index ?? 1e9) - (b.index ?? 1e9));
132
+ return {
133
+ cards,
134
+ orphaned: view.orphaned ?? [],
135
+ raw: { page: view.page ?? null, blocks: byKey, orphaned: view.orphaned ?? [], experiments: view.experiments ?? [], validation: view.validation ?? null }
136
+ };
137
+ }
138
+ const Row = ({ label, children }) => /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "baseline", children: [
139
+ /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", style: { minWidth: "8rem" }, children: label }),
140
+ /* @__PURE__ */ jsx(Box, { children })
141
+ ] });
142
+ const BlockCard = ({ card }) => {
143
+ const rows = cardRows(card);
144
+ return /* @__PURE__ */ jsx(Box, { padding: 4, hasRadius: true, borderColor: "neutral200", background: "neutral0", "data-testid": "experience-card", children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 3, children: [
145
+ /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", children: [
146
+ /* @__PURE__ */ jsx(Typography, { variant: "delta", tag: "h3", children: card.heading }),
147
+ card.title && /* @__PURE__ */ jsx(Typography, { textColor: "neutral600", children: card.title }),
148
+ card.status === "inactive" && /* @__PURE__ */ jsx(Badge, { children: "Inactive" }),
149
+ card.status === "orphaned" && /* @__PURE__ */ jsx(Badge, { backgroundColor: "warning100", textColor: "warning700", children: "Orphaned" }),
150
+ card.experiment?.status === "running" && /* @__PURE__ */ jsx(Badge, { backgroundColor: "success100", textColor: "success700", children: "Running experiment" })
151
+ ] }),
152
+ /* @__PURE__ */ jsx(Flex, { direction: "column", alignItems: "stretch", gap: 1, children: rows.map(
153
+ (row) => row.label === "Validation" ? /* @__PURE__ */ jsx(Row, { label: row.label.toUpperCase(), children: card.validation.length === 0 ? /* @__PURE__ */ jsx(Typography, { variant: "omega", children: "–" }) : /* @__PURE__ */ jsx(Box, { tag: "ul", children: card.validation.map((line, i) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: line.startsWith("✗") ? "danger600" : line.startsWith("⚠") ? "warning600" : "success600", children: line }) }, i)) }) }, row.label) : /* @__PURE__ */ jsx(Row, { label: row.label.toUpperCase(), children: /* @__PURE__ */ jsx(Typography, { variant: "omega", children: row.value }) }, row.label)
154
+ ) })
155
+ ] }) });
156
+ };
157
+ const ModalBody = ({ view, focusKey }) => {
158
+ const { formatMessage } = useIntl();
159
+ const { cards, orphaned, raw } = modalCards(view, focusKey);
160
+ const concepts = view.page?.concepts ?? [];
161
+ return /* @__PURE__ */ jsxs(Tabs.Root, { defaultValue: "blocks", children: [
162
+ /* @__PURE__ */ jsxs(Tabs.List, { "aria-label": "Experience views", children: [
163
+ /* @__PURE__ */ jsx(Tabs.Trigger, { value: "blocks", children: formatMessage({ id: `${pluginId}.modal.tab.blocks`, defaultMessage: "Blocks" }) }),
164
+ /* @__PURE__ */ jsx(Tabs.Trigger, { value: "raw", children: formatMessage({ id: `${pluginId}.modal.tab.raw`, defaultMessage: "Raw JSON" }) })
165
+ ] }),
166
+ /* @__PURE__ */ jsx(Tabs.Content, { value: "blocks", children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, paddingTop: 4, children: [
167
+ !focusKey && /* @__PURE__ */ jsxs(Typography, { variant: "pi", textColor: "neutral600", children: [
168
+ formatMessage({ id: `${pluginId}.modal.page-concepts`, defaultMessage: "Page is about" }),
169
+ ": ",
170
+ concepts.length ? concepts.join(" · ") : "–"
171
+ ] }),
172
+ cards.length === 0 && /* @__PURE__ */ jsx(Typography, { textColor: "neutral500", children: formatMessage({ id: `${pluginId}.modal.empty`, defaultMessage: "No experience mappings on this document." }) }),
173
+ cards.map((card) => /* @__PURE__ */ jsx(BlockCard, { card }, card.blockKey)),
174
+ orphaned.length > 0 && /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, children: [
175
+ /* @__PURE__ */ jsx(Typography, { variant: "delta", tag: "h3", children: formatMessage({ id: `${pluginId}.modal.orphaned.title`, defaultMessage: "Orphaned mappings" }) }),
176
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: formatMessage({
177
+ id: `${pluginId}.modal.orphaned.help`,
178
+ defaultMessage: "Their block is no longer in the draft, so they are not sent. They apply again if the block comes back."
179
+ }) }),
180
+ orphaned.map((card) => /* @__PURE__ */ jsx(BlockCard, { card }, card.blockKey))
181
+ ] }),
182
+ !focusKey && (view.changes?.length ?? 0) > 0 && /* @__PURE__ */ jsxs(Box, { children: [
183
+ /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: formatMessage({ id: `${pluginId}.modal.changes`, defaultMessage: "Last changes" }) }),
184
+ /* @__PURE__ */ jsx(Box, { tag: "ul", children: view.changes.map((c, i) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(Typography, { variant: "pi", children: [
185
+ c.createdAt ? `${String(c.createdAt).replace("T", " ").slice(0, 16)} UTC` : "?",
186
+ " · ",
187
+ c.action,
188
+ " ",
189
+ c.entity,
190
+ c.sectionKey ? ` ${c.sectionKey}${c.variantKey ? `/${c.variantKey}` : ""}` : "",
191
+ c.experimentKey ? ` (${c.experimentKey})` : "",
192
+ c.actor ? ` by ${c.actor}` : "",
193
+ c.correlationId ? ` · correlation ${c.correlationId}` : ""
194
+ ] }) }, i)) })
195
+ ] })
196
+ ] }) }),
197
+ /* @__PURE__ */ jsx(Tabs.Content, { value: "raw", children: /* @__PURE__ */ jsx(Box, { paddingTop: 4, children: /* @__PURE__ */ jsx(Box, { tag: "pre", padding: 4, background: "neutral100", hasRadius: true, style: { overflow: "auto", maxHeight: "60vh", fontSize: "12px" }, children: JSON.stringify(raw, null, 2) }) }) })
198
+ ] });
199
+ };
200
+ const ExperienceModal = ({ open, onClose, uid, documentId, locale, view: given, focusKey, title }) => {
201
+ const { formatMessage } = useIntl();
202
+ const { get } = useFetchClient();
203
+ const [view, setView] = React.useState(given);
204
+ const [failed, setFailed] = React.useState(false);
205
+ React.useEffect(() => {
206
+ if (!open) return;
207
+ if (given) {
208
+ setView(given);
209
+ return;
210
+ }
211
+ let cancelled = false;
212
+ fetchInspect(get, uid, documentId, locale).then((v) => !cancelled && setView(v)).catch(() => !cancelled && setFailed(true));
213
+ return () => {
214
+ cancelled = true;
215
+ };
216
+ }, [open, given, get, uid, documentId, locale]);
217
+ return /* @__PURE__ */ jsx(Modal.Root, { open, onOpenChange: (o) => !o && onClose(), children: /* @__PURE__ */ jsxs(Modal.Content, { onClick: (e) => e.stopPropagation(), "data-testid": "experience-modal", children: [
218
+ /* @__PURE__ */ jsx(Modal.Header, { children: /* @__PURE__ */ jsx(Modal.Title, { children: title ?? formatMessage({ id: `${pluginId}.modal.title`, defaultMessage: "Experience (read-only)" }) }) }),
219
+ /* @__PURE__ */ jsxs(Modal.Body, { children: [
220
+ failed && /* @__PURE__ */ jsx(Typography, { textColor: "danger600", children: formatMessage({ id: `${pluginId}.modal.error`, defaultMessage: "Could not load the experience mappings." }) }),
221
+ !failed && !view && /* @__PURE__ */ jsx(Typography, { textColor: "neutral500", children: "…" }),
222
+ view && /* @__PURE__ */ jsx(ModalBody, { view, focusKey })
223
+ ] }),
224
+ /* @__PURE__ */ jsxs(Modal.Footer, { children: [
225
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: formatMessage({ id: `${pluginId}.modal.readonly`, defaultMessage: "Read-only. Variations, audiences and experiments are authored through the MCP tools." }) }),
226
+ /* @__PURE__ */ jsx(Modal.Close, { children: /* @__PURE__ */ jsx(Button, { variant: "tertiary", children: formatMessage({ id: `${pluginId}.modal.close`, defaultMessage: "Close" }) }) })
227
+ ] })
228
+ ] }) });
229
+ };
230
+ function headerText(summary, formatMessage) {
231
+ const title = formatMessage({ id: `${pluginId}.header.title`, defaultMessage: "Experience" });
232
+ const parts = headerParts(summary, pluginId).map(({ id, defaultMessage, values }) => formatMessage({ id, defaultMessage }, values));
233
+ return [title, ...parts].join(" · ");
234
+ }
235
+ const HeaderBadgeContent = ({ summary, view }) => {
236
+ const { formatMessage } = useIntl();
237
+ const [open, setOpen] = React.useState(false);
238
+ const text = headerText(summary, formatMessage);
239
+ const target = view?.target;
240
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
241
+ /* @__PURE__ */ jsx(
242
+ Button,
243
+ {
244
+ variant: "tertiary",
245
+ size: "S",
246
+ startIcon: /* @__PURE__ */ jsx(Eye, { "aria-hidden": true }),
247
+ onClick: () => setOpen(true),
248
+ disabled: !target,
249
+ "aria-haspopup": "dialog",
250
+ "aria-label": `${text}. ${formatMessage({ id: `${pluginId}.header.open`, defaultMessage: "Open experience details" })}`,
251
+ title: text,
252
+ "data-testid": "experience-header-badge",
253
+ style: { maxWidth: "44rem" },
254
+ children: /* @__PURE__ */ jsx("span", { style: { display: "block", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, children: text })
255
+ }
256
+ ),
257
+ open && target && /* @__PURE__ */ jsx(ExperienceModal, { open: true, onClose: () => setOpen(false), uid: target.uid, documentId: target.documentId, locale: view?.locale, view })
258
+ ] });
259
+ };
260
+ const ExperienceHeaderAction = ({ model, documentId, document: document2 }) => {
261
+ const { formatMessage } = useIntl();
262
+ const { edit } = unstable_useDocumentLayout(model);
263
+ const target = isTargetType(edit?.options);
264
+ const locale = document2?.locale ?? localeFromSearch(window.location.search);
265
+ const view = useInspect(model, documentId ?? document2?.documentId, locale, !target || documentId === "create");
266
+ const summary = view?.summary;
267
+ if (!target || !hasAnything(summary)) return null;
268
+ return {
269
+ label: formatMessage({ id: `${pluginId}.header.title`, defaultMessage: "Experience" }),
270
+ // The `_status` slot renders any node in the header.
271
+ _status: {
272
+ message: /* @__PURE__ */ jsx(HeaderBadgeContent, { summary, view })
273
+ }
274
+ };
275
+ };
276
+ const ModalTrigger = ({
277
+ children,
278
+ label,
279
+ ...modal
280
+ }) => {
281
+ const [open, setOpen] = React.useState(false);
282
+ const stop = (e) => e.stopPropagation();
283
+ return /* @__PURE__ */ jsxs("span", { onClick: stop, onKeyDown: stop, onPointerDown: stop, style: { display: "inline-flex" }, children: [
284
+ /* @__PURE__ */ jsx(
285
+ "button",
286
+ {
287
+ type: "button",
288
+ "aria-label": label,
289
+ "aria-haspopup": "dialog",
290
+ onClick: () => setOpen(true),
291
+ style: { all: "unset", cursor: "pointer", display: "inline-flex" },
292
+ "data-testid": "experience-open-modal",
293
+ children
294
+ }
295
+ ),
296
+ open && /* @__PURE__ */ jsx(ExperienceModal, { open: true, onClose: () => setOpen(false), ...modal })
297
+ ] });
298
+ };
299
+ function markersFor(blockKeys, byBlockKey) {
300
+ return blockKeys.map((key) => key && byBlockKey?.[key] || null);
301
+ }
302
+ const KEY_SEPARATOR = "";
303
+ function encodeKeys(blocks) {
304
+ if (!Array.isArray(blocks)) return "";
305
+ return blocks.map((b) => typeof b?.blockKey === "string" ? b.blockKey : "").join(KEY_SEPARATOR);
306
+ }
307
+ function decodeKeys(encoded) {
308
+ if (!encoded) return [];
309
+ return encoded.split(KEY_SEPARATOR).map((k) => k || null);
310
+ }
311
+ const SLOT_ATTR = "data-experience-context-marker";
312
+ function findZoneList(anchor) {
313
+ let node = anchor;
314
+ for (let depth = 0; node && depth < 12; depth += 1) {
315
+ const list = node.querySelector(":scope > ol");
316
+ if (list) return list;
317
+ node = node.parentElement;
318
+ }
319
+ return null;
320
+ }
321
+ function slotFor(li) {
322
+ const header = li.querySelector("h3");
323
+ if (!header) return null;
324
+ const existing = header.querySelector(`:scope > [${SLOT_ATTR}]`);
325
+ if (existing) return existing;
326
+ const slot = document.createElement("span");
327
+ slot.setAttribute(SLOT_ATTR, "");
328
+ slot.style.display = "inline-flex";
329
+ slot.style.alignItems = "center";
330
+ slot.style.paddingInline = "4px";
331
+ const trigger = header.querySelector(":scope > button");
332
+ header.insertBefore(slot, trigger ? trigger.nextSibling : header.firstChild);
333
+ return slot;
334
+ }
335
+ function zoneSlots(anchor) {
336
+ const list = findZoneList(anchor);
337
+ if (!list) return [];
338
+ return Array.from(list.children).map((li) => slotFor(li));
339
+ }
340
+ const COLORS = {
341
+ default: ["neutral150", "neutral700"],
342
+ variation: ["primary100", "primary700"],
343
+ outcome: ["success100", "success700"],
344
+ concepts: ["secondary100", "secondary700"]
345
+ };
346
+ const BlockMarker = ({ card, view }) => {
347
+ const label = markerLabel(card);
348
+ const [bg, fg] = card.status === "inactive" ? ["neutral150", "neutral500"] : COLORS[card.role];
349
+ const Icon = card.role === "outcome" ? ChartPie : card.role === "concepts" ? PriceTag : Eye;
350
+ const badge = /* @__PURE__ */ jsx(Tooltip, { label, children: /* @__PURE__ */ jsx(Badge, { "aria-label": label, "data-testid": "experience-marker", backgroundColor: bg, textColor: fg, children: /* @__PURE__ */ jsxs(Flex, { gap: 1, style: { whiteSpace: "nowrap" }, children: [
351
+ /* @__PURE__ */ jsx(Icon, { width: "1rem", height: "1rem", "aria-hidden": true }),
352
+ markerText(card),
353
+ card.variantKey && card.role !== "default" ? ` "${card.variantKey}"` : ""
354
+ ] }) }) });
355
+ if (!view?.target) return badge;
356
+ return /* @__PURE__ */ jsx(ModalTrigger, { label: `${label}. Open details`, uid: view.target.uid, documentId: view.target.documentId, locale: view.locale, view, focusKey: card.blockKey, children: badge });
357
+ };
358
+ const BlockMarkers = () => {
359
+ const { formatMessage } = useIntl();
360
+ const location = useLocation();
361
+ const path = parseCmPath(location.pathname);
362
+ const locale = localeFromSearch(location.search);
363
+ const view = useInspect(path?.uid, path?.documentId, locale, !path);
364
+ const encoded = useForm("experience-context/BlockMarkers", (state) => encodeKeys(state.values?.[CONTENT_ZONE]));
365
+ const keys = React.useMemo(() => decodeKeys(encoded), [encoded]);
366
+ const markers = React.useMemo(() => markersFor(keys, view?.byBlockKey), [keys, view]);
367
+ const anchor = React.useRef(null);
368
+ const [slots, setSlots] = React.useState([]);
369
+ const active = Boolean(view?.target);
370
+ const refresh = React.useCallback(() => {
371
+ const next = active ? zoneSlots(anchor.current) : [];
372
+ setSlots((prev) => prev.length === next.length && prev.every((s, i) => s === next[i]) ? prev : next);
373
+ }, [active]);
374
+ React.useLayoutEffect(refresh);
375
+ React.useEffect(() => {
376
+ const list = findZoneList(anchor.current);
377
+ if (!active || !list || typeof MutationObserver === "undefined") return;
378
+ const observer = new MutationObserver(refresh);
379
+ observer.observe(list, { childList: true, subtree: true });
380
+ return () => observer.disconnect();
381
+ }, [active, refresh]);
382
+ const count = markers.filter(Boolean).length;
383
+ if (!view?.target) return /* @__PURE__ */ jsx("span", { ref: anchor });
384
+ const label = formatMessage(
385
+ {
386
+ id: `${pluginId}.zone.count`,
387
+ defaultMessage: "{count, plural, =0 {No mapped blocks} one {# mapped block} other {# mapped blocks}}"
388
+ },
389
+ { count }
390
+ );
391
+ return /* @__PURE__ */ jsxs("span", { ref: anchor, style: { display: "inline-flex" }, children: [
392
+ /* @__PURE__ */ jsx(ModalTrigger, { label: `${label}. Open details`, uid: view.target.uid, documentId: view.target.documentId, locale: view.locale, view, children: /* @__PURE__ */ jsx(Badge, { "aria-label": label, "data-testid": "experience-zone-count", children: /* @__PURE__ */ jsxs(Flex, { gap: 1, style: { whiteSpace: "nowrap" }, children: [
393
+ /* @__PURE__ */ jsx(Eye, { width: "1rem", height: "1rem", "aria-hidden": true }),
394
+ label
395
+ ] }) }) }),
396
+ markers.map((card, i) => card && slots[i] ? createPortal(/* @__PURE__ */ jsx(BlockMarker, { card, view }), slots[i], `m-${i}`) : null)
397
+ ] });
398
+ };
399
+ const withMarkers = (field) => {
400
+ if (field.name !== CONTENT_ZONE || field.type !== "dynamiczone") return field;
401
+ return {
402
+ ...field,
403
+ labelAction: field.labelAction ? /* @__PURE__ */ jsxs(Flex, { gap: 1, children: [
404
+ field.labelAction,
405
+ /* @__PURE__ */ jsx(BlockMarkers, {})
406
+ ] }) : /* @__PURE__ */ jsx(BlockMarkers, {})
407
+ };
408
+ };
409
+ const mutateEditViewHook = (args) => {
410
+ const { layout } = args;
411
+ if (!isTargetType(layout?.options)) return args;
412
+ return {
413
+ ...args,
414
+ layout: {
415
+ ...layout,
416
+ layout: layout.layout.map((panel) => panel.map((row) => row.map(withMarkers)))
417
+ }
418
+ };
419
+ };
420
+ const index = {
421
+ register(app) {
422
+ app.registerPlugin({
423
+ id: pluginId,
424
+ initializer: Initializer,
425
+ isReady: false,
426
+ name: pluginId
427
+ });
428
+ },
429
+ bootstrap(app) {
430
+ const contentManager = app.getPlugin("content-manager");
431
+ if (contentManager) {
432
+ const cm = contentManager.apis;
433
+ cm.addDocumentHeaderAction([ExperienceHeaderAction]);
434
+ }
435
+ app.registerHook("Admin/CM/pages/EditView/mutate-edit-view-layout", mutateEditViewHook);
436
+ },
437
+ // English only for now.
438
+ async registerTrads({ locales }) {
439
+ const en = (await import("../_chunks/en-8ms9Hfxr.mjs")).default;
440
+ return locales.map((locale) => ({
441
+ locale,
442
+ data: locale === "en" ? en : {}
443
+ }));
444
+ }
445
+ };
446
+ export {
447
+ index as default
448
+ };
@@ -0,0 +1,13 @@
1
+ import type { InspectView } from './types';
2
+ /** `useFetchClient().get`, injected so this module stays free of admin imports (and testable). Read-only: GET only. */
3
+ export type GetFn = (url: string, config?: {
4
+ params?: Record<string, unknown>;
5
+ }) => Promise<{
6
+ data: any;
7
+ }>;
8
+ /** Requests for the same document within this window share one response (header badge + markers). */
9
+ export declare const INSPECT_TTL_MS = 5000;
10
+ export declare const inspectUrl: (uid: string, documentId: string | null | undefined) => string;
11
+ export declare function fetchInspect(get: GetFn, uid: string, documentId: string | null | undefined, locale: string | null | undefined, now?: number): Promise<InspectView>;
12
+ /** Test helper. */
13
+ export declare function clearCaches(): void;
@@ -0,0 +1,93 @@
1
+ import type { Experiment } from '@zachariaz/experience-context-core';
2
+ /** Shapes returned by the plugin's read-only admin API (`GET /inspect`, server/src/admin-api/inspect.ts). */
3
+ export interface CreatedVia {
4
+ label: string;
5
+ source: string | null;
6
+ actor: string | null;
7
+ date: string | null;
8
+ correlationId: string | null;
9
+ }
10
+ export interface BlockCard {
11
+ blockKey: string;
12
+ index: number | null;
13
+ componentUid: string | null;
14
+ title: string | null;
15
+ heading: string;
16
+ role: 'default' | 'variation' | 'outcome' | 'concepts';
17
+ sectionKey: string | null;
18
+ variantKey: string | null;
19
+ status: 'active' | 'inactive' | 'orphaned' | null;
20
+ about: string[];
21
+ intendedFor: string[];
22
+ /** `split`: the traffic split, e.g. `a 90% · b 10%`. */
23
+ experiment: {
24
+ key: string;
25
+ outcome: string;
26
+ name: string | null;
27
+ status: string | null;
28
+ split?: string | null;
29
+ } | null;
30
+ fallback: {
31
+ blockKey: string;
32
+ label: string;
33
+ } | null;
34
+ createdVia: CreatedVia | null;
35
+ validation: string[];
36
+ }
37
+ export interface InspectSummary {
38
+ sections: number;
39
+ variations: number;
40
+ concepts: number;
41
+ annotatedBlocks: number;
42
+ experiments: Array<{
43
+ key: string;
44
+ name: string | null;
45
+ status: string;
46
+ running: boolean;
47
+ }>;
48
+ inactive: number;
49
+ orphaned: number;
50
+ errors: number;
51
+ warnings: number;
52
+ }
53
+ export interface InspectView {
54
+ target: {
55
+ uid: string;
56
+ documentId: string;
57
+ kind: 'singleType' | 'collectionType';
58
+ localized: boolean;
59
+ } | null;
60
+ locale?: string | null;
61
+ summary?: InspectSummary;
62
+ page?: {
63
+ concepts: string[];
64
+ };
65
+ blocks?: Array<{
66
+ index: number;
67
+ blockKey: string | null;
68
+ componentUid: string;
69
+ summary: string;
70
+ title: string | null;
71
+ }>;
72
+ byBlockKey?: Record<string, BlockCard>;
73
+ orphaned?: BlockCard[];
74
+ experiments?: Experiment[];
75
+ validation?: {
76
+ ok: boolean;
77
+ errors: unknown[];
78
+ warnings: unknown[];
79
+ checklist: string[];
80
+ };
81
+ changes?: Array<{
82
+ createdAt: string | null;
83
+ action: string;
84
+ entity: string;
85
+ actor: string | null;
86
+ source: string | null;
87
+ sectionKey: string | null;
88
+ variantKey: string | null;
89
+ blockKey: string | null;
90
+ experimentKey: string | null;
91
+ correlationId: string | null;
92
+ }>;
93
+ }
@@ -0,0 +1,3 @@
1
+ import type { InspectView } from './types';
2
+ /** The edit view's inspection data. `skip` for non-target types. 403 and errors yield `null`. */
3
+ export declare function useInspect(uid: string | null | undefined, documentId: string | null | undefined, locale: string | null | undefined, skip?: boolean): InspectView | null | undefined;
@@ -0,0 +1,12 @@
1
+ import * as React from 'react';
2
+ import type { BlockCard, InspectView } from '../api/types';
3
+ /** The marker in a block's header. */
4
+ export declare const BlockMarker: ({ card, view }: {
5
+ card: BlockCard;
6
+ view?: InspectView | null;
7
+ }) => React.JSX.Element;
8
+ /**
9
+ * Label action of the `content` dynamic zone: a count next to the zone's
10
+ * label, plus a marker in the header of each mapped block.
11
+ */
12
+ export declare const BlockMarkers: () => React.JSX.Element;
@@ -0,0 +1,28 @@
1
+ import * as React from 'react';
2
+ import type { BlockCard as Card, InspectView } from '../api/types';
3
+ /**
4
+ * Read-only inspection modal (plan §7.1). It only reads (`GET /inspect`);
5
+ * every change goes through the MCP tools. English only.
6
+ *
7
+ * `focusKey`: open on one block (from its marker); otherwise every mapped
8
+ * block of the document is listed in draft order, then orphaned mappings.
9
+ */
10
+ export interface ExperienceModalProps {
11
+ open: boolean;
12
+ onClose: () => void;
13
+ uid: string;
14
+ documentId?: string | null;
15
+ locale?: string | null;
16
+ /** Already loaded data (the edit view has it); otherwise it is fetched. */
17
+ view?: InspectView | null;
18
+ focusKey?: string | null;
19
+ title?: string;
20
+ }
21
+ export declare const BlockCard: ({ card }: {
22
+ card: Card;
23
+ }) => React.JSX.Element;
24
+ export declare const ModalBody: ({ view, focusKey }: {
25
+ view: InspectView;
26
+ focusKey?: string | null;
27
+ }) => React.JSX.Element;
28
+ export declare const ExperienceModal: ({ open, onClose, uid, documentId, locale, view: given, focusKey, title }: ExperienceModalProps) => React.JSX.Element;
@@ -0,0 +1,19 @@
1
+ import * as React from 'react';
2
+ import { useIntl } from 'react-intl';
3
+ import type { InspectSummary, InspectView } from '../api/types';
4
+ import type { HeaderActionComponent } from '@strapi/content-manager/strapi-admin';
5
+ type FormatMessage = ReturnType<typeof useIntl>['formatMessage'];
6
+ /** "Experience · 2 sections · 3 variations · 1 experiment running · 2 concepts". */
7
+ export declare function headerText(summary: InspectSummary, formatMessage: FormatMessage): string;
8
+ /** One tertiary button that opens the read-only modal. */
9
+ export declare const HeaderBadgeContent: ({ summary, view }: {
10
+ summary: InspectSummary;
11
+ view?: InspectView | null;
12
+ }) => React.JSX.Element;
13
+ /**
14
+ * Edit view header action: sections, variations, running experiments and
15
+ * concepts in one read-only button. Hidden for non-target types, documents
16
+ * without mappings and users without access (the API answers 403).
17
+ */
18
+ export declare const ExperienceHeaderAction: HeaderActionComponent;
19
+ export {};
@@ -0,0 +1,5 @@
1
+ type InitializerProps = {
2
+ setPlugin: (id: string) => void;
3
+ };
4
+ export declare const Initializer: ({ setPlugin }: InitializerProps) => null;
5
+ export {};
@@ -0,0 +1,10 @@
1
+ import * as React from 'react';
2
+ import { type ExperienceModalProps } from './ExperienceModal';
3
+ /**
4
+ * Wraps a badge or marker in a plain button that opens the read-only modal.
5
+ * Clicks stop here so they don't toggle a block's accordion.
6
+ */
7
+ export declare const ModalTrigger: ({ children, label, ...modal }: Omit<ExperienceModalProps, 'open' | 'onClose'> & {
8
+ children: React.ReactNode;
9
+ label: string;
10
+ }) => React.JSX.Element;
@@ -0,0 +1,7 @@
1
+ import type { EditLayout } from '@strapi/content-manager/strapi-admin';
2
+ interface MutateEditViewArgs {
3
+ layout: EditLayout;
4
+ query?: unknown;
5
+ }
6
+ export declare const mutateEditViewHook: (args: MutateEditViewArgs) => MutateEditViewArgs;
7
+ export {};
@@ -0,0 +1,17 @@
1
+ import type { StrapiApp } from '@strapi/strapi/admin';
2
+ /**
3
+ * Read-only Content Manager inspection (plan §7.1): a header badge and
4
+ * block markers in the edit view, both opening the inspection modal. No
5
+ * write affordance anywhere: every change goes through the MCP tools.
6
+ */
7
+ declare const _default: {
8
+ register(app: StrapiApp): void;
9
+ bootstrap(app: StrapiApp): void;
10
+ registerTrads({ locales }: {
11
+ locales: string[];
12
+ }): Promise<{
13
+ locale: string;
14
+ data: {};
15
+ }[]>;
16
+ };
17
+ export default _default;