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