@preprio/toolkit 0.6.0-alpha.9 → 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-5QIWVDP2.js → chunk-33GWVTRJ.js} +1 -1
  7. package/dist/chunk-A2J7R4LR.js +256 -0
  8. package/dist/{chunk-WQBKQG4R.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-J66UOCK6.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 -754
  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 -299
  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-UN4JADNU.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-S5RWVMDJ.js +0 -148
  83. package/dist/chunk-XL4Y7FGW.js +0 -499
  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-CMV6ZP6E.js +0 -549
  93. package/dist/nextjs/graphql.cjs +0 -1836
  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 -1422
  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-XWOABVMW.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-3S5RA6G5.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
@@ -20,18 +20,35 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/astro/index.ts
21
21
  var astro_exports = {};
22
22
  __export(astro_exports, {
23
+ PreprError: () => PreprError,
24
+ extractAccessToken: () => extractAccessToken,
23
25
  getActiveSegment: () => getActiveSegment,
24
26
  getActiveVariant: () => getActiveVariant,
25
27
  getPreprHeaders: () => getPreprHeaders,
26
28
  getPreprUUID: () => getPreprUUID,
27
29
  getToolbarProps: () => getToolbarProps,
28
- isPersonalizedResponse: () => isPersonalizedResponse,
29
- onPreprRequest: () => onPreprRequest
30
+ normalizeQuery: () => normalizeQuery2,
31
+ onPreprRequest: () => onPreprRequest,
32
+ validatePreprToken: () => validatePreprToken
30
33
  });
31
34
  module.exports = __toCommonJS(astro_exports);
32
35
 
33
36
  // src/version.ts
34
- var VERSION = "0.6.0-alpha.9";
37
+ var VERSION = "1.0.0-rc.1";
38
+
39
+ // src/core/constants.ts
40
+ var COOKIE_PREVIEW_MODE = "Prepr-Preview-Mode";
41
+ var COOKIE_SEGMENT = "Prepr-Segments";
42
+ var COOKIE_VARIANT = "Prepr-ABtesting";
43
+ var COOKIE_UID = "__prepr_uid";
44
+ var COOKIE_HUBSPOT = "hubspotutk";
45
+ var PARAM_SEGMENT = "prepr_preview_segment";
46
+ var PARAM_VARIANT = "prepr_preview_ab";
47
+ var PARAM_HIDE_BAR = "prepr_hide_bar";
48
+ var ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;
49
+ var HEADER_LIVE_RENDER = "x-prepr-live";
50
+ var ATTR_ENCODED = "data-prepr-encoded";
51
+ var ENCODED_SELECTOR = `[${ATTR_ENCODED}]`;
35
52
 
36
53
  // src/core/features.ts
37
54
  function isEnabled(config) {
@@ -51,150 +68,6 @@ var ALL_FEATURES_ENABLED = Object.freeze({
51
68
  editMode: true
52
69
  });
53
70
 
54
- // src/core/server.ts
55
- var PreprError = class extends Error {
56
- constructor(message, code, context, originalError) {
57
- super(message);
58
- this.code = code;
59
- this.context = context;
60
- this.originalError = originalError;
61
- this.name = "PreprError";
62
- }
63
- };
64
- function getPreprUUIDFromHeaders(headers) {
65
- return headers.get("prepr-customer-id");
66
- }
67
- function getActiveSegmentFromHeaders(headers) {
68
- return headers.get("Prepr-Segments");
69
- }
70
- function getActiveVariantFromHeaders(headers) {
71
- return headers.get("Prepr-ABtesting");
72
- }
73
- var PREPR_HEADER_KEYS = [
74
- "prepr-customer-id",
75
- "Prepr-Segments",
76
- "Prepr-ABtesting",
77
- "Prepr-Preview-Bar",
78
- "Prepr-Context-utm_source",
79
- "Prepr-Context-utm_medium",
80
- "Prepr-Context-utm_term",
81
- "Prepr-Context-utm_content",
82
- "Prepr-Context-utm_campaign",
83
- "Prepr-Context-initial_referral",
84
- "Prepr-Visitor-IP",
85
- "Prepr-Hubspot-Id",
86
- "Prepr-Customer-Id-Created",
87
- "User-Agent",
88
- "Prepr-Package"
89
- ];
90
- function getPreprHeadersFromHeaders(headers) {
91
- const preprHeaders = {};
92
- const copy = (key) => {
93
- const value = headers.get(key);
94
- if (value !== null) {
95
- preprHeaders[key] = value;
96
- }
97
- };
98
- for (const key of PREPR_HEADER_KEYS) {
99
- copy(key);
100
- }
101
- return preprHeaders;
102
- }
103
- function validatePreprToken(token) {
104
- if (!token) {
105
- throw new PreprError(
106
- "Token is required",
107
- "MISSING_TOKEN",
108
- "validatePreprToken"
109
- );
110
- }
111
- if (!token.startsWith("https://")) {
112
- throw new PreprError(
113
- "Token must be a valid HTTPS URL",
114
- "INVALID_TOKEN",
115
- "validatePreprToken"
116
- );
117
- }
118
- }
119
- async function getPreprEnvironmentSegments(token) {
120
- validatePreprToken(token);
121
- try {
122
- const response = await fetch(token, {
123
- headers: {
124
- "Prepr-Package": `@preprio/toolkit@${VERSION}`,
125
- // Duplicates the version in Prepr-Package. It keeps the User-Agent
126
- // format used by `@preprio/prepr-nextjs`, for Prepr API consumers that
127
- // still identify the toolbar by that string.
128
- "User-Agent": `Prepr-Preview-Bar/${VERSION}`,
129
- "Content-Type": "application/json"
130
- },
131
- method: "POST",
132
- body: JSON.stringify({
133
- query: `{
134
- _Segments {
135
- _id
136
- name
137
- }
138
- }`
139
- })
140
- });
141
- if (!response.ok) {
142
- throw new PreprError(
143
- `HTTP ${response.status}: ${response.statusText}`,
144
- "HTTP_ERROR",
145
- "getPreprEnvironmentSegments"
146
- );
147
- }
148
- const json = await response.json();
149
- if (!json || !json.data || !json.data._Segments) {
150
- throw new PreprError(
151
- "Invalid response format from Prepr API",
152
- "INVALID_RESPONSE",
153
- "getPreprEnvironmentSegments"
154
- );
155
- }
156
- return json.data._Segments;
157
- } catch (error) {
158
- if (error instanceof PreprError) {
159
- throw error;
160
- }
161
- throw new PreprError(
162
- "Failed to fetch segments from Prepr API",
163
- "FETCH_ERROR",
164
- "getPreprEnvironmentSegments",
165
- error instanceof Error ? error : new Error(String(error))
166
- );
167
- }
168
- }
169
- async function getToolbarPropsFromHeaders(headers, token, features) {
170
- const resolved = resolveFeatures(features);
171
- let segments = [];
172
- if (resolved.segments) {
173
- try {
174
- segments = await getPreprEnvironmentSegments(token);
175
- } catch {
176
- segments = [];
177
- }
178
- }
179
- return {
180
- activeSegment: resolved.segments ? getActiveSegmentFromHeaders(headers) : null,
181
- activeVariant: resolved.abTesting ? getActiveVariantFromHeaders(headers) : null,
182
- segments,
183
- data: segments
184
- };
185
- }
186
-
187
- // src/core/constants.ts
188
- var COOKIE_PREVIEW_MODE = "Prepr-Preview-Mode";
189
- var COOKIE_SEGMENT = "Prepr-Segments";
190
- var COOKIE_VARIANT = "Prepr-ABtesting";
191
- var COOKIE_UID = "__prepr_uid";
192
- var COOKIE_HUBSPOT = "hubspotutk";
193
- var PARAM_SEGMENT = "prepr_preview_segment";
194
- var PARAM_VARIANT = "prepr_preview_ab";
195
- var PARAM_HIDE_BAR = "prepr_hide_bar";
196
- var ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;
197
-
198
71
  // src/core/middleware.ts
199
72
  var UTM_PARAMS = [
200
73
  "utm_source",
@@ -204,6 +77,16 @@ var UTM_PARAMS = [
204
77
  "utm_campaign"
205
78
  ];
206
79
  var MAX_HEADER_VALUE_LENGTH = 2048;
80
+ function randomUUID() {
81
+ if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
82
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
83
+ bytes[6] = bytes[6] & 15 | 64;
84
+ bytes[8] = bytes[8] & 63 | 128;
85
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(
86
+ ""
87
+ );
88
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
89
+ }
207
90
  function sanitizeHeaderValue(value) {
208
91
  const stripped = value.replace(/[\u0000-\u001f\u007f]/g, "");
209
92
  return stripped.length > MAX_HEADER_VALUE_LENGTH ? stripped.slice(0, MAX_HEADER_VALUE_LENGTH) : stripped;
@@ -289,7 +172,7 @@ function processFrameworkRequest(request, opts, framework) {
289
172
  }
290
173
  let uid = sanitizeHeaderValue(requestCookies.get(COOKIE_UID) ?? "");
291
174
  if (!uid) {
292
- uid = crypto.randomUUID();
175
+ uid = randomUUID();
293
176
  responseCookies.push({
294
177
  name: COOKIE_UID,
295
178
  value: uid,
@@ -358,58 +241,1548 @@ function processFrameworkRequest(request, opts, framework) {
358
241
  });
359
242
  }
360
243
  }
361
- if (requestHeaders.has("Prepr-Segments")) {
362
- requestHeaders.delete("Prepr-Customer-Id");
363
- requestHeaders.delete("Prepr-Customer-Id-Created");
364
- }
365
244
  return { requestHeaders, responseCookies };
366
245
  }
367
246
 
368
- // src/core/personalization.ts
369
- var PERSONALIZED_VARY = /\bPrepr-(Segments|ABTesting)/i;
370
- function isPersonalizedResponse(source) {
371
- const headers = "headers" in source ? source.headers : source;
372
- return PERSONALIZED_VARY.test(headers.get("vary") ?? "");
247
+ // src/core/live-preview/guards.ts
248
+ function isScalar(value) {
249
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
250
+ }
251
+ function isObject(value) {
252
+ return value !== null && typeof value === "object" && !Array.isArray(value);
373
253
  }
374
254
 
375
- // src/astro/index.ts
376
- async function onPreprRequest(context, next, options) {
377
- const { requestHeaders, responseCookies } = processFrameworkRequest(
378
- context.request,
379
- options,
380
- "astro"
381
- );
382
- requestHeaders.forEach((value, key) => {
383
- context.request.headers.set(key, value);
255
+ // src/core/live-preview/entry-edit-links.ts
256
+ var import_stega = require("@vercel/stega");
257
+
258
+ // src/core/live-preview/validate.ts
259
+ var MAX_DEPTH = 3;
260
+ var MAX_ENTRIES = 50;
261
+ var FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
262
+ var SAFE_URL = /^https?:\/\//i;
263
+ var URL_KEY = /^(?:url|href|src|link)$|(?:_url|Url)$/;
264
+ var URL_IGNORED_ANYWHERE = /[\t\n\r]/g;
265
+ var SCRIPT_SCHEME = /^(?:javascript|vbscript|data):/i;
266
+ function isSafeLinkValue(value) {
267
+ const stripped = value.replace(URL_IGNORED_ANYWHERE, "");
268
+ let start = 0;
269
+ while (start < stripped.length && stripped.charCodeAt(start) <= 32) start++;
270
+ return !SCRIPT_SCHEME.test(stripped.slice(start));
271
+ }
272
+ function isUrlKey(key) {
273
+ return URL_KEY.test(key);
274
+ }
275
+ function isSafeKeyValue(key, value) {
276
+ if (typeof value !== "string") return true;
277
+ if (key === "url") return SAFE_URL.test(value);
278
+ return !isUrlKey(key) || isSafeLinkValue(value);
279
+ }
280
+ function isLiveValue(v, depth = 0) {
281
+ if (v === null || isScalar(v)) return true;
282
+ if (depth >= MAX_DEPTH) return false;
283
+ if (Array.isArray(v)) {
284
+ return depth === 0 && v.length <= MAX_ENTRIES && v.every((entry) => isPlainRecord(entry) && isLiveValue(entry, depth + 1));
285
+ }
286
+ if (!isPlainRecord(v)) return false;
287
+ const keys = Object.keys(v);
288
+ if (keys.length > MAX_ENTRIES) return false;
289
+ return keys.every((key) => {
290
+ if (FORBIDDEN_KEYS.has(key)) return false;
291
+ const value = v[key];
292
+ if (!isSafeKeyValue(key, value)) return false;
293
+ return !Array.isArray(value) && isLiveValue(value, depth + 1);
384
294
  });
385
- const response = await next();
386
- for (const cookie of responseCookies) {
387
- response.headers.append("Set-Cookie", serializeCookie(cookie));
295
+ }
296
+ function isLiveFieldChange(field, value) {
297
+ if (!isLiveValue(value)) return false;
298
+ const name = field.slice(field.lastIndexOf(".") + 1);
299
+ return typeof value !== "string" || !isUrlKey(name) || isSafeLinkValue(value);
300
+ }
301
+ var MAX_LIST_ENTRIES = 200;
302
+ function parseListEntries(value) {
303
+ if (!Array.isArray(value) || value.length > MAX_LIST_ENTRIES) return null;
304
+ const list = [];
305
+ for (const raw of value) {
306
+ if (!isPlainRecord(raw) || typeof raw._id !== "string" || !raw._id) {
307
+ return null;
308
+ }
309
+ const entry = { _id: raw._id };
310
+ if (typeof raw.__typename === "string") entry.__typename = raw.__typename;
311
+ if (typeof raw.body === "string") entry.body = raw.body;
312
+ if (typeof raw.format === "string" || raw.format === null) {
313
+ entry.format = raw.format;
314
+ }
315
+ if (typeof raw.typeName === "string" && raw.typeName.length <= 200) {
316
+ entry.typeName = raw.typeName;
317
+ }
318
+ if (raw.fields !== void 0) {
319
+ if (!isPlainRecord(raw.fields) || !isFieldValue(raw.fields, 0)) {
320
+ return null;
321
+ }
322
+ entry.fields = raw.fields;
323
+ }
324
+ list.push(entry);
388
325
  }
389
- return response;
326
+ return list;
390
327
  }
391
- function getPreprUUID(headers) {
392
- return getPreprUUIDFromHeaders(headers);
328
+ function isPlainRecord(v) {
329
+ return v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
393
330
  }
394
- function getActiveSegment(headers) {
395
- return getActiveSegmentFromHeaders(headers);
331
+ var MAX_FIELD_DEPTH = 6;
332
+ var MAX_FIELD_KEYS = 100;
333
+ function isFieldValue(v, depth) {
334
+ if (v === null || isScalar(v)) return true;
335
+ if (depth >= MAX_FIELD_DEPTH) return false;
336
+ if (Array.isArray(v)) {
337
+ return v.length <= MAX_ENTRIES && v.every(
338
+ (entry) => isScalar(entry) || isPlainRecord(entry) && isFieldValue(entry, depth + 1)
339
+ );
340
+ }
341
+ if (!isPlainRecord(v)) return false;
342
+ const keys = Object.keys(v);
343
+ if (keys.length > MAX_FIELD_KEYS) return false;
344
+ return keys.every((key) => {
345
+ if (FORBIDDEN_KEYS.has(key)) return false;
346
+ const value = v[key];
347
+ if (!isSafeKeyValue(key, value)) return false;
348
+ return isFieldValue(value, depth + 1);
349
+ });
396
350
  }
397
- function getActiveVariant(headers) {
398
- return getActiveVariantFromHeaders(headers);
351
+ var MAX_EDIT_LENGTH = 1e3;
352
+ function parseEditTarget(raw) {
353
+ if (!isPlainRecord(raw)) return void 0;
354
+ const { item, field } = raw;
355
+ if (typeof item !== "string" || !item || item.length > MAX_EDIT_LENGTH) {
356
+ return void 0;
357
+ }
358
+ if (typeof field !== "string" || !field || field.length > MAX_EDIT_LENGTH) {
359
+ return void 0;
360
+ }
361
+ return { item, field };
399
362
  }
400
- function getPreprHeaders(headers) {
401
- return getPreprHeadersFromHeaders(headers);
363
+
364
+ // src/core/live-preview/entry-edit-links.ts
365
+ var EDIT_PATH = /\/content\/edit\/[^/?#]+/;
366
+ function editLinks(result, entry) {
367
+ const edit = entry.fields?.__edit;
368
+ if (!isPlainRecord(edit) || typeof edit.item !== "string") return null;
369
+ return editLinksFor(result, edit.item);
402
370
  }
403
- async function getToolbarProps(headers, token, features) {
404
- return getToolbarPropsFromHeaders(headers, token, features);
371
+ var ITEM_ID = /^[A-Za-z0-9_-]+$/;
372
+ function editLinksFor(result, item) {
373
+ if (!ITEM_ID.test(item)) return null;
374
+ const template = findEditLink(result);
375
+ if (!template) return null;
376
+ return {
377
+ encode(text, field) {
378
+ if ((0, import_stega.vercelStegaSplit)(text).encoded) return text;
379
+ let href;
380
+ try {
381
+ href = new URL(template.href);
382
+ } catch {
383
+ return text;
384
+ }
385
+ href.pathname = href.pathname.replace(
386
+ EDIT_PATH,
387
+ () => `/content/edit/${item}`
388
+ );
389
+ href.searchParams.set("field", field);
390
+ const link = href.toString().replace(/%2E/gi, ".").replace(/%2F/gi, "/");
391
+ return (0, import_stega.vercelStegaCombine)(text, { origin: template.origin, href: link });
392
+ }
393
+ };
394
+ }
395
+ var linkCache = /* @__PURE__ */ new WeakMap();
396
+ function findEditLink(root) {
397
+ if (root === null || typeof root !== "object") return null;
398
+ if (linkCache.has(root)) return linkCache.get(root) ?? null;
399
+ let found = null;
400
+ const seen = /* @__PURE__ */ new WeakSet();
401
+ const walk2 = (node) => {
402
+ if (found) return;
403
+ if (typeof node === "string") {
404
+ if (!(0, import_stega.vercelStegaSplit)(node).encoded) return;
405
+ try {
406
+ const decoded = (0, import_stega.vercelStegaDecode)(node);
407
+ if (typeof decoded?.origin === "string" && typeof decoded.href === "string" && EDIT_PATH.test(decoded.href)) {
408
+ found = { origin: decoded.origin, href: decoded.href };
409
+ }
410
+ } catch {
411
+ }
412
+ return;
413
+ }
414
+ if (node === null || typeof node !== "object" || seen.has(node)) return;
415
+ seen.add(node);
416
+ for (const value of Object.values(node)) walk2(value);
417
+ };
418
+ walk2(root);
419
+ linkCache.set(root, found);
420
+ return found;
421
+ }
422
+
423
+ // src/core/live-preview/patch-log.ts
424
+ var MAX_LOG_ENTRIES = 500;
425
+ var MAX_LOG_SOURCE_LENGTH = 1e6;
426
+ function parsePatchLog(raw) {
427
+ let value = raw;
428
+ if (typeof value === "string") {
429
+ if (!value || value.length > MAX_LOG_SOURCE_LENGTH) return [];
430
+ try {
431
+ value = JSON.parse(value);
432
+ } catch {
433
+ return [];
434
+ }
435
+ }
436
+ if (!Array.isArray(value)) return [];
437
+ const log = [];
438
+ for (const entry of value.slice(-MAX_LOG_ENTRIES)) {
439
+ if (!isPlainRecord(entry)) continue;
440
+ const { type, itemId, field } = entry;
441
+ if (typeof itemId !== "string" || !itemId) continue;
442
+ if (typeof field !== "string" || !field) continue;
443
+ if (type === "field" && isLiveFieldChange(field, entry.value)) {
444
+ const edit = parseEditTarget(entry.edit);
445
+ log.push(
446
+ edit ? { type, itemId, field, value: entry.value, edit } : { type, itemId, field, value: entry.value }
447
+ );
448
+ } else if (type === "list") {
449
+ const entries = parseListEntries(entry.entries);
450
+ if (entries) log.push({ type, itemId, field, entries });
451
+ }
452
+ }
453
+ return log;
454
+ }
455
+
456
+ // src/core/live-preview/normalize-query.ts
457
+ var import_stega3 = require("@vercel/stega");
458
+
459
+ // src/core/shared-state.ts
460
+ var KEY = /* @__PURE__ */ Symbol.for("@preprio/toolkit:shared-state");
461
+ function initialState() {
462
+ return {
463
+ trustedParentOrigin: null,
464
+ debugEnabled: void 0,
465
+ strictMode: false,
466
+ liveAnnouncedStrict: void 0
467
+ };
468
+ }
469
+ function sharedState() {
470
+ const scope = globalThis;
471
+ return scope[KEY] ?? (scope[KEY] = initialState());
472
+ }
473
+
474
+ // src/core/utils.ts
475
+ var DebugLogger = class {
476
+ constructor(options) {
477
+ this.options = {
478
+ prefix: "[Prepr]",
479
+ ...options
480
+ };
481
+ }
482
+ // A local `enabled` wins; otherwise defer to the shared flag so scoped
483
+ // loggers created before initDebugLogger() still pick up the setting.
484
+ isEnabled() {
485
+ if (this.options.enabled !== void 0) {
486
+ return this.options.enabled;
487
+ }
488
+ return sharedState().debugEnabled ?? false;
489
+ }
490
+ log(message, ...args) {
491
+ if (!this.isEnabled()) return;
492
+ const prefix = this.options.prefix;
493
+ console.log(`${prefix} ${message}`, ...args);
494
+ }
495
+ warn(message, ...args) {
496
+ if (!this.isEnabled()) return;
497
+ const prefix = this.options.prefix;
498
+ console.warn(`${prefix} ${message}`, ...args);
499
+ }
500
+ };
501
+ function createScopedLogger(scopeName) {
502
+ return new DebugLogger({
503
+ prefix: `[Prepr][${scopeName}]`
504
+ });
505
+ }
506
+
507
+ // src/core/live-preview/field-name.ts
508
+ var UPPERCASE_BOUNDARY = /(.)(?=[A-Z])/g;
509
+ function graphqlFieldName(apiId) {
510
+ return apiId.replace(UPPERCASE_BOUNDARY, "$1_").toLowerCase();
511
+ }
512
+ var TEXT_BODY_FIELDS = [
513
+ { name: "body", plain: false },
514
+ { name: "html", plain: false },
515
+ { name: "text", plain: true }
516
+ ];
517
+ var TAG_PATTERN = /<[^>]+>/g;
518
+ function plainTextFromHtml(html) {
519
+ return html.replace(TAG_PATTERN, "");
520
+ }
521
+ function isTextEntry(record) {
522
+ const typename = record.__typename;
523
+ if (typeof typename === "string") return typename === "Text";
524
+ return "html" in record || "text" in record && "format" in record;
525
+ }
526
+
527
+ // src/core/live-preview/index-snapshot.ts
528
+ var debug = createScopedLogger("live-preview");
529
+ function indexSnapshot(data) {
530
+ const index = /* @__PURE__ */ new Map();
531
+ const visited = /* @__PURE__ */ new WeakSet();
532
+ const path = [];
533
+ function walk2(node) {
534
+ if (node === null || typeof node !== "object") return;
535
+ if (visited.has(node)) return;
536
+ visited.add(node);
537
+ if (Array.isArray(node)) {
538
+ for (let i = 0; i < node.length; i++) {
539
+ path.push(i);
540
+ walk2(node[i]);
541
+ path.pop();
542
+ }
543
+ return;
544
+ }
545
+ const record = node;
546
+ if (typeof record._id === "string") {
547
+ const paths = index.get(record._id);
548
+ if (paths) paths.push([...path]);
549
+ else index.set(record._id, [[...path]]);
550
+ } else if (typeof record.__typename === "string") {
551
+ debug.log("item without _id will not live-update", {
552
+ __typename: record.__typename
553
+ });
554
+ }
555
+ for (const key in record) {
556
+ if (!Object.prototype.hasOwnProperty.call(record, key)) continue;
557
+ path.push(key);
558
+ walk2(record[key]);
559
+ path.pop();
560
+ }
561
+ }
562
+ walk2(data);
563
+ return index;
564
+ }
565
+
566
+ // src/core/live-preview/patch.ts
567
+ var import_stega2 = require("@vercel/stega");
568
+ var FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
569
+ function mergeObject(current, incoming) {
570
+ let changed = false;
571
+ const next = { ...current };
572
+ for (const key of Object.keys(current)) {
573
+ if (!(key in incoming) || incoming[key] === void 0) continue;
574
+ const value = isObject(current[key]) && isObject(incoming[key]) ? mergeObject(current[key], incoming[key]) : incoming[key];
575
+ if (value !== current[key]) {
576
+ next[key] = value;
577
+ changed = true;
578
+ }
579
+ }
580
+ return changed ? next : current;
581
+ }
582
+ function shapeLike(template, incoming) {
583
+ const out = {};
584
+ for (const key of Object.keys(template)) {
585
+ const value = incoming[key];
586
+ out[key] = value === void 0 ? null : isObject(template[key]) && isObject(value) ? shapeLike(template[key], value) : value;
587
+ }
588
+ return out;
589
+ }
590
+ function isAsset(value) {
591
+ return isObject(value) && (typeof value.url === "string" || value.__typename === "Asset");
592
+ }
593
+ function hasId(list, entry) {
594
+ return entry._id !== void 0 && list.some((c) => isObject(c) && c._id === entry._id);
595
+ }
596
+ function isAssetValue(value) {
597
+ return Array.isArray(value) ? value.length > 0 && value.every(isAsset) : isAsset(value);
598
+ }
599
+ function keepRemovedAssets(current, next) {
600
+ const listed = /* @__PURE__ */ new Set();
601
+ for (const entry of next) {
602
+ if (isObject(entry) && entry._id !== void 0) listed.add(entry._id);
603
+ }
604
+ let out = next;
605
+ current.forEach((entry, position) => {
606
+ if (!isObject(entry) || entry._id === void 0) return;
607
+ if (listed.has(entry._id)) return;
608
+ if (out === next) out = [...next];
609
+ out.splice(Math.min(position, out.length), 0, entry);
610
+ });
611
+ return out;
612
+ }
613
+ function mergeStructured(current, incoming) {
614
+ if (incoming === null || Array.isArray(incoming) && !incoming.length) {
615
+ if (isAssetValue(current)) return current;
616
+ if (Array.isArray(current)) return current.length ? [] : current;
617
+ return null;
618
+ }
619
+ const list = Array.isArray(incoming) ? incoming : [incoming];
620
+ if (current === null || current === void 0) return incoming;
621
+ if (Array.isArray(current)) {
622
+ const template = current.find(isObject);
623
+ const next = list.map((entry) => {
624
+ const match = current.find(
625
+ (c) => isObject(c) && c._id !== void 0 && c._id === entry._id
626
+ );
627
+ if (isObject(match)) return mergeObject(match, entry);
628
+ return isObject(template) ? shapeLike(template, entry) : entry;
629
+ });
630
+ if (!isAssetValue(current) || list.some((entry) => !hasId(current, entry))) {
631
+ return next;
632
+ }
633
+ const kept = keepRemovedAssets(current, next);
634
+ return kept.length === current.length && kept.every((entry, i) => entry === current[i]) ? current : kept;
635
+ }
636
+ if (isObject(current)) return mergeObject(current, list[0]);
637
+ return current;
638
+ }
639
+ function isPatchable(current) {
640
+ return current === null || typeof current === "string" || typeof current === "number" || typeof current === "boolean";
641
+ }
642
+ function cloneNode(node) {
643
+ return Array.isArray(node) ? [...node] : { ...node };
644
+ }
645
+ function writeAtPath(root, fullPath, value, markChanged = () => {
646
+ }) {
647
+ if (!fullPath.length) return root;
648
+ if (fullPath.some((s) => FORBIDDEN_SEGMENTS.has(String(s)))) return root;
649
+ const last = fullPath.length - 1;
650
+ let node = root;
651
+ for (let i = 0; i < last; i++) {
652
+ if (node === null || typeof node !== "object") return root;
653
+ node = node[fullPath[i]];
654
+ }
655
+ if (node === null || typeof node !== "object") return root;
656
+ const container = node;
657
+ const key = fullPath[last];
658
+ if (!(key in container)) return root;
659
+ let next;
660
+ if (value === null || typeof value === "object") {
661
+ next = mergeStructured(container[key], value);
662
+ } else if (!isPatchable(container[key])) {
663
+ return root;
664
+ } else {
665
+ next = keepEditLink(container[key], value);
666
+ }
667
+ if (container[key] === next) return root;
668
+ const newRoot = cloneNode(root);
669
+ let cursor = newRoot;
670
+ for (let i = 0; i < last; i++) {
671
+ const child = cloneNode(cursor[fullPath[i]]);
672
+ cursor[fullPath[i]] = child;
673
+ cursor = child;
674
+ }
675
+ cursor[key] = next;
676
+ markChanged();
677
+ return newRoot;
678
+ }
679
+ function listKeysOf(entry) {
680
+ if (!isObject(entry)) return [];
681
+ const keys = [];
682
+ if (typeof entry._id === "string") keys.push(entry._id);
683
+ const first = Array.isArray(entry.items) ? entry.items[0] : null;
684
+ if (isObject(first) && typeof first._id === "string") {
685
+ keys.push(first._id);
686
+ }
687
+ return keys;
688
+ }
689
+ function buildText(entry, template) {
690
+ const body = typeof entry.body === "string" ? entry.body : "";
691
+ const full = {
692
+ __typename: "Text",
693
+ _id: entry._id,
694
+ body,
695
+ html: body,
696
+ text: plainTextFromHtml(body),
697
+ format: entry.format ?? null
698
+ };
699
+ if (!template) return full;
700
+ const out = {};
701
+ for (const key of Object.keys(template)) {
702
+ out[key] = key in full ? full[key] : null;
703
+ }
704
+ return out;
705
+ }
706
+ function syncList(current, entries, build) {
707
+ if (current === null || current === void 0) {
708
+ const built = syncList([], entries, build);
709
+ return built.length ? built : current;
710
+ }
711
+ if (!Array.isArray(current)) return current;
712
+ const byKey = /* @__PURE__ */ new Map();
713
+ const templates = /* @__PURE__ */ new Map();
714
+ for (const c of current) {
715
+ for (const key of listKeysOf(c)) byKey.set(key, c);
716
+ if (isObject(c) && typeof c.__typename === "string") {
717
+ if (!templates.has(c.__typename)) templates.set(c.__typename, c);
718
+ }
719
+ }
720
+ if (!entries.length) return current.length ? [] : current;
721
+ if (current.length && !byKey.size) return current;
722
+ if (current.length && !entries.some((e) => byKey.has(e._id))) return current;
723
+ const next = [];
724
+ for (const entry of entries) {
725
+ const existing = byKey.get(entry._id);
726
+ const built = existing === void 0 && entry.fields ? build?.(entry) : void 0;
727
+ if (existing !== void 0) {
728
+ next.push(existing);
729
+ } else if (built) {
730
+ next.push(built);
731
+ } else if (entry.__typename === "Text") {
732
+ next.push(buildText(entry, templates.get("Text")));
733
+ }
734
+ }
735
+ const same = next.length === current.length && next.every((n, i) => n === current[i]);
736
+ return same ? current : next;
737
+ }
738
+ function syncListAtPath(root, fullPath, entries, build) {
739
+ if (!fullPath.length) return root;
740
+ if (fullPath.some((s) => FORBIDDEN_SEGMENTS.has(String(s)))) return root;
741
+ let node = root;
742
+ for (const key of fullPath) {
743
+ node = node !== null && typeof node === "object" ? node[key] : void 0;
744
+ }
745
+ const next = syncList(node, entries, build);
746
+ if (next === node) return root;
747
+ const newRoot = cloneNode(root);
748
+ let cursor = newRoot;
749
+ for (let i = 0; i < fullPath.length - 1; i++) {
750
+ const child = cloneNode(cursor[fullPath[i]]);
751
+ cursor[fullPath[i]] = child;
752
+ cursor = child;
753
+ }
754
+ cursor[fullPath[fullPath.length - 1]] = next;
755
+ return newRoot;
756
+ }
757
+ function keepEditLink(current, value) {
758
+ if (typeof current !== "string" || typeof value !== "string") return value;
759
+ const { encoded } = (0, import_stega2.vercelStegaSplit)(current);
760
+ if (!encoded || (0, import_stega2.vercelStegaSplit)(value).encoded) return value;
761
+ return value + encoded;
762
+ }
763
+
764
+ // src/core/live-preview/query-document.ts
765
+ var NAME_START = /[_A-Za-z]/;
766
+ var NAME_CONTINUE = /[_0-9A-Za-z]/;
767
+ var PUNCT = /* @__PURE__ */ new Set([
768
+ "!",
769
+ "$",
770
+ "&",
771
+ "(",
772
+ ")",
773
+ ":",
774
+ "=",
775
+ "@",
776
+ "[",
777
+ "]",
778
+ "{",
779
+ "|",
780
+ "}"
781
+ ]);
782
+ function tokenize(source) {
783
+ const tokens = [];
784
+ let i = 0;
785
+ const n = source.length;
786
+ while (i < n) {
787
+ const ch = source[i];
788
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "," || ch === "\uFEFF") {
789
+ i++;
790
+ } else if (ch === "#") {
791
+ while (i < n && source[i] !== "\n" && source[i] !== "\r") i++;
792
+ } else if (ch === "." && source.startsWith("...", i)) {
793
+ tokens.push({ type: "punct", value: "..." });
794
+ i += 3;
795
+ } else if (PUNCT.has(ch)) {
796
+ tokens.push({ type: "punct", value: ch });
797
+ i++;
798
+ } else if (NAME_START.test(ch)) {
799
+ const start = i;
800
+ while (i < n && NAME_CONTINUE.test(source[i])) i++;
801
+ tokens.push({ type: "name", value: source.slice(start, i) });
802
+ } else if (ch === '"') {
803
+ if (source.startsWith('"""', i)) {
804
+ i += 3;
805
+ while (i < n && !source.startsWith('"""', i)) {
806
+ i += source.startsWith('\\"""', i) ? 4 : 1;
807
+ }
808
+ if (i >= n) throw new SyntaxError("Unterminated block string");
809
+ i += 3;
810
+ } else {
811
+ i++;
812
+ while (i < n && source[i] !== '"') {
813
+ if (source[i] === "\n" || source[i] === "\r") {
814
+ throw new SyntaxError("Unterminated string");
815
+ }
816
+ i += source[i] === "\\" ? 2 : 1;
817
+ }
818
+ if (i >= n) throw new SyntaxError("Unterminated string");
819
+ i++;
820
+ }
821
+ tokens.push({ type: "value" });
822
+ } else if (ch === "-" || ch >= "0" && ch <= "9") {
823
+ i++;
824
+ while (i < n && /[0-9.eE+-]/.test(source[i])) i++;
825
+ tokens.push({ type: "value" });
826
+ } else {
827
+ throw new SyntaxError(`Unexpected character "${ch}"`);
828
+ }
829
+ }
830
+ return tokens;
831
+ }
832
+ function parseSource(source, operationName) {
833
+ const tokens = tokenize(source);
834
+ let pos = 0;
835
+ const peek = () => tokens[pos];
836
+ const isPunct = (value) => {
837
+ const t = tokens[pos];
838
+ return t?.type === "punct" && t.value === value;
839
+ };
840
+ const expectPunct = (value) => {
841
+ if (!isPunct(value)) throw new SyntaxError(`Expected "${value}"`);
842
+ pos++;
843
+ };
844
+ const expectName = () => {
845
+ const t = tokens[pos];
846
+ if (t?.type !== "name") throw new SyntaxError("Expected a name");
847
+ pos++;
848
+ return t.value;
849
+ };
850
+ const skipParens = () => {
851
+ expectPunct("(");
852
+ let depth = 1;
853
+ while (depth > 0) {
854
+ const t = tokens[pos++];
855
+ if (!t) throw new SyntaxError("Unbalanced parentheses");
856
+ if (t.type === "punct" && t.value === "(") depth++;
857
+ else if (t.type === "punct" && t.value === ")") depth--;
858
+ }
859
+ };
860
+ const skipDirectives = () => {
861
+ while (isPunct("@")) {
862
+ pos++;
863
+ expectName();
864
+ if (isPunct("(")) skipParens();
865
+ }
866
+ };
867
+ const parseSelectionSet = () => {
868
+ expectPunct("{");
869
+ const selections = [];
870
+ while (!isPunct("}")) {
871
+ if (!peek()) throw new SyntaxError("Unterminated selection set");
872
+ selections.push(parseSelection());
873
+ }
874
+ pos++;
875
+ return selections;
876
+ };
877
+ const parseSelection = () => {
878
+ if (isPunct("...")) {
879
+ pos++;
880
+ const t = peek();
881
+ if (t?.type === "name" && t.value !== "on") {
882
+ pos++;
883
+ skipDirectives();
884
+ return { kind: "spread", name: t.value };
885
+ }
886
+ let on = null;
887
+ if (t?.type === "name") {
888
+ pos++;
889
+ on = expectName();
890
+ }
891
+ skipDirectives();
892
+ return { kind: "inline", on, selections: parseSelectionSet() };
893
+ }
894
+ let name = expectName();
895
+ const key = name;
896
+ if (isPunct(":")) {
897
+ pos++;
898
+ name = expectName();
899
+ }
900
+ let hasArgs = false;
901
+ if (isPunct("(")) {
902
+ hasArgs = true;
903
+ skipParens();
904
+ }
905
+ skipDirectives();
906
+ const selections = isPunct("{") ? parseSelectionSet() : null;
907
+ return { kind: "field", name, key, hasArgs, selections };
908
+ };
909
+ const fragments = /* @__PURE__ */ new Map();
910
+ const operations = [];
911
+ while (pos < tokens.length) {
912
+ if (isPunct("{")) {
913
+ operations.push({ name: null, selections: parseSelectionSet() });
914
+ continue;
915
+ }
916
+ const keyword = expectName();
917
+ if (keyword === "fragment") {
918
+ const name = expectName();
919
+ if (expectName() !== "on") throw new SyntaxError('Expected "on"');
920
+ const on = expectName();
921
+ skipDirectives();
922
+ fragments.set(name, { on, selections: parseSelectionSet() });
923
+ } else if (keyword === "query" || keyword === "mutation" || keyword === "subscription") {
924
+ const t = peek();
925
+ let name = null;
926
+ if (t?.type === "name") name = expectName();
927
+ if (isPunct("(")) skipParens();
928
+ skipDirectives();
929
+ operations.push({ name, selections: parseSelectionSet() });
930
+ } else {
931
+ throw new SyntaxError(`Unexpected "${keyword}"`);
932
+ }
933
+ }
934
+ return { operation: pickOperation(operations, operationName), fragments };
935
+ }
936
+ function pickOperation(operations, operationName) {
937
+ const op = operationName ? operations.find((o) => o.name === operationName) : operations[0];
938
+ if (!op) throw new SyntaxError("The document has no operation");
939
+ return op.selections;
940
+ }
941
+ function fromAstSelections(set) {
942
+ return set.selections.map((s) => {
943
+ if (s.kind === "FragmentSpread")
944
+ return { kind: "spread", name: s.name.value };
945
+ if (s.kind === "InlineFragment") {
946
+ return {
947
+ kind: "inline",
948
+ on: s.typeCondition?.name.value ?? null,
949
+ selections: fromAstSelections(s.selectionSet)
950
+ };
951
+ }
952
+ const name = s.name.value;
953
+ return {
954
+ kind: "field",
955
+ name,
956
+ key: s.alias?.value ?? name,
957
+ hasArgs: Boolean(s.arguments?.length),
958
+ selections: s.selectionSet ? fromAstSelections(s.selectionSet) : null
959
+ };
960
+ });
961
+ }
962
+ function fromAst(doc, operationName) {
963
+ const fragments = /* @__PURE__ */ new Map();
964
+ const operations = [];
965
+ for (const def of doc.definitions ?? []) {
966
+ if (def.kind === "FragmentDefinition" && def.name && def.typeCondition && def.selectionSet) {
967
+ fragments.set(def.name.value, {
968
+ on: def.typeCondition.name.value,
969
+ selections: fromAstSelections(def.selectionSet)
970
+ });
971
+ } else if (def.kind === "OperationDefinition" && def.selectionSet) {
972
+ operations.push({
973
+ name: def.name?.value ?? null,
974
+ selections: fromAstSelections(def.selectionSet)
975
+ });
976
+ }
977
+ }
978
+ return { operation: pickOperation(operations, operationName), fragments };
979
+ }
980
+ var astCache = /* @__PURE__ */ new WeakMap();
981
+ var sourceCache = /* @__PURE__ */ new Map();
982
+ var SOURCE_CACHE_LIMIT = 200;
983
+ function readQueryDocument(query, operationName) {
984
+ const cacheKey = operationName ?? "";
985
+ if (typeof query === "object" && query !== null && query.kind === "Document") {
986
+ let byName = astCache.get(query);
987
+ if (!byName) astCache.set(query, byName = /* @__PURE__ */ new Map());
988
+ let parsed2 = byName.get(cacheKey);
989
+ if (!parsed2) {
990
+ parsed2 = fromAst(
991
+ query,
992
+ operationName
993
+ );
994
+ byName.set(cacheKey, parsed2);
995
+ }
996
+ return parsed2;
997
+ }
998
+ const source = String(query);
999
+ const sourceKey = `${cacheKey}
1000
+ ${source}`;
1001
+ let parsed = sourceCache.get(sourceKey);
1002
+ if (!parsed) {
1003
+ parsed = parseSource(source, operationName);
1004
+ if (sourceCache.size >= SOURCE_CACHE_LIMIT) {
1005
+ sourceCache.delete(sourceCache.keys().next().value);
1006
+ }
1007
+ sourceCache.set(sourceKey, parsed);
1008
+ }
1009
+ return parsed;
1010
+ }
1011
+ var fieldsCache = /* @__PURE__ */ new WeakMap();
1012
+ function collectFields(selections, typename, doc, options = {}) {
1013
+ const cacheKey = `${options.strict ? "s" : "l"}:${typename ?? ""}`;
1014
+ let cached = fieldsCache.get(selections);
1015
+ if (!cached) {
1016
+ cached = /* @__PURE__ */ new Map();
1017
+ fieldsCache.set(selections, cached);
1018
+ }
1019
+ const hit = cached.get(cacheKey);
1020
+ if (hit) return hit;
1021
+ const fields = resolveFields(selections, typename, doc, options);
1022
+ cached.set(cacheKey, fields);
1023
+ return fields;
1024
+ }
1025
+ function resolveFields(selections, typename, doc, options) {
1026
+ const exact = /* @__PURE__ */ new Map();
1027
+ const loose = /* @__PURE__ */ new Map();
1028
+ const merged = /* @__PURE__ */ new Map();
1029
+ const walkedMatched = /* @__PURE__ */ new Set();
1030
+ const walkedLoose = /* @__PURE__ */ new Set();
1031
+ const add = (target, s) => {
1032
+ let field = target.get(s.key);
1033
+ if (!field) {
1034
+ field = { name: s.name, key: s.key, hasArgs: s.hasArgs, selections: [] };
1035
+ target.set(s.key, field);
1036
+ merged.set(field, /* @__PURE__ */ new Set());
1037
+ }
1038
+ const done = merged.get(field);
1039
+ if (s.selections && !done.has(s.selections)) {
1040
+ done.add(s.selections);
1041
+ field.selections = [...field.selections, ...s.selections];
1042
+ }
1043
+ };
1044
+ const applies = (on, list) => conditionMatches(on, typename) || typename !== void 0 && typeConditions(list, doc).includes(typename);
1045
+ const walk2 = (list, matched) => {
1046
+ for (const s of list) {
1047
+ if (s.kind === "field") {
1048
+ add(matched ? exact : loose, s);
1049
+ } else if (s.kind === "inline") {
1050
+ walk2(s.selections, matched && applies(s.on, s.selections));
1051
+ } else {
1052
+ const fragment = doc.fragments.get(s.name);
1053
+ if (!fragment) continue;
1054
+ const asMatched = matched && applies(fragment.on, fragment.selections);
1055
+ if (walkedMatched.has(fragment)) continue;
1056
+ if (!asMatched && walkedLoose.has(fragment)) continue;
1057
+ (asMatched ? walkedMatched : walkedLoose).add(fragment);
1058
+ walk2(fragment.selections, asMatched);
1059
+ }
1060
+ }
1061
+ };
1062
+ walk2(selections, true);
1063
+ if (!options.strict) {
1064
+ for (const [key, field] of loose) {
1065
+ if (!exact.has(key)) exact.set(key, field);
1066
+ }
1067
+ }
1068
+ return exact;
1069
+ }
1070
+ function conditionMatches(on, typename) {
1071
+ return on === null || typename === void 0 || on === typename;
1072
+ }
1073
+ var conditionsCache = /* @__PURE__ */ new WeakMap();
1074
+ function typeConditions(selections, doc) {
1075
+ const hit = conditionsCache.get(selections);
1076
+ if (hit) return hit;
1077
+ const names = /* @__PURE__ */ new Set();
1078
+ const seen = /* @__PURE__ */ new Set();
1079
+ const walk2 = (list) => {
1080
+ for (const s of list) {
1081
+ if (s.kind === "inline") {
1082
+ if (s.on) names.add(s.on);
1083
+ walk2(s.selections);
1084
+ } else if (s.kind === "spread") {
1085
+ const fragment = doc.fragments.get(s.name);
1086
+ if (!fragment || seen.has(fragment)) continue;
1087
+ seen.add(fragment);
1088
+ names.add(fragment.on);
1089
+ walk2(fragment.selections);
1090
+ }
1091
+ }
1092
+ };
1093
+ walk2(selections);
1094
+ const conditions = [...names];
1095
+ conditionsCache.set(selections, conditions);
1096
+ return conditions;
1097
+ }
1098
+
1099
+ // src/core/live-preview/normalize-query.ts
1100
+ var debug2 = createScopedLogger("live-preview:normalize");
1101
+ var INDEX_SEGMENT = /^\d+$/;
1102
+ var FORBIDDEN_SEGMENTS2 = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
1103
+ var ENVELOPE_KEYS = /* @__PURE__ */ new Set(["data", "errors", "extensions"]);
1104
+ function normalizeQuery(query, result, options = {}) {
1105
+ return applyPatchLog(
1106
+ query,
1107
+ result,
1108
+ parsePatchLog(options.log),
1109
+ options.operationName
1110
+ );
1111
+ }
1112
+ function applyPatchLog(query, result, log, operationName) {
1113
+ if (!log.length || result === null || typeof result !== "object") {
1114
+ return result;
1115
+ }
1116
+ if (isEnvelope(result)) {
1117
+ const data = applyPatchLog(query, result.data, log, operationName);
1118
+ return data === result.data ? result : { ...result, data };
1119
+ }
1120
+ let doc = null;
1121
+ try {
1122
+ doc = readQueryDocument(query, operationName);
1123
+ } catch (error) {
1124
+ debug2.log("could not read the query; applying fields by literal path", {
1125
+ error: String(error)
1126
+ });
1127
+ }
1128
+ let root = result;
1129
+ let index = null;
1130
+ for (const patch of log) {
1131
+ try {
1132
+ index ?? (index = indexSnapshot(root));
1133
+ const next = applyPatch(root, index, patch, doc, result);
1134
+ if (next !== root) {
1135
+ root = next;
1136
+ if (patch.type === "list" || !isScalarValue(patch.value)) {
1137
+ index = null;
1138
+ }
1139
+ }
1140
+ } catch (error) {
1141
+ debug2.log("could not apply a change", {
1142
+ itemId: patch.itemId,
1143
+ field: patch.field,
1144
+ error: String(error)
1145
+ });
1146
+ }
1147
+ }
1148
+ return root;
1149
+ }
1150
+ function isScalarValue(value) {
1151
+ return value === null || typeof value !== "object";
1152
+ }
1153
+ function applyPatch(root, index, patch, doc, result) {
1154
+ const ownerPaths = index.get(patch.itemId);
1155
+ if (!ownerPaths?.length) return root;
1156
+ const segments = patch.field.split(".");
1157
+ if (segments.some((s) => !s || FORBIDDEN_SEGMENTS2.has(s))) return root;
1158
+ const targets = [];
1159
+ const plain = /* @__PURE__ */ new Set();
1160
+ for (const ownerPath of ownerPaths) {
1161
+ if (doc) {
1162
+ const resolved = resolveTargets(root, doc, ownerPath, segments);
1163
+ root = resolved.root;
1164
+ targets.push(...resolved.targets);
1165
+ resolved.plain.forEach((target) => plain.add(target));
1166
+ } else {
1167
+ targets.push([...ownerPath, ...segments.map(toPathSegment)]);
1168
+ }
1169
+ }
1170
+ if (!targets.length) {
1171
+ debug2.log("no field in the query matches", {
1172
+ itemId: patch.itemId,
1173
+ field: patch.field
1174
+ });
1175
+ return root;
1176
+ }
1177
+ if (patch.type === "field") {
1178
+ for (const target of targets) {
1179
+ const pushed = plain.has(target) && typeof patch.value === "string" ? plainTextFromHtml(patch.value) : patch.value;
1180
+ let value = keepEditLink(readAtPath(root, target), pushed);
1181
+ if (patch.edit && typeof value === "string" && !(0, import_stega3.vercelStegaSplit)(value).encoded) {
1182
+ value = editLinksFor(result, patch.edit.item)?.encode(
1183
+ value,
1184
+ patch.edit.field
1185
+ ) ?? value;
1186
+ }
1187
+ root = writeAtPath(root, target, value);
1188
+ }
1189
+ } else {
1190
+ for (const target of targets) {
1191
+ const selections = doc ? selectionsAt(root, doc, target) : null;
1192
+ const build = doc && selections ? (entry) => buildEntry(doc, selections, entry, {
1193
+ links: editLinks(result, entry),
1194
+ lists: listKeysIn(result)
1195
+ }) : void 0;
1196
+ root = syncListAtPath(root, target, patch.entries, build);
1197
+ }
1198
+ }
1199
+ return root;
1200
+ }
1201
+ function readAtPath(root, path) {
1202
+ let node = root;
1203
+ for (const step of path) {
1204
+ if (node === null || typeof node !== "object") return void 0;
1205
+ node = node[step];
1206
+ }
1207
+ return node;
1208
+ }
1209
+ function isEnvelope(value) {
1210
+ if (Array.isArray(value) || !("data" in value)) return false;
1211
+ return Object.keys(value).every((key) => ENVELOPE_KEYS.has(key));
1212
+ }
1213
+ function toPathSegment(segment) {
1214
+ return INDEX_SEGMENT.test(segment) ? Number(segment) : segment;
1215
+ }
1216
+ function typenameOf(node) {
1217
+ const typename = node.__typename;
1218
+ return typeof typename === "string" ? typename : void 0;
1219
+ }
1220
+ function selectionsAt(root, doc, path) {
1221
+ let node = root;
1222
+ let selections = doc.operation;
1223
+ for (const step of path) {
1224
+ if (Array.isArray(node)) {
1225
+ node = node[step];
1226
+ continue;
1227
+ }
1228
+ if (node === null || typeof node !== "object") return null;
1229
+ const field = collectFields(selections, typenameOf(node), doc).get(
1230
+ String(step)
1231
+ );
1232
+ if (!field) return null;
1233
+ selections = field.selections;
1234
+ node = node[String(step)];
1235
+ }
1236
+ return selections;
1237
+ }
1238
+ function resolveTargets(root, doc, ownerPath, segments) {
1239
+ let owner = root;
1240
+ for (const step of ownerPath) {
1241
+ owner = owner[step];
1242
+ }
1243
+ const selections = selectionsAt(root, doc, ownerPath);
1244
+ if (!selections) return { root, targets: [], plain: /* @__PURE__ */ new Set() };
1245
+ let current = root;
1246
+ const out = [];
1247
+ const plain = /* @__PURE__ */ new Set();
1248
+ const walk2 = (node, sel, i, path) => {
1249
+ if (i === segments.length) {
1250
+ out.push(path);
1251
+ return;
1252
+ }
1253
+ const segment = segments[i];
1254
+ if (Array.isArray(node)) {
1255
+ if (INDEX_SEGMENT.test(segment)) {
1256
+ const position = Number(segment);
1257
+ if (position < node.length) {
1258
+ walk2(node[position], sel, i + 1, [...path, position]);
1259
+ }
1260
+ } else if (segment === "items") {
1261
+ walk2(node, sel, i + 1, path);
1262
+ }
1263
+ return;
1264
+ }
1265
+ if (node === null || typeof node !== "object") return;
1266
+ const record = node;
1267
+ const wanted = graphqlFieldName(segment);
1268
+ const textBody = i === segments.length - 1 && segment === "body" && isTextEntry(record) ? TEXT_BODY_FIELDS : null;
1269
+ let matched = false;
1270
+ for (const field of collectFields(sel, typenameOf(node), doc).values()) {
1271
+ const alias = textBody?.find((f) => f.name === field.name);
1272
+ if (field.name !== segment && field.name !== wanted && !alias) continue;
1273
+ if (!Object.prototype.hasOwnProperty.call(record, field.key)) continue;
1274
+ matched = true;
1275
+ const fieldPath = [...path, field.key];
1276
+ if (alias?.plain) plain.add(fieldPath);
1277
+ let value = record[field.key];
1278
+ const next = segments[i + 1];
1279
+ if (value === null && field.selections.length && next !== void 0 && next !== "items" && !INDEX_SEGMENT.test(next)) {
1280
+ const typename = resolveTypename(
1281
+ doc,
1282
+ field.selections,
1283
+ void 0,
1284
+ void 0
1285
+ );
1286
+ if (typename !== void 0) {
1287
+ value = fillObject(doc, field.selections, typename, {}, void 0, {
1288
+ links: null,
1289
+ lists: listKeysIn(root)
1290
+ });
1291
+ current = writeAtPath(current, fieldPath, value);
1292
+ }
1293
+ }
1294
+ walk2(value, field.selections, i + 1, fieldPath);
1295
+ }
1296
+ if (!matched && segment === "items") walk2(node, sel, i + 1, path);
1297
+ };
1298
+ walk2(owner, selections, 0, ownerPath);
1299
+ return { root: current, targets: out, plain };
1300
+ }
1301
+ var NON_ALPHANUMERIC = /[^a-z0-9]/gi;
1302
+ var typeKey = (name) => name.replace(NON_ALPHANUMERIC, "").toLowerCase();
1303
+ function resolveTypename(doc, selections, typename, typeName) {
1304
+ const known = typeConditions(selections, doc);
1305
+ const explicit = typeof typename === "string" ? typename : void 0;
1306
+ if (!known.length) return explicit ?? null;
1307
+ if (explicit && known.includes(explicit)) return explicit;
1308
+ for (const candidate of [explicit, typeName]) {
1309
+ if (typeof candidate !== "string" || !candidate) continue;
1310
+ const match = known.find((name) => typeKey(name) === typeKey(candidate));
1311
+ if (match) return match;
1312
+ }
1313
+ const named = explicit !== void 0 || typeof typeName === "string";
1314
+ return known.length === 1 && !named ? known[0] : void 0;
1315
+ }
1316
+ function buildEntry(doc, selections, entry, ctx) {
1317
+ const typename = resolveTypename(
1318
+ doc,
1319
+ selections,
1320
+ entry.__typename,
1321
+ entry.typeName
1322
+ );
1323
+ if (typename === void 0) return void 0;
1324
+ return fillObject(
1325
+ doc,
1326
+ selections,
1327
+ typename,
1328
+ entry.fields ?? {},
1329
+ entry._id,
1330
+ ctx
1331
+ );
1332
+ }
1333
+ function fillObject(doc, selections, typename, values, id, ctx) {
1334
+ const out = {};
1335
+ const { links } = ctx;
1336
+ const lists = ctx.lists(typename);
1337
+ const edit = isPlainRecord(values.__edit) ? values.__edit : null;
1338
+ const apiIdOf = /* @__PURE__ */ new Map();
1339
+ for (const key of Object.keys(values)) {
1340
+ apiIdOf.set(key, key);
1341
+ const name = graphqlFieldName(key);
1342
+ if (!apiIdOf.has(name)) apiIdOf.set(name, key);
1343
+ }
1344
+ if (edit && isPlainRecord(edit.apiIds)) {
1345
+ for (const [name, apiId] of Object.entries(edit.apiIds)) {
1346
+ if (typeof apiId === "string") apiIdOf.set(name, apiId);
1347
+ }
1348
+ }
1349
+ const valueOf = (name) => {
1350
+ if (Object.prototype.hasOwnProperty.call(values, name)) return values[name];
1351
+ const key = apiIdOf.get(name);
1352
+ return key !== void 0 && key in values ? values[key] : void 0;
1353
+ };
1354
+ const editField = (name) => {
1355
+ if (!edit) return null;
1356
+ if (typeof edit.field === "string")
1357
+ return name === "body" ? edit.field : null;
1358
+ if (typeof edit.path !== "string") return null;
1359
+ const apiId = apiIdOf.get(name) ?? name;
1360
+ const text = Array.isArray(edit.text) ? edit.text : [];
1361
+ if (!text.includes(apiId) && !text.includes(name)) return null;
1362
+ return `${edit.path}.items.${apiId}`;
1363
+ };
1364
+ const fields = collectFields(selections, typename ?? void 0, doc, {
1365
+ strict: true
1366
+ });
1367
+ for (const field of fields.values()) {
1368
+ if (field.name === "__typename") {
1369
+ out[field.key] = typename;
1370
+ } else if (field.name === "_id") {
1371
+ out[field.key] = typeof id === "string" ? id : values._id ?? null;
1372
+ } else if (field.selections.length) {
1373
+ const value = valueOf(field.name);
1374
+ out[field.key] = value == null && lists.has(field.key) ? [] : fillNested(doc, field.selections, value, ctx);
1375
+ } else {
1376
+ const value = valueOf(field.name);
1377
+ if (Array.isArray(value) && value.every(isScalar)) {
1378
+ out[field.key] = value;
1379
+ continue;
1380
+ }
1381
+ if (value == null && lists.has(field.key)) {
1382
+ out[field.key] = [];
1383
+ continue;
1384
+ }
1385
+ const scalar = value === void 0 || value !== null && typeof value === "object" ? null : value;
1386
+ const target = typeof scalar === "string" ? editField(field.name) : null;
1387
+ out[field.key] = target && links ? links.encode(scalar, target) : scalar;
1388
+ }
1389
+ }
1390
+ return out;
1391
+ }
1392
+ function fillNested(doc, selections, value, ctx) {
1393
+ const one = (item) => {
1394
+ if (!isPlainRecord(item)) return null;
1395
+ const typename = resolveTypename(
1396
+ doc,
1397
+ selections,
1398
+ item.__typename,
1399
+ item.typeName
1400
+ );
1401
+ if (typename === void 0) return null;
1402
+ return fillObject(doc, selections, typename, item, item._id, ctx);
1403
+ };
1404
+ if (Array.isArray(value)) return value.map(one).filter((v) => v !== null);
1405
+ return value === void 0 ? null : one(value);
1406
+ }
1407
+ var NO_KEYS = /* @__PURE__ */ new Set();
1408
+ var listKeysCache = /* @__PURE__ */ new WeakMap();
1409
+ function listKeysIn(result) {
1410
+ return (typename) => {
1411
+ if (!typename || result === null || typeof result !== "object") {
1412
+ return NO_KEYS;
1413
+ }
1414
+ let byType = listKeysCache.get(result);
1415
+ if (!byType) {
1416
+ byType = /* @__PURE__ */ new Map();
1417
+ const seen = /* @__PURE__ */ new WeakSet();
1418
+ const walk2 = (node) => {
1419
+ if (node === null || typeof node !== "object" || seen.has(node)) return;
1420
+ seen.add(node);
1421
+ if (Array.isArray(node)) {
1422
+ node.forEach(walk2);
1423
+ return;
1424
+ }
1425
+ const record = node;
1426
+ const type = typeof record.__typename === "string" ? record.__typename : null;
1427
+ for (const [key, value] of Object.entries(record)) {
1428
+ if (type && Array.isArray(value)) {
1429
+ let keys = byType.get(type);
1430
+ if (!keys) byType.set(type, keys = /* @__PURE__ */ new Set());
1431
+ keys.add(key);
1432
+ }
1433
+ walk2(value);
1434
+ }
1435
+ };
1436
+ walk2(result);
1437
+ listKeysCache.set(result, byType);
1438
+ }
1439
+ return byType.get(typename) ?? NO_KEYS;
1440
+ };
1441
+ }
1442
+
1443
+ // src/core/live-preview/live-request.ts
1444
+ var MAX_BODY_BYTES = 1e6;
1445
+ function requestOrigin(request) {
1446
+ const url = new URL(request.url);
1447
+ const proto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
1448
+ if (proto === "https" || proto === "http") url.protocol = `${proto}:`;
1449
+ return url.origin;
1450
+ }
1451
+ async function readLiveLogFromRequest(request) {
1452
+ try {
1453
+ if (request.method !== "POST") return [];
1454
+ if (request.headers.get(HEADER_LIVE_RENDER) !== "1") return [];
1455
+ const origin = request.headers.get("origin");
1456
+ if (!origin || origin !== requestOrigin(request)) return [];
1457
+ const type = request.headers.get("content-type") ?? "";
1458
+ if (!type.toLowerCase().startsWith("application/json")) return [];
1459
+ const length = Number(request.headers.get("content-length") ?? "0");
1460
+ if (length > MAX_BODY_BYTES) return [];
1461
+ const text = await request.clone().text();
1462
+ if (text.length > MAX_BODY_BYTES) return [];
1463
+ const body = JSON.parse(text);
1464
+ return parsePatchLog(body?.log);
1465
+ } catch {
1466
+ return [];
1467
+ }
1468
+ }
1469
+
1470
+ // src/core/live-preview/edit-links.ts
1471
+ var import_stega4 = require("@vercel/stega");
1472
+ var ENTRY_PARAM = "entry";
1473
+ var TOP_LEVEL_ENTRY = /^[A-Za-z0-9_]+\.\d+$/;
1474
+ function entryIdOf(element) {
1475
+ if (!isObject(element)) return void 0;
1476
+ if (typeof element._id === "string") return element._id;
1477
+ if (element.__typename !== "Assets" || !Array.isArray(element.items)) {
1478
+ return void 0;
1479
+ }
1480
+ const first = element.items[0];
1481
+ return isObject(first) && typeof first._id === "string" ? first._id : void 0;
1482
+ }
1483
+ function annotate(value, ctx) {
1484
+ if (!ctx.entryId) return value;
1485
+ const { cleaned, encoded } = (0, import_stega4.vercelStegaSplit)(value);
1486
+ if (!encoded) return value;
1487
+ let payload;
1488
+ try {
1489
+ payload = (0, import_stega4.vercelStegaDecode)(encoded);
1490
+ } catch {
1491
+ return value;
1492
+ }
1493
+ if (typeof payload?.href !== "string") return value;
1494
+ let url;
1495
+ try {
1496
+ url = new URL(payload.href);
1497
+ } catch {
1498
+ return value;
1499
+ }
1500
+ if (url.searchParams.has(ENTRY_PARAM)) return value;
1501
+ url.searchParams.set(ENTRY_PARAM, ctx.entryId);
1502
+ const itemId = decodeURIComponent(url.pathname.split("/").pop() ?? "");
1503
+ if (!url.searchParams.has("field") && ctx.entryField && TOP_LEVEL_ENTRY.test(ctx.entryField) && itemId === ctx.entryOwnerId) {
1504
+ url.searchParams.set("field", ctx.entryField);
1505
+ }
1506
+ return (0, import_stega4.vercelStegaCombine)(
1507
+ cleaned,
1508
+ { ...payload, href: url.toString() },
1509
+ false
1510
+ );
1511
+ }
1512
+ function walk(value, selections, ctx) {
1513
+ if (typeof value === "string") return annotate(value, ctx);
1514
+ if (Array.isArray(value)) {
1515
+ let changed2 = false;
1516
+ const next2 = value.map((element, index) => {
1517
+ const path = [...ctx.path, String(index)];
1518
+ const entryId = ctx.inAssets ? void 0 : entryIdOf(element);
1519
+ const entry = entryId ? {
1520
+ entryId,
1521
+ entryField: ctx.ownerId ? path.join(".") : void 0,
1522
+ entryOwnerId: ctx.ownerId,
1523
+ inAssets: isObject(element) && element._id === void 0
1524
+ } : {};
1525
+ const out = walk(element, selections, { ...ctx, ...entry, path });
1526
+ if (out !== element) changed2 = true;
1527
+ return out;
1528
+ });
1529
+ return changed2 ? next2 : value;
1530
+ }
1531
+ if (!isObject(value)) return value;
1532
+ const id = typeof value._id === "string" ? value._id : void 0;
1533
+ const typename = typeof value.__typename === "string" ? value.__typename : void 0;
1534
+ const fields = ctx.doc && selections ? collectFields(selections, typename, ctx.doc) : null;
1535
+ let changed = false;
1536
+ const next = {};
1537
+ for (const [key, child] of Object.entries(value)) {
1538
+ const field = fields?.get(key);
1539
+ const name = field?.name ?? key;
1540
+ const out = walk(child, field?.selections ?? null, {
1541
+ ...ctx,
1542
+ ownerId: id ?? ctx.ownerId,
1543
+ path: id ? [name] : [...ctx.path, name]
1544
+ });
1545
+ if (out !== child) changed = true;
1546
+ next[key] = out;
1547
+ }
1548
+ return changed ? next : value;
1549
+ }
1550
+ function annotateEditLinks(result, query, operationName) {
1551
+ let doc = null;
1552
+ if (query !== void 0) {
1553
+ try {
1554
+ doc = readQueryDocument(query, operationName);
1555
+ } catch {
1556
+ doc = null;
1557
+ }
1558
+ }
1559
+ return walk(result, doc?.operation ?? null, { doc, path: [] });
1560
+ }
1561
+
1562
+ // src/core/server.ts
1563
+ var PreprError = class extends Error {
1564
+ constructor(message, code, context, originalError) {
1565
+ super(message);
1566
+ this.code = code;
1567
+ this.context = context;
1568
+ this.originalError = originalError;
1569
+ this.name = "PreprError";
1570
+ }
1571
+ };
1572
+ function getPreprUUIDFromHeaders(headers) {
1573
+ return headers.get("prepr-customer-id");
1574
+ }
1575
+ function getActiveSegmentFromHeaders(headers) {
1576
+ return headers.get("Prepr-Segments");
1577
+ }
1578
+ function getActiveVariantFromHeaders(headers) {
1579
+ return headers.get("Prepr-ABtesting");
1580
+ }
1581
+ var PREPR_HEADER_KEYS = [
1582
+ "prepr-customer-id",
1583
+ "Prepr-Segments",
1584
+ "Prepr-ABtesting",
1585
+ "Prepr-Preview-Bar",
1586
+ "Prepr-Context-utm_source",
1587
+ "Prepr-Context-utm_medium",
1588
+ "Prepr-Context-utm_term",
1589
+ "Prepr-Context-utm_content",
1590
+ "Prepr-Context-utm_campaign",
1591
+ "Prepr-Context-initial_referral",
1592
+ "Prepr-Visitor-IP",
1593
+ "Prepr-Hubspot-Id",
1594
+ "Prepr-Customer-Id-Created",
1595
+ "User-Agent",
1596
+ "Prepr-Package"
1597
+ ];
1598
+ function getPreprHeadersFromHeaders(headers) {
1599
+ const preprHeaders = {};
1600
+ const copy = (key) => {
1601
+ const value = headers.get(key);
1602
+ if (value !== null) {
1603
+ preprHeaders[key] = value;
1604
+ }
1605
+ };
1606
+ for (const key of PREPR_HEADER_KEYS) {
1607
+ copy(key);
1608
+ }
1609
+ return preprHeaders;
1610
+ }
1611
+ function validatePreprToken(token) {
1612
+ if (!token) {
1613
+ throw new PreprError(
1614
+ "Token is required",
1615
+ "MISSING_TOKEN",
1616
+ "validatePreprToken"
1617
+ );
1618
+ }
1619
+ if (!token.startsWith("https://")) {
1620
+ throw new PreprError(
1621
+ "Token must be a valid HTTPS URL",
1622
+ "INVALID_TOKEN",
1623
+ "validatePreprToken"
1624
+ );
1625
+ }
1626
+ }
1627
+ function extractAccessToken(graphqlUrl) {
1628
+ let url;
1629
+ try {
1630
+ url = new URL(graphqlUrl);
1631
+ } catch (error) {
1632
+ throw new PreprError(
1633
+ "Token must be a valid URL",
1634
+ "INVALID_TOKEN",
1635
+ "extractAccessToken",
1636
+ error instanceof Error ? error : new Error(String(error))
1637
+ );
1638
+ }
1639
+ if (url.hostname !== "graphql.prepr.io") {
1640
+ throw new PreprError(
1641
+ "Token must be a graphql.prepr.io URL",
1642
+ "INVALID_TOKEN",
1643
+ "extractAccessToken"
1644
+ );
1645
+ }
1646
+ const pathParts = url.pathname.split("/");
1647
+ const token = pathParts[pathParts.length - 1];
1648
+ if (!token) {
1649
+ throw new PreprError(
1650
+ "Token URL is missing an access token segment",
1651
+ "INVALID_TOKEN",
1652
+ "extractAccessToken"
1653
+ );
1654
+ }
1655
+ return token;
1656
+ }
1657
+ async function getPreprEnvironmentSegments(token) {
1658
+ validatePreprToken(token);
1659
+ try {
1660
+ const response = await fetch(token, {
1661
+ headers: {
1662
+ "Prepr-Package": `@preprio/toolkit@${VERSION}`,
1663
+ // Duplicates the version in Prepr-Package. It keeps the User-Agent
1664
+ // format used by `@preprio/prepr-nextjs`, for Prepr API consumers that
1665
+ // still identify the toolbar by that string.
1666
+ "User-Agent": `Prepr-Preview-Bar/${VERSION}`,
1667
+ "Content-Type": "application/json"
1668
+ },
1669
+ method: "POST",
1670
+ body: JSON.stringify({
1671
+ query: `{
1672
+ _Segments {
1673
+ _id
1674
+ name
1675
+ }
1676
+ }`
1677
+ })
1678
+ });
1679
+ if (!response.ok) {
1680
+ throw new PreprError(
1681
+ `HTTP ${response.status}: ${response.statusText}`,
1682
+ "HTTP_ERROR",
1683
+ "getPreprEnvironmentSegments"
1684
+ );
1685
+ }
1686
+ const json = await response.json();
1687
+ if (!json || !json.data || !json.data._Segments) {
1688
+ throw new PreprError(
1689
+ "Invalid response format from Prepr API",
1690
+ "INVALID_RESPONSE",
1691
+ "getPreprEnvironmentSegments"
1692
+ );
1693
+ }
1694
+ return json.data._Segments;
1695
+ } catch (error) {
1696
+ if (error instanceof PreprError) {
1697
+ throw error;
1698
+ }
1699
+ throw new PreprError(
1700
+ "Failed to fetch segments from Prepr API",
1701
+ "FETCH_ERROR",
1702
+ "getPreprEnvironmentSegments",
1703
+ error instanceof Error ? error : new Error(String(error))
1704
+ );
1705
+ }
1706
+ }
1707
+ async function getToolbarPropsFromHeaders(headers, token, features) {
1708
+ const resolved = resolveFeatures(features);
1709
+ let segments = [];
1710
+ if (resolved.segments) {
1711
+ try {
1712
+ segments = await getPreprEnvironmentSegments(token);
1713
+ } catch {
1714
+ segments = [];
1715
+ }
1716
+ }
1717
+ return {
1718
+ activeSegment: resolved.segments ? getActiveSegmentFromHeaders(headers) : null,
1719
+ activeVariant: resolved.abTesting ? getActiveVariantFromHeaders(headers) : null,
1720
+ segments,
1721
+ data: segments
1722
+ };
1723
+ }
1724
+
1725
+ // src/core/request-helpers.ts
1726
+ function getPreprUUID(headers) {
1727
+ return getPreprUUIDFromHeaders(headers);
1728
+ }
1729
+ function getActiveSegment(headers) {
1730
+ return getActiveSegmentFromHeaders(headers);
1731
+ }
1732
+ function getActiveVariant(headers) {
1733
+ return getActiveVariantFromHeaders(headers);
1734
+ }
1735
+ function getPreprHeaders(headers) {
1736
+ return getPreprHeadersFromHeaders(headers);
1737
+ }
1738
+ async function getToolbarProps(headers, token, features) {
1739
+ return getToolbarPropsFromHeaders(headers, token, features);
1740
+ }
1741
+
1742
+ // src/astro/index.ts
1743
+ var LIVE_LOG = /* @__PURE__ */ Symbol.for("@preprio/toolkit/astro-live-log");
1744
+ async function onPreprRequest(context, next, options) {
1745
+ const { requestHeaders, responseCookies } = processFrameworkRequest(
1746
+ context.request,
1747
+ options,
1748
+ "astro"
1749
+ );
1750
+ requestHeaders.forEach((value, key) => {
1751
+ context.request.headers.set(key, value);
1752
+ });
1753
+ const log = options?.preview && context.locals ? await readLiveLogFromRequest(context.request) : [];
1754
+ if (log.length && context.locals) {
1755
+ context.locals[LIVE_LOG] = log;
1756
+ }
1757
+ const response = await next();
1758
+ if (log.length) {
1759
+ response.headers.set("Cache-Control", "private, no-store");
1760
+ }
1761
+ for (const cookie of responseCookies) {
1762
+ response.headers.append("Set-Cookie", serializeCookie(cookie));
1763
+ }
1764
+ return response;
1765
+ }
1766
+ function normalizeQuery2(query, result, options = {}) {
1767
+ if (!options.enabled) return result;
1768
+ const annotated = annotateEditLinks(result, query, options.operationName);
1769
+ const log = options.locals?.[LIVE_LOG];
1770
+ if (!log?.length) return annotated;
1771
+ return normalizeQuery(query, annotated, {
1772
+ log,
1773
+ operationName: options.operationName
1774
+ });
405
1775
  }
406
1776
  // Annotate the CommonJS export names for ESM import in node:
407
1777
  0 && (module.exports = {
1778
+ PreprError,
1779
+ extractAccessToken,
408
1780
  getActiveSegment,
409
1781
  getActiveVariant,
410
1782
  getPreprHeaders,
411
1783
  getPreprUUID,
412
1784
  getToolbarProps,
413
- isPersonalizedResponse,
414
- onPreprRequest
1785
+ normalizeQuery,
1786
+ onPreprRequest,
1787
+ validatePreprToken
415
1788
  });