@preprio/toolkit 0.6.0-alpha.8 → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +111 -1363
  2. package/dist/astro/index.cjs +1555 -182
  3. package/dist/astro/index.d.cts +201 -1
  4. package/dist/astro/index.d.ts +201 -1
  5. package/dist/astro/index.js +1557 -29
  6. package/dist/{chunk-ATPB7GEC.js → chunk-33GWVTRJ.js} +1 -1
  7. package/dist/chunk-A2J7R4LR.js +256 -0
  8. package/dist/{chunk-T7ESBVBI.js → chunk-DSJ22P6J.js} +6 -1
  9. package/dist/chunk-KM2GME62.js +1255 -0
  10. package/dist/chunk-UTKH7DOI.js +58 -0
  11. package/dist/chunk-V7MCHPE7.js +85 -0
  12. package/dist/{chunk-2QGUP7VQ.js → chunk-WBMN4L7G.js} +1680 -579
  13. package/dist/chunk-Y7JWV7WV.js +374 -0
  14. package/dist/codegen/index.cjs +82 -0
  15. package/dist/codegen/index.d.cts +70 -0
  16. package/dist/codegen/index.d.ts +70 -0
  17. package/dist/codegen/index.js +64 -0
  18. package/dist/index.cjs +3729 -553
  19. package/dist/index.d.cts +403 -19
  20. package/dist/index.d.ts +403 -19
  21. package/dist/index.js +345 -24
  22. package/dist/live-preview-HCBNBC6C.js +19 -0
  23. package/dist/nextjs/components.cjs +1872 -729
  24. package/dist/nextjs/components.d.cts +5 -51
  25. package/dist/nextjs/components.d.ts +5 -51
  26. package/dist/nextjs/components.js +8 -274
  27. package/dist/nextjs/index.cjs +1228 -181
  28. package/dist/nextjs/index.d.cts +247 -92
  29. package/dist/nextjs/index.d.ts +247 -92
  30. package/dist/nextjs/index.js +1629 -111
  31. package/dist/nextjs/live-action.cjs +298 -0
  32. package/dist/nextjs/live-action.d.cts +12 -0
  33. package/dist/nextjs/live-action.d.ts +12 -0
  34. package/dist/nextjs/live-action.js +68 -0
  35. package/dist/nextjs/live.cjs +2010 -0
  36. package/dist/nextjs/live.d.cts +54 -0
  37. package/dist/nextjs/live.d.ts +54 -0
  38. package/dist/nextjs/live.js +287 -0
  39. package/dist/nuxt/chunk-5RBZPRQN.js +350 -0
  40. package/dist/nuxt/chunk-LUKVPOJ2.js +32 -0
  41. package/dist/nuxt/index.cjs +15 -16
  42. package/dist/nuxt/index.d.cts +167 -6
  43. package/dist/nuxt/index.d.ts +167 -6
  44. package/dist/nuxt/index.js +402 -15
  45. package/dist/nuxt/live-preview-KO4IKWTX.js +1234 -0
  46. package/dist/nuxt/live.cjs +1928 -0
  47. package/dist/nuxt/live.d.cts +45 -0
  48. package/dist/nuxt/live.d.ts +45 -0
  49. package/dist/nuxt/live.js +216 -0
  50. package/dist/{types-BYH9XqmN.d.cts → pixel-DqU7NvgW.d.cts} +102 -5
  51. package/dist/{types-BYH9XqmN.d.ts → pixel-DqU7NvgW.d.ts} +102 -5
  52. package/dist/react/components.cjs +1865 -480
  53. package/dist/react/components.d.cts +43 -8
  54. package/dist/react/components.d.ts +43 -8
  55. package/dist/react/components.js +1865 -480
  56. package/dist/sveltekit/chunk-5RBZPRQN.js +350 -0
  57. package/dist/sveltekit/chunk-LUKVPOJ2.js +32 -0
  58. package/dist/sveltekit/index.cjs +15 -16
  59. package/dist/sveltekit/index.d.cts +111 -10
  60. package/dist/sveltekit/index.d.ts +111 -10
  61. package/dist/sveltekit/index.js +398 -15
  62. package/dist/sveltekit/live-preview-KO4IKWTX.js +1234 -0
  63. package/dist/sveltekit/live.cjs +1940 -0
  64. package/dist/sveltekit/live.d.cts +61 -0
  65. package/dist/sveltekit/live.d.ts +61 -0
  66. package/dist/sveltekit/live.js +220 -0
  67. package/package.json +132 -71
  68. package/src/astro/PreprToolbar.astro +7 -1
  69. package/src/astro/PreprTrackingPixel.astro +2 -4
  70. package/src/nuxt/PreprToolbar.vue +12 -1
  71. package/src/nuxt/PreprTrackingPixel.vue +2 -4
  72. package/src/sveltekit/PreprToolbar.svelte +17 -2
  73. package/src/sveltekit/PreprTrackingPixel.svelte +2 -4
  74. package/dist/astro/chunk-R2YPGDVU.js +0 -173
  75. package/dist/astro/graphql.cjs +0 -1078
  76. package/dist/astro/graphql.d.cts +0 -300
  77. package/dist/astro/graphql.d.ts +0 -300
  78. package/dist/astro/graphql.js +0 -984
  79. package/dist/astro/index-XT_z-RYT.d.cts +0 -130
  80. package/dist/astro/index-XT_z-RYT.d.ts +0 -130
  81. package/dist/chunk-3NCEVJJ3.js +0 -10
  82. package/dist/chunk-OY7OKO6Q.js +0 -499
  83. package/dist/chunk-S5RWVMDJ.js +0 -148
  84. package/dist/graphql/codegen.cjs +0 -557
  85. package/dist/graphql/codegen.d.cts +0 -23
  86. package/dist/graphql/codegen.d.ts +0 -23
  87. package/dist/graphql/codegen.js +0 -99
  88. package/dist/graphql.cjs +0 -1020
  89. package/dist/graphql.d.cts +0 -335
  90. package/dist/graphql.d.ts +0 -335
  91. package/dist/graphql.js +0 -448
  92. package/dist/nextjs/chunk-O2SBSBDG.js +0 -549
  93. package/dist/nextjs/graphql.cjs +0 -1811
  94. package/dist/nextjs/graphql.d.cts +0 -498
  95. package/dist/nextjs/graphql.d.ts +0 -498
  96. package/dist/nextjs/graphql.js +0 -1397
  97. package/dist/nextjs/server-BL-sqZvu.d.cts +0 -156
  98. package/dist/nextjs/server-BL-sqZvu.d.ts +0 -156
  99. package/dist/nuxt/chunk-SX3MSVPK.js +0 -417
  100. package/dist/nuxt/graphql.cjs +0 -1085
  101. package/dist/nuxt/graphql.d.cts +0 -297
  102. package/dist/nuxt/graphql.d.ts +0 -297
  103. package/dist/nuxt/graphql.js +0 -985
  104. package/dist/nuxt/server-8v6OHbsw.d.cts +0 -158
  105. package/dist/nuxt/server-8v6OHbsw.d.ts +0 -158
  106. package/dist/pixel-DwW7cXJm.d.cts +0 -49
  107. package/dist/pixel-DwW7cXJm.d.ts +0 -49
  108. package/dist/server-Brr1UgtW.d.ts +0 -59
  109. package/dist/server-DJuS3YU0.d.cts +0 -59
  110. package/dist/sveltekit/chunk-UOASSHZO.js +0 -413
  111. package/dist/sveltekit/graphql.cjs +0 -1091
  112. package/dist/sveltekit/graphql.d.cts +0 -302
  113. package/dist/sveltekit/graphql.d.ts +0 -302
  114. package/dist/sveltekit/graphql.js +0 -991
  115. package/dist/sveltekit/server-CO847mEV.d.cts +0 -98
  116. package/dist/sveltekit/server-CO847mEV.d.ts +0 -98
package/dist/index.cjs CHANGED
@@ -23,6 +23,7 @@ __export(src_exports, {
23
23
  PreprError: () => PreprError,
24
24
  PreprToolbarElement: () => PreprToolbarElement,
25
25
  VERSION: () => VERSION,
26
+ annotateEditLinks: () => annotateEditLinks,
26
27
  createPreprPreview: () => createPreprPreview,
27
28
  createToolbarStore: () => createToolbarStore,
28
29
  definePreprToolbar: () => definePreprToolbar,
@@ -33,19 +34,24 @@ __export(src_exports, {
33
34
  getPreprHeadersFromHeaders: () => getPreprHeadersFromHeaders,
34
35
  getPreprUUIDFromHeaders: () => getPreprUUIDFromHeaders,
35
36
  getToolbarPropsFromHeaders: () => getToolbarPropsFromHeaders,
36
- isPersonalizedResponse: () => isPersonalizedResponse,
37
37
  loadTrackingPixel: () => loadTrackingPixel,
38
+ normalizeQuery: () => normalizeQuery,
39
+ parsePatchLog: () => parsePatchLog,
40
+ previewAttrs: () => previewAttrs,
38
41
  processPreprRequest: () => processPreprRequest,
42
+ readLiveLogFromRequest: () => readLiveLogFromRequest,
39
43
  resolveFeatures: () => resolveFeatures,
40
44
  setTrackingParam: () => setTrackingParam,
45
+ startHtmlLivePreview: () => startHtmlLivePreview,
41
46
  stegaClean: () => stegaClean,
47
+ stegaTarget: () => stegaTarget,
42
48
  trackEvent: () => trackEvent,
43
49
  validatePreprToken: () => validatePreprToken
44
50
  });
45
51
  module.exports = __toCommonJS(src_exports);
46
52
 
47
53
  // src/version.ts
48
- var VERSION = "0.6.0-alpha.8";
54
+ var VERSION = "1.0.0-rc.1";
49
55
 
50
56
  // src/core/features.ts
51
57
  function isEnabled(config) {
@@ -76,6 +82,23 @@ var PARAM_SEGMENT = "prepr_preview_segment";
76
82
  var PARAM_VARIANT = "prepr_preview_ab";
77
83
  var PARAM_HIDE_BAR = "prepr_hide_bar";
78
84
  var ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;
85
+ var HEADER_LIVE_RENDER = "x-prepr-live";
86
+ var ATTR_ENCODED = "data-prepr-encoded";
87
+ var ATTR_ID = "data-prepr-id";
88
+ var ATTR_FIELD = "data-prepr-field";
89
+ var ATTR_LOCALE = "data-prepr-locale";
90
+ var ATTR_HREF = "data-prepr-href";
91
+ var ENCODED_SELECTOR = `[${ATTR_ENCODED}]`;
92
+ var TOOLBAR_TAG = "prepr-toolbar";
93
+ var SEGMENT_ALL_OTHER_USERS = "all_other_users";
94
+ var EVENT_INIT = "prepr:initVE";
95
+ var EVENT_REFERENCES = "prepr:references";
96
+ var EVENT_GET_SCROLL_POSITION = "prepr:getScrollPosition";
97
+ var EVENT_SCROLL_TO_FIELD = "prepr:scrollToField";
98
+ var EVENT_ALLOW_NAVIGATION = "prepr:allowNavigation";
99
+ var EVENT_ITEM_CHANGED = "prepr:itemChanged";
100
+ var EVENT_FIELD_CHANGE = "prepr:fieldChange";
101
+ var EVENT_LIST_CHANGE = "prepr:listChange";
79
102
 
80
103
  // src/core/cookies.ts
81
104
  function getCookie(name) {
@@ -83,7 +106,11 @@ function getCookie(name) {
83
106
  const match = document.cookie.split("; ").find((row) => row.startsWith(`${name}=`));
84
107
  if (!match) return null;
85
108
  const value = match.slice(name.length + 1);
86
- return decodeURIComponent(value);
109
+ try {
110
+ return decodeURIComponent(value);
111
+ } catch {
112
+ return value;
113
+ }
87
114
  }
88
115
  function setCookie(name, value, options = {}) {
89
116
  if (typeof document === "undefined") return;
@@ -117,6 +144,40 @@ function crossSiteCookieOptions() {
117
144
  return { sameSite: "None", secure: true };
118
145
  }
119
146
 
147
+ // src/core/locales/de.json
148
+ var de_default = {
149
+ common: {
150
+ viewingAs: "Ansicht als:",
151
+ user: "Benutzer",
152
+ off: "Aus",
153
+ on: "An",
154
+ reset: "Zur\xFCcksetzen",
155
+ toolbar: "Symbolleiste"
156
+ },
157
+ adaptiveContent: {
158
+ adaptiveContent: "Adaptive Inhalte",
159
+ enablePreview: "Vorschaumodus",
160
+ segment: "Segment",
161
+ ABVariant: "A/B-Variante",
162
+ chooseSegment: "Segment w\xE4hlen",
163
+ searchSegments: "Segmente suchen",
164
+ none: "Keine Segmente",
165
+ allOtherUsers: "Alle anderen Benutzer",
166
+ offDescription: "Die Website als echter Benutzer ansehen (Cookies verwenden)",
167
+ onDescription: "Mit der Symbolleiste Segmente und A/B-Varianten simulieren"
168
+ },
169
+ editingTools: {
170
+ editingTools: "Bearbeitungswerkzeuge",
171
+ editMode: "Bearbeitungsmodus",
172
+ ariaCloseEditMode: "Bearbeitungsmodus schlie\xDFen"
173
+ },
174
+ visualEditor: {
175
+ edit: "Bearbeiten",
176
+ otherItem: "anderes Element",
177
+ linkedItem: "verkn\xFCpftes Element"
178
+ }
179
+ };
180
+
120
181
  // src/core/locales/en.json
121
182
  var en_default = {
122
183
  common: {
@@ -143,6 +204,45 @@ var en_default = {
143
204
  editingTools: "Editing tools",
144
205
  editMode: "Edit mode",
145
206
  ariaCloseEditMode: "Close edit mode"
207
+ },
208
+ visualEditor: {
209
+ edit: "Edit",
210
+ otherItem: "other item",
211
+ linkedItem: "linked item"
212
+ }
213
+ };
214
+
215
+ // src/core/locales/fr.json
216
+ var fr_default = {
217
+ common: {
218
+ viewingAs: "Affichage en tant que :",
219
+ user: "Utilisateur",
220
+ off: "D\xE9sactiv\xE9",
221
+ on: "Activ\xE9",
222
+ reset: "R\xE9initialiser",
223
+ toolbar: "Barre d'outils"
224
+ },
225
+ adaptiveContent: {
226
+ adaptiveContent: "Contenu adaptatif",
227
+ enablePreview: "Mode aper\xE7u",
228
+ segment: "Segment",
229
+ ABVariant: "Variante A/B",
230
+ chooseSegment: "Choisir un segment",
231
+ searchSegments: "Rechercher des segments",
232
+ none: "Aucun segment",
233
+ allOtherUsers: "Tous les autres utilisateurs",
234
+ offDescription: "Voir le site comme un vrai utilisateur (utiliser les cookies)",
235
+ onDescription: "Utilisez la barre d'outils pour simuler des segments et des variantes A/B"
236
+ },
237
+ editingTools: {
238
+ editingTools: "Outils d'\xE9dition",
239
+ editMode: "Mode \xE9dition",
240
+ ariaCloseEditMode: "Fermer le mode \xE9dition"
241
+ },
242
+ visualEditor: {
243
+ edit: "Modifier",
244
+ otherItem: "autre \xE9l\xE9ment",
245
+ linkedItem: "\xE9l\xE9ment li\xE9"
146
246
  }
147
247
  };
148
248
 
@@ -172,13 +272,20 @@ var nl_default = {
172
272
  editingTools: "Editing Tools",
173
273
  editMode: "Edit mode",
174
274
  ariaCloseEditMode: "Edit mode sluiten"
275
+ },
276
+ visualEditor: {
277
+ edit: "Bewerken",
278
+ otherItem: "ander item",
279
+ linkedItem: "gekoppeld item"
175
280
  }
176
281
  };
177
282
 
178
283
  // src/core/i18n.ts
179
284
  var dictionaries = {
180
285
  en: en_default,
181
- nl: nl_default
286
+ nl: nl_default,
287
+ fr: fr_default,
288
+ de: de_default
182
289
  };
183
290
  var LOCALES = Object.keys(dictionaries);
184
291
  function isLocale(value) {
@@ -207,10 +314,27 @@ function t(key, locale, vars) {
207
314
  return key;
208
315
  }
209
316
 
317
+ // src/core/shared-state.ts
318
+ var KEY = /* @__PURE__ */ Symbol.for("@preprio/toolkit:shared-state");
319
+ function initialState() {
320
+ return {
321
+ trustedParentOrigin: null,
322
+ debugEnabled: void 0,
323
+ strictMode: false,
324
+ liveAnnouncedStrict: void 0
325
+ };
326
+ }
327
+ function sharedState() {
328
+ const scope = globalThis;
329
+ return scope[KEY] ?? (scope[KEY] = initialState());
330
+ }
331
+
210
332
  // src/core/utils.ts
211
- var trustedParentOrigin = null;
212
333
  function setTrustedParentOrigin(origin) {
213
- trustedParentOrigin = origin;
334
+ sharedState().trustedParentOrigin = origin;
335
+ }
336
+ function getTrustedParentOrigin() {
337
+ return sharedState().trustedParentOrigin;
214
338
  }
215
339
  function sendPreprEvent(event, data, options) {
216
340
  if (typeof window !== "undefined") {
@@ -223,6 +347,7 @@ function sendPreprEvent(event, data, options) {
223
347
  new CustomEvent("prepr_preview_bar", { detail: message })
224
348
  );
225
349
  if (window.parent && window.parent !== window) {
350
+ const trustedParentOrigin = getTrustedParentOrigin();
226
351
  if (trustedParentOrigin) {
227
352
  window.parent.postMessage(message, trustedParentOrigin);
228
353
  } else if (options?.allowUntrustedTarget) {
@@ -238,13 +363,13 @@ var DebugLogger = class {
238
363
  ...options
239
364
  };
240
365
  }
241
- // A local `enabled` wins; otherwise defer to the global logger so scoped
366
+ // A local `enabled` wins; otherwise defer to the shared flag so scoped
242
367
  // loggers created before initDebugLogger() still pick up the setting.
243
368
  isEnabled() {
244
369
  if (this.options.enabled !== void 0) {
245
370
  return this.options.enabled;
246
371
  }
247
- return globalDebugLogger?.options?.enabled ?? false;
372
+ return sharedState().debugEnabled ?? false;
248
373
  }
249
374
  log(message, ...args) {
250
375
  if (!this.isEnabled()) return;
@@ -256,66 +381,62 @@ var DebugLogger = class {
256
381
  const prefix = this.options.prefix;
257
382
  console.warn(`${prefix} ${message}`, ...args);
258
383
  }
259
- error(message, ...args) {
260
- if (!this.isEnabled()) return;
261
- const prefix = this.options.prefix;
262
- console.error(`${prefix} ${message}`, ...args);
263
- }
264
384
  };
265
- var globalDebugLogger = null;
266
385
  function initDebugLogger(enabled = false) {
267
- globalDebugLogger = new DebugLogger({ enabled });
386
+ sharedState().debugEnabled = enabled;
268
387
  }
269
388
  function createScopedLogger(scopeName) {
270
389
  return new DebugLogger({
271
390
  prefix: `[Prepr][${scopeName}]`
272
391
  });
273
392
  }
274
- function throttle(func, delay) {
275
- let timeoutId = null;
276
- let lastExecTime = 0;
277
- const throttledFunc = ((...args) => {
278
- const currentTime = Date.now();
279
- const timeSinceLastExec = currentTime - lastExecTime;
280
- if (timeSinceLastExec >= delay) {
281
- func(...args);
282
- lastExecTime = currentTime;
283
- } else {
284
- if (timeoutId) {
285
- clearTimeout(timeoutId);
286
- }
287
- timeoutId = setTimeout(() => {
288
- func(...args);
289
- lastExecTime = Date.now();
290
- timeoutId = null;
291
- }, delay - timeSinceLastExec);
292
- }
293
- });
294
- throttledFunc.cancel = () => {
295
- if (timeoutId) {
296
- clearTimeout(timeoutId);
297
- timeoutId = null;
298
- }
299
- };
300
- return throttledFunc;
393
+
394
+ // src/core/iframe-bridge.ts
395
+ var debug = createScopedLogger("iframe-bridge");
396
+ var MAX_REFERENCES = 500;
397
+ var MAX_HREF_LENGTH = 8192;
398
+ var MAX_ASSETS = 500;
399
+ var MAX_ASSET_KEY_LENGTH = 2048;
400
+ var MAX_ASSET_FIELD_LENGTH = 512;
401
+ function parseIds(value) {
402
+ if (!Array.isArray(value)) return void 0;
403
+ return value.slice(0, MAX_REFERENCES).filter((id) => typeof id === "string" && id.length > 0);
301
404
  }
302
- function createElementCache(query, ttl = 1e3) {
303
- let cache = null;
304
- let lastCacheTime = 0;
305
- return () => {
306
- const now = Date.now();
307
- if (!cache || now - lastCacheTime > ttl) {
308
- cache = document.querySelectorAll(query);
309
- lastCacheTime = now;
405
+ function parseReferences(value) {
406
+ if (!Array.isArray(value)) return void 0;
407
+ const list = [];
408
+ for (const entry of value.slice(0, MAX_REFERENCES)) {
409
+ const id = entry?.id;
410
+ const field = entry?.field;
411
+ if (typeof id === "string" && id && typeof field === "string" && field) {
412
+ list.push({ id, field });
310
413
  }
311
- return cache;
312
- };
414
+ }
415
+ return list;
416
+ }
417
+ function boundedString(value, max) {
418
+ return typeof value === "string" && value && value.length <= max ? value : void 0;
419
+ }
420
+ function parseAssets(value) {
421
+ if (!Array.isArray(value)) return void 0;
422
+ const list = [];
423
+ for (const entry of value.slice(0, MAX_ASSETS)) {
424
+ if (!entry || typeof entry !== "object") continue;
425
+ const raw = entry;
426
+ const key = boundedString(raw.key, MAX_ASSET_KEY_LENGTH);
427
+ const field = boundedString(raw.field, MAX_ASSET_FIELD_LENGTH);
428
+ if (!key || !field) continue;
429
+ const entryId = boundedString(raw.entryId, MAX_ASSET_FIELD_LENGTH);
430
+ list.push(entryId ? { key, field, entryId } : { key, field });
431
+ }
432
+ return list;
313
433
  }
314
-
315
- // src/core/iframe-bridge.ts
316
434
  var EDITOR_BASE_DOMAIN = "prepr.io";
317
435
  function isAllowedEditorOrigin(origin, allowed) {
318
- if (allowed) return allowed.includes(origin);
436
+ if (allowed) {
437
+ if (allowed.includes("*")) return origin !== "null";
438
+ return allowed.includes(origin);
439
+ }
319
440
  let url;
320
441
  try {
321
442
  url = new URL(origin);
@@ -330,6 +451,12 @@ function isAllowedEditorOrigin(origin, allowed) {
330
451
  }
331
452
  function createIframeBridge(store, options = {}) {
332
453
  const allowedOrigins = options.allowedEditorOrigins;
454
+ const onScrollToField = options.onScrollToField;
455
+ const onHandshake = options.onHandshake;
456
+ const onReferences = options.onReferences;
457
+ const onAssets = options.onAssets;
458
+ const onAllowNavigation = options.onAllowNavigation;
459
+ const onItemChanged = options.onItemChanged;
333
460
  let parentOrigin = null;
334
461
  const onKeyDown = (event) => {
335
462
  const key = event.key.toLowerCase();
@@ -337,9 +464,13 @@ function createIframeBridge(store, options = {}) {
337
464
  if (blocked) event.preventDefault();
338
465
  };
339
466
  const onMessage = (evt) => {
467
+ if (evt.source !== window.parent) return;
340
468
  const data = evt?.data;
341
- if (data?.event === "prepr:initVE" && !parentOrigin) {
342
- if (!isAllowedEditorOrigin(evt.origin, allowedOrigins)) return;
469
+ if (data?.event === EVENT_INIT && !parentOrigin) {
470
+ if (!isAllowedEditorOrigin(evt.origin, allowedOrigins)) {
471
+ debug.warn("ignored editor handshake from origin", evt.origin);
472
+ return;
473
+ }
343
474
  parentOrigin = evt.origin;
344
475
  setTrustedParentOrigin(parentOrigin);
345
476
  if (data.scrollPosition != null) {
@@ -347,12 +478,84 @@ function createIframeBridge(store, options = {}) {
347
478
  setTimeout(() => window.scrollTo(0, top), 1);
348
479
  }
349
480
  store?.set({ previewMode: true, editMode: data.editMode ?? true });
481
+ const itemId = typeof data.itemId === "string" && data.itemId ? data.itemId : void 0;
482
+ const referencedIds = parseReferences(data.referencedIds);
483
+ const componentIds = parseIds(data.componentIds);
484
+ const uiLocale = isLocale(data.uiLocale) ? data.uiLocale : void 0;
485
+ const navigationGuard = data.navigationGuard === true;
486
+ const assets = parseAssets(data.assets);
487
+ try {
488
+ onHandshake?.({
489
+ ...itemId && { itemId },
490
+ ...referencedIds && { referencedIds },
491
+ ...componentIds && { componentIds },
492
+ ...uiLocale && { uiLocale },
493
+ ...navigationGuard && { navigationGuard },
494
+ ...assets && { assets }
495
+ });
496
+ } catch (error) {
497
+ debug.warn("handshake handler failed", error);
498
+ }
350
499
  }
351
500
  if (!parentOrigin || evt.origin !== parentOrigin) return;
352
- if (data?.event === "prepr:getScrollPosition") {
501
+ if (data?.event === EVENT_REFERENCES) {
502
+ const assets = parseAssets(data.assets);
503
+ if (assets) {
504
+ try {
505
+ onAssets?.(assets);
506
+ } catch (error) {
507
+ debug.warn("assets handler failed", error);
508
+ }
509
+ }
510
+ const referencedIds = parseReferences(data.referencedIds);
511
+ if (!referencedIds) return;
512
+ try {
513
+ onReferences?.(referencedIds, parseIds(data.componentIds));
514
+ } catch (error) {
515
+ debug.warn("references handler failed", error);
516
+ }
517
+ }
518
+ if (data?.event === EVENT_GET_SCROLL_POSITION) {
353
519
  const currentScrollY = window.scrollY || document.documentElement.scrollTop;
354
520
  sendPreprEvent("getScrollPosition", { value: currentScrollY });
355
521
  }
522
+ if (data?.event === EVENT_SCROLL_TO_FIELD) {
523
+ if (typeof data.field !== "string" || !data.field) return;
524
+ if (data.id !== void 0 && typeof data.id !== "string") return;
525
+ const block = typeof data.block === "number" && Number.isInteger(data.block) ? data.block : void 0;
526
+ const entryId = typeof data.entryId === "string" && data.entryId ? data.entryId : void 0;
527
+ const fieldById = typeof data.fieldById === "string" && data.fieldById ? data.fieldById : void 0;
528
+ try {
529
+ onScrollToField?.({
530
+ field: data.field,
531
+ id: data.id,
532
+ block,
533
+ entryId,
534
+ fieldById
535
+ });
536
+ } catch (error) {
537
+ debug.warn("scrollToField handler failed", error);
538
+ }
539
+ }
540
+ if (data?.event === EVENT_ALLOW_NAVIGATION) {
541
+ const href = data.href;
542
+ if (typeof href !== "string" || !href || href.length > MAX_HREF_LENGTH) {
543
+ return;
544
+ }
545
+ try {
546
+ onAllowNavigation?.(href);
547
+ } catch (error) {
548
+ debug.warn("allowNavigation handler failed", error);
549
+ }
550
+ }
551
+ if (data?.event === EVENT_ITEM_CHANGED) {
552
+ if (typeof data.itemId !== "string" || !data.itemId) return;
553
+ try {
554
+ onItemChanged?.(data.itemId);
555
+ } catch (error) {
556
+ debug.warn("itemChanged handler failed", error);
557
+ }
558
+ }
356
559
  };
357
560
  return {
358
561
  start() {
@@ -377,7 +580,7 @@ var import_stega2 = require("@vercel/stega");
377
580
 
378
581
  // src/core/stega/clean.ts
379
582
  var import_stega = require("@vercel/stega");
380
- var debug = createScopedLogger("stega:clean");
583
+ var debug2 = createScopedLogger("stega:clean");
381
584
  function stegaClean(text) {
382
585
  if (!text) return text;
383
586
  return (0, import_stega.vercelStegaClean)(text);
@@ -390,7 +593,7 @@ function decodeStega(str) {
390
593
  return decoded;
391
594
  }
392
595
  } catch (error) {
393
- debug.log("error decoding stega data", error);
596
+ debug2.log("error decoding stega data", error);
394
597
  const match = str.match(/{"origin.*?}/);
395
598
  if (match) {
396
599
  try {
@@ -399,7 +602,7 @@ function decodeStega(str) {
399
602
  return decodedMatch;
400
603
  }
401
604
  } catch (innerError) {
402
- debug.log("error decoding stega regex match", innerError);
605
+ debug2.log("error decoding stega regex match", innerError);
403
606
  }
404
607
  }
405
608
  }
@@ -408,6 +611,7 @@ function decodeStega(str) {
408
611
 
409
612
  // src/core/stega/dom.ts
410
613
  var IGNORED_ANCESTORS = "script, style, noscript";
614
+ var AUTO_ENTRY_ATTR = "data-prepr-entry-auto";
411
615
  function isIgnoredTextNode(node) {
412
616
  if (node.parentElement?.closest(IGNORED_ANCESTORS)) return true;
413
617
  return !node.textContent?.trim();
@@ -435,64 +639,90 @@ function isRenderedElement(element) {
435
639
  if (!style) return true;
436
640
  return style.visibility !== "hidden" && style.display !== "none";
437
641
  }
642
+ function parseEditHref(href) {
643
+ try {
644
+ const url = new URL(href, window.location.origin);
645
+ return {
646
+ id: url.pathname.split("/").pop() || void 0,
647
+ field: url.searchParams.get("field") || void 0,
648
+ locale: url.searchParams.get("locale") || void 0,
649
+ // Added by the toolkit's `annotateEditLinks`, not by Prepr.
650
+ entry: url.searchParams.get("entry") || void 0
651
+ };
652
+ } catch {
653
+ return {};
654
+ }
655
+ }
656
+ function setOrRemove(element, name, value) {
657
+ if (value) {
658
+ element.setAttribute(name, value);
659
+ } else {
660
+ element.removeAttribute(name);
661
+ }
662
+ }
438
663
  function tagEncodedElement(element, decoded) {
439
- element.setAttribute("data-prepr-encoded", "");
440
- element.setAttribute("data-prepr-href", decoded.href);
664
+ if (isSiteTagged(element)) return false;
665
+ element.setAttribute(ATTR_ENCODED, "");
666
+ element.setAttribute(ATTR_HREF, decoded.href);
441
667
  element.setAttribute("data-prepr-origin", decoded.origin);
668
+ const { id, field, locale, entry } = parseEditHref(decoded.href);
669
+ setOrRemove(element, ATTR_ID, id);
670
+ const fieldHint = element.getAttribute("data-prepr-edit-target")?.trim() || void 0;
671
+ setOrRemove(element, ATTR_FIELD, field ?? fieldHint);
672
+ setOrRemove(element, ATTR_LOCALE, locale);
673
+ const siteEntry = element.hasAttribute("data-prepr-entry-id") && !element.hasAttribute(AUTO_ENTRY_ATTR);
674
+ if (!siteEntry) {
675
+ setOrRemove(element, "data-prepr-entry-id", entry);
676
+ setOrRemove(element, AUTO_ENTRY_ATTR, entry && "true");
677
+ }
678
+ return true;
679
+ }
680
+ function isSiteTagged(element) {
681
+ return element.hasAttribute(ATTR_ENCODED) && !element.hasAttribute(ATTR_HREF);
682
+ }
683
+ function readEditPayload(element) {
684
+ return {
685
+ href: element.getAttribute(ATTR_HREF) ?? "",
686
+ origin: element.getAttribute("data-prepr-origin") ?? "",
687
+ id: element.getAttribute(ATTR_ID) ?? void 0,
688
+ field: element.getAttribute(ATTR_FIELD) ?? void 0,
689
+ locale: element.getAttribute(ATTR_LOCALE) ?? void 0,
690
+ entryId: element.getAttribute("data-prepr-entry-id") || void 0
691
+ };
442
692
  }
443
693
 
444
694
  // src/core/stega/auto-clean.ts
445
- var debug2 = createScopedLogger("stega:auto-clean");
446
- var HYDRATION_RETRY_MS = 100;
695
+ var debug3 = createScopedLogger("stega:auto-clean");
696
+ var cleanedNodes = /* @__PURE__ */ new WeakMap();
447
697
  function createStegaAutoClean(options) {
448
698
  const stripText = options?.enabled ?? true;
449
699
  let observer = null;
450
700
  let processing = false;
451
- let cleaned = /* @__PURE__ */ new WeakMap();
452
701
  let pendingHidden = /* @__PURE__ */ new Set();
453
702
  let pendingDirty = /* @__PURE__ */ new Set();
454
703
  let debounceTimeout = null;
455
- const isHydrated = options?.isHydrated;
456
- let pendingHydration = /* @__PURE__ */ new Set();
457
- let hydrationTimeout = null;
458
- function retryPendingHydration() {
459
- hydrationTimeout = null;
460
- processing = true;
461
- const batch = [...pendingHydration];
462
- pendingHydration.clear();
463
- batch.forEach((textNode) => {
464
- if (textNode.isConnected) cleanTextNode(textNode);
465
- });
466
- processing = false;
467
- }
468
704
  function cleanTextNode(textNode) {
469
705
  if (isIgnoredTextNode(textNode)) return false;
470
- if (isHydrated && !isHydrated(textNode)) {
471
- pendingHydration.add(textNode);
472
- hydrationTimeout ?? (hydrationTimeout = setTimeout(
473
- retryPendingHydration,
474
- HYDRATION_RETRY_MS
475
- ));
476
- return false;
477
- }
478
706
  const textContent = textNode.textContent;
479
- const info = cleaned.get(textNode);
707
+ const info = cleanedNodes.get(textNode);
480
708
  const settled = stripText ? info?.cleaned : info?.original;
481
709
  if (info && textContent === settled) {
482
710
  if (!info.decoded) return false;
483
711
  const shown = resolveEditTarget(textNode);
484
- if (!shown) return false;
712
+ if (!shown) {
713
+ pendingHidden.add(textNode);
714
+ return false;
715
+ }
485
716
  pendingHidden.delete(textNode);
486
- if (shown.hasAttribute("data-prepr-encoded")) return false;
487
- tagEncodedElement(shown, info.decoded);
488
- return true;
717
+ if (shown.hasAttribute(ATTR_ENCODED)) return false;
718
+ return tagEncodedElement(shown, info.decoded);
489
719
  }
490
720
  try {
491
721
  const { cleaned: stripped, encoded } = (0, import_stega2.vercelStegaSplit)(textContent);
492
722
  if (!encoded || stripped === textContent) return false;
493
723
  const decoded = decodeStega(textContent);
494
724
  if (!decoded?.href && !stripText) return false;
495
- cleaned.set(textNode, {
725
+ cleanedNodes.set(textNode, {
496
726
  original: textContent,
497
727
  cleaned: stripped,
498
728
  decoded: decoded?.href ? decoded : null
@@ -502,12 +732,11 @@ function createStegaAutoClean(options) {
502
732
  const target = resolveEditTarget(textNode);
503
733
  if (target) {
504
734
  pendingHidden.delete(textNode);
505
- tagEncodedElement(target, decoded);
506
- return true;
735
+ return tagEncodedElement(target, decoded);
507
736
  }
508
737
  pendingHidden.add(textNode);
509
738
  } catch (error) {
510
- debug2.log("error cleaning text node", error);
739
+ debug3.log("error cleaning text node", error);
511
740
  }
512
741
  return false;
513
742
  }
@@ -534,7 +763,7 @@ function createStegaAutoClean(options) {
534
763
  }
535
764
  if (mutation.type === "characterData" && mutation.target.nodeType === Node.TEXT_NODE) {
536
765
  const textNode = mutation.target;
537
- const info = cleaned.get(textNode);
766
+ const info = cleanedNodes.get(textNode);
538
767
  const text = textNode.textContent ?? "";
539
768
  const settled = stripText ? info?.cleaned : info?.original;
540
769
  if (text !== settled && (0, import_stega2.vercelStegaSplit)(text).encoded) {
@@ -577,7 +806,16 @@ function createStegaAutoClean(options) {
577
806
  retryPendingHidden();
578
807
  }, 50);
579
808
  }
809
+ let resizeTimeout = null;
810
+ function handleResize() {
811
+ if (pendingHidden.size === 0 || resizeTimeout) return;
812
+ resizeTimeout = setTimeout(() => {
813
+ resizeTimeout = null;
814
+ retryPendingHidden();
815
+ }, 100);
816
+ }
580
817
  function setupObserver() {
818
+ window.addEventListener("resize", handleResize, { passive: true });
581
819
  observer = new MutationObserver(handleMutations);
582
820
  observer.observe(document.body, {
583
821
  childList: true,
@@ -593,40 +831,471 @@ function createStegaAutoClean(options) {
593
831
  if (observer || typeof window === "undefined") return;
594
832
  scanAndClean();
595
833
  setupObserver();
596
- debug2.log("stega auto-clean started");
834
+ debug3.log("stega auto-clean started");
597
835
  }
598
836
  function stop() {
599
837
  if (debounceTimeout) {
600
838
  clearTimeout(debounceTimeout);
601
839
  debounceTimeout = null;
602
840
  }
603
- if (hydrationTimeout) {
604
- clearTimeout(hydrationTimeout);
605
- hydrationTimeout = null;
841
+ if (resizeTimeout) {
842
+ clearTimeout(resizeTimeout);
843
+ resizeTimeout = null;
606
844
  }
607
845
  if (observer) {
608
846
  observer.disconnect();
609
847
  observer = null;
848
+ window.removeEventListener("resize", handleResize);
610
849
  }
611
- cleaned = /* @__PURE__ */ new WeakMap();
612
850
  pendingHidden = /* @__PURE__ */ new Set();
613
851
  pendingDirty = /* @__PURE__ */ new Set();
614
- pendingHydration = /* @__PURE__ */ new Set();
615
- debug2.log("stega auto-clean stopped");
852
+ debug3.log("stega auto-clean stopped");
616
853
  }
617
854
  return { start, stop };
618
855
  }
619
856
 
857
+ // src/core/visual-editor/overlay.ts
858
+ var HOST_TAG = "prepr-visual-editor";
859
+ var SCROLL_SETTLE_MS = 120;
860
+ var LABEL_SPACE_PX = 22;
861
+ var BOX_PADDING_PX = 3;
862
+ var LABEL_MARGIN_PX = 4;
863
+ var PROBE_POINTS = [
864
+ [0.5, 0.5],
865
+ [0.15, 0.2],
866
+ [0.85, 0.2],
867
+ [0.15, 0.8],
868
+ [0.85, 0.8]
869
+ ];
870
+ function overlapsBox(area, rect) {
871
+ return area.left < rect.right + BOX_PADDING_PX && area.right > rect.left - BOX_PADDING_PX && area.top < rect.bottom + BOX_PADDING_PX && area.bottom > rect.top - BOX_PADDING_PX;
872
+ }
873
+ function overlaps(a2, b2) {
874
+ return a2.left < b2.right && b2.left < a2.right && a2.top < b2.bottom && b2.top < a2.bottom;
875
+ }
876
+ function coverOf(hit, target, x2, y2) {
877
+ let cover = hit.getBoundingClientRect();
878
+ for (let el = hit.parentElement; el && !el.contains(target) && el !== document.body; el = el.parentElement) {
879
+ const r2 = el.getBoundingClientRect();
880
+ if (x2 < r2.left || x2 >= r2.right || y2 < r2.top || y2 >= r2.bottom) break;
881
+ cover = r2;
882
+ }
883
+ return cover;
884
+ }
885
+ function mergeAreas(areas) {
886
+ const merged = areas.slice();
887
+ for (let i2 = 0; i2 < merged.length; i2++) {
888
+ for (let j2 = i2 + 1; j2 < merged.length; j2++) {
889
+ if (!overlaps(merged[i2], merged[j2])) continue;
890
+ merged[i2] = {
891
+ left: Math.min(merged[i2].left, merged[j2].left),
892
+ top: Math.min(merged[i2].top, merged[j2].top),
893
+ right: Math.max(merged[i2].right, merged[j2].right),
894
+ bottom: Math.max(merged[i2].bottom, merged[j2].bottom)
895
+ };
896
+ merged.splice(j2, 1);
897
+ j2 = i2;
898
+ }
899
+ }
900
+ return merged;
901
+ }
902
+ function findCovers(target, rect) {
903
+ const width = window.innerWidth;
904
+ const height = window.innerHeight;
905
+ const covers = [];
906
+ const seen = /* @__PURE__ */ new Set();
907
+ let probed = false;
908
+ let reached = false;
909
+ for (const [fx, fy] of PROBE_POINTS) {
910
+ const x2 = rect.left + rect.width * fx;
911
+ const y2 = rect.top + rect.height * fy;
912
+ if (x2 < 0 || y2 < 0 || x2 >= width || y2 >= height) continue;
913
+ probed = true;
914
+ const hit = document.elementFromPoint(x2, y2);
915
+ if (!hit || hit === target || target.contains(hit)) {
916
+ reached = true;
917
+ continue;
918
+ }
919
+ if (seen.has(hit)) continue;
920
+ seen.add(hit);
921
+ if (covers.some(
922
+ (c2) => x2 >= c2.left && x2 < c2.right && y2 >= c2.top && y2 < c2.bottom
923
+ )) {
924
+ continue;
925
+ }
926
+ covers.push(coverOf(hit, target, x2, y2));
927
+ }
928
+ if (!probed) return [];
929
+ return reached ? mergeAreas(covers) : null;
930
+ }
931
+ function clipPath(x2, y2, covers) {
932
+ const far = 1e5;
933
+ const points = [
934
+ `${-far}px ${-far}px`,
935
+ `${far}px ${-far}px`,
936
+ `${far}px ${far}px`,
937
+ `${-far}px ${far}px`,
938
+ `${-far}px ${-far}px`
939
+ ];
940
+ for (const c2 of covers) {
941
+ const l2 = c2.left - x2;
942
+ const t3 = c2.top - y2;
943
+ const r2 = c2.right - x2;
944
+ const b2 = c2.bottom - y2;
945
+ points.push(
946
+ `${l2}px ${t3}px`,
947
+ `${r2}px ${t3}px`,
948
+ `${r2}px ${b2}px`,
949
+ `${l2}px ${b2}px`,
950
+ `${l2}px ${t3}px`,
951
+ `${-far}px ${-far}px`
952
+ );
953
+ }
954
+ return `polygon(evenodd, ${points.join(", ")})`;
955
+ }
956
+ var STYLES = `
957
+ :host {
958
+ all: initial;
959
+ position: fixed;
960
+ inset: 0;
961
+ pointer-events: none;
962
+ z-index: 2147483646;
963
+ contain: strict;
964
+ }
965
+ .box {
966
+ position: absolute;
967
+ top: 0;
968
+ left: 0;
969
+ box-sizing: border-box;
970
+ border-radius: 6px;
971
+ opacity: 0;
972
+ will-change: transform, width, height;
973
+ transition:
974
+ transform 180ms cubic-bezier(0.2, 0.8, 0.2, 1),
975
+ width 180ms cubic-bezier(0.2, 0.8, 0.2, 1),
976
+ height 180ms cubic-bezier(0.2, 0.8, 0.2, 1),
977
+ opacity 140ms ease;
978
+ }
979
+ .box[data-visible] { opacity: 1; }
980
+ .box[data-instant], :host([data-scrolling]) .box {
981
+ transition: opacity 140ms ease;
982
+ }
983
+ .hover {
984
+ border: 1.5px solid rgba(79, 70, 229, 0.9);
985
+ background: rgba(79, 70, 229, 0.06);
986
+ }
987
+ .selected {
988
+ border: 2px solid #4f46e5;
989
+ box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.18);
990
+ }
991
+ .label {
992
+ position: absolute;
993
+ left: -2px;
994
+ bottom: 100%;
995
+ margin-bottom: 4px;
996
+ padding: 3px 7px;
997
+ border-radius: 5px;
998
+ background: #4f46e5;
999
+ color: #fff;
1000
+ font: 500 11px/1.3 ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
1001
+ letter-spacing: 0.01em;
1002
+ white-space: nowrap;
1003
+ display: flex;
1004
+ max-width: 240px;
1005
+ box-shadow: 0 1px 3px rgba(15, 23, 42, 0.25);
1006
+ }
1007
+ .text {
1008
+ min-width: 0;
1009
+ overflow: hidden;
1010
+ text-overflow: ellipsis;
1011
+ }
1012
+ .hover .label { background: rgba(79, 70, 229, 0.92); }
1013
+ /* Content of another item than the one open in the editor: still clickable,
1014
+ but visibly not part of the item being edited. */
1015
+ .hover[data-item-kind='other'] {
1016
+ border: 1.5px dashed #a5b4fc;
1017
+ background: rgba(100, 116, 139, 0.05);
1018
+ }
1019
+ .hover[data-item-kind='other'] .label { background: #64748b; }
1020
+ .hover[data-item-kind='referenced'] {
1021
+ border: 1.5px solid #a5b4fc;
1022
+ background: rgba(79, 70, 229, 0.03);
1023
+ }
1024
+ .hover[data-item-kind='referenced'] .label { background: #818cf8; }
1025
+ .box[data-label-covered] .label { visibility: hidden; }
1026
+ .box[data-label-inside] .label {
1027
+ bottom: auto;
1028
+ top: 2px;
1029
+ left: 2px;
1030
+ margin: 0;
1031
+ }
1032
+ /* A clickable hover label (edit mode on the live site). Only while shown, so
1033
+ a fading box never leaves an invisible click target behind. */
1034
+ :host([data-label-action]) .hover[data-visible] .label {
1035
+ pointer-events: auto;
1036
+ cursor: pointer;
1037
+ }
1038
+ :host([data-label-action]) .hover .label::after {
1039
+ content: '\\2197';
1040
+ margin-left: 5px;
1041
+ }
1042
+ :host([data-label-action]) .hover .label:hover { background: #4338ca; }
1043
+ /* Bridges the gap between the label and its element, so the pointer can
1044
+ travel from one to the other without the hover ending on the way. */
1045
+ :host([data-label-action]) .hover .label::before {
1046
+ content: '';
1047
+ position: absolute;
1048
+ left: 0;
1049
+ right: 0;
1050
+ top: 100%;
1051
+ height: ${LABEL_MARGIN_PX + BOX_PADDING_PX + 2}px;
1052
+ }
1053
+ @media (prefers-reduced-motion: reduce) {
1054
+ .box { transition: opacity 80ms linear; }
1055
+ }
1056
+ `;
1057
+ var VisualEditorOverlay = class {
1058
+ constructor(options = {}) {
1059
+ this.host = null;
1060
+ this.hoverBox = null;
1061
+ this.selectedBox = null;
1062
+ this.frame = null;
1063
+ this.scrollTimeout = null;
1064
+ this.resizeObserver = null;
1065
+ this.onLabelClick = options.onLabelClick;
1066
+ }
1067
+ mount() {
1068
+ if (this.host) return;
1069
+ const host = document.createElement(HOST_TAG);
1070
+ const shadow = host.attachShadow({ mode: "open" });
1071
+ const style = document.createElement("style");
1072
+ style.textContent = STYLES;
1073
+ shadow.appendChild(style);
1074
+ this.hoverBox = this.createBox(shadow, "hover");
1075
+ this.selectedBox = this.createBox(shadow, "selected");
1076
+ const onLabelClick = this.onLabelClick;
1077
+ if (onLabelClick) {
1078
+ host.setAttribute("data-label-action", "");
1079
+ const hoverBox = this.hoverBox;
1080
+ hoverBox.label.addEventListener("click", () => {
1081
+ if (hoverBox.target) onLabelClick(hoverBox.target);
1082
+ });
1083
+ }
1084
+ document.documentElement.appendChild(host);
1085
+ this.host = host;
1086
+ if (typeof ResizeObserver !== "undefined") {
1087
+ this.resizeObserver = new ResizeObserver(() => this.schedule());
1088
+ }
1089
+ }
1090
+ unmount() {
1091
+ if (this.frame !== null) cancelAnimationFrame(this.frame);
1092
+ if (this.scrollTimeout) clearTimeout(this.scrollTimeout);
1093
+ this.frame = null;
1094
+ this.scrollTimeout = null;
1095
+ this.resizeObserver?.disconnect();
1096
+ this.resizeObserver = null;
1097
+ this.host?.remove();
1098
+ this.host = null;
1099
+ this.hoverBox = null;
1100
+ this.selectedBox = null;
1101
+ }
1102
+ /**
1103
+ * Whether a pointer event target is this chrome: events from inside the
1104
+ * shadow root reach the page retargeted to its host.
1105
+ */
1106
+ owns(node) {
1107
+ return node !== null && node === this.host;
1108
+ }
1109
+ getHoverTarget() {
1110
+ return this.hoverBox?.target ?? null;
1111
+ }
1112
+ getSelectedTarget() {
1113
+ return this.selectedBox?.target ?? null;
1114
+ }
1115
+ setHover(target, label, options = {}) {
1116
+ if (target) {
1117
+ this.hoverBox?.root.setAttribute(
1118
+ "data-item-kind",
1119
+ options.kind ?? "current"
1120
+ );
1121
+ }
1122
+ this.retarget(this.hoverBox, target, label);
1123
+ }
1124
+ setSelected(target, label) {
1125
+ this.retarget(this.selectedBox, target, label);
1126
+ }
1127
+ /** Call on every scroll; positions follow in the next frame, untransitioned. */
1128
+ onScroll() {
1129
+ if (!this.host) return;
1130
+ this.host.setAttribute("data-scrolling", "");
1131
+ if (this.scrollTimeout) clearTimeout(this.scrollTimeout);
1132
+ this.scrollTimeout = setTimeout(() => {
1133
+ this.host?.removeAttribute("data-scrolling");
1134
+ this.scrollTimeout = null;
1135
+ }, SCROLL_SETTLE_MS);
1136
+ this.schedule();
1137
+ }
1138
+ /** Re-measure both boxes in the next animation frame. */
1139
+ schedule() {
1140
+ if (this.frame !== null || !this.host) return;
1141
+ this.frame = requestAnimationFrame(() => {
1142
+ this.frame = null;
1143
+ this.render();
1144
+ });
1145
+ }
1146
+ createBox(shadow, kind) {
1147
+ const root = document.createElement("div");
1148
+ root.className = `box ${kind}`;
1149
+ const label = document.createElement("div");
1150
+ label.className = "label";
1151
+ const text = document.createElement("span");
1152
+ text.className = "text";
1153
+ label.appendChild(text);
1154
+ root.appendChild(label);
1155
+ shadow.appendChild(root);
1156
+ return { root, label, text, target: null };
1157
+ }
1158
+ retarget(box, target, label) {
1159
+ if (!box || box.target === target) return;
1160
+ const previous = box.target;
1161
+ if (previous) this.resizeObserver?.unobserve(previous);
1162
+ box.target = target;
1163
+ if (target) {
1164
+ this.resizeObserver?.observe(target);
1165
+ box.text.textContent = label;
1166
+ if (!box.root.hasAttribute("data-visible")) {
1167
+ box.root.setAttribute("data-instant", "");
1168
+ }
1169
+ }
1170
+ this.schedule();
1171
+ }
1172
+ render() {
1173
+ const hover = this.hoverBox ? this.measure(this.hoverBox) : null;
1174
+ const selected = this.selectedBox ? this.measure(this.selectedBox) : null;
1175
+ if (this.hoverBox) this.paint(this.hoverBox, hover, selected);
1176
+ if (this.selectedBox) this.paint(this.selectedBox, selected, hover);
1177
+ }
1178
+ measure(box) {
1179
+ const target = box.target;
1180
+ if (!target) return null;
1181
+ if (!target.isConnected) {
1182
+ this.resizeObserver?.unobserve(target);
1183
+ box.target = null;
1184
+ return null;
1185
+ }
1186
+ const rect = target.getBoundingClientRect();
1187
+ if (rect.width === 0 && rect.height === 0) return null;
1188
+ const covers = findCovers(target, rect);
1189
+ if (!covers) return null;
1190
+ return {
1191
+ rect,
1192
+ covers,
1193
+ labelWidth: covers.length ? box.label.offsetWidth : 0,
1194
+ labelHeight: covers.length ? box.label.offsetHeight : 0
1195
+ };
1196
+ }
1197
+ paint(box, measurement, other = null) {
1198
+ const root = box.root;
1199
+ if (!measurement) {
1200
+ root.removeAttribute("data-visible");
1201
+ return;
1202
+ }
1203
+ const { rect, covers } = measurement;
1204
+ const x2 = rect.left - BOX_PADDING_PX;
1205
+ const y2 = rect.top - BOX_PADDING_PX;
1206
+ const labelAbove = {
1207
+ left: x2 - 2,
1208
+ top: y2 - LABEL_SPACE_PX,
1209
+ right: x2 - 2 + (measurement.labelWidth || Math.min(240, rect.width)),
1210
+ bottom: y2
1211
+ };
1212
+ const labelInside = y2 < LABEL_SPACE_PX || other !== null && other.rect !== rect && overlapsBox(labelAbove, other.rect);
1213
+ root.style.transform = `translate3d(${x2}px, ${y2}px, 0)`;
1214
+ root.style.width = `${rect.width + BOX_PADDING_PX * 2}px`;
1215
+ root.style.height = `${rect.height + BOX_PADDING_PX * 2}px`;
1216
+ root.toggleAttribute("data-label-inside", labelInside);
1217
+ root.style.clipPath = covers.length ? clipPath(x2, y2, covers) : "";
1218
+ const labelLeft = labelInside ? x2 + 2 : x2 - 2;
1219
+ const labelTop = labelInside ? y2 + 2 : y2 - LABEL_MARGIN_PX - measurement.labelHeight;
1220
+ const label = {
1221
+ left: labelLeft,
1222
+ top: labelTop,
1223
+ right: labelLeft + measurement.labelWidth,
1224
+ bottom: labelTop + measurement.labelHeight
1225
+ };
1226
+ root.toggleAttribute(
1227
+ "data-label-covered",
1228
+ covers.some((c2) => overlaps(c2, label))
1229
+ );
1230
+ if (root.hasAttribute("data-instant")) {
1231
+ root.setAttribute("data-visible", "");
1232
+ requestAnimationFrame(() => root.removeAttribute("data-instant"));
1233
+ return;
1234
+ }
1235
+ root.setAttribute("data-visible", "");
1236
+ }
1237
+ };
1238
+
1239
+ // src/core/visual-editor/field-path.ts
1240
+ var INDEX_SEGMENT = /^\d+$/;
1241
+ var WORD_SEPARATORS = /[_-]+/g;
1242
+ function normalizeFieldPath(path) {
1243
+ return path.split(".").map(
1244
+ (segment) => INDEX_SEGMENT.test(segment) ? String(Number.parseInt(segment, 10)) : segment
1245
+ ).join(".");
1246
+ }
1247
+ var GENERIC_LEAVES = /* @__PURE__ */ new Set(["value", "text", "body", "content", "label"]);
1248
+ function humanize(name) {
1249
+ const words = name.replace(WORD_SEPARATORS, " ").trim();
1250
+ return words.charAt(0).toUpperCase() + words.slice(1);
1251
+ }
1252
+ function fieldLabel(path, locale = "en") {
1253
+ if (!path) return t("visualEditor.edit", locale);
1254
+ const segments = path.split(".").filter((s2) => s2 && s2 !== "items" && !INDEX_SEGMENT.test(s2));
1255
+ const name = segments[segments.length - 1];
1256
+ if (!name) return t("visualEditor.edit", locale);
1257
+ const parent = segments[segments.length - 2];
1258
+ if (parent && GENERIC_LEAVES.has(name)) {
1259
+ return `${humanize(parent)} \u203A ${humanize(name)}`;
1260
+ }
1261
+ return humanize(name);
1262
+ }
1263
+ function findFieldElement(lookup) {
1264
+ if (!lookup.field) return null;
1265
+ const candidates = document.querySelectorAll(ENCODED_SELECTOR);
1266
+ if (lookup.entryId) {
1267
+ for (const candidate of candidates) {
1268
+ if (candidate.getAttribute("data-prepr-entry-id") === lookup.entryId) {
1269
+ return candidate;
1270
+ }
1271
+ }
1272
+ }
1273
+ for (const path of [lookup.field, lookup.fieldById]) {
1274
+ if (!path) continue;
1275
+ const wanted = normalizeFieldPath(path);
1276
+ for (const candidate of candidates) {
1277
+ const field = candidate.getAttribute(ATTR_FIELD);
1278
+ if (!field || normalizeFieldPath(field) !== wanted) continue;
1279
+ if (lookup.id && candidate.getAttribute(ATTR_ID) !== lookup.id) {
1280
+ continue;
1281
+ }
1282
+ return candidate;
1283
+ }
1284
+ }
1285
+ return null;
1286
+ }
1287
+
620
1288
  // src/core/stega/elements.ts
621
- var debug3 = createScopedLogger("stega:elements");
1289
+ var debug4 = createScopedLogger("stega:elements");
622
1290
  var StegaElements = class {
623
1291
  constructor(decode = decodeStega) {
624
1292
  this.observer = null;
1293
+ this.rescanTimer = null;
625
1294
  this.decode = decode;
626
1295
  }
627
1296
  getElements() {
628
1297
  if (!this.elements) {
629
- this.elements = document.querySelectorAll("[data-prepr-encoded]");
1298
+ this.elements = document.querySelectorAll(ENCODED_SELECTOR);
630
1299
  }
631
1300
  return this.elements;
632
1301
  }
@@ -635,7 +1304,7 @@ var StegaElements = class {
635
1304
  const decoded = this.decode(node.textContent);
636
1305
  if (!decoded?.href) return false;
637
1306
  const target = resolveEditTarget(node);
638
- if (!target || target.hasAttribute("data-prepr-encoded")) return false;
1307
+ if (!target || target.hasAttribute(ATTR_ENCODED)) return false;
639
1308
  tagEncodedElement(target, decoded);
640
1309
  return true;
641
1310
  }
@@ -653,7 +1322,7 @@ var StegaElements = class {
653
1322
  */
654
1323
  scanDocument(skipIfTagged = false) {
655
1324
  if (skipIfTagged) {
656
- const existing = document.querySelectorAll("[data-prepr-encoded]");
1325
+ const existing = document.querySelectorAll(ENCODED_SELECTOR);
657
1326
  if (existing.length > 0) {
658
1327
  this.elements = existing;
659
1328
  return;
@@ -663,16 +1332,13 @@ var StegaElements = class {
663
1332
  walkTextNodes(document.body, (textNode) => {
664
1333
  if (this.tagFromTextNode(textNode)) encodedCount++;
665
1334
  });
666
- debug3.log("document scan complete, encoded", encodedCount, "elements");
667
- this.elements = document.querySelectorAll("[data-prepr-encoded]");
1335
+ debug4.log("document scan complete, encoded", encodedCount, "elements");
1336
+ this.elements = document.querySelectorAll(ENCODED_SELECTOR);
668
1337
  }
669
1338
  /** `onUpdate` fires after each debounced batch, for refreshing derived state. */
670
1339
  setupMutationObserver(onUpdate) {
671
- if (this.observer) {
672
- this.observer.disconnect();
673
- }
1340
+ this.disconnectObserver();
674
1341
  let pending = [];
675
- let debounceTimeout = null;
676
1342
  const processMutations = () => {
677
1343
  const addedNodes = /* @__PURE__ */ new Set();
678
1344
  pending.forEach((mutation) => {
@@ -688,13 +1354,13 @@ var StegaElements = class {
688
1354
  if (node.isConnected) this.scanNode(node);
689
1355
  });
690
1356
  pending = [];
691
- this.elements = document.querySelectorAll("[data-prepr-encoded]");
1357
+ this.elements = document.querySelectorAll(ENCODED_SELECTOR);
692
1358
  onUpdate?.();
693
1359
  };
694
1360
  this.observer = new MutationObserver((mutations) => {
695
1361
  pending.push(...mutations);
696
- if (debounceTimeout) clearTimeout(debounceTimeout);
697
- debounceTimeout = setTimeout(processMutations, 100);
1362
+ if (this.rescanTimer) clearTimeout(this.rescanTimer);
1363
+ this.rescanTimer = setTimeout(processMutations, 100);
698
1364
  });
699
1365
  this.observer.observe(document.body, {
700
1366
  childList: true,
@@ -706,231 +1372,27 @@ var StegaElements = class {
706
1372
  attributeFilter: ["class", "style", "hidden", "open", "aria-expanded"]
707
1373
  });
708
1374
  }
709
- /** Drops the active class but keeps the data attributes, unlike cleanup(). */
710
- cleanupVisuals() {
711
- document.querySelectorAll(".prepr-overlay-active").forEach((element) => element.classList.remove("prepr-overlay-active"));
712
- }
713
- cleanup() {
714
- if (this.observer) {
715
- this.observer.disconnect();
716
- this.observer = null;
717
- }
718
- document.querySelectorAll("[data-prepr-encoded]").forEach((element) => {
719
- element.removeAttribute("data-prepr-encoded");
720
- element.removeAttribute("data-prepr-href");
721
- element.removeAttribute("data-prepr-origin");
722
- element.classList.remove("prepr-overlay-active");
723
- });
1375
+ /**
1376
+ * Stops watching for new content. Tags stay on their elements: the page's
1377
+ * stega characters are stripped once they are read, so a tag removed here
1378
+ * could never be rebuilt when edit mode is turned back on.
1379
+ */
1380
+ disconnect() {
1381
+ this.disconnectObserver();
724
1382
  this.elements = void 0;
725
1383
  }
726
- };
727
-
728
- // src/core/stega/overlay.ts
729
- var debug4 = createScopedLogger("stega:overlay");
730
- var StegaOverlay = class {
731
- constructor(onEdit) {
732
- this.overlay = null;
733
- this.tooltip = null;
734
- this.hideTimeout = null;
735
- this.currentElement = null;
736
- this.onEdit = onEdit;
737
- }
738
- create() {
739
- const overlay = document.createElement("div");
740
- overlay.className = "prepr-overlay";
741
- overlay.style.display = "none";
742
- const tooltip = document.createElement("div");
743
- tooltip.className = "prepr-tooltip";
744
- tooltip.style.display = "none";
745
- document.body.appendChild(overlay);
746
- document.body.appendChild(tooltip);
747
- this.overlay = overlay;
748
- this.tooltip = tooltip;
749
- return { overlay, tooltip };
750
- }
751
- getTooltip() {
752
- return this.tooltip;
753
- }
754
- hasCurrentElement() {
755
- return this.currentElement !== null;
756
- }
757
- clearHideTimeout() {
758
- if (this.hideTimeout) {
759
- clearTimeout(this.hideTimeout);
760
- this.hideTimeout = null;
761
- }
762
- }
763
- show(element) {
764
- if (!this.overlay || !this.tooltip) return;
765
- this.clearHideTimeout();
766
- if (this.currentElement && this.currentElement !== element) {
767
- this.currentElement.classList.remove("prepr-overlay-active");
768
- }
769
- const rect = element.getBoundingClientRect();
770
- const href = element.getAttribute("data-prepr-href");
771
- const origin = element.getAttribute("data-prepr-origin");
772
- const id = element.getAttribute("data-prepr-id") ?? void 0;
773
- const field = element.getAttribute("data-prepr-field") ?? void 0;
774
- debug4.log("showing overlay", { href, origin });
775
- const overlay = this.overlay;
776
- overlay.style.display = "block";
777
- overlay.style.top = `${rect.top + window.scrollY - 2}px`;
778
- overlay.style.left = `${rect.left + window.scrollX - 4}px`;
779
- overlay.style.width = `${rect.width + 8}px`;
780
- overlay.style.height = `${rect.height + 4}px`;
781
- const tooltip = this.tooltip;
782
- if (href && origin) {
783
- const MIN_WIDTH_FOR_TEXT = 80;
784
- const isCompact = rect.width < MIN_WIDTH_FOR_TEXT;
785
- tooltip.textContent = isCompact ? "\u2197" : `${origin} \u2197`;
786
- tooltip.style.display = "block";
787
- tooltip.style.minWidth = isCompact ? "auto" : "80px";
788
- requestAnimationFrame(() => {
789
- let top = rect.top + window.scrollY - tooltip.clientHeight - 2;
790
- let left = rect.right + 4 - tooltip.clientWidth;
791
- const minTop = window.scrollY + 4;
792
- const maxTop = window.scrollY + window.innerHeight - tooltip.clientHeight - 4;
793
- const minLeft = window.scrollX + 4;
794
- const maxLeft = window.scrollX + window.innerWidth - tooltip.clientWidth - 4;
795
- const below = top < minTop;
796
- if (below) {
797
- top = rect.bottom + window.scrollY + 2;
798
- }
799
- top = Math.max(minTop, Math.min(top, maxTop));
800
- left = Math.max(minLeft, Math.min(left, maxLeft));
801
- tooltip.dataset.preprPlacement = below ? "below" : "above";
802
- tooltip.style.top = `${top}px`;
803
- tooltip.style.left = `${left}px`;
804
- });
805
- tooltip.onclick = () => {
806
- this.onEdit({ href, origin, id, field });
807
- };
808
- }
809
- this.currentElement = element;
810
- element.classList.add("prepr-overlay-active");
811
- }
812
- hideImmediate() {
813
- this.clearHideTimeout();
814
- if (this.overlay) this.overlay.style.display = "none";
815
- if (this.tooltip) this.tooltip.style.display = "none";
816
- if (this.currentElement) {
817
- this.currentElement.classList.remove("prepr-overlay-active");
818
- this.currentElement = null;
819
- }
820
- }
821
- hide() {
822
- if (!this.overlay || !this.tooltip) return;
823
- this.clearHideTimeout();
824
- this.hideTimeout = setTimeout(() => this.hideImmediate(), 100);
825
- }
826
- cleanup() {
827
- this.clearHideTimeout();
828
- if (this.overlay) {
829
- this.overlay.style.display = "none";
830
- this.overlay.parentNode?.removeChild(this.overlay);
831
- this.overlay = null;
832
- }
833
- if (this.tooltip) {
834
- this.tooltip.style.display = "none";
835
- this.tooltip.parentNode?.removeChild(this.tooltip);
836
- this.tooltip = null;
837
- }
838
- if (this.currentElement) {
839
- this.currentElement.classList.remove("prepr-overlay-active");
840
- this.currentElement = null;
841
- }
842
- }
843
- };
844
-
845
- // src/core/stega/proximity.ts
846
- var debug5 = createScopedLogger("stega:proximity");
847
- var StegaProximity = class {
848
- constructor() {
849
- this.highlighted = /* @__PURE__ */ new Set();
850
- this.visible = /* @__PURE__ */ new Set();
1384
+ // A rescan already scheduled must not run after the observer stopped: it
1385
+ // would tag elements and call `onUpdate` on a controller that was shut down.
1386
+ disconnectObserver() {
1387
+ this.observer?.disconnect();
851
1388
  this.observer = null;
852
- this.getEncodedElements = createElementCache(
853
- "[data-prepr-encoded]",
854
- 200
855
- );
856
- }
857
- /** Call after the encoded element set changes — rebuilds the observer. */
858
- refreshObserving() {
859
- try {
860
- if (typeof IntersectionObserver === "undefined") return;
861
- if (this.observer) {
862
- this.observer.disconnect();
863
- this.observer = null;
864
- }
865
- this.visible = /* @__PURE__ */ new Set();
866
- this.observer = new IntersectionObserver(
867
- (entries) => {
868
- entries.forEach((entry) => {
869
- const el = entry.target;
870
- if (entry.isIntersecting) {
871
- this.visible.add(el);
872
- } else {
873
- this.visible.delete(el);
874
- }
875
- });
876
- },
877
- { root: null, rootMargin: "0px", threshold: 0 }
878
- );
879
- const nodes = this.getEncodedElements();
880
- nodes.forEach((el) => this.observer.observe(el));
881
- debug5.log("observing", nodes.length, "encoded elements");
882
- } catch (error) {
883
- debug5.log("error setting up IntersectionObserver", error);
884
- }
885
- }
886
- stopObserving() {
887
- if (this.observer) {
888
- this.observer.disconnect();
889
- this.observer = null;
890
- this.visible.clear();
891
- }
892
- }
893
- updateElementGradients(cursorX, cursorY) {
894
- const candidates = this.visible.size > 0 ? Array.from(this.visible) : Array.from(this.getEncodedElements());
895
- const newHighlighted = /* @__PURE__ */ new Set();
896
- candidates.forEach((element) => {
897
- const rect = element.getBoundingClientRect();
898
- const distance = Math.min(
899
- Math.abs(cursorX - rect.left),
900
- Math.abs(cursorX - rect.right),
901
- Math.abs(cursorY - rect.top),
902
- Math.abs(cursorY - rect.bottom)
903
- );
904
- if (distance < 150) {
905
- const relativeX = cursorX - rect.left;
906
- const relativeY = cursorY - rect.top;
907
- element.style.setProperty("--cursor-x", `${relativeX}px`);
908
- element.style.setProperty("--cursor-y", `${relativeY}px`);
909
- const baseGradientSize = Math.max(
910
- 150,
911
- Math.max(rect.width, rect.height) * 1.1
912
- );
913
- const distanceScale = Math.max(0, (400 - distance) / 400);
914
- const gradientSize = baseGradientSize * distanceScale;
915
- element.style.setProperty("--gradient-size", `${gradientSize}px`);
916
- element.classList.add("prepr-proximity-highlight");
917
- newHighlighted.add(element);
918
- } else {
919
- element.classList.remove("prepr-proximity-highlight");
920
- }
921
- });
922
- this.highlighted = newHighlighted;
923
- }
924
- clearAllHighlights() {
925
- this.highlighted.forEach(
926
- (element) => element.classList.remove("prepr-proximity-highlight")
927
- );
928
- this.highlighted.clear();
1389
+ if (this.rescanTimer) clearTimeout(this.rescanTimer);
1390
+ this.rescanTimer = null;
929
1391
  }
930
1392
  };
931
1393
 
932
1394
  // src/core/stega/stega.generated.ts
933
- var STEGA_STYLES = '[data-prepr-encoded]{position:relative}.prepr-overlay{pointer-events:none;z-index:10000;border:2px solid #4f46e5;border-radius:4px 0 4px 4px;transition:all .2s ease-in-out;position:absolute}.prepr-tooltip{color:#fff;white-space:nowrap;z-index:10001;text-align:center;pointer-events:auto;cursor:pointer;background-color:#4f46e5;border-radius:4px 4px 0 0;min-width:80px;padding:4px 8px;font-size:12px;line-height:1;transition:opacity .2s ease-in-out;position:absolute}.prepr-tooltip[data-prepr-placement=below]{border-radius:0 0 4px 4px}.prepr-tooltip:hover{background-color:#4338ca}.prepr-proximity-highlight{z-index:1;position:relative}.prepr-proximity-highlight,.prepr-proximity-highlight *{overflow:visible!important}.prepr-proximity-highlight:before{content:"";pointer-events:none;background:radial-gradient(circle var(--gradient-size) at var(--cursor-x) var(--cursor-y), #4f46e526 0%, #2563eb00 70%);z-index:9999;border:2px solid #4f46e526;border-radius:4px;transition:all .2s;position:absolute;top:-2px;bottom:-2px;left:-4px;right:-4px;overflow:visible}';
1395
+ var STEGA_STYLES = '@property --prepr-presence{syntax:"<number>";inherits:true;initial-value:1}[data-prepr-encoded]{outline:1px dashed rgb(79 70 229/calc(.3 * var(--prepr-presence,1)));outline-offset:2px}';
934
1396
 
935
1397
  // src/core/stega/styles.ts
936
1398
  var STEGA_STYLE_MARKER = "data-prepr-stega";
@@ -950,45 +1412,79 @@ function removeStegaStyles() {
950
1412
  }
951
1413
 
952
1414
  // src/core/stega/scan.ts
953
- var debug6 = createScopedLogger("stega:scan");
954
- var EDITOR_MODE_STYLES = "[data-prepr-encoded]{cursor:pointer}";
1415
+ var debug5 = createScopedLogger("stega:scan");
1416
+ var PRESENCE_FADE_MS = 400;
1417
+ var EDITOR_MODE_STYLES = `${ENCODED_SELECTOR}{cursor:pointer}`;
1418
+ function fadeInPresence() {
1419
+ const root = document.documentElement;
1420
+ if (typeof root.animate !== "function") return;
1421
+ if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return;
1422
+ root.animate(
1423
+ { "--prepr-presence": ["0", "1"] },
1424
+ { duration: PRESENCE_FADE_MS, easing: "ease-out" }
1425
+ );
1426
+ }
955
1427
  function createStegaController(opts) {
956
1428
  const tooltipEnabled = opts.tooltip ?? true;
957
- const overlay = new StegaOverlay(opts.onEdit);
958
- const proximity = new StegaProximity();
1429
+ const locale = opts.locale ?? "en";
959
1430
  const elements = new StegaElements();
1431
+ const overlay = new VisualEditorOverlay({
1432
+ onLabelClick: (target) => opts.onEdit(readEditPayload(target))
1433
+ });
960
1434
  let initialized = false;
961
- let throttledMouseMove = null;
962
- const handleTooltipMouseEnter = () => {
963
- overlay.clearHideTimeout();
1435
+ let pointerFrame = null;
1436
+ let pointerTarget = null;
1437
+ let pointerX = 0;
1438
+ let pointerY = 0;
1439
+ let hitTestPending = false;
1440
+ const updateHover = () => {
1441
+ pointerFrame = null;
1442
+ if (hitTestPending) {
1443
+ hitTestPending = false;
1444
+ pointerTarget = document.elementFromPoint(pointerX, pointerY);
1445
+ }
1446
+ if (overlay.owns(pointerTarget)) return;
1447
+ const encoded = pointerTarget instanceof Element ? pointerTarget.closest(ENCODED_SELECTOR) : null;
1448
+ overlay.setHover(
1449
+ encoded,
1450
+ encoded ? fieldLabel(encoded.getAttribute(ATTR_FIELD), locale) : ""
1451
+ );
964
1452
  };
965
- const handleTooltipMouseLeave = () => {
966
- if (!overlay.hasCurrentElement()) {
967
- overlay.hide();
1453
+ const scheduleHover = () => {
1454
+ if (pointerFrame === null) {
1455
+ pointerFrame = requestAnimationFrame(updateHover);
968
1456
  }
969
1457
  };
1458
+ const handlePointer = (e2) => {
1459
+ pointerTarget = e2.target;
1460
+ pointerX = e2.clientX;
1461
+ pointerY = e2.clientY;
1462
+ hitTestPending = false;
1463
+ scheduleHover();
1464
+ };
1465
+ const handlePointerLeave = () => {
1466
+ pointerTarget = null;
1467
+ hitTestPending = false;
1468
+ overlay.setHover(null, "");
1469
+ };
970
1470
  const handleScroll = () => {
971
- overlay.hideImmediate();
972
- proximity.clearAllHighlights();
1471
+ overlay.onScroll();
1472
+ if (pointerTarget === null) return;
1473
+ hitTestPending = true;
1474
+ scheduleHover();
973
1475
  };
1476
+ const handleResize = () => overlay.schedule();
974
1477
  const handleClick = (e2) => {
975
1478
  const target = e2.target;
976
- const encoded = target?.closest(
977
- "[data-prepr-encoded]"
978
- );
1479
+ const encoded = target?.closest(ENCODED_SELECTOR);
979
1480
  if (!encoded) return;
980
1481
  e2.preventDefault();
981
1482
  e2.stopPropagation();
982
- opts.onEdit({
983
- href: encoded.getAttribute("data-prepr-href") ?? "",
984
- origin: encoded.getAttribute("data-prepr-origin") ?? "",
985
- id: encoded.getAttribute("data-prepr-id") ?? void 0,
986
- field: encoded.getAttribute("data-prepr-field") ?? void 0
987
- });
1483
+ opts.onEdit(readEditPayload(encoded));
988
1484
  };
989
1485
  const start = () => {
990
1486
  if (initialized) {
991
- debug6.log("already initialized, skipping setup");
1487
+ debug5.log("already initialized, skipping setup");
992
1488
  return;
993
1489
  }
994
1490
  if (!tooltipEnabled) {
@@ -998,71 +1494,92 @@ function createStegaController(opts) {
998
1494
  });
999
1495
  document.addEventListener("click", handleClick, { capture: true });
1000
1496
  initialized = true;
1001
- debug6.log("stega controller started (editor mode)");
1497
+ debug5.log("stega controller started (headless)");
1002
1498
  return;
1003
1499
  }
1004
1500
  injectStegaStyles();
1005
- const { tooltip } = overlay.create();
1006
- tooltip.addEventListener("mouseenter", handleTooltipMouseEnter);
1007
- tooltip.addEventListener("mouseleave", handleTooltipMouseLeave);
1501
+ fadeInPresence();
1502
+ overlay.mount();
1008
1503
  elements.scanDocument(true);
1009
- proximity.refreshObserving();
1010
- elements.setupMutationObserver(() => proximity.refreshObserving());
1011
- throttledMouseMove = throttle((e2) => {
1012
- const mouseEvent = e2;
1013
- const target = mouseEvent.target;
1014
- if (!target) return;
1015
- if (target.closest(".prepr-tooltip")) return;
1016
- proximity.updateElementGradients(mouseEvent.clientX, mouseEvent.clientY);
1017
- const encoded = target.closest("[data-prepr-encoded]");
1018
- if (encoded) {
1019
- overlay.show(encoded);
1020
- } else {
1021
- overlay.hide();
1022
- }
1023
- }, 16);
1024
- document.addEventListener("mousemove", throttledMouseMove, {
1025
- passive: true
1504
+ elements.setupMutationObserver(() => {
1505
+ if (pointerTarget === null) return;
1506
+ hitTestPending = true;
1507
+ scheduleHover();
1026
1508
  });
1509
+ document.addEventListener("pointermove", handlePointer, { passive: true });
1510
+ document.addEventListener("pointerdown", handlePointer, { passive: true });
1511
+ document.documentElement.addEventListener(
1512
+ "pointerleave",
1513
+ handlePointerLeave
1514
+ );
1027
1515
  window.addEventListener("scroll", handleScroll, {
1028
1516
  capture: true,
1029
1517
  passive: true
1030
1518
  });
1519
+ window.addEventListener("resize", handleResize, { passive: true });
1031
1520
  initialized = true;
1032
- debug6.log("stega controller started");
1521
+ debug5.log("stega controller started");
1033
1522
  };
1034
1523
  const stop = () => {
1035
1524
  if (!initialized) return;
1525
+ initialized = false;
1036
1526
  if (!tooltipEnabled) {
1037
1527
  document.removeEventListener("click", handleClick, { capture: true });
1038
- elements.cleanup();
1528
+ elements.disconnect();
1039
1529
  removeStegaStyles();
1040
- initialized = false;
1041
- debug6.log("stega controller stopped (editor mode)");
1530
+ debug5.log("stega controller stopped (headless)");
1042
1531
  return;
1043
1532
  }
1044
- if (throttledMouseMove) {
1045
- document.removeEventListener("mousemove", throttledMouseMove);
1046
- throttledMouseMove.cancel();
1047
- throttledMouseMove = null;
1048
- }
1533
+ if (pointerFrame !== null) cancelAnimationFrame(pointerFrame);
1534
+ pointerFrame = null;
1535
+ pointerTarget = null;
1536
+ hitTestPending = false;
1537
+ document.removeEventListener("pointermove", handlePointer);
1538
+ document.removeEventListener("pointerdown", handlePointer);
1539
+ document.documentElement.removeEventListener(
1540
+ "pointerleave",
1541
+ handlePointerLeave
1542
+ );
1049
1543
  window.removeEventListener("scroll", handleScroll, { capture: true });
1050
- const tooltip = overlay.getTooltip();
1051
- if (tooltip) {
1052
- tooltip.removeEventListener("mouseenter", handleTooltipMouseEnter);
1053
- tooltip.removeEventListener("mouseleave", handleTooltipMouseLeave);
1054
- }
1055
- overlay.cleanup();
1056
- proximity.clearAllHighlights();
1057
- proximity.stopObserving();
1058
- elements.cleanup();
1544
+ window.removeEventListener("resize", handleResize);
1545
+ overlay.unmount();
1546
+ elements.disconnect();
1059
1547
  removeStegaStyles();
1060
- initialized = false;
1061
- debug6.log("stega controller stopped");
1548
+ debug5.log("stega controller stopped");
1062
1549
  };
1063
1550
  return { start, stop };
1064
1551
  }
1065
1552
 
1553
+ // src/core/stega/scroll-to-field.ts
1554
+ var debug6 = createScopedLogger("stega:scroll");
1555
+ var FLASH_DURATION_MS = 1200;
1556
+ var flashTimeout = null;
1557
+ function scrollToField(request) {
1558
+ const { field, id } = request;
1559
+ if (!field) return false;
1560
+ const candidates = document.querySelectorAll(ENCODED_SELECTOR);
1561
+ let target = null;
1562
+ for (const candidate of candidates) {
1563
+ if (candidate.getAttribute(ATTR_FIELD) !== field) continue;
1564
+ if (id && candidate.getAttribute(ATTR_ID) !== id) continue;
1565
+ target = candidate;
1566
+ break;
1567
+ }
1568
+ if (!target) {
1569
+ debug6.log("no element found for field", field);
1570
+ return false;
1571
+ }
1572
+ target.scrollIntoView({ behavior: "smooth", block: "center" });
1573
+ if (flashTimeout) clearTimeout(flashTimeout);
1574
+ document.querySelectorAll(".prepr-overlay-active").forEach((el) => el.classList.remove("prepr-overlay-active"));
1575
+ target.classList.add("prepr-overlay-active");
1576
+ flashTimeout = setTimeout(() => {
1577
+ target.classList.remove("prepr-overlay-active");
1578
+ flashTimeout = null;
1579
+ }, FLASH_DURATION_MS);
1580
+ return true;
1581
+ }
1582
+
1066
1583
  // src/core/store.ts
1067
1584
  var DEFAULT_STATE = {
1068
1585
  locale: "en",
@@ -1197,7 +1714,7 @@ function splitPath(full) {
1197
1714
  return [full.slice(0, index), full.slice(index + 1)];
1198
1715
  }
1199
1716
 
1200
- // ../../node_modules/.pnpm/preact@10.29.7/node_modules/preact/dist/preact.mjs
1717
+ // ../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/dist/preact.mjs
1201
1718
  var n;
1202
1719
  var l;
1203
1720
  var u;
@@ -1268,8 +1785,8 @@ function H() {
1268
1785
  }
1269
1786
  }
1270
1787
  function L(n2, l2, u3, t3, i2, r2, o2, e2, f3, c2, a2) {
1271
- var s2, h2, p2, v2, y2, _2, g2, m2 = t3 && t3.__k || w, b2 = l2.length;
1272
- for (f3 = T(u3, l2, m2, f3, b2), s2 = 0; s2 < b2; s2++) null != (p2 = u3.__k[s2]) && (h2 = -1 != p2.__i && m2[p2.__i] || d, p2.__i = s2, _2 = q(n2, p2, h2, i2, r2, o2, e2, f3, c2, a2), v2 = p2.__e, p2.ref && h2.ref != p2.ref && (h2.ref && J(h2.ref, null, p2), a2.push(p2.ref, p2.__c || v2, p2)), null == y2 && null != v2 && (y2 = v2), (g2 = !!(4 & p2.__u)) || h2.__k === p2.__k ? (f3 = j(p2, f3, n2, g2), g2 && h2.__e && (h2.__e = null)) : "function" == typeof p2.type && void 0 !== _2 ? f3 = _2 : v2 && (f3 = v2.nextSibling), p2.__u &= -7);
1788
+ var s2, h2, p2, v2, y2, _2, g2 = t3 && t3.__k || w, m2 = l2.length;
1789
+ for (f3 = T(u3, l2, g2, f3, m2), s2 = 0; s2 < m2; s2++) null != (p2 = u3.__k[s2]) && (h2 = -1 != p2.__i && g2[p2.__i] || d, p2.__i = s2, _2 = q(n2, p2, h2, i2, r2, o2, e2, f3, c2, a2), v2 = p2.__e, p2.ref && h2.ref != p2.ref && (h2.ref && J(h2.ref, null, p2), a2.push(p2.ref, p2.__c || v2, p2)), null == y2 && null != v2 && (y2 = v2), 4 & p2.__u ? (f3 = j(p2, f3, n2), h2.__e && (h2.__e = null)) : "function" == typeof p2.type && void 0 !== _2 ? f3 = _2 : v2 && (f3 = v2.nextSibling), p2.__u &= -7);
1273
1790
  return u3.__e = y2, f3;
1274
1791
  }
1275
1792
  function T(n2, l2, u3, t3, i2) {
@@ -1278,13 +1795,13 @@ function T(n2, l2, u3, t3, i2) {
1278
1795
  if (s2) for (r2 = 0; r2 < a2; r2++) null != (e2 = u3[r2]) && 0 == (2 & e2.__u) && (e2.__e == t3 && (t3 = $(e2)), K(e2, e2));
1279
1796
  return t3;
1280
1797
  }
1281
- function j(n2, l2, u3, t3) {
1282
- var i2, r2;
1798
+ function j(n2, l2, u3) {
1799
+ var t3, i2;
1283
1800
  if ("function" == typeof n2.type) {
1284
- for (i2 = n2.__k, r2 = 0; i2 && r2 < i2.length; r2++) i2[r2] && (i2[r2].__ = n2, l2 = j(i2[r2], l2, u3, t3));
1801
+ for (t3 = n2.__k, i2 = 0; t3 && i2 < t3.length; i2++) t3[i2] && (t3[i2].__ = n2, l2 = j(t3[i2], l2, u3));
1285
1802
  return l2;
1286
1803
  }
1287
- n2.__e != l2 && (t3 && (l2 && n2.type && !l2.parentNode && (l2 = $(n2)), u3.insertBefore(n2.__e, l2 || null)), l2 = n2.__e);
1804
+ n2.__e != l2 && (l2 && n2.type && !l2.parentNode && (l2 = $(n2)), l2 = u3.insertBefore(n2.__e, l2 || null));
1288
1805
  do {
1289
1806
  l2 = l2 && l2.nextSibling;
1290
1807
  } while (null != l2 && 8 == l2.nodeType);
@@ -1330,35 +1847,35 @@ function V(n2) {
1330
1847
  };
1331
1848
  }
1332
1849
  function q(n2, u3, t3, i2, r2, o2, e2, f3, c2, a2) {
1333
- var s2, h2, p2, v2, y2, d2, _2, k2, x2, M, $2, I2, P2, A2, H2, T2, j2 = u3.type;
1850
+ var s2, h2, p2, v2, y2, d2, _2, k2, x2, M, I2, P2, A2, H2, T2, j2, F = u3.type;
1334
1851
  if (void 0 !== u3.constructor) return null;
1335
1852
  128 & t3.__u && (c2 = !!(32 & t3.__u), o2 = [f3 = u3.__e = t3.__e]), (s2 = l.__b) && s2(u3);
1336
- n: if ("function" == typeof j2) {
1853
+ n: if ("function" == typeof F) {
1337
1854
  h2 = e2.length;
1338
1855
  try {
1339
- if (x2 = u3.props, M = j2.prototype && j2.prototype.render, $2 = (s2 = j2.contextType) && i2[s2.__c], I2 = s2 ? $2 ? $2.props.value : s2.__ : i2, t3.__c ? k2 = (p2 = u3.__c = t3.__c).__ = p2.__E : (M ? u3.__c = p2 = new j2(x2, I2) : (u3.__c = p2 = new C(x2, I2), p2.constructor = j2, p2.render = Q), $2 && $2.sub(p2), p2.state || (p2.state = {}), p2.__n = i2, v2 = p2.__d = true, p2.__h = [], p2._sb = []), M && null == p2.__s && (p2.__s = p2.state), M && null != j2.getDerivedStateFromProps && (p2.__s == p2.state && (p2.__s = m({}, p2.__s)), m(p2.__s, j2.getDerivedStateFromProps(x2, p2.__s))), y2 = p2.props, d2 = p2.state, p2.__v = u3, v2) M && null == j2.getDerivedStateFromProps && null != p2.componentWillMount && p2.componentWillMount(), M && null != p2.componentDidMount && p2.__h.push(p2.componentDidMount);
1856
+ if (x2 = u3.props, M = F.prototype && F.prototype.render, I2 = (s2 = F.contextType) && i2[s2.__c], P2 = s2 ? I2 ? I2.props.value : s2.__ : i2, t3.__c ? k2 = (p2 = u3.__c = t3.__c).__ = p2.__E : (M ? u3.__c = p2 = new F(x2, P2) : (u3.__c = p2 = new C(x2, P2), p2.constructor = F, p2.render = Q), I2 && I2.sub(p2), p2.state || (p2.state = {}), p2.__n = i2, v2 = p2.__d = true, p2.__h = [], p2._sb = []), M && null == p2.__s && (p2.__s = p2.state), M && null != F.getDerivedStateFromProps && (p2.__s == p2.state && (p2.__s = m({}, p2.__s)), m(p2.__s, F.getDerivedStateFromProps(x2, p2.__s))), y2 = p2.props, d2 = p2.state, p2.__v = u3, v2) M && null == F.getDerivedStateFromProps && null != p2.componentWillMount && p2.componentWillMount(), M && null != p2.componentDidMount && p2.__h.push(p2.componentDidMount);
1340
1857
  else {
1341
- if (M && null == j2.getDerivedStateFromProps && x2 !== y2 && null != p2.componentWillReceiveProps && p2.componentWillReceiveProps(x2, I2), u3.__v == t3.__v || !p2.__e && null != p2.shouldComponentUpdate && false === p2.shouldComponentUpdate(x2, p2.__s, I2)) {
1858
+ if (M && null == F.getDerivedStateFromProps && x2 !== y2 && null != p2.componentWillReceiveProps && p2.componentWillReceiveProps(x2, P2), u3.__v == t3.__v || !p2.__e && null != p2.shouldComponentUpdate && false === p2.shouldComponentUpdate(x2, p2.__s, P2)) {
1342
1859
  u3.__v != t3.__v && (p2.props = x2, p2.state = p2.__s, p2.__d = false), u3.__e = t3.__e, u3.__k = t3.__k, u3.__k.some(function(n3) {
1343
1860
  n3 && (n3.__ = u3);
1344
- }), w.push.apply(p2.__h, p2._sb), p2._sb = [], p2.__h.length && e2.push(p2);
1861
+ }), w.push.apply(p2.__h, p2._sb), p2._sb = [], p2.__h.length && e2.push(p2), f3 = $(t3);
1345
1862
  break n;
1346
1863
  }
1347
- null != p2.componentWillUpdate && p2.componentWillUpdate(x2, p2.__s, I2), M && null != p2.componentDidUpdate && p2.__h.push(function() {
1864
+ null != p2.componentWillUpdate && p2.componentWillUpdate(x2, p2.__s, P2), M && null != p2.componentDidUpdate && p2.__h.push(function() {
1348
1865
  p2.componentDidUpdate(y2, d2, _2);
1349
1866
  });
1350
1867
  }
1351
- if (p2.context = I2, p2.props = x2, p2.__P = n2, p2.__e = false, P2 = l.__r, A2 = 0, M) p2.state = p2.__s, p2.__d = false, P2 && P2(u3), s2 = p2.render(p2.props, p2.state, p2.context), w.push.apply(p2.__h, p2._sb), p2._sb = [];
1868
+ if (p2.context = P2, p2.props = x2, p2.__P = n2, p2.__e = false, A2 = l.__r, H2 = 0, M) p2.state = p2.__s, p2.__d = false, A2 && A2(u3), s2 = p2.render(p2.props, p2.state, p2.context), w.push.apply(p2.__h, p2._sb), p2._sb = [];
1352
1869
  else do {
1353
- p2.__d = false, P2 && P2(u3), s2 = p2.render(p2.props, p2.state, p2.context), p2.state = p2.__s;
1354
- } while (p2.__d && ++A2 < 25);
1355
- p2.state = p2.__s, null != p2.getChildContext && (i2 = m(m({}, i2), p2.getChildContext())), M && !v2 && null != p2.getSnapshotBeforeUpdate && (_2 = p2.getSnapshotBeforeUpdate(y2, d2)), H2 = null != s2 && s2.type === S && null == s2.key ? E(s2.props.children) : s2, f3 = L(n2, g(H2) ? H2 : [H2], u3, t3, i2, r2, o2, e2, f3, c2, a2), p2.base = u3.__e, u3.__u &= -161, p2.__h.length && e2.push(p2), k2 && (p2.__E = p2.__ = null);
1870
+ p2.__d = false, A2 && A2(u3), s2 = p2.render(p2.props, p2.state, p2.context), p2.state = p2.__s;
1871
+ } while (p2.__d && ++H2 < 25);
1872
+ p2.state = p2.__s, null != p2.getChildContext && (i2 = m(m({}, i2), p2.getChildContext())), M && !v2 && null != p2.getSnapshotBeforeUpdate && (_2 = p2.getSnapshotBeforeUpdate(y2, d2)), T2 = null != s2 && s2.type === S && null == s2.key ? E(s2.props.children) : s2, f3 = L(n2, g(T2) ? T2 : [T2], u3, t3, i2, r2, o2, e2, f3, c2, a2), p2.base = u3.__e, u3.__u &= -161, p2.__h.length && e2.push(p2), k2 && (p2.__E = p2.__ = null);
1356
1873
  } catch (n3) {
1357
1874
  if (e2.length = h2, u3.__v = null, c2 || null != o2) {
1358
1875
  if (n3.then) {
1359
1876
  for (u3.__u |= c2 ? 160 : 128; f3 && 8 == f3.nodeType && f3.nextSibling; ) f3 = f3.nextSibling;
1360
1877
  null != o2 && (o2[o2.indexOf(f3)] = null), u3.__e = f3;
1361
- } else if (null != o2) for (T2 = o2.length; T2--; ) b(o2[T2]);
1878
+ } else if (null != o2) for (j2 = o2.length; j2--; ) b(o2[j2]);
1362
1879
  } else u3.__e = t3.__e;
1363
1880
  null == u3.__k && (u3.__k = t3.__k || []), n3.then || B(u3), l.__e(n3, u3, t3);
1364
1881
  }
@@ -1479,9 +1996,9 @@ var CLOSE_ICON_SVG = `<svg width="10" height="10" viewBox="0 0 10 10" fill="none
1479
1996
  </svg>`;
1480
1997
 
1481
1998
  // src/core/ui/toolbar.generated.ts
1482
- var TOOLBAR_CSS = ":host{--prepr-primary:#4338ca;--prepr-bg:#eef2ff;--prepr-text:#1f2937;--prepr-radius:8px;--prepr-shadow:0px 0px 40px 0px #1f29373d;--prepr-z-index:10000;--prepr-primary-50:#eef2ff;--prepr-primary-100:#e0e7ff;--prepr-primary-800:#3730a3;--prepr-indigo-600:#4f46e5;--prepr-indigo-50:#eef2ff;--prepr-indigo-700:#4338ca;--prepr-secondary-400:#fb923c;--prepr-secondary-500:#f97316;--prepr-gray-100:#f3f4f6;--prepr-gray-200:#e5e7eb;--prepr-gray-300:#d1d5db;--prepr-gray-400:#9ca3af;--prepr-gray-500:#6b7280;--prepr-gray-700:#374151;--prepr-gray-800:#1f2937;--prepr-gray-900:#111827;--prepr-shadow-sm:0px 0px 12px 0px #c3c3c3cc;color:var(--prepr-text);box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;font-size:14px;line-height:1.5}:host *,:host :before,:host :after,*,:before,:after{box-sizing:border-box}button{font-family:inherit;font-size:inherit;margin:0}.prepr-regular-text{font-size:.875rem;font-weight:500;line-height:1.5}.prepr-backdrop{z-index:calc(var(--prepr-z-index) - 1);opacity:0;pointer-events:none;background:#0000001a;transition:opacity .2s ease-in-out;position:fixed;top:0;bottom:0;left:0;right:0}.prepr-backdrop[data-open=true]{opacity:1;pointer-events:auto;animation:.2s ease-in-out prepr-fade-in}.prepr-container{z-index:var(--prepr-z-index);justify-content:flex-end;align-items:center;display:flex;position:fixed;top:calc(50% - 64px);right:0}.prepr-toggle-holder{padding:.5rem}.prepr-toggle{cursor:pointer;background:var(--prepr-primary);color:#fff;border:none;border-radius:9999px;justify-content:center;align-items:center;width:2.25rem;height:2.25rem;display:flex}.prepr-toggle>span{display:flex}.prepr-toggle svg{color:#fff}.prepr-panel{z-index:var(--prepr-z-index);opacity:0;pointer-events:none;justify-content:flex-end;padding:.75rem;transition:opacity .2s ease-in-out;display:flex;position:fixed;top:50%;right:0;transform:translateY(-50%)}.prepr-panel[data-open=true]{opacity:1;pointer-events:auto;animation:.2s ease-in-out prepr-fade-in}.prepr-content{box-shadow:var(--prepr-shadow);border-radius:var(--prepr-radius);background:var(--prepr-bg);flex-direction:column;gap:2.5rem;width:100%;padding:1.5rem;display:flex}@media (min-width:640px){.prepr-panel{margin-right:4rem;padding:0}.prepr-content{width:502px;padding:2.5rem}}.prepr-header{justify-content:space-between;align-items:center;gap:.5rem;display:flex}.prepr-header-left{align-items:flex-start;gap:.75rem;display:flex}.prepr-badge{background:var(--prepr-primary-100);height:1.5rem;color:var(--prepr-primary);border-radius:4px;align-items:center;padding:.25rem .75rem;font-size:.875rem;display:flex}.prepr-header-close{cursor:pointer;background:var(--prepr-primary-100);width:2rem;height:2rem;color:var(--prepr-gray-700);border:none;border-radius:6px;justify-content:center;align-items:center;display:flex}.prepr-section{flex-direction:column;gap:.5rem;display:flex}.prepr-section-label{color:var(--prepr-gray-400);font-size:.875rem}.prepr-row{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:.5rem 1.5rem;display:flex}.prepr-row-title{color:var(--prepr-gray-800);margin:0;font-size:1rem;font-weight:600}.prepr-radiogroup{border-radius:var(--prepr-radius);border:1px solid var(--prepr-gray-300);background:#fff;align-items:center;gap:.25rem;height:2.5rem;padding:.25rem;display:flex}.prepr-radiogroup[data-disabled=true]{cursor:not-allowed;opacity:.5}.prepr-radiogroup[data-disabled=true] .prepr-radio{pointer-events:none}.prepr-radio{cursor:pointer;white-space:nowrap;text-align:center;height:2rem;color:var(--prepr-gray-900);background:0 0;border:none;border-radius:6px;justify-content:center;align-items:center;padding:.5rem 1.125rem;font-size:.875rem;font-weight:500;transition:all .2s ease-in-out;display:flex}.prepr-radio[data-checked=true]{background:var(--prepr-indigo-600);color:#fff;box-shadow:var(--prepr-shadow-sm)}.prepr-radio[data-checked=true][data-off=true]{background:var(--prepr-gray-800);color:#fff}.prepr-radio-variant{width:82px}.prepr-listbox{position:relative}.prepr-segment-button{border-radius:var(--prepr-radius);border:1px solid var(--prepr-gray-300);width:240px;height:2.5rem;color:var(--prepr-gray-500);cursor:pointer;background:#fff;flex-shrink:0;align-items:center;gap:.5rem;padding:0 .5rem;font-size:.875rem;font-weight:500;display:flex;overflow:hidden}@media (min-width:768px){.prepr-segment-button{padding:0 1rem}}.prepr-segment-button:disabled{cursor:not-allowed;background:var(--prepr-gray-200);color:var(--prepr-gray-400)}.prepr-segment-button[aria-expanded=true]{border-bottom-color:#fff;border-bottom-right-radius:0;border-bottom-left-radius:0}.prepr-segment-label{white-space:nowrap;text-overflow:ellipsis;text-align:left;width:100%;margin-right:auto;overflow:hidden}.prepr-segment-caret{color:var(--prepr-gray-800);display:flex}.prepr-options{z-index:calc(var(--prepr-z-index) + 1);border-left:1px solid var(--prepr-gray-300);border-right:1px solid var(--prepr-gray-300);border-bottom:1px solid var(--prepr-gray-300);-ms-overflow-style:none;scrollbar-width:none;background:#fff;border-radius:0 0 6px 6px;width:240px;max-height:300px;margin:0;padding:0;list-style:none;position:absolute;top:100%;left:0;overflow-y:auto;box-shadow:0 20px 25px -5px #0000001a,0 8px 10px -6px #0000001a}.prepr-options::-webkit-scrollbar{display:none}.prepr-options[hidden]{display:none}.prepr-option-search{background:#fff;padding:.5rem;position:-webkit-sticky;position:sticky;top:0}.prepr-segment-search{border:1px solid var(--prepr-gray-300);border-radius:var(--prepr-radius);width:100%;height:2rem;font:inherit;color:var(--prepr-gray-900);box-sizing:border-box;background:#fff;padding:0 .5rem;font-size:.875rem}.prepr-segment-search::placeholder{color:var(--prepr-gray-400)}.prepr-segment-search:focus{border-color:var(--prepr-gray-400);outline:none}.prepr-option{cursor:pointer;width:100%;color:var(--prepr-gray-900);background:#fff;align-items:center;padding:.5rem 1rem;font-size:.875rem;font-weight:500;display:flex}.prepr-option:hover{background:var(--prepr-gray-100)}.prepr-option[aria-selected=true]{background:var(--prepr-indigo-50);color:var(--prepr-indigo-700)}.prepr-option-label{white-space:nowrap;text-overflow:ellipsis;text-align:left;width:100%;margin-right:auto;overflow:hidden}.prepr-reset{background:var(--prepr-secondary-400);color:#fff;cursor:pointer;border:none;border-radius:6px;justify-content:center;align-items:center;gap:.5rem;width:100%;height:2.5rem;padding:.5rem .75rem;font-size:.875rem;font-weight:500;display:flex}.prepr-reset:hover:not(:disabled){background:var(--prepr-secondary-500)}.prepr-reset:disabled{background:var(--prepr-gray-400);color:var(--prepr-gray-500);cursor:not-allowed}@media (min-width:768px){.prepr-reset{width:108px}}.prepr-indicators{z-index:var(--prepr-z-index);gap:.75rem;display:flex;position:fixed;bottom:1.5rem;right:1.5rem}.prepr-status-pill{background:var(--prepr-primary);color:#fff;cursor:pointer;border:none;border-radius:9999px;align-items:center;gap:.5rem;padding:.5rem 1rem;font-size:.75rem;font-weight:500;transition:background-color .15s;display:flex;box-shadow:0 10px 15px -3px #0000001a,0 4px 6px -4px #0000001a}.prepr-status-pill[data-interactive=false]{cursor:default;opacity:1;color:#fff}.prepr-status-pill[data-interactive=true]:hover{background:var(--prepr-primary-800)}.prepr-status-pill[hidden]{display:none}.prepr-status-viewing{color:#fff9;font-size:10px}.prepr-status-segment{text-overflow:ellipsis;white-space:nowrap;max-width:120px;display:inline-block;overflow:hidden}.prepr-status-variant{text-overflow:ellipsis;white-space:nowrap;background:#fff3;border-radius:4px;max-width:80px;padding:0 .5rem;display:inline-block;overflow:hidden}.prepr-status-x{color:#fff;width:.75rem;height:.75rem}.prepr-close-edit-pill{background:var(--prepr-primary-50);color:var(--prepr-gray-800);cursor:pointer;border:none;border-radius:9999px;align-items:center;gap:.5rem;padding:.5rem 1rem;font-size:.75rem;font-weight:500;transition:background-color .15s;display:flex;box-shadow:0 10px 15px -3px #0000001a,0 4px 6px -4px #0000001a}.prepr-close-edit-pill:hover{background:var(--prepr-primary-100)}.prepr-close-edit-pill[hidden]{display:none}.prepr-close-edit-x{width:1rem;height:1rem;color:var(--prepr-gray-500);transition:color .15s}.prepr-close-edit-pill:hover .prepr-close-edit-x{color:var(--prepr-gray-700)}.prepr-tip{z-index:calc(var(--prepr-z-index) + 2);overflow-wrap:break-word;background:var(--prepr-gray-900);color:#fff;pointer-events:none;border-radius:6px;width:auto;max-width:min(420px,100vw - 16px);padding:.5rem .75rem;font-size:.75rem;font-weight:500;position:fixed;box-shadow:0 20px 25px -5px #0000001a,0 8px 10px -6px #0000001a}.prepr-tip-arrow{border-left:6px solid #0000;border-right:6px solid #0000;border-top:6px solid var(--prepr-gray-900);width:0;height:0;position:absolute;top:100%;transform:translate(-50%)}[hidden]{display:none!important}@keyframes prepr-fade-in{0%{opacity:0}to{opacity:1}}";
1999
+ var TOOLBAR_CSS = ":host{--prepr-primary:#4338ca;--prepr-bg:#eef2ff;--prepr-text:#1f2937;--prepr-radius:8px;--prepr-shadow:0px 0px 40px 0px #1f29373d;--prepr-z-index:10000;--prepr-primary-50:#eef2ff;--prepr-primary-100:#e0e7ff;--prepr-primary-800:#3730a3;--prepr-indigo-600:#4f46e5;--prepr-indigo-50:#eef2ff;--prepr-indigo-700:#4338ca;--prepr-secondary-400:#fb923c;--prepr-secondary-500:#f97316;--prepr-gray-100:#f3f4f6;--prepr-gray-200:#e5e7eb;--prepr-gray-300:#d1d5db;--prepr-gray-400:#9ca3af;--prepr-gray-500:#6b7280;--prepr-gray-700:#374151;--prepr-gray-800:#1f2937;--prepr-gray-900:#111827;--prepr-shadow-sm:0px 0px 12px 0px #c3c3c3cc;color:var(--prepr-text);box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;font-size:14px;line-height:1.5}:host *,:host :before,:host :after,*,:before,:after{box-sizing:border-box}button{font-family:inherit;font-size:inherit;margin:0}.prepr-regular-text{font-size:.875rem;font-weight:500;line-height:1.5}.prepr-backdrop{z-index:calc(var(--prepr-z-index) - 1);opacity:0;pointer-events:none;background:#0000001a;transition:opacity .2s ease-in-out;position:fixed;top:0;bottom:0;left:0;right:0}.prepr-backdrop[data-open=true]{opacity:1;pointer-events:auto;animation:.2s ease-in-out prepr-fade-in}.prepr-container{z-index:var(--prepr-z-index);justify-content:flex-end;align-items:center;display:flex;position:fixed;top:calc(50% - 64px);right:0}.prepr-toggle-holder{padding:.5rem}.prepr-toggle{cursor:pointer;background:var(--prepr-primary);color:#fff;border:none;border-radius:9999px;justify-content:center;align-items:center;width:2.25rem;height:2.25rem;display:flex}.prepr-toggle>span{display:flex}.prepr-toggle svg{color:#fff}.prepr-panel{z-index:var(--prepr-z-index);opacity:0;pointer-events:none;justify-content:flex-end;padding:.75rem;transition:opacity .2s ease-in-out;display:flex;position:fixed;top:50%;right:0;transform:translateY(-50%)}.prepr-panel[data-open=true]{opacity:1;pointer-events:auto;animation:.2s ease-in-out prepr-fade-in}.prepr-content{box-shadow:var(--prepr-shadow);border-radius:var(--prepr-radius);background:var(--prepr-bg);flex-direction:column;gap:2.5rem;width:100%;padding:1.5rem;display:flex}@media (min-width:640px){.prepr-panel{margin-right:4rem;padding:0}.prepr-content{width:502px;padding:2.5rem}}.prepr-header{justify-content:space-between;align-items:center;gap:.5rem;display:flex}.prepr-header-left{align-items:flex-start;gap:.75rem;display:flex}.prepr-badge{background:var(--prepr-primary-100);height:1.5rem;color:var(--prepr-primary);border-radius:4px;align-items:center;padding:.25rem .75rem;font-size:.875rem;display:flex}.prepr-header-close{cursor:pointer;background:var(--prepr-primary-100);width:2rem;height:2rem;color:var(--prepr-gray-700);border:none;border-radius:6px;justify-content:center;align-items:center;display:flex}.prepr-section{flex-direction:column;gap:.5rem;display:flex}.prepr-section-label{color:var(--prepr-gray-400);font-size:.875rem}.prepr-row{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:.5rem 1.5rem;display:flex}.prepr-row-title{color:var(--prepr-gray-800);margin:0;font-size:1rem;font-weight:600}.prepr-radiogroup{border-radius:var(--prepr-radius);border:1px solid var(--prepr-gray-300);background:#fff;align-items:center;gap:.25rem;height:2.5rem;padding:.25rem;display:flex}.prepr-radiogroup[data-disabled=true]{cursor:not-allowed;opacity:.5}.prepr-radiogroup[data-disabled=true] .prepr-radio{pointer-events:none}.prepr-radio{cursor:pointer;white-space:nowrap;text-align:center;height:2rem;color:var(--prepr-gray-900);background:0 0;border:none;border-radius:6px;justify-content:center;align-items:center;padding:.5rem 1.125rem;font-size:.875rem;font-weight:500;transition:all .2s ease-in-out;display:flex}.prepr-radio[data-checked=true]{background:var(--prepr-indigo-600);color:#fff;box-shadow:var(--prepr-shadow-sm)}.prepr-radio[data-checked=true][data-off=true]{background:var(--prepr-gray-800);color:#fff}.prepr-radio-variant{width:82px}.prepr-listbox{position:relative}.prepr-segment-button{border-radius:var(--prepr-radius);border:1px solid var(--prepr-gray-300);width:240px;height:2.5rem;color:var(--prepr-gray-500);cursor:pointer;background:#fff;flex-shrink:0;align-items:center;gap:.5rem;padding:0 .5rem;font-size:.875rem;font-weight:500;display:flex;overflow:hidden}@media (min-width:768px){.prepr-segment-button{padding:0 1rem}}.prepr-segment-button:disabled{cursor:not-allowed;background:var(--prepr-gray-200);color:var(--prepr-gray-400)}.prepr-segment-button[aria-expanded=true]{border-bottom-color:#fff;border-bottom-right-radius:0;border-bottom-left-radius:0}.prepr-segment-label{white-space:nowrap;text-overflow:ellipsis;text-align:left;width:100%;margin-right:auto;overflow:hidden}.prepr-segment-caret{color:var(--prepr-gray-800);display:flex}.prepr-options{z-index:calc(var(--prepr-z-index) + 1);border-left:1px solid var(--prepr-gray-300);border-right:1px solid var(--prepr-gray-300);border-bottom:1px solid var(--prepr-gray-300);-ms-overflow-style:none;scrollbar-width:none;background:#fff;border-radius:0 0 6px 6px;width:240px;max-height:300px;margin:0;padding:0;list-style:none;position:absolute;top:100%;left:0;overflow-y:auto;box-shadow:0 20px 25px -5px #0000001a,0 8px 10px -6px #0000001a}.prepr-options::-webkit-scrollbar{display:none}.prepr-options[hidden]{display:none}.prepr-option-search{background:#fff;padding:.5rem;position:sticky;top:0}.prepr-segment-search{border:1px solid var(--prepr-gray-300);border-radius:var(--prepr-radius);width:100%;height:2rem;font:inherit;color:var(--prepr-gray-900);box-sizing:border-box;background:#fff;padding:0 .5rem;font-size:.875rem}@media (pointer:coarse){.prepr-segment-search{font-size:16px}}.prepr-segment-search::placeholder{color:var(--prepr-gray-400)}.prepr-segment-search:focus{border-color:var(--prepr-gray-400);outline:none}.prepr-option{cursor:pointer;width:100%;color:var(--prepr-gray-900);background:#fff;align-items:center;padding:.5rem 1rem;font-size:.875rem;font-weight:500;display:flex}.prepr-option:hover{background:var(--prepr-gray-100)}.prepr-option[aria-selected=true]{background:var(--prepr-indigo-50);color:var(--prepr-indigo-700)}.prepr-option-label{white-space:nowrap;text-overflow:ellipsis;text-align:left;width:100%;margin-right:auto;overflow:hidden}.prepr-reset{background:var(--prepr-secondary-400);color:#fff;cursor:pointer;border:none;border-radius:6px;justify-content:center;align-items:center;gap:.5rem;width:100%;height:2.5rem;padding:.5rem .75rem;font-size:.875rem;font-weight:500;display:flex}.prepr-reset:hover:not(:disabled){background:var(--prepr-secondary-500)}.prepr-reset:disabled{background:var(--prepr-gray-400);color:var(--prepr-gray-500);cursor:not-allowed}@media (min-width:768px){.prepr-reset{width:108px}}.prepr-indicators{z-index:var(--prepr-z-index);gap:.75rem;display:flex;position:fixed;bottom:1.5rem;right:1.5rem}.prepr-status-pill{background:var(--prepr-primary);color:#fff;cursor:pointer;border:none;border-radius:9999px;align-items:center;gap:.5rem;padding:.5rem 1rem;font-size:.75rem;font-weight:500;transition:background-color .15s;display:flex;box-shadow:0 10px 15px -3px #0000001a,0 4px 6px -4px #0000001a}.prepr-status-pill[data-interactive=false]{cursor:default;opacity:1;color:#fff}.prepr-status-pill[data-interactive=true]:hover{background:var(--prepr-primary-800)}.prepr-status-pill[hidden]{display:none}.prepr-status-viewing{color:#fff9;font-size:10px}.prepr-status-segment{text-overflow:ellipsis;white-space:nowrap;max-width:120px;display:inline-block;overflow:hidden}.prepr-status-variant{text-overflow:ellipsis;white-space:nowrap;background:#fff3;border-radius:4px;max-width:80px;padding:0 .5rem;display:inline-block;overflow:hidden}.prepr-status-x{color:#fff;width:.75rem;height:.75rem}.prepr-close-edit-pill{background:var(--prepr-primary-50);color:var(--prepr-gray-800);cursor:pointer;border:none;border-radius:9999px;align-items:center;gap:.5rem;padding:.5rem 1rem;font-size:.75rem;font-weight:500;transition:background-color .15s;display:flex;box-shadow:0 10px 15px -3px #0000001a,0 4px 6px -4px #0000001a}.prepr-close-edit-pill:hover{background:var(--prepr-primary-100)}.prepr-close-edit-pill[hidden]{display:none}.prepr-close-edit-x{width:1rem;height:1rem;color:var(--prepr-gray-500);transition:color .15s}.prepr-close-edit-pill:hover .prepr-close-edit-x{color:var(--prepr-gray-700)}.prepr-tip{z-index:calc(var(--prepr-z-index) + 2);overflow-wrap:break-word;background:var(--prepr-gray-900);color:#fff;pointer-events:none;border-radius:6px;width:auto;max-width:min(420px,100vw - 16px);padding:.5rem .75rem;font-size:.75rem;font-weight:500;position:fixed;box-shadow:0 20px 25px -5px #0000001a,0 8px 10px -6px #0000001a}.prepr-tip-arrow{border-left:6px solid #0000;border-right:6px solid #0000;border-top:6px solid var(--prepr-gray-900);width:0;height:0;position:absolute;top:100%;transform:translate(-50%)}[hidden]{display:none!important}@keyframes prepr-fade-in{0%{opacity:0}to{opacity:1}}";
1483
2000
 
1484
- // ../../node_modules/.pnpm/preact@10.29.7/node_modules/preact/jsx-runtime/dist/jsxRuntime.mjs
2001
+ // ../../node_modules/.pnpm/preact@10.29.8/node_modules/preact/jsx-runtime/dist/jsxRuntime.mjs
1485
2002
  var f2 = 0;
1486
2003
  function u2(e2, t3, n2, o2, i2, u3) {
1487
2004
  t3 || (t3 = {});
@@ -1728,7 +2245,7 @@ function StatusPill({
1728
2245
  handlers
1729
2246
  }) {
1730
2247
  const { features } = state;
1731
- const defaultSegmentName = state.segments.find((s2) => s2._id === "all_other_users")?.name ?? t3("adaptiveContent.allOtherUsers");
2248
+ const defaultSegmentName = state.segments.find((s2) => s2._id === SEGMENT_ALL_OTHER_USERS)?.name ?? t3("adaptiveContent.allOtherUsers");
1732
2249
  let segmentLabel;
1733
2250
  if (!state.previewMode || !features.segments) {
1734
2251
  segmentLabel = t3("common.user");
@@ -1909,7 +2426,6 @@ function Panel({
1909
2426
  }
1910
2427
 
1911
2428
  // src/core/ui/toolbar-element.ts
1912
- var TAG_NAME = "prepr-toolbar";
1913
2429
  var HTMLElementBase = typeof HTMLElement === "undefined" ? class {
1914
2430
  } : HTMLElement;
1915
2431
  var PreprToolbarElement = class extends HTMLElementBase {
@@ -1983,6 +2499,13 @@ var PreprToolbarElement = class extends HTMLElementBase {
1983
2499
  document.addEventListener("mousedown", this.onDocumentMouseDown);
1984
2500
  this.renderPanel(store.get());
1985
2501
  }
2502
+ /**
2503
+ * Re-wires a toolbar that was detached and attached again, e.g. when a
2504
+ * framework replaces `<body>` on navigation and the element is moved back.
2505
+ */
2506
+ connectedCallback() {
2507
+ if (this.store && !this.unsubscribe) this.connect(this.store, this.t);
2508
+ }
1986
2509
  disconnectedCallback() {
1987
2510
  this.unsubscribe?.();
1988
2511
  this.unsubscribe = null;
@@ -2169,161 +2692,2802 @@ var PreprToolbarElement = class extends HTMLElementBase {
2169
2692
  };
2170
2693
  function definePreprToolbar() {
2171
2694
  if (typeof customElements === "undefined") return;
2172
- if (!customElements.get(TAG_NAME)) {
2173
- customElements.define(TAG_NAME, PreprToolbarElement);
2695
+ if (!customElements.get(TOOLBAR_TAG)) {
2696
+ customElements.define(TOOLBAR_TAG, PreprToolbarElement);
2174
2697
  }
2175
2698
  }
2176
2699
 
2177
- // src/core/create-preview.ts
2178
- var debug7 = createScopedLogger("create-preview");
2179
- var controllerStores = /* @__PURE__ */ new WeakMap();
2180
- function defaultNavigation() {
2181
- return {
2182
- navigate: (url) => window.location.assign(url),
2183
- currentPath: () => window.location.pathname + window.location.search
2184
- };
2185
- }
2186
- function safeEditUrl(href) {
2700
+ // src/core/visual-editor/asset-images.ts
2701
+ var MAX_URL_LENGTH = 4096;
2702
+ var MIN_KEY_SEGMENTS = 2;
2703
+ var TRANSFORM_OPTION = /^[a-z]{1,3}_[\w.-]*$/i;
2704
+ var FORMAT_PLACEHOLDER = "{format}";
2705
+ var PROXY_PARAMS = ["url", "href", "src", "image"];
2706
+ var ABSOLUTE_HTTP = /^https?:\/\//i;
2707
+ var SOURCE_URL_ATTRIBUTES = ["src", "data-src"];
2708
+ var SOURCE_SET_ATTRIBUTES = ["srcset", "data-srcset"];
2709
+ var ASSET_ATTR = "data-prepr-asset";
2710
+ var REMOVED_ATTR = "data-prepr-removed";
2711
+ var ASSET_SOURCE_ATTRIBUTES = [
2712
+ ...SOURCE_URL_ATTRIBUTES,
2713
+ ...SOURCE_SET_ATTRIBUTES
2714
+ ];
2715
+ var TAG_ATTRIBUTES = [
2716
+ ATTR_ENCODED,
2717
+ ATTR_ID,
2718
+ ATTR_FIELD,
2719
+ "data-prepr-entry-id",
2720
+ ASSET_ATTR,
2721
+ REMOVED_ATTR
2722
+ ];
2723
+ function decodeSegment(segment) {
2187
2724
  try {
2188
- const url = new URL(href, window.location.href);
2189
- return url.protocol === "https:" || url.protocol === "http:" ? url.href : null;
2725
+ return decodeURIComponent(segment);
2190
2726
  } catch {
2191
- return null;
2727
+ return segment;
2192
2728
  }
2193
2729
  }
2194
- function buildSegments(data) {
2195
- return [{ _id: "all_other_users", name: "All other users" }, ...data];
2730
+ function isTransformSegment(segment) {
2731
+ return segment === FORMAT_PLACEHOLDER || segment.split(",").every((option) => TRANSFORM_OPTION.test(option));
2196
2732
  }
2197
- function resolveLocale(options) {
2198
- const explicit = options?.locale;
2199
- if (isLocale(explicit)) return explicit;
2733
+ function assetKey(url, depth = 0) {
2734
+ if (!url || url.length > MAX_URL_LENGTH) return null;
2735
+ let parsed;
2736
+ try {
2737
+ parsed = new URL(url, "https://base.invalid");
2738
+ } catch {
2739
+ return null;
2740
+ }
2741
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
2742
+ if (depth === 0) {
2743
+ for (const name of PROXY_PARAMS) {
2744
+ const inner = parsed.searchParams.get(name);
2745
+ if (inner && ABSOLUTE_HTTP.test(inner)) return assetKey(inner, 1);
2746
+ }
2747
+ }
2748
+ const segments = parsed.pathname.split("/").filter(Boolean).map(decodeSegment);
2749
+ const file = segments.pop();
2750
+ if (!file) return null;
2751
+ const kept = segments.filter((segment) => !isTransformSegment(segment));
2752
+ kept.push(file);
2753
+ return kept.length >= MIN_KEY_SEGMENTS ? kept.join("/") : null;
2754
+ }
2755
+ function srcsetUrls(srcset) {
2756
+ const urls = [];
2757
+ let expectUrl = true;
2758
+ for (const token of srcset.split(/\s+/)) {
2759
+ if (!token) continue;
2760
+ if (!expectUrl) {
2761
+ const comma = token.indexOf(",");
2762
+ if (comma === -1) continue;
2763
+ expectUrl = true;
2764
+ const rest = token.slice(comma + 1);
2765
+ if (!rest) continue;
2766
+ urls.push(rest.replace(/,+$/, ""));
2767
+ expectUrl = rest.endsWith(",");
2768
+ continue;
2769
+ }
2770
+ const url = token.replace(/^,+|,+$/g, "");
2771
+ if (url) urls.push(url);
2772
+ expectUrl = token.endsWith(",");
2773
+ }
2774
+ return urls;
2775
+ }
2776
+ function createAssetIndex(assets) {
2777
+ const index = /* @__PURE__ */ new Map();
2778
+ for (const asset of assets) {
2779
+ const key = assetKey(asset.key);
2780
+ if (key && !index.has(key)) index.set(key, asset);
2781
+ }
2782
+ return index;
2783
+ }
2784
+ function urlsOf(img) {
2785
+ const urls = [];
2786
+ const collect = (el) => {
2787
+ for (const name of SOURCE_URL_ATTRIBUTES) {
2788
+ const value = el.getAttribute(name);
2789
+ if (value) urls.push(value);
2790
+ }
2791
+ for (const name of SOURCE_SET_ATTRIBUTES) {
2792
+ const value = el.getAttribute(name);
2793
+ if (value) urls.push(...srcsetUrls(value));
2794
+ }
2795
+ };
2796
+ collect(img);
2797
+ const picture = img.parentElement;
2798
+ if (picture?.tagName === "PICTURE") {
2799
+ for (const source of picture.children) {
2800
+ if (source.tagName === "SOURCE") collect(source);
2801
+ }
2802
+ }
2803
+ return urls;
2804
+ }
2805
+ function matchAsset(img, index, keys) {
2806
+ for (const url of urlsOf(img)) {
2807
+ let key = keys.get(url);
2808
+ if (key === void 0) {
2809
+ key = assetKey(url);
2810
+ keys.set(url, key);
2811
+ }
2812
+ const asset = key ? index.get(key) : void 0;
2813
+ if (asset) return asset;
2814
+ }
2815
+ return void 0;
2816
+ }
2817
+ function setIfChanged(el, name, value) {
2818
+ if (value === null) {
2819
+ if (el.hasAttribute(name)) el.removeAttribute(name);
2820
+ } else if (el.getAttribute(name) !== value) {
2821
+ el.setAttribute(name, value);
2822
+ }
2823
+ }
2824
+ function untagAssetImage(img) {
2825
+ for (const name of TAG_ATTRIBUTES) img.removeAttribute(name);
2826
+ }
2827
+ var TEXT_FIELD_SELECTOR = `${ENCODED_SELECTOR}:not([${ASSET_ATTR}])`;
2828
+ function besideOtherItem(img, isCurrentItem) {
2829
+ for (let block = img.parentElement; block && block !== document.body; block = block.parentElement) {
2830
+ const texts = block.querySelectorAll(TEXT_FIELD_SELECTOR);
2831
+ if (texts.length === 0) continue;
2832
+ for (const text of texts) {
2833
+ if (isCurrentItem(text)) return false;
2834
+ }
2835
+ return true;
2836
+ }
2837
+ return false;
2838
+ }
2839
+ function tagAssetImages(index, itemId, keys, options = {}) {
2840
+ const { isCurrentItem, removed } = options;
2841
+ let showsRemoved = false;
2842
+ for (const img of document.getElementsByTagName("img")) {
2843
+ const ours = img.hasAttribute(ASSET_ATTR);
2844
+ let match = index.size ? matchAsset(img, index, keys) : void 0;
2845
+ let isRemoved = false;
2846
+ if (!match && removed?.size) {
2847
+ match = matchAsset(img, removed, keys);
2848
+ isRemoved = match !== void 0;
2849
+ }
2850
+ if (!ours && img.hasAttribute(ATTR_ENCODED)) {
2851
+ const mark = isRemoved && (!isCurrentItem || isCurrentItem(img));
2852
+ setIfChanged(img, REMOVED_ATTR, mark ? "" : null);
2853
+ showsRemoved || (showsRemoved = mark);
2854
+ continue;
2855
+ }
2856
+ const asset = match && isCurrentItem && besideOtherItem(img, isCurrentItem) ? void 0 : match;
2857
+ if (!asset) {
2858
+ if (ours) untagAssetImage(img);
2859
+ continue;
2860
+ }
2861
+ setIfChanged(img, ATTR_ENCODED, "");
2862
+ setIfChanged(img, ASSET_ATTR, "");
2863
+ setIfChanged(img, ATTR_ID, itemId);
2864
+ setIfChanged(img, ATTR_FIELD, asset.field);
2865
+ setIfChanged(img, "data-prepr-entry-id", asset.entryId ?? null);
2866
+ setIfChanged(img, REMOVED_ATTR, isRemoved ? "" : null);
2867
+ showsRemoved || (showsRemoved = isRemoved);
2868
+ }
2869
+ return showsRemoved;
2870
+ }
2871
+ function untagAssetImages() {
2872
+ document.querySelectorAll(`img[${ASSET_ATTR}]`).forEach(untagAssetImage);
2873
+ document.querySelectorAll(`img[${REMOVED_ATTR}]`).forEach((img) => img.removeAttribute(REMOVED_ATTR));
2874
+ }
2875
+
2876
+ // src/core/visual-editor/item-scope.ts
2877
+ var REFERENCE_ATTR = "data-prepr-reference";
2878
+ var REFERENCE_SELECTOR = `[${REFERENCE_ATTR}]`;
2879
+ var OTHER_ITEM_ATTR = "data-prepr-other-item";
2880
+ var OTHER_ITEM_SELECTOR = `[${OTHER_ITEM_ATTR}="on"],[${OTHER_ITEM_ATTR}="off"]`;
2881
+ var CHROME_SELECTOR = "header, footer, nav, [role=banner], [role=contentinfo], [role=navigation]";
2882
+ var SECTIONING_SELECTOR = "article, aside, main, nav, section";
2883
+ var PLAIN_HEADER_FOOTER = "header:not([role]), footer:not([role])";
2884
+ function createItemScope() {
2885
+ let currentItemId = null;
2886
+ let references = null;
2887
+ let ownComponents = /* @__PURE__ */ new Set();
2888
+ const isCurrentItem = (el) => {
2889
+ if (currentItemId === null) return true;
2890
+ const id = el.getAttribute(ATTR_ID);
2891
+ return !id || id === currentItemId || ownComponents.has(id);
2892
+ };
2893
+ const linkedIdOf = (el) => {
2894
+ if (!references) return null;
2895
+ const id = el.getAttribute(ATTR_ID) ?? "";
2896
+ if (references.has(id)) return id;
2897
+ let container = el.closest(REFERENCE_SELECTOR);
2898
+ while (container) {
2899
+ const linked = container.getAttribute(REFERENCE_ATTR) ?? "";
2900
+ if (references.has(linked)) return linked;
2901
+ container = container.parentElement?.closest(REFERENCE_SELECTOR) ?? null;
2902
+ }
2903
+ return null;
2904
+ };
2905
+ const inSiteChrome = (el) => {
2906
+ let chrome = el.closest(CHROME_SELECTOR);
2907
+ while (chrome) {
2908
+ if (!chrome.matches(PLAIN_HEADER_FOOTER) || !chrome.parentElement?.closest(SECTIONING_SELECTOR)) {
2909
+ return true;
2910
+ }
2911
+ chrome = chrome.parentElement?.closest(CHROME_SELECTOR) ?? null;
2912
+ }
2913
+ return false;
2914
+ };
2915
+ const showsOtherItem = (el) => {
2916
+ const choice = el.closest(OTHER_ITEM_SELECTOR);
2917
+ if (choice) return choice.getAttribute(OTHER_ITEM_ATTR) === "on";
2918
+ return !inSiteChrome(el);
2919
+ };
2920
+ const itemKind = (el) => {
2921
+ if (isCurrentItem(el)) return "current";
2922
+ if (!references) return "other";
2923
+ if (linkedIdOf(el)) return "referenced";
2924
+ return showsOtherItem(el) ? "other" : null;
2925
+ };
2926
+ const referenceFieldOf = (el) => {
2927
+ const linked = linkedIdOf(el);
2928
+ return linked ? references?.get(linked) : void 0;
2929
+ };
2930
+ return {
2931
+ currentItemId: () => currentItemId,
2932
+ setCurrentItem(itemId) {
2933
+ currentItemId = itemId;
2934
+ },
2935
+ setComponents(componentIds) {
2936
+ ownComponents = new Set(componentIds);
2937
+ },
2938
+ setReferences(list) {
2939
+ references = /* @__PURE__ */ new Map();
2940
+ for (const { id, field } of list) {
2941
+ if (!references.has(id)) references.set(id, field);
2942
+ }
2943
+ },
2944
+ isCurrentItem,
2945
+ linkedIdOf,
2946
+ itemKind,
2947
+ referenceFieldOf
2948
+ };
2949
+ }
2950
+
2951
+ // src/core/visual-editor/list-items.ts
2952
+ function listItemIn(encoded, target) {
2953
+ if (!(target instanceof Element)) return null;
2954
+ const li = target.closest("li");
2955
+ if (!li || !encoded.contains(li) || !li.parentElement) return null;
2956
+ const items = Array.from(li.parentElement.children).filter(
2957
+ (child) => child.tagName === "LI"
2958
+ );
2959
+ return { element: li, index: items.indexOf(li) };
2960
+ }
2961
+ function nthListItem(encoded, block) {
2962
+ const list = encoded.querySelector("ul, ol");
2963
+ if (!list) return null;
2964
+ const items = Array.from(list.children).filter(
2965
+ (child) => child.tagName === "LI"
2966
+ );
2967
+ return items[block] ?? null;
2968
+ }
2969
+
2970
+ // src/core/visual-editor/navigation-guard.ts
2971
+ var debug7 = createScopedLogger("navigation-guard");
2972
+ var trimSlash = (path) => path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
2973
+ function resolve(url) {
2974
+ try {
2975
+ return new URL(url, document.baseURI);
2976
+ } catch {
2977
+ return null;
2978
+ }
2979
+ }
2980
+ function leavesPage(url) {
2981
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
2982
+ const here = window.location;
2983
+ return url.origin !== here.origin || trimSlash(url.pathname) !== trimSlash(here.pathname);
2984
+ }
2985
+ function leavingLinkHref(target) {
2986
+ if (!(target instanceof Element)) return null;
2987
+ const link = target.closest("a[href]");
2988
+ if (!link || link.hasAttribute("download")) return null;
2989
+ const linkTarget = link.getAttribute("target");
2990
+ if (linkTarget && linkTarget !== "_self") return null;
2991
+ const href = link.getAttribute("href") ?? "";
2992
+ if (href.startsWith("#")) return null;
2993
+ const url = resolve(href);
2994
+ return url && leavesPage(url) ? url.href : null;
2995
+ }
2996
+ function submitterAttr(submitter, attr) {
2997
+ if (!submitter?.hasAttribute(attr)) return null;
2998
+ if (attr === "formaction") return submitter.formAction;
2999
+ if (attr === "formmethod") return submitter.formMethod;
3000
+ return submitter.formTarget;
3001
+ }
3002
+ function submissionUrl(form, submitter) {
3003
+ const method = (submitterAttr(submitter, "formmethod") ?? form.method).toLowerCase();
3004
+ if (method === "dialog") return null;
3005
+ const target = submitterAttr(submitter, "formtarget") ?? form.target;
3006
+ if (target && target !== "_self") return null;
3007
+ const url = resolve(
3008
+ submitterAttr(submitter, "formaction") ?? (form.action || location.href)
3009
+ );
3010
+ if (!url) return null;
3011
+ if (method === "get") {
3012
+ let data;
3013
+ try {
3014
+ data = new FormData(form, submitter);
3015
+ } catch {
3016
+ data = new FormData(form);
3017
+ }
3018
+ const query = new URLSearchParams();
3019
+ data.forEach((value, key) => {
3020
+ query.append(key, typeof value === "string" ? value : value.name);
3021
+ });
3022
+ url.search = query.toString();
3023
+ }
3024
+ return url;
3025
+ }
3026
+ function createNavigationGuard(opts) {
3027
+ let active = false;
3028
+ let permitted = null;
3029
+ let pendingForm = null;
3030
+ let originalPush = null;
3031
+ let guardedPush = null;
3032
+ const isPermitted = (url) => permitted === url.href;
3033
+ const guarding = () => active && opts.showsEditedContent();
3034
+ const report = (href) => {
3035
+ debug7.log("blocked navigation to", href);
3036
+ opts.onBlocked(href);
3037
+ };
3038
+ const onSubmit = (e2) => {
3039
+ if (e2.defaultPrevented || !(e2.target instanceof HTMLFormElement)) return;
3040
+ if (!guarding()) return;
3041
+ const submitter = e2.submitter ?? null;
3042
+ const url = submissionUrl(e2.target, submitter);
3043
+ if (!url || !leavesPage(url) || isPermitted(url)) return;
3044
+ e2.preventDefault();
3045
+ pendingForm = { form: e2.target, submitter, href: url.href };
3046
+ report(url.href);
3047
+ };
3048
+ const onNavigate = (event) => {
3049
+ const e2 = event;
3050
+ if (e2.navigationType === "traverse" || e2.navigationType === "reload") {
3051
+ return;
3052
+ }
3053
+ if (!e2.cancelable || e2.hashChange || e2.downloadRequest !== null) return;
3054
+ if (!guarding()) return;
3055
+ if (e2.navigationType === "replace" && e2.destination.sameDocument) return;
3056
+ const url = resolve(e2.destination.url);
3057
+ if (!url || !leavesPage(url) || isPermitted(url)) return;
3058
+ e2.preventDefault();
3059
+ report(url.href);
3060
+ if (e2.destination.sameDocument) window.location.reload();
3061
+ };
3062
+ const navigation = () => window.navigation;
3063
+ function installPushGuard() {
3064
+ const original = history.pushState;
3065
+ const guard = function(data, unused, url) {
3066
+ if (guarding() && guardedPush === guard && url != null) {
3067
+ const target = resolve(url);
3068
+ if (target && leavesPage(target) && !isPermitted(target)) {
3069
+ report(target.href);
3070
+ window.location.reload();
3071
+ return;
3072
+ }
3073
+ }
3074
+ return original.call(this, data, unused, url);
3075
+ };
3076
+ originalPush = original;
3077
+ guardedPush = guard;
3078
+ history.pushState = guard;
3079
+ }
3080
+ function uninstallPushGuard() {
3081
+ if (history.pushState === guardedPush && originalPush) {
3082
+ history.pushState = originalPush;
3083
+ }
3084
+ originalPush = null;
3085
+ guardedPush = null;
3086
+ }
3087
+ return {
3088
+ start() {
3089
+ if (active) return;
3090
+ active = true;
3091
+ installPushGuard();
3092
+ window.addEventListener("submit", onSubmit);
3093
+ navigation()?.addEventListener("navigate", onNavigate);
3094
+ },
3095
+ stop() {
3096
+ if (!active) return;
3097
+ active = false;
3098
+ uninstallPushGuard();
3099
+ window.removeEventListener("submit", onSubmit);
3100
+ navigation()?.removeEventListener("navigate", onNavigate);
3101
+ pendingForm = null;
3102
+ },
3103
+ isActive: guarding,
3104
+ block(href) {
3105
+ report(href);
3106
+ },
3107
+ permit(href) {
3108
+ permitted = resolve(href)?.href ?? null;
3109
+ },
3110
+ allow(href) {
3111
+ const url = resolve(href);
3112
+ if (!url || url.protocol !== "http:" && url.protocol !== "https:") {
3113
+ debug7.warn("ignored navigation to unsupported URL");
3114
+ return;
3115
+ }
3116
+ permitted = url.href;
3117
+ const form = pendingForm;
3118
+ pendingForm = null;
3119
+ if (form && form.href === url.href && form.form.isConnected) {
3120
+ try {
3121
+ form.form.requestSubmit(form.submitter ?? void 0);
3122
+ } catch {
3123
+ form.form.requestSubmit();
3124
+ }
3125
+ return;
3126
+ }
3127
+ window.location.assign(url.href);
3128
+ }
3129
+ };
3130
+ }
3131
+
3132
+ // src/core/visual-editor/index.ts
3133
+ var debug8 = createScopedLogger("visual-editor");
3134
+ var CURSOR_STYLE_MARKER = "data-prepr-visual-editor";
3135
+ var REMOVED_STYLES = `img[${REMOVED_ATTR}]{opacity:.2!important;transition:opacity .2s ease}@media (prefers-reduced-motion:reduce){img[${REMOVED_ATTR}]{transition:none}}`;
3136
+ var CURSOR_STYLES = `${ENCODED_SELECTOR}{cursor:pointer}html[data-prepr-ve-suspended] ${ENCODED_SELECTOR}{cursor:auto}${REMOVED_STYLES}`;
3137
+ var SUSPENDED_ATTR = "data-prepr-ve-suspended";
3138
+ var FIND_RETRY_MS = 150;
3139
+ var FIND_RETRIES = 6;
3140
+ var MAX_CACHED_KEYS = 2e3;
3141
+ var SAVED_FADE_MS = 1e4;
3142
+ var LAYOUT_MUTATIONS = {
3143
+ childList: true,
3144
+ subtree: true,
3145
+ characterData: true,
3146
+ attributes: true,
3147
+ attributeFilter: [
3148
+ "class",
3149
+ "style",
3150
+ "hidden",
3151
+ "open",
3152
+ ATTR_ENCODED,
3153
+ // An image swapped by a carousel or lazy loader can show another asset.
3154
+ ...ASSET_SOURCE_ATTRIBUTES
3155
+ ]
3156
+ };
3157
+ function scrollIntoFrame(el) {
3158
+ const rect = el.getBoundingClientRect();
3159
+ const offset = Math.max(0, (window.innerHeight - rect.height) / 2);
3160
+ window.scrollTo({
3161
+ top: Math.max(0, window.scrollY + rect.top - offset),
3162
+ behavior: "smooth"
3163
+ });
3164
+ }
3165
+ var isVisible = (el) => typeof el.checkVisibility === "function" ? el.checkVisibility() : el.getClientRects().length > 0;
3166
+ function createVisualEditor(opts) {
3167
+ const overlay = new VisualEditorOverlay();
3168
+ let running = false;
3169
+ const scope = createItemScope();
3170
+ const { isCurrentItem, itemKind, linkedIdOf, referenceFieldOf } = scope;
3171
+ let locale = opts.locale ?? "en";
3172
+ let suspended = false;
3173
+ let pointerFrame = null;
3174
+ let lastPointerTarget = null;
3175
+ let lastPointerX = 0;
3176
+ let lastPointerY = 0;
3177
+ let mutationFrame = null;
3178
+ let mutationObserver = null;
3179
+ let selection = null;
3180
+ let findTimeout = null;
3181
+ let settlePendingFind = null;
3182
+ let guardEnabled = false;
3183
+ let assetIndex = /* @__PURE__ */ new Map();
3184
+ const assetKeys = /* @__PURE__ */ new Map();
3185
+ const removedAssets = /* @__PURE__ */ new Map();
3186
+ let saved = false;
3187
+ let savedTimeout = null;
3188
+ const guard = createNavigationGuard({
3189
+ onBlocked: (href) => opts.onNavigationBlocked?.(href),
3190
+ showsEditedContent: () => showsEditedContent()
3191
+ });
3192
+ const encodedFrom = (node) => node instanceof Element ? node.closest(ENCODED_SELECTOR) : null;
3193
+ const labelFor = (el) => fieldLabel(el.getAttribute(ATTR_FIELD), locale);
3194
+ const showsEditedContent = () => {
3195
+ for (const el of document.querySelectorAll(ENCODED_SELECTOR)) {
3196
+ if (isCurrentItem(el) && isVisible(el)) return true;
3197
+ }
3198
+ return false;
3199
+ };
3200
+ const hoverLabel = (el, kind) => {
3201
+ if (kind === "other") {
3202
+ return `${labelFor(el)} \xB7 ${t("visualEditor.otherItem", locale)}`;
3203
+ }
3204
+ if (kind === "referenced") {
3205
+ const via = referenceFieldOf(el);
3206
+ const prefix = via ? `${fieldLabel(via, locale)} \u203A ` : "";
3207
+ return `${prefix}${labelFor(el)} \xB7 ${t("visualEditor.linkedItem", locale)}`;
3208
+ }
3209
+ return labelFor(el);
3210
+ };
3211
+ const setSuspended = (value) => {
3212
+ if (suspended === value) return;
3213
+ suspended = value;
3214
+ document.documentElement.toggleAttribute(SUSPENDED_ATTR, value);
3215
+ if (value) overlay.setHover(null, "");
3216
+ };
3217
+ const updateHover = () => {
3218
+ pointerFrame = null;
3219
+ overlay.schedule();
3220
+ if (suspended) return;
3221
+ const encoded = encodedFrom(lastPointerTarget);
3222
+ const target = encoded === overlay.getSelectedTarget() ? null : encoded;
3223
+ if (!target) {
3224
+ overlay.setHover(null, "");
3225
+ return;
3226
+ }
3227
+ const kind = itemKind(target);
3228
+ if (!kind) {
3229
+ overlay.setHover(null, "");
3230
+ return;
3231
+ }
3232
+ overlay.setHover(target, hoverLabel(target, kind), { kind });
3233
+ };
3234
+ const handlePointerMove = (e2) => {
3235
+ setSuspended(e2.altKey);
3236
+ lastPointerTarget = e2.target;
3237
+ lastPointerX = e2.clientX;
3238
+ lastPointerY = e2.clientY;
3239
+ if (pointerFrame === null) {
3240
+ pointerFrame = requestAnimationFrame(updateHover);
3241
+ }
3242
+ };
3243
+ const handlePointerLeave = () => {
3244
+ lastPointerTarget = null;
3245
+ overlay.setHover(null, "");
3246
+ };
3247
+ const handleClick = (e2) => {
3248
+ if (e2.altKey) {
3249
+ const href = leavingLinkHref(e2.target);
3250
+ if (href && guard.isActive()) guard.permit(href);
3251
+ return;
3252
+ }
3253
+ const encoded = encodedFrom(e2.target);
3254
+ const kind = encoded ? itemKind(encoded) : null;
3255
+ if (!encoded || !kind) {
3256
+ clearSelection();
3257
+ if (e2.ctrlKey || e2.metaKey || e2.shiftKey || !showsEditedContent()) return;
3258
+ const href = leavingLinkHref(e2.target);
3259
+ if (!href) return;
3260
+ e2.preventDefault();
3261
+ if (guard.isActive()) {
3262
+ e2.stopPropagation();
3263
+ guard.block(href);
3264
+ }
3265
+ return;
3266
+ }
3267
+ if (kind === "other" && (e2.ctrlKey || e2.metaKey || e2.shiftKey)) return;
3268
+ e2.preventDefault();
3269
+ e2.stopPropagation();
3270
+ const item = listItemIn(encoded, e2.target);
3271
+ if (kind === "current")
3272
+ select(item?.element ?? encoded, encoded, item?.index);
3273
+ const referenceField = kind === "referenced" ? referenceFieldOf(encoded) : void 0;
3274
+ const linkedId = kind === "referenced" ? linkedIdOf(encoded) : null;
3275
+ const linkHref = kind === "other" ? leavingLinkHref(e2.target) : null;
3276
+ opts.onEdit({
3277
+ ...readEditPayload(encoded),
3278
+ ...linkedId && { id: linkedId },
3279
+ ...item && { block: item.index },
3280
+ ...referenceField && { referenceField },
3281
+ ...linkHref && { linkHref }
3282
+ });
3283
+ };
3284
+ const handleKey = (e2) => {
3285
+ if (e2.key === "Alt") setSuspended(e2.type === "keydown");
3286
+ if (e2.type === "keydown" && e2.key === "Escape") {
3287
+ clearSelection();
3288
+ }
3289
+ };
3290
+ const handleBlur = () => setSuspended(false);
3291
+ const handleScroll = () => overlay.onScroll();
3292
+ const handleResize = () => overlay.schedule();
3293
+ const handleSettled = () => overlay.schedule();
3294
+ function select(el, field, block) {
3295
+ const entryId = field.getAttribute("data-prepr-entry-id");
3296
+ selection = {
3297
+ lookup: {
3298
+ field: field.getAttribute(ATTR_FIELD) ?? "",
3299
+ id: field.getAttribute(ATTR_ID) ?? void 0,
3300
+ ...entryId && { entryId },
3301
+ ...block !== void 0 && { block }
3302
+ },
3303
+ label: field
3304
+ };
3305
+ overlay.setSelected(el, labelFor(field));
3306
+ if (overlay.getHoverTarget() === el) overlay.setHover(null, "");
3307
+ }
3308
+ function clearSelection() {
3309
+ selection = null;
3310
+ overlay.setSelected(null, "");
3311
+ }
3312
+ function reselect() {
3313
+ if (!selection) return;
3314
+ const current = overlay.getSelectedTarget();
3315
+ if (current?.isConnected && selection.label.isConnected) return;
3316
+ const found = findFieldElement(selection.lookup);
3317
+ if (!found || !isCurrentItem(found)) {
3318
+ overlay.setSelected(null, "");
3319
+ return;
3320
+ }
3321
+ const { block } = selection.lookup;
3322
+ const el = block !== void 0 ? nthListItem(found, block) ?? found : found;
3323
+ select(el, found, block);
3324
+ }
3325
+ const hasAssets = () => assetIndex.size > 0 || removedAssets.size > 0;
3326
+ function tagAssets() {
3327
+ if (assetKeys.size > MAX_CACHED_KEYS) assetKeys.clear();
3328
+ const showsRemoved = tagAssetImages(
3329
+ assetIndex,
3330
+ scope.currentItemId(),
3331
+ assetKeys,
3332
+ {
3333
+ isCurrentItem: (el) => isCurrentItem(el),
3334
+ removed: removedAssets
3335
+ }
3336
+ );
3337
+ if (saved && !showsRemoved) forgetRemoved();
3338
+ }
3339
+ function forgetRemoved() {
3340
+ saved = false;
3341
+ if (savedTimeout) clearTimeout(savedTimeout);
3342
+ savedTimeout = null;
3343
+ if (!removedAssets.size) return;
3344
+ removedAssets.clear();
3345
+ if (running) tagAssets();
3346
+ }
3347
+ function itemSaved() {
3348
+ if (!removedAssets.size) return;
3349
+ saved = true;
3350
+ if (savedTimeout) clearTimeout(savedTimeout);
3351
+ savedTimeout = setTimeout(forgetRemoved, SAVED_FADE_MS);
3352
+ }
3353
+ const handleLayoutFrame = () => {
3354
+ mutationFrame = null;
3355
+ if (hasAssets()) tagAssets();
3356
+ reselect();
3357
+ const hovered = overlay.getHoverTarget();
3358
+ if (hovered && !hovered.isConnected) {
3359
+ lastPointerTarget = document.elementFromPoint(lastPointerX, lastPointerY);
3360
+ updateHover();
3361
+ return;
3362
+ }
3363
+ overlay.schedule();
3364
+ };
3365
+ const handleMutations = () => {
3366
+ if (mutationFrame !== null) return;
3367
+ if (!selection && !overlay.getHoverTarget() && !hasAssets()) return;
3368
+ mutationFrame = requestAnimationFrame(handleLayoutFrame);
3369
+ };
3370
+ function injectCursorStyles() {
3371
+ if (document.querySelector(`style[${CURSOR_STYLE_MARKER}]`)) return;
3372
+ const style = document.createElement("style");
3373
+ style.setAttribute(CURSOR_STYLE_MARKER, "");
3374
+ style.textContent = CURSOR_STYLES;
3375
+ document.head.appendChild(style);
3376
+ }
3377
+ function start() {
3378
+ if (running) return;
3379
+ running = true;
3380
+ overlay.mount();
3381
+ injectCursorStyles();
3382
+ document.addEventListener("pointermove", handlePointerMove, {
3383
+ passive: true
3384
+ });
3385
+ document.documentElement.addEventListener(
3386
+ "pointerleave",
3387
+ handlePointerLeave
3388
+ );
3389
+ document.addEventListener("click", handleClick, { capture: true });
3390
+ window.addEventListener("keydown", handleKey);
3391
+ window.addEventListener("keyup", handleKey);
3392
+ window.addEventListener("blur", handleBlur);
3393
+ window.addEventListener("scroll", handleScroll, {
3394
+ capture: true,
3395
+ passive: true
3396
+ });
3397
+ window.addEventListener("resize", handleResize, { passive: true });
3398
+ document.addEventListener("transitionend", handleSettled, {
3399
+ capture: true,
3400
+ passive: true
3401
+ });
3402
+ document.addEventListener("animationend", handleSettled, {
3403
+ capture: true,
3404
+ passive: true
3405
+ });
3406
+ mutationObserver = new MutationObserver(handleMutations);
3407
+ mutationObserver.observe(document.body, LAYOUT_MUTATIONS);
3408
+ if (hasAssets()) tagAssets();
3409
+ syncGuard();
3410
+ debug8.log("visual editor started");
3411
+ }
3412
+ function stop() {
3413
+ if (!running) return;
3414
+ running = false;
3415
+ if (pointerFrame !== null) cancelAnimationFrame(pointerFrame);
3416
+ if (mutationFrame !== null) cancelAnimationFrame(mutationFrame);
3417
+ mutationObserver?.disconnect();
3418
+ mutationObserver = null;
3419
+ cancelFind();
3420
+ pointerFrame = null;
3421
+ mutationFrame = null;
3422
+ selection = null;
3423
+ lastPointerTarget = null;
3424
+ setSuspended(false);
3425
+ document.removeEventListener("pointermove", handlePointerMove);
3426
+ document.documentElement.removeEventListener(
3427
+ "pointerleave",
3428
+ handlePointerLeave
3429
+ );
3430
+ document.removeEventListener("click", handleClick, { capture: true });
3431
+ window.removeEventListener("keydown", handleKey);
3432
+ window.removeEventListener("keyup", handleKey);
3433
+ window.removeEventListener("blur", handleBlur);
3434
+ window.removeEventListener("scroll", handleScroll, { capture: true });
3435
+ window.removeEventListener("resize", handleResize);
3436
+ document.removeEventListener("transitionend", handleSettled, {
3437
+ capture: true
3438
+ });
3439
+ document.removeEventListener("animationend", handleSettled, {
3440
+ capture: true
3441
+ });
3442
+ document.querySelectorAll(`style[${CURSOR_STYLE_MARKER}]`).forEach((node) => node.remove());
3443
+ overlay.unmount();
3444
+ untagAssetImages();
3445
+ guard.stop();
3446
+ debug8.log("visual editor stopped");
3447
+ }
3448
+ function cancelFind() {
3449
+ if (findTimeout) clearTimeout(findTimeout);
3450
+ findTimeout = null;
3451
+ settlePendingFind?.();
3452
+ settlePendingFind = null;
3453
+ }
3454
+ function focusField(lookup) {
3455
+ cancelFind();
3456
+ return new Promise((resolve2) => {
3457
+ let attempt = 0;
3458
+ const finish = (found) => {
3459
+ settlePendingFind = null;
3460
+ resolve2(found);
3461
+ };
3462
+ settlePendingFind = () => resolve2(false);
3463
+ const tryFind = () => {
3464
+ findTimeout = null;
3465
+ const found = findFieldElement(lookup);
3466
+ if (found) {
3467
+ const el = lookup.block !== void 0 ? nthListItem(found, lookup.block) ?? found : found;
3468
+ scrollIntoFrame(el);
3469
+ if (running && isCurrentItem(found)) select(el, found, lookup.block);
3470
+ finish(true);
3471
+ return;
3472
+ }
3473
+ if (++attempt >= FIND_RETRIES) {
3474
+ debug8.log("no element renders field", lookup.field);
3475
+ finish(false);
3476
+ return;
3477
+ }
3478
+ findTimeout = setTimeout(tryFind, FIND_RETRY_MS);
3479
+ };
3480
+ tryFind();
3481
+ });
3482
+ }
3483
+ function setCurrentItem(itemId, referenceList, componentIds) {
3484
+ if (itemId !== scope.currentItemId()) forgetRemoved();
3485
+ scope.setCurrentItem(itemId);
3486
+ if (referenceList) setReferences(referenceList, componentIds);
3487
+ else if (componentIds) scope.setComponents(componentIds);
3488
+ if (running && hasAssets()) tagAssets();
3489
+ const selected = overlay.getSelectedTarget();
3490
+ const owner = selected ? encodedFrom(selected) : null;
3491
+ if (owner && !isCurrentItem(owner)) clearSelection();
3492
+ }
3493
+ function setAssets(assets) {
3494
+ const hadAssets = hasAssets();
3495
+ const next = createAssetIndex(assets);
3496
+ for (const [key, asset] of assetIndex) {
3497
+ if (!next.has(key)) removedAssets.set(key, asset);
3498
+ }
3499
+ for (const key of next.keys()) removedAssets.delete(key);
3500
+ assetIndex = next;
3501
+ if (running && (hadAssets || hasAssets())) tagAssets();
3502
+ }
3503
+ function setReferences(referenceList, componentIds) {
3504
+ if (componentIds) scope.setComponents(componentIds);
3505
+ scope.setReferences(referenceList);
3506
+ }
3507
+ function setLocale(value) {
3508
+ locale = value;
3509
+ }
3510
+ function syncGuard() {
3511
+ if (running && guardEnabled) guard.start();
3512
+ else guard.stop();
3513
+ }
3514
+ function setNavigationGuard(enabled) {
3515
+ guardEnabled = enabled;
3516
+ syncGuard();
3517
+ }
3518
+ return {
3519
+ start,
3520
+ stop,
3521
+ setCurrentItem,
3522
+ setReferences,
3523
+ setAssets,
3524
+ itemSaved,
3525
+ setLocale,
3526
+ focusField,
3527
+ setNavigationGuard,
3528
+ allowNavigation: (href) => guard.allow(href)
3529
+ };
3530
+ }
3531
+
3532
+ // src/core/create-preview.ts
3533
+ var debug9 = createScopedLogger("create-preview");
3534
+ var controllerStores = /* @__PURE__ */ new WeakMap();
3535
+ function defaultNavigation() {
3536
+ return {
3537
+ navigate: (url) => window.location.assign(url),
3538
+ currentPath: () => window.location.pathname + window.location.search
3539
+ };
3540
+ }
3541
+ function safeEditUrl(href) {
3542
+ try {
3543
+ const url = new URL(href, window.location.href);
3544
+ return url.protocol === "https:" || url.protocol === "http:" ? url.href : null;
3545
+ } catch {
3546
+ return null;
3547
+ }
3548
+ }
3549
+ function buildSegments(data, locale) {
3550
+ return [
3551
+ {
3552
+ _id: SEGMENT_ALL_OTHER_USERS,
3553
+ name: t("adaptiveContent.allOtherUsers", locale)
3554
+ },
3555
+ ...data
3556
+ ];
3557
+ }
3558
+ function resolveLocale(options) {
3559
+ const explicit = options?.locale;
3560
+ if (isLocale(explicit)) return explicit;
2200
3561
  if (typeof navigator !== "undefined") {
2201
3562
  const candidates = Array.isArray(navigator.languages) && navigator.languages.length ? navigator.languages : [navigator.language];
2202
3563
  const match = candidates.filter(Boolean).map((l2) => l2.toLowerCase().split("-")[0]).find(isLocale);
2203
3564
  if (match) return match;
2204
3565
  }
2205
- return "en";
3566
+ return "en";
3567
+ }
3568
+ function createPreprPreview(opts = {}) {
3569
+ const { props, options } = opts;
3570
+ const navigation = opts.navigation ?? defaultNavigation();
3571
+ initDebugLogger(options?.debug ?? false);
3572
+ const noop = () => ({ destroy: () => {
3573
+ } });
3574
+ if (typeof window === "undefined" || typeof document === "undefined") {
3575
+ return noop();
3576
+ }
3577
+ if (options?.strictMode) {
3578
+ const shared = sharedState();
3579
+ shared.strictMode = true;
3580
+ if (shared.liveAnnouncedStrict === false) {
3581
+ sendPreprEvent(
3582
+ "live_ready",
3583
+ { strictMode: true },
3584
+ { allowUntrustedTarget: true }
3585
+ );
3586
+ shared.liveAnnouncedStrict = true;
3587
+ }
3588
+ }
3589
+ const isIframe = window.parent !== window;
3590
+ const search = new URLSearchParams(window.location.search);
3591
+ const hideBar = search.get(PARAM_HIDE_BAR) === "true";
3592
+ if (hideBar) {
3593
+ debug9.log(`${PARAM_HIDE_BAR}=true \u2014 no visible toolbar`);
3594
+ }
3595
+ const mountUi = (options?.ui ?? true) && !isIframe && !hideBar;
3596
+ const locale = resolveLocale(options);
3597
+ const features = resolveFeatures(options?.features);
3598
+ const previewMode = getCookie(COOKIE_PREVIEW_MODE) === "true";
3599
+ const toolbarOpen = getCookie(COOKIE_TOOLBAR_OPEN) === "true";
3600
+ const cookieSegment = features.segments ? getCookie(COOKIE_SEGMENT) : null;
3601
+ const cookieVariant = features.abTesting ? getCookie(COOKIE_VARIANT) : null;
3602
+ const rawVariant = features.abTesting ? props?.activeVariant ?? cookieVariant : null;
3603
+ const selectedVariant = rawVariant === "A" || rawVariant === "B" ? rawVariant : null;
3604
+ const store = createToolbarStore({
3605
+ locale,
3606
+ features,
3607
+ segments: features.segments ? buildSegments(props?.segments ?? props?.data ?? [], locale) : [],
3608
+ selectedSegment: features.segments ? props?.activeSegment ?? cookieSegment ?? null : null,
3609
+ selectedVariant,
3610
+ previewMode,
3611
+ toolbarOpen,
3612
+ isIframe
3613
+ });
3614
+ let el = null;
3615
+ if (mountUi) {
3616
+ definePreprToolbar();
3617
+ el = document.createElement(TOOLBAR_TAG);
3618
+ document.body.appendChild(el);
3619
+ el.connect(store, (key) => t(key, locale));
3620
+ }
3621
+ const editingEnabled = features.editMode || isIframe;
3622
+ const onEdit = ({
3623
+ href,
3624
+ id,
3625
+ field,
3626
+ locale: contentLocale,
3627
+ block,
3628
+ entryId,
3629
+ referenceField,
3630
+ linkHref
3631
+ }) => {
3632
+ const safeHref = href ? safeEditUrl(href) : null;
3633
+ if (href && !safeHref) {
3634
+ debug9.warn("ignored edit request with unsupported href scheme");
3635
+ return;
3636
+ }
3637
+ if (isIframe) {
3638
+ sendPreprEvent("field_edit_requested", {
3639
+ id,
3640
+ field,
3641
+ locale: contentLocale,
3642
+ ...block !== void 0 && { block },
3643
+ ...entryId && { entryId },
3644
+ ...referenceField && { referenceField },
3645
+ ...linkHref && { linkHref }
3646
+ });
3647
+ } else if (safeHref) {
3648
+ window.open(safeHref, "_blank", "noopener,noreferrer");
3649
+ }
3650
+ };
3651
+ const visualEditor = isIframe ? createVisualEditor({
3652
+ onEdit,
3653
+ locale,
3654
+ onNavigationBlocked: (href) => sendPreprEvent("navigation_blocked", { href })
3655
+ }) : null;
3656
+ const stega = visualEditor ?? createStegaController({
3657
+ // The edit-mode marks and hover label are chrome, so they follow the
3658
+ // same decision as the bar: unwanted in a headless preview that asked
3659
+ // for no UI.
3660
+ tooltip: mountUi,
3661
+ onEdit,
3662
+ locale
3663
+ });
3664
+ const autoClean = createStegaAutoClean({
3665
+ enabled: options?.autoClean
3666
+ });
3667
+ autoClean.start();
3668
+ const handleChange = createChangeHandler({
3669
+ store,
3670
+ features,
3671
+ editingEnabled,
3672
+ navigate: (url) => navigation.navigate(url),
3673
+ currentPath: () => navigation.currentPath(),
3674
+ reload: navigation.reload ?? (() => window.location.reload()),
3675
+ stega
3676
+ });
3677
+ let prev = store.get();
3678
+ const unsubscribe = store.subscribe((state) => {
3679
+ const before = prev;
3680
+ prev = state;
3681
+ handleChange(before, state);
3682
+ });
3683
+ const bridge = createIframeBridge(store, {
3684
+ allowedEditorOrigins: options?.allowedEditorOrigins,
3685
+ onHandshake: ({
3686
+ itemId,
3687
+ referencedIds,
3688
+ componentIds,
3689
+ uiLocale,
3690
+ navigationGuard,
3691
+ assets
3692
+ }) => {
3693
+ if (uiLocale) visualEditor?.setLocale(uiLocale);
3694
+ visualEditor?.setCurrentItem(itemId ?? null, referencedIds, componentIds);
3695
+ visualEditor?.setNavigationGuard(navigationGuard === true);
3696
+ if (assets) visualEditor?.setAssets(assets);
3697
+ },
3698
+ onAssets: (assets) => visualEditor?.setAssets(assets),
3699
+ onAllowNavigation: (href) => visualEditor?.allowNavigation(href),
3700
+ onItemChanged: () => visualEditor?.itemSaved(),
3701
+ onReferences: (referencedIds, componentIds) => visualEditor?.setReferences(referencedIds, componentIds),
3702
+ // The editor selecting a field scrolls the matching element into view. The
3703
+ // lookup relies on the attributes the stega scan writes, so it finds
3704
+ // nothing until encoded content has been tagged.
3705
+ onScrollToField: ({ field, id, block, entryId, fieldById }) => {
3706
+ if (visualEditor) {
3707
+ void visualEditor.focusField({ field, id, block, entryId, fieldById });
3708
+ return;
3709
+ }
3710
+ if (!scrollToField({ field, id })) {
3711
+ debug9.log("no element on this page renders field", field);
3712
+ }
3713
+ }
3714
+ });
3715
+ sendPreprEvent(
3716
+ "getScrollPosition",
3717
+ { value: 0 },
3718
+ {
3719
+ allowUntrustedTarget: true
3720
+ }
3721
+ );
3722
+ if (isIframe) {
3723
+ bridge.start();
3724
+ }
3725
+ function destroy() {
3726
+ unsubscribe();
3727
+ stega.stop();
3728
+ autoClean.stop();
3729
+ if (isIframe) {
3730
+ bridge.stop();
3731
+ }
3732
+ el?.remove();
3733
+ debug9.log("preview destroyed");
3734
+ }
3735
+ const controller = { destroy };
3736
+ controllerStores.set(controller, store);
3737
+ return controller;
3738
+ }
3739
+
3740
+ // src/core/preview-attrs.ts
3741
+ function previewAttrs(target, options) {
3742
+ if (!options.enabled || !target?.id || !target.field) return {};
3743
+ const attrs = {
3744
+ "data-prepr-encoded": "",
3745
+ "data-prepr-id": target.id,
3746
+ "data-prepr-field": target.field
3747
+ };
3748
+ if (target.locale) attrs["data-prepr-locale"] = target.locale;
3749
+ if (target.entryId) attrs["data-prepr-entry-id"] = target.entryId;
3750
+ return attrs;
3751
+ }
3752
+ var URL_BASE = "https://prepr.invalid";
3753
+ function stegaTarget(value, options = {}) {
3754
+ const decoded = value ? decodeStega(value) : null;
3755
+ if (!decoded) return null;
3756
+ let url;
3757
+ let id;
3758
+ try {
3759
+ url = new URL(decoded.href, URL_BASE);
3760
+ id = decodeURIComponent(url.pathname.split("/").pop() ?? "");
3761
+ } catch {
3762
+ return null;
3763
+ }
3764
+ const field = url.searchParams.get("field");
3765
+ if (!id || !field) return null;
3766
+ return {
3767
+ id,
3768
+ field: options.field ? `${field.slice(0, field.lastIndexOf(".") + 1)}${options.field}` : field,
3769
+ locale: url.searchParams.get("locale")
3770
+ };
3771
+ }
3772
+
3773
+ // src/core/live-preview/guards.ts
3774
+ function isScalar(value) {
3775
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
3776
+ }
3777
+ function isObject(value) {
3778
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3779
+ }
3780
+
3781
+ // src/core/live-preview/entry-edit-links.ts
3782
+ var import_stega5 = require("@vercel/stega");
3783
+
3784
+ // src/core/live-preview/validate.ts
3785
+ var MAX_DEPTH = 3;
3786
+ var MAX_ENTRIES = 50;
3787
+ var FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
3788
+ var SAFE_URL = /^https?:\/\//i;
3789
+ var URL_KEY = /^(?:url|href|src|link)$|(?:_url|Url)$/;
3790
+ var URL_IGNORED_ANYWHERE = /[\t\n\r]/g;
3791
+ var SCRIPT_SCHEME = /^(?:javascript|vbscript|data):/i;
3792
+ function isSafeLinkValue(value) {
3793
+ const stripped = value.replace(URL_IGNORED_ANYWHERE, "");
3794
+ let start = 0;
3795
+ while (start < stripped.length && stripped.charCodeAt(start) <= 32) start++;
3796
+ return !SCRIPT_SCHEME.test(stripped.slice(start));
3797
+ }
3798
+ function isUrlKey(key) {
3799
+ return URL_KEY.test(key);
3800
+ }
3801
+ function isSafeKeyValue(key, value) {
3802
+ if (typeof value !== "string") return true;
3803
+ if (key === "url") return SAFE_URL.test(value);
3804
+ return !isUrlKey(key) || isSafeLinkValue(value);
3805
+ }
3806
+ function isLiveValue(v2, depth = 0) {
3807
+ if (v2 === null || isScalar(v2)) return true;
3808
+ if (depth >= MAX_DEPTH) return false;
3809
+ if (Array.isArray(v2)) {
3810
+ return depth === 0 && v2.length <= MAX_ENTRIES && v2.every((entry) => isPlainRecord(entry) && isLiveValue(entry, depth + 1));
3811
+ }
3812
+ if (!isPlainRecord(v2)) return false;
3813
+ const keys = Object.keys(v2);
3814
+ if (keys.length > MAX_ENTRIES) return false;
3815
+ return keys.every((key) => {
3816
+ if (FORBIDDEN_KEYS.has(key)) return false;
3817
+ const value = v2[key];
3818
+ if (!isSafeKeyValue(key, value)) return false;
3819
+ return !Array.isArray(value) && isLiveValue(value, depth + 1);
3820
+ });
3821
+ }
3822
+ function isLiveFieldChange(field, value) {
3823
+ if (!isLiveValue(value)) return false;
3824
+ const name = field.slice(field.lastIndexOf(".") + 1);
3825
+ return typeof value !== "string" || !isUrlKey(name) || isSafeLinkValue(value);
3826
+ }
3827
+ var MAX_LIST_ENTRIES = 200;
3828
+ function parseListEntries(value) {
3829
+ if (!Array.isArray(value) || value.length > MAX_LIST_ENTRIES) return null;
3830
+ const list = [];
3831
+ for (const raw of value) {
3832
+ if (!isPlainRecord(raw) || typeof raw._id !== "string" || !raw._id) {
3833
+ return null;
3834
+ }
3835
+ const entry = { _id: raw._id };
3836
+ if (typeof raw.__typename === "string") entry.__typename = raw.__typename;
3837
+ if (typeof raw.body === "string") entry.body = raw.body;
3838
+ if (typeof raw.format === "string" || raw.format === null) {
3839
+ entry.format = raw.format;
3840
+ }
3841
+ if (typeof raw.typeName === "string" && raw.typeName.length <= 200) {
3842
+ entry.typeName = raw.typeName;
3843
+ }
3844
+ if (raw.fields !== void 0) {
3845
+ if (!isPlainRecord(raw.fields) || !isFieldValue(raw.fields, 0)) {
3846
+ return null;
3847
+ }
3848
+ entry.fields = raw.fields;
3849
+ }
3850
+ list.push(entry);
3851
+ }
3852
+ return list;
3853
+ }
3854
+ function isPlainRecord(v2) {
3855
+ return v2 !== null && typeof v2 === "object" && Object.getPrototypeOf(v2) === Object.prototype;
3856
+ }
3857
+ var MAX_FIELD_DEPTH = 6;
3858
+ var MAX_FIELD_KEYS = 100;
3859
+ function isFieldValue(v2, depth) {
3860
+ if (v2 === null || isScalar(v2)) return true;
3861
+ if (depth >= MAX_FIELD_DEPTH) return false;
3862
+ if (Array.isArray(v2)) {
3863
+ return v2.length <= MAX_ENTRIES && v2.every(
3864
+ (entry) => isScalar(entry) || isPlainRecord(entry) && isFieldValue(entry, depth + 1)
3865
+ );
3866
+ }
3867
+ if (!isPlainRecord(v2)) return false;
3868
+ const keys = Object.keys(v2);
3869
+ if (keys.length > MAX_FIELD_KEYS) return false;
3870
+ return keys.every((key) => {
3871
+ if (FORBIDDEN_KEYS.has(key)) return false;
3872
+ const value = v2[key];
3873
+ if (!isSafeKeyValue(key, value)) return false;
3874
+ return isFieldValue(value, depth + 1);
3875
+ });
3876
+ }
3877
+ var MAX_EDIT_LENGTH = 1e3;
3878
+ function parseEditTarget(raw) {
3879
+ if (!isPlainRecord(raw)) return void 0;
3880
+ const { item, field } = raw;
3881
+ if (typeof item !== "string" || !item || item.length > MAX_EDIT_LENGTH) {
3882
+ return void 0;
3883
+ }
3884
+ if (typeof field !== "string" || !field || field.length > MAX_EDIT_LENGTH) {
3885
+ return void 0;
3886
+ }
3887
+ return { item, field };
3888
+ }
3889
+
3890
+ // src/core/live-preview/entry-edit-links.ts
3891
+ var EDIT_PATH = /\/content\/edit\/[^/?#]+/;
3892
+ function editLinks(result, entry) {
3893
+ const edit = entry.fields?.__edit;
3894
+ if (!isPlainRecord(edit) || typeof edit.item !== "string") return null;
3895
+ return editLinksFor(result, edit.item);
3896
+ }
3897
+ var ITEM_ID = /^[A-Za-z0-9_-]+$/;
3898
+ function editLinksFor(result, item) {
3899
+ if (!ITEM_ID.test(item)) return null;
3900
+ const template = findEditLink(result);
3901
+ if (!template) return null;
3902
+ return {
3903
+ encode(text, field) {
3904
+ if ((0, import_stega5.vercelStegaSplit)(text).encoded) return text;
3905
+ let href;
3906
+ try {
3907
+ href = new URL(template.href);
3908
+ } catch {
3909
+ return text;
3910
+ }
3911
+ href.pathname = href.pathname.replace(
3912
+ EDIT_PATH,
3913
+ () => `/content/edit/${item}`
3914
+ );
3915
+ href.searchParams.set("field", field);
3916
+ const link = href.toString().replace(/%2E/gi, ".").replace(/%2F/gi, "/");
3917
+ return (0, import_stega5.vercelStegaCombine)(text, { origin: template.origin, href: link });
3918
+ }
3919
+ };
3920
+ }
3921
+ var linkCache = /* @__PURE__ */ new WeakMap();
3922
+ function findEditLink(root) {
3923
+ if (root === null || typeof root !== "object") return null;
3924
+ if (linkCache.has(root)) return linkCache.get(root) ?? null;
3925
+ let found = null;
3926
+ const seen = /* @__PURE__ */ new WeakSet();
3927
+ const walk2 = (node) => {
3928
+ if (found) return;
3929
+ if (typeof node === "string") {
3930
+ if (!(0, import_stega5.vercelStegaSplit)(node).encoded) return;
3931
+ try {
3932
+ const decoded = (0, import_stega5.vercelStegaDecode)(node);
3933
+ if (typeof decoded?.origin === "string" && typeof decoded.href === "string" && EDIT_PATH.test(decoded.href)) {
3934
+ found = { origin: decoded.origin, href: decoded.href };
3935
+ }
3936
+ } catch {
3937
+ }
3938
+ return;
3939
+ }
3940
+ if (node === null || typeof node !== "object" || seen.has(node)) return;
3941
+ seen.add(node);
3942
+ for (const value of Object.values(node)) walk2(value);
3943
+ };
3944
+ walk2(root);
3945
+ linkCache.set(root, found);
3946
+ return found;
3947
+ }
3948
+
3949
+ // src/core/live-preview/patch-log.ts
3950
+ var MAX_LOG_ENTRIES = 500;
3951
+ var MAX_LOG_SOURCE_LENGTH = 1e6;
3952
+ function parsePatchLog(raw) {
3953
+ let value = raw;
3954
+ if (typeof value === "string") {
3955
+ if (!value || value.length > MAX_LOG_SOURCE_LENGTH) return [];
3956
+ try {
3957
+ value = JSON.parse(value);
3958
+ } catch {
3959
+ return [];
3960
+ }
3961
+ }
3962
+ if (!Array.isArray(value)) return [];
3963
+ const log = [];
3964
+ for (const entry of value.slice(-MAX_LOG_ENTRIES)) {
3965
+ if (!isPlainRecord(entry)) continue;
3966
+ const { type, itemId, field } = entry;
3967
+ if (typeof itemId !== "string" || !itemId) continue;
3968
+ if (typeof field !== "string" || !field) continue;
3969
+ if (type === "field" && isLiveFieldChange(field, entry.value)) {
3970
+ const edit = parseEditTarget(entry.edit);
3971
+ log.push(
3972
+ edit ? { type, itemId, field, value: entry.value, edit } : { type, itemId, field, value: entry.value }
3973
+ );
3974
+ } else if (type === "list") {
3975
+ const entries = parseListEntries(entry.entries);
3976
+ if (entries) log.push({ type, itemId, field, entries });
3977
+ }
3978
+ }
3979
+ return log;
3980
+ }
3981
+
3982
+ // src/core/live-preview/normalize-query.ts
3983
+ var import_stega7 = require("@vercel/stega");
3984
+
3985
+ // src/core/live-preview/field-name.ts
3986
+ var UPPERCASE_BOUNDARY = /(.)(?=[A-Z])/g;
3987
+ function graphqlFieldName(apiId) {
3988
+ return apiId.replace(UPPERCASE_BOUNDARY, "$1_").toLowerCase();
3989
+ }
3990
+ function fieldKeyIn(record, apiId) {
3991
+ if (Object.prototype.hasOwnProperty.call(record, apiId)) return apiId;
3992
+ const name = graphqlFieldName(apiId);
3993
+ return Object.prototype.hasOwnProperty.call(record, name) ? name : void 0;
3994
+ }
3995
+ var TEXT_BODY_FIELDS = [
3996
+ { name: "body", plain: false },
3997
+ { name: "html", plain: false },
3998
+ { name: "text", plain: true }
3999
+ ];
4000
+ var TAG_PATTERN = /<[^>]+>/g;
4001
+ function plainTextFromHtml(html) {
4002
+ return html.replace(TAG_PATTERN, "");
4003
+ }
4004
+ function isTextEntry(record) {
4005
+ const typename = record.__typename;
4006
+ if (typeof typename === "string") return typename === "Text";
4007
+ return "html" in record || "text" in record && "format" in record;
4008
+ }
4009
+
4010
+ // src/core/live-preview/index-snapshot.ts
4011
+ var debug10 = createScopedLogger("live-preview");
4012
+ function indexSnapshot(data) {
4013
+ const index = /* @__PURE__ */ new Map();
4014
+ const visited = /* @__PURE__ */ new WeakSet();
4015
+ const path = [];
4016
+ function walk2(node) {
4017
+ if (node === null || typeof node !== "object") return;
4018
+ if (visited.has(node)) return;
4019
+ visited.add(node);
4020
+ if (Array.isArray(node)) {
4021
+ for (let i2 = 0; i2 < node.length; i2++) {
4022
+ path.push(i2);
4023
+ walk2(node[i2]);
4024
+ path.pop();
4025
+ }
4026
+ return;
4027
+ }
4028
+ const record = node;
4029
+ if (typeof record._id === "string") {
4030
+ const paths = index.get(record._id);
4031
+ if (paths) paths.push([...path]);
4032
+ else index.set(record._id, [[...path]]);
4033
+ } else if (typeof record.__typename === "string") {
4034
+ debug10.log("item without _id will not live-update", {
4035
+ __typename: record.__typename
4036
+ });
4037
+ }
4038
+ for (const key in record) {
4039
+ if (!Object.prototype.hasOwnProperty.call(record, key)) continue;
4040
+ path.push(key);
4041
+ walk2(record[key]);
4042
+ path.pop();
4043
+ }
4044
+ }
4045
+ walk2(data);
4046
+ return index;
4047
+ }
4048
+
4049
+ // src/core/live-preview/patch.ts
4050
+ var import_stega6 = require("@vercel/stega");
4051
+ var INDEX_SEGMENT2 = /^\d+$/;
4052
+ var FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
4053
+ function mergeObject(current, incoming) {
4054
+ let changed = false;
4055
+ const next = { ...current };
4056
+ for (const key of Object.keys(current)) {
4057
+ if (!(key in incoming) || incoming[key] === void 0) continue;
4058
+ const value = isObject(current[key]) && isObject(incoming[key]) ? mergeObject(current[key], incoming[key]) : incoming[key];
4059
+ if (value !== current[key]) {
4060
+ next[key] = value;
4061
+ changed = true;
4062
+ }
4063
+ }
4064
+ return changed ? next : current;
4065
+ }
4066
+ function shapeLike(template, incoming) {
4067
+ const out = {};
4068
+ for (const key of Object.keys(template)) {
4069
+ const value = incoming[key];
4070
+ out[key] = value === void 0 ? null : isObject(template[key]) && isObject(value) ? shapeLike(template[key], value) : value;
4071
+ }
4072
+ return out;
4073
+ }
4074
+ function isAsset(value) {
4075
+ return isObject(value) && (typeof value.url === "string" || value.__typename === "Asset");
4076
+ }
4077
+ function hasId(list, entry) {
4078
+ return entry._id !== void 0 && list.some((c2) => isObject(c2) && c2._id === entry._id);
4079
+ }
4080
+ function isAssetValue(value) {
4081
+ return Array.isArray(value) ? value.length > 0 && value.every(isAsset) : isAsset(value);
4082
+ }
4083
+ function keepRemovedAssets(current, next) {
4084
+ const listed = /* @__PURE__ */ new Set();
4085
+ for (const entry of next) {
4086
+ if (isObject(entry) && entry._id !== void 0) listed.add(entry._id);
4087
+ }
4088
+ let out = next;
4089
+ current.forEach((entry, position) => {
4090
+ if (!isObject(entry) || entry._id === void 0) return;
4091
+ if (listed.has(entry._id)) return;
4092
+ if (out === next) out = [...next];
4093
+ out.splice(Math.min(position, out.length), 0, entry);
4094
+ });
4095
+ return out;
4096
+ }
4097
+ function mergeStructured(current, incoming) {
4098
+ if (incoming === null || Array.isArray(incoming) && !incoming.length) {
4099
+ if (isAssetValue(current)) return current;
4100
+ if (Array.isArray(current)) return current.length ? [] : current;
4101
+ return null;
4102
+ }
4103
+ const list = Array.isArray(incoming) ? incoming : [incoming];
4104
+ if (current === null || current === void 0) return incoming;
4105
+ if (Array.isArray(current)) {
4106
+ const template = current.find(isObject);
4107
+ const next = list.map((entry) => {
4108
+ const match = current.find(
4109
+ (c2) => isObject(c2) && c2._id !== void 0 && c2._id === entry._id
4110
+ );
4111
+ if (isObject(match)) return mergeObject(match, entry);
4112
+ return isObject(template) ? shapeLike(template, entry) : entry;
4113
+ });
4114
+ if (!isAssetValue(current) || list.some((entry) => !hasId(current, entry))) {
4115
+ return next;
4116
+ }
4117
+ const kept = keepRemovedAssets(current, next);
4118
+ return kept.length === current.length && kept.every((entry, i2) => entry === current[i2]) ? current : kept;
4119
+ }
4120
+ if (isObject(current)) return mergeObject(current, list[0]);
4121
+ return current;
4122
+ }
4123
+ function isPatchable(current) {
4124
+ return current === null || typeof current === "string" || typeof current === "number" || typeof current === "boolean";
4125
+ }
4126
+ function cloneNode(node) {
4127
+ return Array.isArray(node) ? [...node] : { ...node };
4128
+ }
4129
+ function patchSnapshot(snapshot, index, itemId, field, value) {
4130
+ const paths = index.get(itemId);
4131
+ if (!paths?.length) return snapshot;
4132
+ let root = snapshot;
4133
+ let changed = false;
4134
+ const markChanged = () => {
4135
+ changed = true;
4136
+ };
4137
+ for (const path of paths) {
4138
+ for (const [target, targetValue] of expandTextBody(
4139
+ root,
4140
+ path,
4141
+ field,
4142
+ value
4143
+ )) {
4144
+ root = patchAtPath(root, path, target, targetValue, markChanged);
4145
+ }
4146
+ }
4147
+ return changed ? root : snapshot;
4148
+ }
4149
+ function expandTextBody(root, path, field, value) {
4150
+ const segments = field.split(".");
4151
+ if (segments[segments.length - 1] !== "body" || typeof value !== "string") {
4152
+ return [[field, value]];
4153
+ }
4154
+ let node = root;
4155
+ for (const step of path) {
4156
+ node = node[step];
4157
+ }
4158
+ for (const segment of segments.slice(0, -1)) {
4159
+ if (node === null || typeof node !== "object") return [[field, value]];
4160
+ const record2 = node;
4161
+ node = INDEX_SEGMENT2.test(segment) ? record2[Number(segment)] : record2[fieldKeyIn(record2, segment) ?? segment];
4162
+ }
4163
+ if (node === null || typeof node !== "object" || Array.isArray(node)) {
4164
+ return [[field, value]];
4165
+ }
4166
+ const record = node;
4167
+ if (!isTextEntry(record)) return [[field, value]];
4168
+ const prefix = segments.slice(0, -1);
4169
+ const writes = [];
4170
+ for (const { name, plain } of TEXT_BODY_FIELDS) {
4171
+ if (!(name in record)) continue;
4172
+ writes.push([
4173
+ [...prefix, name].join("."),
4174
+ plain ? plainTextFromHtml(value) : value
4175
+ ]);
4176
+ }
4177
+ return writes.length ? writes : [[field, value]];
4178
+ }
4179
+ function patchAtPath(root, path, field, value, markChanged) {
4180
+ const segments = field.split(".");
4181
+ if (segments.some((s2) => FORBIDDEN_SEGMENTS.has(s2))) return root;
4182
+ let node = root;
4183
+ for (const step of path) {
4184
+ node = node[step];
4185
+ }
4186
+ const fullPath = [...path];
4187
+ for (const segment of segments) {
4188
+ let step = segment;
4189
+ if (INDEX_SEGMENT2.test(segment)) {
4190
+ step = Number(segment);
4191
+ } else if (node !== null && typeof node === "object") {
4192
+ step = fieldKeyIn(node, segment) ?? segment;
4193
+ }
4194
+ fullPath.push(step);
4195
+ node = node !== null && typeof node === "object" ? node[step] : void 0;
4196
+ }
4197
+ return writeAtPath(root, fullPath, value, markChanged);
4198
+ }
4199
+ function writeAtPath(root, fullPath, value, markChanged = () => {
4200
+ }) {
4201
+ if (!fullPath.length) return root;
4202
+ if (fullPath.some((s2) => FORBIDDEN_SEGMENTS.has(String(s2)))) return root;
4203
+ const last = fullPath.length - 1;
4204
+ let node = root;
4205
+ for (let i2 = 0; i2 < last; i2++) {
4206
+ if (node === null || typeof node !== "object") return root;
4207
+ node = node[fullPath[i2]];
4208
+ }
4209
+ if (node === null || typeof node !== "object") return root;
4210
+ const container = node;
4211
+ const key = fullPath[last];
4212
+ if (!(key in container)) return root;
4213
+ let next;
4214
+ if (value === null || typeof value === "object") {
4215
+ next = mergeStructured(container[key], value);
4216
+ } else if (!isPatchable(container[key])) {
4217
+ return root;
4218
+ } else {
4219
+ next = keepEditLink(container[key], value);
4220
+ }
4221
+ if (container[key] === next) return root;
4222
+ const newRoot = cloneNode(root);
4223
+ let cursor = newRoot;
4224
+ for (let i2 = 0; i2 < last; i2++) {
4225
+ const child = cloneNode(cursor[fullPath[i2]]);
4226
+ cursor[fullPath[i2]] = child;
4227
+ cursor = child;
4228
+ }
4229
+ cursor[key] = next;
4230
+ markChanged();
4231
+ return newRoot;
4232
+ }
4233
+ function listKeysOf(entry) {
4234
+ if (!isObject(entry)) return [];
4235
+ const keys = [];
4236
+ if (typeof entry._id === "string") keys.push(entry._id);
4237
+ const first = Array.isArray(entry.items) ? entry.items[0] : null;
4238
+ if (isObject(first) && typeof first._id === "string") {
4239
+ keys.push(first._id);
4240
+ }
4241
+ return keys;
4242
+ }
4243
+ function buildText(entry, template) {
4244
+ const body = typeof entry.body === "string" ? entry.body : "";
4245
+ const full = {
4246
+ __typename: "Text",
4247
+ _id: entry._id,
4248
+ body,
4249
+ html: body,
4250
+ text: plainTextFromHtml(body),
4251
+ format: entry.format ?? null
4252
+ };
4253
+ if (!template) return full;
4254
+ const out = {};
4255
+ for (const key of Object.keys(template)) {
4256
+ out[key] = key in full ? full[key] : null;
4257
+ }
4258
+ return out;
4259
+ }
4260
+ function syncList(current, entries, build) {
4261
+ if (current === null || current === void 0) {
4262
+ const built = syncList([], entries, build);
4263
+ return built.length ? built : current;
4264
+ }
4265
+ if (!Array.isArray(current)) return current;
4266
+ const byKey = /* @__PURE__ */ new Map();
4267
+ const templates = /* @__PURE__ */ new Map();
4268
+ for (const c2 of current) {
4269
+ for (const key of listKeysOf(c2)) byKey.set(key, c2);
4270
+ if (isObject(c2) && typeof c2.__typename === "string") {
4271
+ if (!templates.has(c2.__typename)) templates.set(c2.__typename, c2);
4272
+ }
4273
+ }
4274
+ if (!entries.length) return current.length ? [] : current;
4275
+ if (current.length && !byKey.size) return current;
4276
+ if (current.length && !entries.some((e2) => byKey.has(e2._id))) return current;
4277
+ const next = [];
4278
+ for (const entry of entries) {
4279
+ const existing = byKey.get(entry._id);
4280
+ const built = existing === void 0 && entry.fields ? build?.(entry) : void 0;
4281
+ if (existing !== void 0) {
4282
+ next.push(existing);
4283
+ } else if (built) {
4284
+ next.push(built);
4285
+ } else if (entry.__typename === "Text") {
4286
+ next.push(buildText(entry, templates.get("Text")));
4287
+ }
4288
+ }
4289
+ const same = next.length === current.length && next.every((n2, i2) => n2 === current[i2]);
4290
+ return same ? current : next;
4291
+ }
4292
+ function syncListSnapshot(snapshot, index, itemId, field, entries) {
4293
+ const paths = index.get(itemId);
4294
+ if (!paths?.length) return snapshot;
4295
+ const fieldPath = field.split(".");
4296
+ if (fieldPath.some((s2) => FORBIDDEN_SEGMENTS.has(s2))) return snapshot;
4297
+ let root = snapshot;
4298
+ for (const path of paths) {
4299
+ root = syncListAtPath(root, [...path, ...fieldPath], entries);
4300
+ }
4301
+ return root;
4302
+ }
4303
+ function syncListAtPath(root, fullPath, entries, build) {
4304
+ if (!fullPath.length) return root;
4305
+ if (fullPath.some((s2) => FORBIDDEN_SEGMENTS.has(String(s2)))) return root;
4306
+ let node = root;
4307
+ for (const key of fullPath) {
4308
+ node = node !== null && typeof node === "object" ? node[key] : void 0;
4309
+ }
4310
+ const next = syncList(node, entries, build);
4311
+ if (next === node) return root;
4312
+ const newRoot = cloneNode(root);
4313
+ let cursor = newRoot;
4314
+ for (let i2 = 0; i2 < fullPath.length - 1; i2++) {
4315
+ const child = cloneNode(cursor[fullPath[i2]]);
4316
+ cursor[fullPath[i2]] = child;
4317
+ cursor = child;
4318
+ }
4319
+ cursor[fullPath[fullPath.length - 1]] = next;
4320
+ return newRoot;
4321
+ }
4322
+ function keepEditLink(current, value) {
4323
+ if (typeof current !== "string" || typeof value !== "string") return value;
4324
+ const { encoded } = (0, import_stega6.vercelStegaSplit)(current);
4325
+ if (!encoded || (0, import_stega6.vercelStegaSplit)(value).encoded) return value;
4326
+ return value + encoded;
4327
+ }
4328
+
4329
+ // src/core/live-preview/query-document.ts
4330
+ var NAME_START = /[_A-Za-z]/;
4331
+ var NAME_CONTINUE = /[_0-9A-Za-z]/;
4332
+ var PUNCT = /* @__PURE__ */ new Set([
4333
+ "!",
4334
+ "$",
4335
+ "&",
4336
+ "(",
4337
+ ")",
4338
+ ":",
4339
+ "=",
4340
+ "@",
4341
+ "[",
4342
+ "]",
4343
+ "{",
4344
+ "|",
4345
+ "}"
4346
+ ]);
4347
+ function tokenize(source) {
4348
+ const tokens = [];
4349
+ let i2 = 0;
4350
+ const n2 = source.length;
4351
+ while (i2 < n2) {
4352
+ const ch = source[i2];
4353
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "," || ch === "\uFEFF") {
4354
+ i2++;
4355
+ } else if (ch === "#") {
4356
+ while (i2 < n2 && source[i2] !== "\n" && source[i2] !== "\r") i2++;
4357
+ } else if (ch === "." && source.startsWith("...", i2)) {
4358
+ tokens.push({ type: "punct", value: "..." });
4359
+ i2 += 3;
4360
+ } else if (PUNCT.has(ch)) {
4361
+ tokens.push({ type: "punct", value: ch });
4362
+ i2++;
4363
+ } else if (NAME_START.test(ch)) {
4364
+ const start = i2;
4365
+ while (i2 < n2 && NAME_CONTINUE.test(source[i2])) i2++;
4366
+ tokens.push({ type: "name", value: source.slice(start, i2) });
4367
+ } else if (ch === '"') {
4368
+ if (source.startsWith('"""', i2)) {
4369
+ i2 += 3;
4370
+ while (i2 < n2 && !source.startsWith('"""', i2)) {
4371
+ i2 += source.startsWith('\\"""', i2) ? 4 : 1;
4372
+ }
4373
+ if (i2 >= n2) throw new SyntaxError("Unterminated block string");
4374
+ i2 += 3;
4375
+ } else {
4376
+ i2++;
4377
+ while (i2 < n2 && source[i2] !== '"') {
4378
+ if (source[i2] === "\n" || source[i2] === "\r") {
4379
+ throw new SyntaxError("Unterminated string");
4380
+ }
4381
+ i2 += source[i2] === "\\" ? 2 : 1;
4382
+ }
4383
+ if (i2 >= n2) throw new SyntaxError("Unterminated string");
4384
+ i2++;
4385
+ }
4386
+ tokens.push({ type: "value" });
4387
+ } else if (ch === "-" || ch >= "0" && ch <= "9") {
4388
+ i2++;
4389
+ while (i2 < n2 && /[0-9.eE+-]/.test(source[i2])) i2++;
4390
+ tokens.push({ type: "value" });
4391
+ } else {
4392
+ throw new SyntaxError(`Unexpected character "${ch}"`);
4393
+ }
4394
+ }
4395
+ return tokens;
4396
+ }
4397
+ function parseSource(source, operationName) {
4398
+ const tokens = tokenize(source);
4399
+ let pos = 0;
4400
+ const peek = () => tokens[pos];
4401
+ const isPunct = (value) => {
4402
+ const t3 = tokens[pos];
4403
+ return t3?.type === "punct" && t3.value === value;
4404
+ };
4405
+ const expectPunct = (value) => {
4406
+ if (!isPunct(value)) throw new SyntaxError(`Expected "${value}"`);
4407
+ pos++;
4408
+ };
4409
+ const expectName = () => {
4410
+ const t3 = tokens[pos];
4411
+ if (t3?.type !== "name") throw new SyntaxError("Expected a name");
4412
+ pos++;
4413
+ return t3.value;
4414
+ };
4415
+ const skipParens = () => {
4416
+ expectPunct("(");
4417
+ let depth = 1;
4418
+ while (depth > 0) {
4419
+ const t3 = tokens[pos++];
4420
+ if (!t3) throw new SyntaxError("Unbalanced parentheses");
4421
+ if (t3.type === "punct" && t3.value === "(") depth++;
4422
+ else if (t3.type === "punct" && t3.value === ")") depth--;
4423
+ }
4424
+ };
4425
+ const skipDirectives = () => {
4426
+ while (isPunct("@")) {
4427
+ pos++;
4428
+ expectName();
4429
+ if (isPunct("(")) skipParens();
4430
+ }
4431
+ };
4432
+ const parseSelectionSet = () => {
4433
+ expectPunct("{");
4434
+ const selections = [];
4435
+ while (!isPunct("}")) {
4436
+ if (!peek()) throw new SyntaxError("Unterminated selection set");
4437
+ selections.push(parseSelection());
4438
+ }
4439
+ pos++;
4440
+ return selections;
4441
+ };
4442
+ const parseSelection = () => {
4443
+ if (isPunct("...")) {
4444
+ pos++;
4445
+ const t3 = peek();
4446
+ if (t3?.type === "name" && t3.value !== "on") {
4447
+ pos++;
4448
+ skipDirectives();
4449
+ return { kind: "spread", name: t3.value };
4450
+ }
4451
+ let on = null;
4452
+ if (t3?.type === "name") {
4453
+ pos++;
4454
+ on = expectName();
4455
+ }
4456
+ skipDirectives();
4457
+ return { kind: "inline", on, selections: parseSelectionSet() };
4458
+ }
4459
+ let name = expectName();
4460
+ const key = name;
4461
+ if (isPunct(":")) {
4462
+ pos++;
4463
+ name = expectName();
4464
+ }
4465
+ let hasArgs = false;
4466
+ if (isPunct("(")) {
4467
+ hasArgs = true;
4468
+ skipParens();
4469
+ }
4470
+ skipDirectives();
4471
+ const selections = isPunct("{") ? parseSelectionSet() : null;
4472
+ return { kind: "field", name, key, hasArgs, selections };
4473
+ };
4474
+ const fragments = /* @__PURE__ */ new Map();
4475
+ const operations = [];
4476
+ while (pos < tokens.length) {
4477
+ if (isPunct("{")) {
4478
+ operations.push({ name: null, selections: parseSelectionSet() });
4479
+ continue;
4480
+ }
4481
+ const keyword = expectName();
4482
+ if (keyword === "fragment") {
4483
+ const name = expectName();
4484
+ if (expectName() !== "on") throw new SyntaxError('Expected "on"');
4485
+ const on = expectName();
4486
+ skipDirectives();
4487
+ fragments.set(name, { on, selections: parseSelectionSet() });
4488
+ } else if (keyword === "query" || keyword === "mutation" || keyword === "subscription") {
4489
+ const t3 = peek();
4490
+ let name = null;
4491
+ if (t3?.type === "name") name = expectName();
4492
+ if (isPunct("(")) skipParens();
4493
+ skipDirectives();
4494
+ operations.push({ name, selections: parseSelectionSet() });
4495
+ } else {
4496
+ throw new SyntaxError(`Unexpected "${keyword}"`);
4497
+ }
4498
+ }
4499
+ return { operation: pickOperation(operations, operationName), fragments };
4500
+ }
4501
+ function pickOperation(operations, operationName) {
4502
+ const op = operationName ? operations.find((o2) => o2.name === operationName) : operations[0];
4503
+ if (!op) throw new SyntaxError("The document has no operation");
4504
+ return op.selections;
4505
+ }
4506
+ function fromAstSelections(set) {
4507
+ return set.selections.map((s2) => {
4508
+ if (s2.kind === "FragmentSpread")
4509
+ return { kind: "spread", name: s2.name.value };
4510
+ if (s2.kind === "InlineFragment") {
4511
+ return {
4512
+ kind: "inline",
4513
+ on: s2.typeCondition?.name.value ?? null,
4514
+ selections: fromAstSelections(s2.selectionSet)
4515
+ };
4516
+ }
4517
+ const name = s2.name.value;
4518
+ return {
4519
+ kind: "field",
4520
+ name,
4521
+ key: s2.alias?.value ?? name,
4522
+ hasArgs: Boolean(s2.arguments?.length),
4523
+ selections: s2.selectionSet ? fromAstSelections(s2.selectionSet) : null
4524
+ };
4525
+ });
4526
+ }
4527
+ function fromAst(doc, operationName) {
4528
+ const fragments = /* @__PURE__ */ new Map();
4529
+ const operations = [];
4530
+ for (const def of doc.definitions ?? []) {
4531
+ if (def.kind === "FragmentDefinition" && def.name && def.typeCondition && def.selectionSet) {
4532
+ fragments.set(def.name.value, {
4533
+ on: def.typeCondition.name.value,
4534
+ selections: fromAstSelections(def.selectionSet)
4535
+ });
4536
+ } else if (def.kind === "OperationDefinition" && def.selectionSet) {
4537
+ operations.push({
4538
+ name: def.name?.value ?? null,
4539
+ selections: fromAstSelections(def.selectionSet)
4540
+ });
4541
+ }
4542
+ }
4543
+ return { operation: pickOperation(operations, operationName), fragments };
4544
+ }
4545
+ var astCache = /* @__PURE__ */ new WeakMap();
4546
+ var sourceCache = /* @__PURE__ */ new Map();
4547
+ var SOURCE_CACHE_LIMIT = 200;
4548
+ function readQueryDocument(query, operationName) {
4549
+ const cacheKey = operationName ?? "";
4550
+ if (typeof query === "object" && query !== null && query.kind === "Document") {
4551
+ let byName = astCache.get(query);
4552
+ if (!byName) astCache.set(query, byName = /* @__PURE__ */ new Map());
4553
+ let parsed2 = byName.get(cacheKey);
4554
+ if (!parsed2) {
4555
+ parsed2 = fromAst(
4556
+ query,
4557
+ operationName
4558
+ );
4559
+ byName.set(cacheKey, parsed2);
4560
+ }
4561
+ return parsed2;
4562
+ }
4563
+ const source = String(query);
4564
+ const sourceKey = `${cacheKey}
4565
+ ${source}`;
4566
+ let parsed = sourceCache.get(sourceKey);
4567
+ if (!parsed) {
4568
+ parsed = parseSource(source, operationName);
4569
+ if (sourceCache.size >= SOURCE_CACHE_LIMIT) {
4570
+ sourceCache.delete(sourceCache.keys().next().value);
4571
+ }
4572
+ sourceCache.set(sourceKey, parsed);
4573
+ }
4574
+ return parsed;
4575
+ }
4576
+ var fieldsCache = /* @__PURE__ */ new WeakMap();
4577
+ function collectFields(selections, typename, doc, options = {}) {
4578
+ const cacheKey = `${options.strict ? "s" : "l"}:${typename ?? ""}`;
4579
+ let cached = fieldsCache.get(selections);
4580
+ if (!cached) {
4581
+ cached = /* @__PURE__ */ new Map();
4582
+ fieldsCache.set(selections, cached);
4583
+ }
4584
+ const hit = cached.get(cacheKey);
4585
+ if (hit) return hit;
4586
+ const fields = resolveFields(selections, typename, doc, options);
4587
+ cached.set(cacheKey, fields);
4588
+ return fields;
4589
+ }
4590
+ function resolveFields(selections, typename, doc, options) {
4591
+ const exact = /* @__PURE__ */ new Map();
4592
+ const loose = /* @__PURE__ */ new Map();
4593
+ const merged = /* @__PURE__ */ new Map();
4594
+ const walkedMatched = /* @__PURE__ */ new Set();
4595
+ const walkedLoose = /* @__PURE__ */ new Set();
4596
+ const add = (target, s2) => {
4597
+ let field = target.get(s2.key);
4598
+ if (!field) {
4599
+ field = { name: s2.name, key: s2.key, hasArgs: s2.hasArgs, selections: [] };
4600
+ target.set(s2.key, field);
4601
+ merged.set(field, /* @__PURE__ */ new Set());
4602
+ }
4603
+ const done = merged.get(field);
4604
+ if (s2.selections && !done.has(s2.selections)) {
4605
+ done.add(s2.selections);
4606
+ field.selections = [...field.selections, ...s2.selections];
4607
+ }
4608
+ };
4609
+ const applies = (on, list) => conditionMatches(on, typename) || typename !== void 0 && typeConditions(list, doc).includes(typename);
4610
+ const walk2 = (list, matched) => {
4611
+ for (const s2 of list) {
4612
+ if (s2.kind === "field") {
4613
+ add(matched ? exact : loose, s2);
4614
+ } else if (s2.kind === "inline") {
4615
+ walk2(s2.selections, matched && applies(s2.on, s2.selections));
4616
+ } else {
4617
+ const fragment = doc.fragments.get(s2.name);
4618
+ if (!fragment) continue;
4619
+ const asMatched = matched && applies(fragment.on, fragment.selections);
4620
+ if (walkedMatched.has(fragment)) continue;
4621
+ if (!asMatched && walkedLoose.has(fragment)) continue;
4622
+ (asMatched ? walkedMatched : walkedLoose).add(fragment);
4623
+ walk2(fragment.selections, asMatched);
4624
+ }
4625
+ }
4626
+ };
4627
+ walk2(selections, true);
4628
+ if (!options.strict) {
4629
+ for (const [key, field] of loose) {
4630
+ if (!exact.has(key)) exact.set(key, field);
4631
+ }
4632
+ }
4633
+ return exact;
4634
+ }
4635
+ function conditionMatches(on, typename) {
4636
+ return on === null || typename === void 0 || on === typename;
4637
+ }
4638
+ var conditionsCache = /* @__PURE__ */ new WeakMap();
4639
+ function typeConditions(selections, doc) {
4640
+ const hit = conditionsCache.get(selections);
4641
+ if (hit) return hit;
4642
+ const names = /* @__PURE__ */ new Set();
4643
+ const seen = /* @__PURE__ */ new Set();
4644
+ const walk2 = (list) => {
4645
+ for (const s2 of list) {
4646
+ if (s2.kind === "inline") {
4647
+ if (s2.on) names.add(s2.on);
4648
+ walk2(s2.selections);
4649
+ } else if (s2.kind === "spread") {
4650
+ const fragment = doc.fragments.get(s2.name);
4651
+ if (!fragment || seen.has(fragment)) continue;
4652
+ seen.add(fragment);
4653
+ names.add(fragment.on);
4654
+ walk2(fragment.selections);
4655
+ }
4656
+ }
4657
+ };
4658
+ walk2(selections);
4659
+ const conditions = [...names];
4660
+ conditionsCache.set(selections, conditions);
4661
+ return conditions;
4662
+ }
4663
+
4664
+ // src/core/live-preview/normalize-query.ts
4665
+ var debug11 = createScopedLogger("live-preview:normalize");
4666
+ var INDEX_SEGMENT3 = /^\d+$/;
4667
+ var FORBIDDEN_SEGMENTS2 = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
4668
+ var ENVELOPE_KEYS = /* @__PURE__ */ new Set(["data", "errors", "extensions"]);
4669
+ function normalizeQuery(query, result, options = {}) {
4670
+ return applyPatchLog(
4671
+ query,
4672
+ result,
4673
+ parsePatchLog(options.log),
4674
+ options.operationName
4675
+ );
4676
+ }
4677
+ function applyPatchLog(query, result, log, operationName) {
4678
+ if (!log.length || result === null || typeof result !== "object") {
4679
+ return result;
4680
+ }
4681
+ if (isEnvelope(result)) {
4682
+ const data = applyPatchLog(query, result.data, log, operationName);
4683
+ return data === result.data ? result : { ...result, data };
4684
+ }
4685
+ let doc = null;
4686
+ try {
4687
+ doc = readQueryDocument(query, operationName);
4688
+ } catch (error) {
4689
+ debug11.log("could not read the query; applying fields by literal path", {
4690
+ error: String(error)
4691
+ });
4692
+ }
4693
+ let root = result;
4694
+ let index = null;
4695
+ for (const patch of log) {
4696
+ try {
4697
+ index ?? (index = indexSnapshot(root));
4698
+ const next = applyPatch(root, index, patch, doc, result);
4699
+ if (next !== root) {
4700
+ root = next;
4701
+ if (patch.type === "list" || !isScalarValue(patch.value)) {
4702
+ index = null;
4703
+ }
4704
+ }
4705
+ } catch (error) {
4706
+ debug11.log("could not apply a change", {
4707
+ itemId: patch.itemId,
4708
+ field: patch.field,
4709
+ error: String(error)
4710
+ });
4711
+ }
4712
+ }
4713
+ return root;
4714
+ }
4715
+ function isScalarValue(value) {
4716
+ return value === null || typeof value !== "object";
4717
+ }
4718
+ function applyPatch(root, index, patch, doc, result) {
4719
+ const ownerPaths = index.get(patch.itemId);
4720
+ if (!ownerPaths?.length) return root;
4721
+ const segments = patch.field.split(".");
4722
+ if (segments.some((s2) => !s2 || FORBIDDEN_SEGMENTS2.has(s2))) return root;
4723
+ const targets = [];
4724
+ const plain = /* @__PURE__ */ new Set();
4725
+ for (const ownerPath of ownerPaths) {
4726
+ if (doc) {
4727
+ const resolved = resolveTargets(root, doc, ownerPath, segments);
4728
+ root = resolved.root;
4729
+ targets.push(...resolved.targets);
4730
+ resolved.plain.forEach((target) => plain.add(target));
4731
+ } else {
4732
+ targets.push([...ownerPath, ...segments.map(toPathSegment)]);
4733
+ }
4734
+ }
4735
+ if (!targets.length) {
4736
+ debug11.log("no field in the query matches", {
4737
+ itemId: patch.itemId,
4738
+ field: patch.field
4739
+ });
4740
+ return root;
4741
+ }
4742
+ if (patch.type === "field") {
4743
+ for (const target of targets) {
4744
+ const pushed = plain.has(target) && typeof patch.value === "string" ? plainTextFromHtml(patch.value) : patch.value;
4745
+ let value = keepEditLink(readAtPath(root, target), pushed);
4746
+ if (patch.edit && typeof value === "string" && !(0, import_stega7.vercelStegaSplit)(value).encoded) {
4747
+ value = editLinksFor(result, patch.edit.item)?.encode(
4748
+ value,
4749
+ patch.edit.field
4750
+ ) ?? value;
4751
+ }
4752
+ root = writeAtPath(root, target, value);
4753
+ }
4754
+ } else {
4755
+ for (const target of targets) {
4756
+ const selections = doc ? selectionsAt(root, doc, target) : null;
4757
+ const build = doc && selections ? (entry) => buildEntry(doc, selections, entry, {
4758
+ links: editLinks(result, entry),
4759
+ lists: listKeysIn(result)
4760
+ }) : void 0;
4761
+ root = syncListAtPath(root, target, patch.entries, build);
4762
+ }
4763
+ }
4764
+ return root;
4765
+ }
4766
+ function readAtPath(root, path) {
4767
+ let node = root;
4768
+ for (const step of path) {
4769
+ if (node === null || typeof node !== "object") return void 0;
4770
+ node = node[step];
4771
+ }
4772
+ return node;
4773
+ }
4774
+ function isEnvelope(value) {
4775
+ if (Array.isArray(value) || !("data" in value)) return false;
4776
+ return Object.keys(value).every((key) => ENVELOPE_KEYS.has(key));
4777
+ }
4778
+ function toPathSegment(segment) {
4779
+ return INDEX_SEGMENT3.test(segment) ? Number(segment) : segment;
4780
+ }
4781
+ function typenameOf(node) {
4782
+ const typename = node.__typename;
4783
+ return typeof typename === "string" ? typename : void 0;
4784
+ }
4785
+ function selectionsAt(root, doc, path) {
4786
+ let node = root;
4787
+ let selections = doc.operation;
4788
+ for (const step of path) {
4789
+ if (Array.isArray(node)) {
4790
+ node = node[step];
4791
+ continue;
4792
+ }
4793
+ if (node === null || typeof node !== "object") return null;
4794
+ const field = collectFields(selections, typenameOf(node), doc).get(
4795
+ String(step)
4796
+ );
4797
+ if (!field) return null;
4798
+ selections = field.selections;
4799
+ node = node[String(step)];
4800
+ }
4801
+ return selections;
4802
+ }
4803
+ function resolveTargets(root, doc, ownerPath, segments) {
4804
+ let owner = root;
4805
+ for (const step of ownerPath) {
4806
+ owner = owner[step];
4807
+ }
4808
+ const selections = selectionsAt(root, doc, ownerPath);
4809
+ if (!selections) return { root, targets: [], plain: /* @__PURE__ */ new Set() };
4810
+ let current = root;
4811
+ const out = [];
4812
+ const plain = /* @__PURE__ */ new Set();
4813
+ const walk2 = (node, sel, i2, path) => {
4814
+ if (i2 === segments.length) {
4815
+ out.push(path);
4816
+ return;
4817
+ }
4818
+ const segment = segments[i2];
4819
+ if (Array.isArray(node)) {
4820
+ if (INDEX_SEGMENT3.test(segment)) {
4821
+ const position = Number(segment);
4822
+ if (position < node.length) {
4823
+ walk2(node[position], sel, i2 + 1, [...path, position]);
4824
+ }
4825
+ } else if (segment === "items") {
4826
+ walk2(node, sel, i2 + 1, path);
4827
+ }
4828
+ return;
4829
+ }
4830
+ if (node === null || typeof node !== "object") return;
4831
+ const record = node;
4832
+ const wanted = graphqlFieldName(segment);
4833
+ const textBody = i2 === segments.length - 1 && segment === "body" && isTextEntry(record) ? TEXT_BODY_FIELDS : null;
4834
+ let matched = false;
4835
+ for (const field of collectFields(sel, typenameOf(node), doc).values()) {
4836
+ const alias = textBody?.find((f3) => f3.name === field.name);
4837
+ if (field.name !== segment && field.name !== wanted && !alias) continue;
4838
+ if (!Object.prototype.hasOwnProperty.call(record, field.key)) continue;
4839
+ matched = true;
4840
+ const fieldPath = [...path, field.key];
4841
+ if (alias?.plain) plain.add(fieldPath);
4842
+ let value = record[field.key];
4843
+ const next = segments[i2 + 1];
4844
+ if (value === null && field.selections.length && next !== void 0 && next !== "items" && !INDEX_SEGMENT3.test(next)) {
4845
+ const typename = resolveTypename(
4846
+ doc,
4847
+ field.selections,
4848
+ void 0,
4849
+ void 0
4850
+ );
4851
+ if (typename !== void 0) {
4852
+ value = fillObject(doc, field.selections, typename, {}, void 0, {
4853
+ links: null,
4854
+ lists: listKeysIn(root)
4855
+ });
4856
+ current = writeAtPath(current, fieldPath, value);
4857
+ }
4858
+ }
4859
+ walk2(value, field.selections, i2 + 1, fieldPath);
4860
+ }
4861
+ if (!matched && segment === "items") walk2(node, sel, i2 + 1, path);
4862
+ };
4863
+ walk2(owner, selections, 0, ownerPath);
4864
+ return { root: current, targets: out, plain };
4865
+ }
4866
+ var NON_ALPHANUMERIC = /[^a-z0-9]/gi;
4867
+ var typeKey = (name) => name.replace(NON_ALPHANUMERIC, "").toLowerCase();
4868
+ function resolveTypename(doc, selections, typename, typeName) {
4869
+ const known = typeConditions(selections, doc);
4870
+ const explicit = typeof typename === "string" ? typename : void 0;
4871
+ if (!known.length) return explicit ?? null;
4872
+ if (explicit && known.includes(explicit)) return explicit;
4873
+ for (const candidate of [explicit, typeName]) {
4874
+ if (typeof candidate !== "string" || !candidate) continue;
4875
+ const match = known.find((name) => typeKey(name) === typeKey(candidate));
4876
+ if (match) return match;
4877
+ }
4878
+ const named = explicit !== void 0 || typeof typeName === "string";
4879
+ return known.length === 1 && !named ? known[0] : void 0;
2206
4880
  }
2207
- function createPreprPreview(opts = {}) {
2208
- const { props, options } = opts;
2209
- const navigation = opts.navigation ?? defaultNavigation();
2210
- initDebugLogger(options?.debug ?? false);
2211
- const noop = () => ({ destroy: () => {
2212
- } });
2213
- if (typeof window === "undefined" || typeof document === "undefined") {
2214
- return noop();
4881
+ function buildEntry(doc, selections, entry, ctx) {
4882
+ const typename = resolveTypename(
4883
+ doc,
4884
+ selections,
4885
+ entry.__typename,
4886
+ entry.typeName
4887
+ );
4888
+ if (typename === void 0) return void 0;
4889
+ return fillObject(
4890
+ doc,
4891
+ selections,
4892
+ typename,
4893
+ entry.fields ?? {},
4894
+ entry._id,
4895
+ ctx
4896
+ );
4897
+ }
4898
+ function fillObject(doc, selections, typename, values, id, ctx) {
4899
+ const out = {};
4900
+ const { links } = ctx;
4901
+ const lists = ctx.lists(typename);
4902
+ const edit = isPlainRecord(values.__edit) ? values.__edit : null;
4903
+ const apiIdOf = /* @__PURE__ */ new Map();
4904
+ for (const key of Object.keys(values)) {
4905
+ apiIdOf.set(key, key);
4906
+ const name = graphqlFieldName(key);
4907
+ if (!apiIdOf.has(name)) apiIdOf.set(name, key);
2215
4908
  }
2216
- const isIframe = window.parent !== window;
2217
- const search = new URLSearchParams(window.location.search);
2218
- const hideBar = search.get(PARAM_HIDE_BAR) === "true";
2219
- if (hideBar) {
2220
- debug7.log(`${PARAM_HIDE_BAR}=true \u2014 no visible toolbar`);
4909
+ if (edit && isPlainRecord(edit.apiIds)) {
4910
+ for (const [name, apiId] of Object.entries(edit.apiIds)) {
4911
+ if (typeof apiId === "string") apiIdOf.set(name, apiId);
4912
+ }
2221
4913
  }
2222
- const mountUi = (options?.ui ?? true) && !isIframe && !hideBar;
2223
- const locale = resolveLocale(options);
2224
- const features = resolveFeatures(options?.features);
2225
- const previewMode = getCookie(COOKIE_PREVIEW_MODE) === "true";
2226
- const toolbarOpen = getCookie(COOKIE_TOOLBAR_OPEN) === "true";
2227
- const cookieSegment = features.segments ? getCookie(COOKIE_SEGMENT) : null;
2228
- const cookieVariant = features.abTesting ? getCookie(COOKIE_VARIANT) : null;
2229
- const rawVariant = features.abTesting ? props?.activeVariant ?? cookieVariant : null;
2230
- const selectedVariant = rawVariant === "A" || rawVariant === "B" ? rawVariant : null;
2231
- const store = createToolbarStore({
2232
- locale,
2233
- features,
2234
- segments: features.segments ? buildSegments(props?.segments ?? props?.data ?? []) : [],
2235
- selectedSegment: features.segments ? props?.activeSegment ?? cookieSegment ?? null : null,
2236
- selectedVariant,
2237
- previewMode,
2238
- toolbarOpen,
2239
- isIframe
4914
+ const valueOf = (name) => {
4915
+ if (Object.prototype.hasOwnProperty.call(values, name)) return values[name];
4916
+ const key = apiIdOf.get(name);
4917
+ return key !== void 0 && key in values ? values[key] : void 0;
4918
+ };
4919
+ const editField = (name) => {
4920
+ if (!edit) return null;
4921
+ if (typeof edit.field === "string")
4922
+ return name === "body" ? edit.field : null;
4923
+ if (typeof edit.path !== "string") return null;
4924
+ const apiId = apiIdOf.get(name) ?? name;
4925
+ const text = Array.isArray(edit.text) ? edit.text : [];
4926
+ if (!text.includes(apiId) && !text.includes(name)) return null;
4927
+ return `${edit.path}.items.${apiId}`;
4928
+ };
4929
+ const fields = collectFields(selections, typename ?? void 0, doc, {
4930
+ strict: true
2240
4931
  });
2241
- let el = null;
2242
- if (mountUi) {
2243
- definePreprToolbar();
2244
- el = document.createElement("prepr-toolbar");
2245
- document.body.appendChild(el);
2246
- el.connect(store, (key) => t(key, locale));
4932
+ for (const field of fields.values()) {
4933
+ if (field.name === "__typename") {
4934
+ out[field.key] = typename;
4935
+ } else if (field.name === "_id") {
4936
+ out[field.key] = typeof id === "string" ? id : values._id ?? null;
4937
+ } else if (field.selections.length) {
4938
+ const value = valueOf(field.name);
4939
+ out[field.key] = value == null && lists.has(field.key) ? [] : fillNested(doc, field.selections, value, ctx);
4940
+ } else {
4941
+ const value = valueOf(field.name);
4942
+ if (Array.isArray(value) && value.every(isScalar)) {
4943
+ out[field.key] = value;
4944
+ continue;
4945
+ }
4946
+ if (value == null && lists.has(field.key)) {
4947
+ out[field.key] = [];
4948
+ continue;
4949
+ }
4950
+ const scalar = value === void 0 || value !== null && typeof value === "object" ? null : value;
4951
+ const target = typeof scalar === "string" ? editField(field.name) : null;
4952
+ out[field.key] = target && links ? links.encode(scalar, target) : scalar;
4953
+ }
2247
4954
  }
2248
- const editingEnabled = features.editMode || isIframe;
2249
- const stega = createStegaController({
2250
- // The CMS deep-link tooltip is chrome, so it follows the same decision as
2251
- // the bar: noise inside the editor (clicking the element itself requests
2252
- // the edit there), and unwanted in a headless preview that asked for no UI.
2253
- tooltip: mountUi,
2254
- // In the editor, ask the parent to focus the field instead of opening a new
2255
- // tab. Standalone previews keep the window.open behaviour.
2256
- onEdit: ({ href, origin, id, field }) => {
2257
- const safeHref = href ? safeEditUrl(href) : null;
2258
- if (href && !safeHref) {
2259
- debug7.warn("ignored edit request with unsupported href scheme");
2260
- return;
4955
+ return out;
4956
+ }
4957
+ function fillNested(doc, selections, value, ctx) {
4958
+ const one = (item) => {
4959
+ if (!isPlainRecord(item)) return null;
4960
+ const typename = resolveTypename(
4961
+ doc,
4962
+ selections,
4963
+ item.__typename,
4964
+ item.typeName
4965
+ );
4966
+ if (typename === void 0) return null;
4967
+ return fillObject(doc, selections, typename, item, item._id, ctx);
4968
+ };
4969
+ if (Array.isArray(value)) return value.map(one).filter((v2) => v2 !== null);
4970
+ return value === void 0 ? null : one(value);
4971
+ }
4972
+ var NO_KEYS = /* @__PURE__ */ new Set();
4973
+ var listKeysCache = /* @__PURE__ */ new WeakMap();
4974
+ function listKeysIn(result) {
4975
+ return (typename) => {
4976
+ if (!typename || result === null || typeof result !== "object") {
4977
+ return NO_KEYS;
4978
+ }
4979
+ let byType = listKeysCache.get(result);
4980
+ if (!byType) {
4981
+ byType = /* @__PURE__ */ new Map();
4982
+ const seen = /* @__PURE__ */ new WeakSet();
4983
+ const walk2 = (node) => {
4984
+ if (node === null || typeof node !== "object" || seen.has(node)) return;
4985
+ seen.add(node);
4986
+ if (Array.isArray(node)) {
4987
+ node.forEach(walk2);
4988
+ return;
4989
+ }
4990
+ const record = node;
4991
+ const type = typeof record.__typename === "string" ? record.__typename : null;
4992
+ for (const [key, value] of Object.entries(record)) {
4993
+ if (type && Array.isArray(value)) {
4994
+ let keys = byType.get(type);
4995
+ if (!keys) byType.set(type, keys = /* @__PURE__ */ new Set());
4996
+ keys.add(key);
4997
+ }
4998
+ walk2(value);
4999
+ }
5000
+ };
5001
+ walk2(result);
5002
+ listKeysCache.set(result, byType);
5003
+ }
5004
+ return byType.get(typename) ?? NO_KEYS;
5005
+ };
5006
+ }
5007
+
5008
+ // src/core/live-preview/edit-links.ts
5009
+ var import_stega8 = require("@vercel/stega");
5010
+ var ENTRY_PARAM = "entry";
5011
+ var TOP_LEVEL_ENTRY = /^[A-Za-z0-9_]+\.\d+$/;
5012
+ function entryIdOf(element) {
5013
+ if (!isObject(element)) return void 0;
5014
+ if (typeof element._id === "string") return element._id;
5015
+ if (element.__typename !== "Assets" || !Array.isArray(element.items)) {
5016
+ return void 0;
5017
+ }
5018
+ const first = element.items[0];
5019
+ return isObject(first) && typeof first._id === "string" ? first._id : void 0;
5020
+ }
5021
+ function annotate(value, ctx) {
5022
+ if (!ctx.entryId) return value;
5023
+ const { cleaned, encoded } = (0, import_stega8.vercelStegaSplit)(value);
5024
+ if (!encoded) return value;
5025
+ let payload;
5026
+ try {
5027
+ payload = (0, import_stega8.vercelStegaDecode)(encoded);
5028
+ } catch {
5029
+ return value;
5030
+ }
5031
+ if (typeof payload?.href !== "string") return value;
5032
+ let url;
5033
+ try {
5034
+ url = new URL(payload.href);
5035
+ } catch {
5036
+ return value;
5037
+ }
5038
+ if (url.searchParams.has(ENTRY_PARAM)) return value;
5039
+ url.searchParams.set(ENTRY_PARAM, ctx.entryId);
5040
+ const itemId = decodeURIComponent(url.pathname.split("/").pop() ?? "");
5041
+ if (!url.searchParams.has("field") && ctx.entryField && TOP_LEVEL_ENTRY.test(ctx.entryField) && itemId === ctx.entryOwnerId) {
5042
+ url.searchParams.set("field", ctx.entryField);
5043
+ }
5044
+ return (0, import_stega8.vercelStegaCombine)(
5045
+ cleaned,
5046
+ { ...payload, href: url.toString() },
5047
+ false
5048
+ );
5049
+ }
5050
+ function walk(value, selections, ctx) {
5051
+ if (typeof value === "string") return annotate(value, ctx);
5052
+ if (Array.isArray(value)) {
5053
+ let changed2 = false;
5054
+ const next2 = value.map((element, index) => {
5055
+ const path = [...ctx.path, String(index)];
5056
+ const entryId = ctx.inAssets ? void 0 : entryIdOf(element);
5057
+ const entry = entryId ? {
5058
+ entryId,
5059
+ entryField: ctx.ownerId ? path.join(".") : void 0,
5060
+ entryOwnerId: ctx.ownerId,
5061
+ inAssets: isObject(element) && element._id === void 0
5062
+ } : {};
5063
+ const out = walk(element, selections, { ...ctx, ...entry, path });
5064
+ if (out !== element) changed2 = true;
5065
+ return out;
5066
+ });
5067
+ return changed2 ? next2 : value;
5068
+ }
5069
+ if (!isObject(value)) return value;
5070
+ const id = typeof value._id === "string" ? value._id : void 0;
5071
+ const typename = typeof value.__typename === "string" ? value.__typename : void 0;
5072
+ const fields = ctx.doc && selections ? collectFields(selections, typename, ctx.doc) : null;
5073
+ let changed = false;
5074
+ const next = {};
5075
+ for (const [key, child] of Object.entries(value)) {
5076
+ const field = fields?.get(key);
5077
+ const name = field?.name ?? key;
5078
+ const out = walk(child, field?.selections ?? null, {
5079
+ ...ctx,
5080
+ ownerId: id ?? ctx.ownerId,
5081
+ path: id ? [name] : [...ctx.path, name]
5082
+ });
5083
+ if (out !== child) changed = true;
5084
+ next[key] = out;
5085
+ }
5086
+ return changed ? next : value;
5087
+ }
5088
+ function annotateEditLinks(result, query, operationName) {
5089
+ let doc = null;
5090
+ if (query !== void 0) {
5091
+ try {
5092
+ doc = readQueryDocument(query, operationName);
5093
+ } catch {
5094
+ doc = null;
5095
+ }
5096
+ }
5097
+ return walk(result, doc?.operation ?? null, { doc, path: [] });
5098
+ }
5099
+
5100
+ // src/core/live-preview/bridge-events.ts
5101
+ var debug12 = createScopedLogger("live-preview:bridge");
5102
+ function createLiveBridge(store, options = {}) {
5103
+ let parentOrigin = null;
5104
+ const onMessage = (evt) => {
5105
+ if (evt.source !== window.parent) return;
5106
+ const data = evt?.data;
5107
+ if (data?.event === EVENT_INIT && !parentOrigin) {
5108
+ if (isAllowedEditorOrigin(evt.origin, options.allowedEditorOrigins?.())) {
5109
+ parentOrigin = evt.origin;
5110
+ } else {
5111
+ debug12.warn("ignored live preview handshake from origin", evt.origin);
2261
5112
  }
2262
- if (isIframe) {
2263
- sendPreprEvent("field_edit_requested", {
2264
- href: safeHref ?? void 0,
2265
- origin,
2266
- id,
2267
- field
2268
- });
2269
- } else if (safeHref) {
2270
- window.open(safeHref, "_blank", "noopener,noreferrer");
5113
+ return;
5114
+ }
5115
+ const trusted = parentOrigin ?? getTrustedParentOrigin();
5116
+ if (!trusted || evt.origin !== trusted) return;
5117
+ if (data?.event === EVENT_FIELD_CHANGE) {
5118
+ if (typeof data.itemId === "string" && typeof data.field === "string" && data.field && isLiveFieldChange(data.field, data.value)) {
5119
+ const edit = parseEditTarget(data.edit);
5120
+ if (edit) store.pushPatch(data.itemId, data.field, data.value, edit);
5121
+ else store.pushPatch(data.itemId, data.field, data.value);
5122
+ } else {
5123
+ debug12.log("dropped malformed fieldChange", data);
2271
5124
  }
5125
+ return;
2272
5126
  }
2273
- });
2274
- const autoClean = createStegaAutoClean({
2275
- enabled: options?.autoClean,
2276
- isHydrated: opts.isHydrated
2277
- });
2278
- autoClean.start();
2279
- const handleChange = createChangeHandler({
2280
- store,
2281
- features,
2282
- editingEnabled,
2283
- navigate: (url) => navigation.navigate(url),
2284
- currentPath: () => navigation.currentPath(),
2285
- reload: navigation.reload ?? (() => window.location.reload()),
2286
- stega
2287
- });
2288
- let prev = store.get();
2289
- const unsubscribe = store.subscribe((state) => {
2290
- const before = prev;
2291
- prev = state;
2292
- handleChange(before, state);
2293
- });
2294
- const bridge = createIframeBridge(store, {
2295
- allowedEditorOrigins: options?.allowedEditorOrigins
2296
- });
2297
- sendPreprEvent(
2298
- "getScrollPosition",
2299
- { value: 0 },
2300
- {
2301
- allowUntrustedTarget: true
5127
+ if (data?.event === EVENT_LIST_CHANGE) {
5128
+ const list = parseListEntries(data.entries);
5129
+ if (typeof data.itemId === "string" && typeof data.field === "string" && data.field && list) {
5130
+ store.pushList(data.itemId, data.field, list);
5131
+ } else {
5132
+ debug12.log("dropped malformed listChange", data);
5133
+ }
5134
+ return;
5135
+ }
5136
+ if (data?.event === EVENT_ITEM_CHANGED) {
5137
+ if (typeof data.itemId === "string") {
5138
+ store.invalidate(data.itemId);
5139
+ } else {
5140
+ debug12.log("dropped malformed itemChanged", data);
5141
+ }
5142
+ }
5143
+ };
5144
+ return {
5145
+ start() {
5146
+ window.addEventListener("message", onMessage);
5147
+ const shared = sharedState();
5148
+ const strict = Boolean(options.strictMode?.() || shared.strictMode);
5149
+ sendPreprEvent("live_ready", strict ? { strictMode: true } : void 0, {
5150
+ allowUntrustedTarget: true
5151
+ });
5152
+ shared.liveAnnouncedStrict = strict;
5153
+ },
5154
+ stop() {
5155
+ window.removeEventListener("message", onMessage);
5156
+ sharedState().liveAnnouncedStrict = void 0;
5157
+ }
5158
+ };
5159
+ }
5160
+
5161
+ // src/core/live-preview/live-store.ts
5162
+ var debug13 = createScopedLogger("live-preview");
5163
+ var INVALIDATE_DEBOUNCE_MS = 150;
5164
+ var MAX_LOG_ENTRIES2 = 500;
5165
+ function withPatch(log, patch) {
5166
+ let previous = -1;
5167
+ for (let i2 = log.length - 1; i2 >= 0; i2--) {
5168
+ const p2 = log[i2];
5169
+ if (p2.type === patch.type && p2.itemId === patch.itemId && p2.field === patch.field) {
5170
+ previous = i2;
5171
+ break;
2302
5172
  }
5173
+ }
5174
+ if (previous === -1) return [...log, patch];
5175
+ const since = log.slice(previous + 1);
5176
+ const listPrefix = `${patch.field}.`;
5177
+ const dependsOnPosition = since.some(
5178
+ (p2) => p2.type === "list" || patch.type === "list" && p2.itemId === patch.itemId && p2.field.startsWith(listPrefix)
2303
5179
  );
2304
- if (isIframe) {
2305
- bridge.start();
5180
+ if (dependsOnPosition) return [...log, patch];
5181
+ return [...log.slice(0, previous), ...since, patch];
5182
+ }
5183
+ function createLiveStore(options = {}) {
5184
+ const accepts = (patch) => options.accept ? options.accept(patch) : true;
5185
+ const entries = /* @__PURE__ */ new Set();
5186
+ const invalidateListeners = /* @__PURE__ */ new Set();
5187
+ const pendingInvalidates = /* @__PURE__ */ new Map();
5188
+ let defaultFetcher = null;
5189
+ let log = [];
5190
+ const logListeners = /* @__PURE__ */ new Set();
5191
+ function record(patch) {
5192
+ log = withPatch(log, patch).slice(-MAX_LOG_ENTRIES2);
5193
+ logListeners.forEach((fn) => fn(log));
2306
5194
  }
2307
- function destroy() {
2308
- unsubscribe();
2309
- stega.stop();
2310
- autoClean.stop();
2311
- if (isIframe) {
2312
- bridge.stop();
5195
+ function notify(entry) {
5196
+ entry.listeners.forEach((fn) => fn());
5197
+ }
5198
+ async function refetch(entry) {
5199
+ const fetcher = entry.opts.fetcher ?? defaultFetcher;
5200
+ if (!fetcher || entry.opts.query == null) return;
5201
+ const token = ++entry.fetchToken;
5202
+ try {
5203
+ const result = await fetcher(entry.opts.query, entry.opts.variables);
5204
+ if (token !== entry.fetchToken || !entries.has(entry)) return;
5205
+ entry.snapshot = result;
5206
+ entry.index = indexSnapshot(result);
5207
+ notify(entry);
5208
+ } catch (error) {
5209
+ debug13.log("refetch failed, keeping previous snapshot", error);
2313
5210
  }
2314
- el?.remove();
2315
- debug7.log("preview destroyed");
2316
5211
  }
2317
- const controller = { destroy };
2318
- controllerStores.set(controller, store);
2319
- return controller;
5212
+ function runInvalidate(itemId) {
5213
+ pendingInvalidates.delete(itemId);
5214
+ invalidateListeners.forEach((fn) => fn(itemId));
5215
+ for (const entry of entries) {
5216
+ if (entry.index.has(itemId)) void refetch(entry);
5217
+ }
5218
+ }
5219
+ return {
5220
+ register(data, opts = {}) {
5221
+ const entry = {
5222
+ snapshot: data,
5223
+ index: indexSnapshot(data),
5224
+ opts,
5225
+ listeners: /* @__PURE__ */ new Set(),
5226
+ fetchToken: 0
5227
+ };
5228
+ for (const patch of log) {
5229
+ if (patch.type === "field") {
5230
+ entry.snapshot = patchSnapshot(
5231
+ entry.snapshot,
5232
+ entry.index,
5233
+ patch.itemId,
5234
+ patch.field,
5235
+ patch.value
5236
+ );
5237
+ } else {
5238
+ const next = syncListSnapshot(
5239
+ entry.snapshot,
5240
+ entry.index,
5241
+ patch.itemId,
5242
+ patch.field,
5243
+ patch.entries
5244
+ );
5245
+ if (next !== entry.snapshot) {
5246
+ entry.snapshot = next;
5247
+ entry.index = indexSnapshot(next);
5248
+ }
5249
+ }
5250
+ }
5251
+ entries.add(entry);
5252
+ return {
5253
+ getSnapshot: () => entry.snapshot,
5254
+ subscribe(fn) {
5255
+ entry.listeners.add(fn);
5256
+ return () => entry.listeners.delete(fn);
5257
+ },
5258
+ unregister() {
5259
+ entry.listeners.clear();
5260
+ entries.delete(entry);
5261
+ }
5262
+ };
5263
+ },
5264
+ pushPatch(itemId, field, value, edit) {
5265
+ const patch = edit ? { type: "field", itemId, field, value, edit } : { type: "field", itemId, field, value };
5266
+ if (!accepts(patch)) return;
5267
+ record(patch);
5268
+ for (const entry of entries) {
5269
+ const next = patchSnapshot(
5270
+ entry.snapshot,
5271
+ entry.index,
5272
+ itemId,
5273
+ field,
5274
+ value
5275
+ );
5276
+ if (next !== entry.snapshot) {
5277
+ entry.snapshot = next;
5278
+ notify(entry);
5279
+ }
5280
+ }
5281
+ },
5282
+ pushList(itemId, field, list) {
5283
+ const patch = { type: "list", itemId, field, entries: list };
5284
+ if (!accepts(patch)) return;
5285
+ record(patch);
5286
+ for (const entry of entries) {
5287
+ const next = syncListSnapshot(
5288
+ entry.snapshot,
5289
+ entry.index,
5290
+ itemId,
5291
+ field,
5292
+ list
5293
+ );
5294
+ if (next !== entry.snapshot) {
5295
+ entry.snapshot = next;
5296
+ entry.index = indexSnapshot(next);
5297
+ notify(entry);
5298
+ }
5299
+ }
5300
+ },
5301
+ invalidate(itemId) {
5302
+ if (log.length) {
5303
+ log = [];
5304
+ logListeners.forEach((fn) => fn(log));
5305
+ }
5306
+ const pending = pendingInvalidates.get(itemId);
5307
+ if (pending) clearTimeout(pending);
5308
+ pendingInvalidates.set(
5309
+ itemId,
5310
+ setTimeout(() => runInvalidate(itemId), INVALIDATE_DEBOUNCE_MS)
5311
+ );
5312
+ },
5313
+ setFetcher(fetcher) {
5314
+ defaultFetcher = fetcher;
5315
+ },
5316
+ onInvalidate(fn) {
5317
+ invalidateListeners.add(fn);
5318
+ return () => invalidateListeners.delete(fn);
5319
+ },
5320
+ getLog: () => log,
5321
+ onLogChange(fn) {
5322
+ logListeners.add(fn);
5323
+ return () => logListeners.delete(fn);
5324
+ }
5325
+ };
5326
+ }
5327
+
5328
+ // src/core/live-preview/morph.ts
5329
+ function morphElement(current, next) {
5330
+ syncAttributes(current, next);
5331
+ morphChildren(current, next);
5332
+ }
5333
+ var SKIP_ATTR = "data-prepr-morph-skip";
5334
+ var RUNTIME_ATTR_PREFIXES = ["data-prepr-"];
5335
+ function isRuntimeAttribute(name) {
5336
+ return RUNTIME_ATTR_PREFIXES.some((prefix) => name.startsWith(prefix));
5337
+ }
5338
+ function syncAttributes(current, next) {
5339
+ for (const { name } of Array.from(current.attributes)) {
5340
+ if (!next.hasAttribute(name) && !isRuntimeAttribute(name)) {
5341
+ current.removeAttribute(name);
5342
+ }
5343
+ }
5344
+ for (const { name, value } of Array.from(next.attributes)) {
5345
+ if (current.getAttribute(name) !== value) current.setAttribute(name, value);
5346
+ }
5347
+ }
5348
+ function isSkipped(node) {
5349
+ return node.nodeType === Node.ELEMENT_NODE && (node.hasAttribute(SKIP_ATTR) || node.localName === TOOLBAR_TAG);
5350
+ }
5351
+ function sameKind(a2, b2) {
5352
+ if (a2.nodeType !== b2.nodeType) return false;
5353
+ if (a2.nodeType !== Node.ELEMENT_NODE) return true;
5354
+ const ea = a2;
5355
+ const eb = b2;
5356
+ return ea.localName === eb.localName && ea.id === eb.id;
5357
+ }
5358
+ function morphChildren(current, next) {
5359
+ const wanted = Array.from(next.childNodes).filter((n2) => !isSkipped(n2));
5360
+ const existing = Array.from(current.childNodes).filter((n2) => !isSkipped(n2));
5361
+ wanted.forEach((target, i2) => {
5362
+ const node = existing[i2];
5363
+ if (node && sameKind(node, target)) {
5364
+ if (node.nodeType === Node.ELEMENT_NODE) {
5365
+ const element = node;
5366
+ if (element.localName === "script") return;
5367
+ if (element.localName === "astro-island" && !element.isEqualNode(target)) {
5368
+ element.replaceWith(adopt(target, current));
5369
+ return;
5370
+ }
5371
+ morphElement(element, target);
5372
+ } else if (node.nodeValue !== target.nodeValue) {
5373
+ node.nodeValue = target.nodeValue;
5374
+ }
5375
+ return;
5376
+ }
5377
+ const replacement = adopt(target, current);
5378
+ if (node) node.replaceWith(replacement);
5379
+ else current.appendChild(replacement);
5380
+ });
5381
+ for (const extra of existing.slice(wanted.length)) extra.remove();
5382
+ }
5383
+ function adopt(node, parent) {
5384
+ const copy = parent.ownerDocument.importNode(node, true);
5385
+ if (copy.nodeType === Node.ELEMENT_NODE) {
5386
+ const element = copy;
5387
+ const scripts = element.localName === "script" ? [element] : Array.from(element.querySelectorAll("script"));
5388
+ scripts.forEach((s2) => s2.setAttribute("data-prepr-morphed", ""));
5389
+ }
5390
+ return copy;
5391
+ }
5392
+
5393
+ // src/core/live-preview/html-live.ts
5394
+ var debug14 = createScopedLogger("live-preview:html");
5395
+ var COMPLETE_DOCUMENT = /<\/html>\s*$/i;
5396
+ var SYNC_DEBOUNCE_MS = 150;
5397
+ function startHtmlLivePreview(options = {}) {
5398
+ if (typeof window === "undefined" || window.self === window.top) {
5399
+ return { stop() {
5400
+ } };
5401
+ }
5402
+ const store = createLiveStore();
5403
+ const bridge = createLiveBridge(store, {
5404
+ allowedEditorOrigins: () => options.allowedEditorOrigins,
5405
+ strictMode: () => options.strictMode
5406
+ });
5407
+ bridge.start();
5408
+ let timer = null;
5409
+ let inFlight = false;
5410
+ let pending = null;
5411
+ let stopped = false;
5412
+ const render = async (log) => {
5413
+ inFlight = true;
5414
+ try {
5415
+ const response = await fetch(window.location.href, {
5416
+ method: log.length ? "POST" : "GET",
5417
+ headers: log.length ? { "Content-Type": "application/json", [HEADER_LIVE_RENDER]: "1" } : {},
5418
+ body: log.length ? JSON.stringify({ log }) : void 0,
5419
+ credentials: "same-origin",
5420
+ cache: "no-store"
5421
+ });
5422
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
5423
+ const html = await response.text();
5424
+ if (stopped) return;
5425
+ if (!COMPLETE_DOCUMENT.test(html)) {
5426
+ throw new Error("incomplete page; a component failed to render");
5427
+ }
5428
+ const next = new DOMParser().parseFromString(html, "text/html");
5429
+ if (next.title && next.title !== document.title)
5430
+ document.title = next.title;
5431
+ morphElement(document.body, next.body);
5432
+ } catch (error) {
5433
+ debug14.log("re-render failed", error);
5434
+ } finally {
5435
+ inFlight = false;
5436
+ }
5437
+ if (pending && !stopped) {
5438
+ const queued = pending;
5439
+ pending = null;
5440
+ void render(queued);
5441
+ }
5442
+ };
5443
+ const schedule = (log) => {
5444
+ if (timer) clearTimeout(timer);
5445
+ timer = setTimeout(() => {
5446
+ timer = null;
5447
+ if (inFlight) pending = log;
5448
+ else void render(log);
5449
+ }, SYNC_DEBOUNCE_MS);
5450
+ };
5451
+ const offLog = store.onLogChange((log) => {
5452
+ if (log.length) schedule(log);
5453
+ });
5454
+ const offInvalidate = store.onInvalidate(() => schedule([]));
5455
+ return {
5456
+ stop() {
5457
+ stopped = true;
5458
+ if (timer) clearTimeout(timer);
5459
+ offLog();
5460
+ offInvalidate();
5461
+ bridge.stop();
5462
+ }
5463
+ };
2320
5464
  }
2321
5465
 
2322
- // src/core/personalization.ts
2323
- var PERSONALIZED_VARY = /\bPrepr-(Segments|ABTesting)/i;
2324
- function isPersonalizedResponse(source) {
2325
- const headers = "headers" in source ? source.headers : source;
2326
- return PERSONALIZED_VARY.test(headers.get("vary") ?? "");
5466
+ // src/core/live-preview/live-request.ts
5467
+ var MAX_BODY_BYTES = 1e6;
5468
+ function requestOrigin(request) {
5469
+ const url = new URL(request.url);
5470
+ const proto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
5471
+ if (proto === "https" || proto === "http") url.protocol = `${proto}:`;
5472
+ return url.origin;
5473
+ }
5474
+ async function readLiveLogFromRequest(request) {
5475
+ try {
5476
+ if (request.method !== "POST") return [];
5477
+ if (request.headers.get(HEADER_LIVE_RENDER) !== "1") return [];
5478
+ const origin = request.headers.get("origin");
5479
+ if (!origin || origin !== requestOrigin(request)) return [];
5480
+ const type = request.headers.get("content-type") ?? "";
5481
+ if (!type.toLowerCase().startsWith("application/json")) return [];
5482
+ const length = Number(request.headers.get("content-length") ?? "0");
5483
+ if (length > MAX_BODY_BYTES) return [];
5484
+ const text = await request.clone().text();
5485
+ if (text.length > MAX_BODY_BYTES) return [];
5486
+ const body = JSON.parse(text);
5487
+ return parsePatchLog(body?.log);
5488
+ } catch {
5489
+ return [];
5490
+ }
2327
5491
  }
2328
5492
 
2329
5493
  // src/core/server.ts
@@ -2498,6 +5662,16 @@ var UTM_PARAMS = [
2498
5662
  "utm_campaign"
2499
5663
  ];
2500
5664
  var MAX_HEADER_VALUE_LENGTH = 2048;
5665
+ function randomUUID() {
5666
+ if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
5667
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
5668
+ bytes[6] = bytes[6] & 15 | 64;
5669
+ bytes[8] = bytes[8] & 63 | 128;
5670
+ const hex = Array.from(bytes, (b2) => b2.toString(16).padStart(2, "0")).join(
5671
+ ""
5672
+ );
5673
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
5674
+ }
2501
5675
  function sanitizeHeaderValue(value) {
2502
5676
  const stripped = value.replace(/[\u0000-\u001f\u007f]/g, "");
2503
5677
  return stripped.length > MAX_HEADER_VALUE_LENGTH ? stripped.slice(0, MAX_HEADER_VALUE_LENGTH) : stripped;
@@ -2572,7 +5746,7 @@ function processFrameworkRequest(request, opts, framework) {
2572
5746
  }
2573
5747
  let uid = sanitizeHeaderValue(requestCookies.get(COOKIE_UID) ?? "");
2574
5748
  if (!uid) {
2575
- uid = crypto.randomUUID();
5749
+ uid = randomUUID();
2576
5750
  responseCookies.push({
2577
5751
  name: COOKIE_UID,
2578
5752
  value: uid,
@@ -2641,10 +5815,6 @@ function processFrameworkRequest(request, opts, framework) {
2641
5815
  });
2642
5816
  }
2643
5817
  }
2644
- if (requestHeaders.has("Prepr-Segments")) {
2645
- requestHeaders.delete("Prepr-Customer-Id");
2646
- requestHeaders.delete("Prepr-Customer-Id-Created");
2647
- }
2648
5818
  return { requestHeaders, responseCookies };
2649
5819
  }
2650
5820
 
@@ -2717,6 +5887,7 @@ function setTrackingParam(key, value) {
2717
5887
  PreprError,
2718
5888
  PreprToolbarElement,
2719
5889
  VERSION,
5890
+ annotateEditLinks,
2720
5891
  createPreprPreview,
2721
5892
  createToolbarStore,
2722
5893
  definePreprToolbar,
@@ -2727,12 +5898,17 @@ function setTrackingParam(key, value) {
2727
5898
  getPreprHeadersFromHeaders,
2728
5899
  getPreprUUIDFromHeaders,
2729
5900
  getToolbarPropsFromHeaders,
2730
- isPersonalizedResponse,
2731
5901
  loadTrackingPixel,
5902
+ normalizeQuery,
5903
+ parsePatchLog,
5904
+ previewAttrs,
2732
5905
  processPreprRequest,
5906
+ readLiveLogFromRequest,
2733
5907
  resolveFeatures,
2734
5908
  setTrackingParam,
5909
+ startHtmlLivePreview,
2735
5910
  stegaClean,
5911
+ stegaTarget,
2736
5912
  trackEvent,
2737
5913
  validatePreprToken
2738
5914
  });