@preprio/toolkit 0.5.0-rc.2 → 0.6.0-alpha.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 (78) hide show
  1. package/README.md +415 -27
  2. package/dist/astro/chunk-O7N6GPAH.js +173 -0
  3. package/dist/astro/graphql.cjs +1030 -0
  4. package/dist/astro/graphql.d.cts +305 -0
  5. package/dist/astro/graphql.d.ts +305 -0
  6. package/dist/astro/graphql.js +936 -0
  7. package/dist/astro/index-XT_z-RYT.d.cts +130 -0
  8. package/dist/astro/index-XT_z-RYT.d.ts +130 -0
  9. package/dist/astro/index.cjs +14 -1
  10. package/dist/astro/index.d.cts +1 -120
  11. package/dist/astro/index.d.ts +1 -120
  12. package/dist/astro/index.js +15 -153
  13. package/dist/chunk-3JLWZQ37.js +179 -0
  14. package/dist/chunk-3NCEVJJ3.js +10 -0
  15. package/dist/chunk-S5RWVMDJ.js +148 -0
  16. package/dist/chunk-TBKSBXGH.js +452 -0
  17. package/dist/{chunk-FLPNN3CV.js → chunk-VI6QZTBM.js} +73 -276
  18. package/dist/chunk-YWIKKWBR.js +26 -0
  19. package/dist/graphql/codegen.cjs +510 -0
  20. package/dist/graphql/codegen.d.cts +23 -0
  21. package/dist/graphql/codegen.d.ts +23 -0
  22. package/dist/graphql/codegen.js +99 -0
  23. package/dist/graphql.cjs +941 -0
  24. package/dist/graphql.d.cts +305 -0
  25. package/dist/graphql.d.ts +305 -0
  26. package/dist/graphql.js +419 -0
  27. package/dist/index.cjs +76 -119
  28. package/dist/index.d.cts +12 -64
  29. package/dist/index.d.ts +12 -64
  30. package/dist/index.js +27 -167
  31. package/dist/nextjs/chunk-BQ6IGSH6.js +231 -0
  32. package/dist/nextjs/components.cjs +190 -122
  33. package/dist/nextjs/components.d.cts +33 -2
  34. package/dist/nextjs/components.d.ts +33 -2
  35. package/dist/nextjs/components.js +133 -4
  36. package/dist/nextjs/graphql.cjs +1362 -0
  37. package/dist/nextjs/graphql.d.cts +435 -0
  38. package/dist/nextjs/graphql.d.ts +435 -0
  39. package/dist/nextjs/graphql.js +1261 -0
  40. package/dist/nextjs/index.cjs +126 -6
  41. package/dist/nextjs/index.d.cts +53 -147
  42. package/dist/nextjs/index.d.ts +53 -147
  43. package/dist/nextjs/index.js +113 -203
  44. package/dist/nextjs/server-CjpELYvq.d.cts +156 -0
  45. package/dist/nextjs/server-CjpELYvq.d.ts +156 -0
  46. package/dist/nuxt/chunk-IQDSBPDN.js +417 -0
  47. package/dist/nuxt/graphql.cjs +1037 -0
  48. package/dist/nuxt/graphql.d.cts +302 -0
  49. package/dist/nuxt/graphql.d.ts +302 -0
  50. package/dist/nuxt/graphql.js +937 -0
  51. package/dist/nuxt/index.cjs +14 -1
  52. package/dist/nuxt/index.d.cts +3 -148
  53. package/dist/nuxt/index.d.ts +3 -148
  54. package/dist/nuxt/index.js +15 -391
  55. package/dist/nuxt/server-8v6OHbsw.d.cts +158 -0
  56. package/dist/nuxt/server-8v6OHbsw.d.ts +158 -0
  57. package/dist/pixel-DwW7cXJm.d.cts +49 -0
  58. package/dist/pixel-DwW7cXJm.d.ts +49 -0
  59. package/dist/react/components.cjs +88 -120
  60. package/dist/react/components.d.cts +2 -8
  61. package/dist/react/components.d.ts +2 -8
  62. package/dist/react/components.js +88 -120
  63. package/dist/server-Brr1UgtW.d.ts +59 -0
  64. package/dist/server-DJuS3YU0.d.cts +59 -0
  65. package/dist/sveltekit/chunk-OKYZ6HPH.js +413 -0
  66. package/dist/sveltekit/graphql.cjs +1043 -0
  67. package/dist/sveltekit/graphql.d.cts +307 -0
  68. package/dist/sveltekit/graphql.d.ts +307 -0
  69. package/dist/sveltekit/graphql.js +943 -0
  70. package/dist/sveltekit/index.cjs +14 -1
  71. package/dist/sveltekit/index.d.cts +3 -88
  72. package/dist/sveltekit/index.d.ts +3 -88
  73. package/dist/sveltekit/index.js +15 -387
  74. package/dist/sveltekit/server-CO847mEV.d.cts +98 -0
  75. package/dist/sveltekit/server-CO847mEV.d.ts +98 -0
  76. package/dist/{pixel-B3oQNbZ3.d.cts → types-BYH9XqmN.d.cts} +4 -58
  77. package/dist/{pixel-B3oQNbZ3.d.ts → types-BYH9XqmN.d.ts} +4 -58
  78. package/package.json +36 -1
@@ -0,0 +1,413 @@
1
+ // src/version.ts
2
+ var VERSION = "0.6.0-alpha.1";
3
+
4
+ // src/core/constants.ts
5
+ var COOKIE_PREVIEW_MODE = "Prepr-Preview-Mode";
6
+ var COOKIE_SEGMENT = "Prepr-Segments";
7
+ var COOKIE_VARIANT = "Prepr-ABtesting";
8
+ var COOKIE_UID = "__prepr_uid";
9
+ var COOKIE_HUBSPOT = "hubspotutk";
10
+ var PARAM_SEGMENT = "prepr_preview_segment";
11
+ var PARAM_VARIANT = "prepr_preview_ab";
12
+ var PARAM_HIDE_BAR = "prepr_hide_bar";
13
+ var ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;
14
+
15
+ // src/core/features.ts
16
+ function isEnabled(config) {
17
+ if (typeof config === "boolean") return config;
18
+ return config?.enabled ?? true;
19
+ }
20
+ function resolveFeatures(features) {
21
+ return {
22
+ segments: isEnabled(features?.segments),
23
+ abTesting: isEnabled(features?.abTesting),
24
+ editMode: isEnabled(features?.editMode)
25
+ };
26
+ }
27
+ var ALL_FEATURES_ENABLED = Object.freeze({
28
+ segments: true,
29
+ abTesting: true,
30
+ editMode: true
31
+ });
32
+
33
+ // src/core/middleware.ts
34
+ var UTM_PARAMS = [
35
+ "utm_source",
36
+ "utm_medium",
37
+ "utm_term",
38
+ "utm_content",
39
+ "utm_campaign"
40
+ ];
41
+ var MAX_HEADER_VALUE_LENGTH = 2048;
42
+ function sanitizeHeaderValue(value) {
43
+ const stripped = value.replace(/[\u0000-\u001f\u007f]/g, "");
44
+ return stripped.length > MAX_HEADER_VALUE_LENGTH ? stripped.slice(0, MAX_HEADER_VALUE_LENGTH) : stripped;
45
+ }
46
+ function serializeCookie(cookie) {
47
+ const parts = [
48
+ `${cookie.name}=${encodeURIComponent(cookie.value)}`,
49
+ `Max-Age=${cookie.maxAge}`,
50
+ `Path=${cookie.path}`
51
+ ];
52
+ if (cookie.sameSite) {
53
+ parts.push(`SameSite=${cookie.sameSite}`);
54
+ }
55
+ if (cookie.secure) {
56
+ parts.push("Secure");
57
+ }
58
+ return parts.join("; ");
59
+ }
60
+ function parseCookies(request) {
61
+ const cookies = /* @__PURE__ */ new Map();
62
+ const header = request.headers.get("cookie");
63
+ if (!header) return cookies;
64
+ for (const part of header.split(";")) {
65
+ const eq = part.indexOf("=");
66
+ if (eq === -1) continue;
67
+ const name = part.slice(0, eq).trim();
68
+ const value = part.slice(eq + 1).trim();
69
+ if (!name) continue;
70
+ try {
71
+ cookies.set(name, decodeURIComponent(value));
72
+ } catch {
73
+ cookies.set(name, value);
74
+ }
75
+ }
76
+ return cookies;
77
+ }
78
+ function processFrameworkRequest(request, opts, framework) {
79
+ const requestHeaders = new Headers(request.headers);
80
+ const responseCookies = [];
81
+ const inboundPreprHeaders = [];
82
+ requestHeaders.forEach((_value, key) => {
83
+ if (key.toLowerCase().startsWith("prepr-")) {
84
+ inboundPreprHeaders.push(key);
85
+ }
86
+ });
87
+ for (const key of inboundPreprHeaders) {
88
+ requestHeaders.delete(key);
89
+ }
90
+ const requestCookies = parseCookies(request);
91
+ const url = new URL(request.url);
92
+ const searchParams = url.searchParams;
93
+ const forwardedProto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
94
+ const isSecure = forwardedProto ? forwardedProto === "https" : url.protocol === "https:";
95
+ const crossSite = isSecure ? { sameSite: "None", secure: true } : {};
96
+ for (const key of UTM_PARAMS) {
97
+ const value = searchParams.get(key);
98
+ if (value !== null) {
99
+ requestHeaders.set(`Prepr-Context-${key}`, sanitizeHeaderValue(value));
100
+ }
101
+ }
102
+ const referer = request.headers.get("referer");
103
+ if (referer) {
104
+ requestHeaders.set(
105
+ "Prepr-Context-initial_referral",
106
+ sanitizeHeaderValue(referer)
107
+ );
108
+ }
109
+ const userAgent = request.headers.get("user-agent");
110
+ if (userAgent) {
111
+ requestHeaders.set("User-Agent", sanitizeHeaderValue(userAgent));
112
+ }
113
+ const packageParts = [`@preprio/toolkit@${opts?.version ?? VERSION}`];
114
+ if (framework) packageParts.push(`framework=${framework}`);
115
+ packageParts.push(`preview=${opts?.preview ? "true" : "false"}`);
116
+ requestHeaders.set("Prepr-Package", packageParts.join("; "));
117
+ const ip = request.headers.get("Cf-Connecting-Ip") ?? request.headers.get("x-real-ip");
118
+ if (ip) {
119
+ requestHeaders.set("Prepr-Visitor-IP", sanitizeHeaderValue(ip));
120
+ }
121
+ const hutkCookie = requestCookies.get(COOKIE_HUBSPOT);
122
+ if (hutkCookie) {
123
+ requestHeaders.set("Prepr-Hubspot-Id", sanitizeHeaderValue(hutkCookie));
124
+ }
125
+ let uid = sanitizeHeaderValue(requestCookies.get(COOKIE_UID) ?? "");
126
+ if (!uid) {
127
+ uid = crypto.randomUUID();
128
+ responseCookies.push({
129
+ name: COOKIE_UID,
130
+ value: uid,
131
+ maxAge: ONE_YEAR_SECONDS,
132
+ path: "/"
133
+ });
134
+ requestHeaders.set("Prepr-Customer-Id-Created", "true");
135
+ }
136
+ requestHeaders.set("Prepr-Customer-Id", uid);
137
+ if (!opts?.preview) {
138
+ return { requestHeaders, responseCookies };
139
+ }
140
+ const features = resolveFeatures(opts?.features);
141
+ const hasPreviewParams = features.segments && searchParams.has(PARAM_SEGMENT) || features.abTesting && searchParams.has(PARAM_VARIANT);
142
+ if (!hasPreviewParams) {
143
+ const previewModeCookie = requestCookies.get(COOKIE_PREVIEW_MODE);
144
+ const previewModeEnabled = previewModeCookie !== "false";
145
+ if (!previewModeEnabled) {
146
+ return { requestHeaders, responseCookies };
147
+ }
148
+ }
149
+ requestHeaders.set("Prepr-Preview-Bar", "true");
150
+ const isLivePreview = searchParams.get(PARAM_HIDE_BAR) === "true";
151
+ if (!isLivePreview && !requestCookies.has(COOKIE_PREVIEW_MODE)) {
152
+ responseCookies.push({
153
+ name: COOKIE_PREVIEW_MODE,
154
+ value: "true",
155
+ maxAge: ONE_YEAR_SECONDS,
156
+ path: "/",
157
+ ...crossSite
158
+ });
159
+ }
160
+ if (!isLivePreview) {
161
+ const segmentCookie = features.segments ? requestCookies.get(COOKIE_SEGMENT) : void 0;
162
+ if (segmentCookie) {
163
+ requestHeaders.set("Prepr-Segments", sanitizeHeaderValue(segmentCookie));
164
+ }
165
+ const abCookie = features.abTesting ? requestCookies.get(COOKIE_VARIANT) : void 0;
166
+ if (abCookie) {
167
+ requestHeaders.set("Prepr-ABtesting", sanitizeHeaderValue(abCookie));
168
+ }
169
+ }
170
+ const previewAb = features.abTesting ? searchParams.get(PARAM_VARIANT) : null;
171
+ if (previewAb !== null) {
172
+ requestHeaders.set("Prepr-ABtesting", sanitizeHeaderValue(previewAb));
173
+ if (!isLivePreview) {
174
+ responseCookies.push({
175
+ name: COOKIE_VARIANT,
176
+ value: previewAb,
177
+ maxAge: ONE_YEAR_SECONDS,
178
+ path: "/",
179
+ ...crossSite
180
+ });
181
+ }
182
+ }
183
+ const previewSegment = features.segments ? searchParams.get(PARAM_SEGMENT) : null;
184
+ if (previewSegment !== null) {
185
+ requestHeaders.set("Prepr-Segments", sanitizeHeaderValue(previewSegment));
186
+ if (!isLivePreview) {
187
+ responseCookies.push({
188
+ name: COOKIE_SEGMENT,
189
+ value: previewSegment,
190
+ maxAge: ONE_YEAR_SECONDS,
191
+ path: "/",
192
+ ...crossSite
193
+ });
194
+ }
195
+ }
196
+ if (requestHeaders.has("Prepr-Segments")) {
197
+ requestHeaders.delete("Prepr-Customer-Id");
198
+ requestHeaders.delete("Prepr-Customer-Id-Created");
199
+ }
200
+ return { requestHeaders, responseCookies };
201
+ }
202
+
203
+ // src/sveltekit/hooks.ts
204
+ var PREPR_LOCALS_KEY = "prepr";
205
+ function preprHandle(options) {
206
+ return async ({ event, resolve }) => {
207
+ const { requestHeaders, responseCookies } = processFrameworkRequest(
208
+ event.request,
209
+ options,
210
+ "sveltekit"
211
+ );
212
+ requestHeaders.forEach((value, key) => {
213
+ event.request.headers.set(key, value);
214
+ });
215
+ if (event.locals) {
216
+ event.locals[PREPR_LOCALS_KEY] = requestHeaders;
217
+ }
218
+ const response = await resolve(event);
219
+ for (const cookie of responseCookies) {
220
+ response.headers.append("Set-Cookie", serializeCookie(cookie));
221
+ }
222
+ return response;
223
+ };
224
+ }
225
+ function getPreprHeadersFromLocals(locals) {
226
+ const headers = locals[PREPR_LOCALS_KEY];
227
+ return headers instanceof Headers ? headers : new Headers();
228
+ }
229
+
230
+ // src/core/server.ts
231
+ var PreprError = class extends Error {
232
+ constructor(message, code, context, originalError) {
233
+ super(message);
234
+ this.code = code;
235
+ this.context = context;
236
+ this.originalError = originalError;
237
+ this.name = "PreprError";
238
+ }
239
+ };
240
+ function getPreprUUIDFromHeaders(headers) {
241
+ return headers.get("prepr-customer-id");
242
+ }
243
+ function getActiveSegmentFromHeaders(headers) {
244
+ return headers.get("Prepr-Segments");
245
+ }
246
+ function getActiveVariantFromHeaders(headers) {
247
+ return headers.get("Prepr-ABtesting");
248
+ }
249
+ var PREPR_HEADER_KEYS = [
250
+ "prepr-customer-id",
251
+ "Prepr-Segments",
252
+ "Prepr-ABtesting",
253
+ "Prepr-Preview-Bar",
254
+ "Prepr-Context-utm_source",
255
+ "Prepr-Context-utm_medium",
256
+ "Prepr-Context-utm_term",
257
+ "Prepr-Context-utm_content",
258
+ "Prepr-Context-utm_campaign",
259
+ "Prepr-Context-initial_referral",
260
+ "Prepr-Visitor-IP",
261
+ "Prepr-Hubspot-Id",
262
+ "Prepr-Customer-Id-Created",
263
+ "User-Agent",
264
+ "Prepr-Package"
265
+ ];
266
+ function getPreprHeadersFromHeaders(headers) {
267
+ const preprHeaders = {};
268
+ const copy = (key) => {
269
+ const value = headers.get(key);
270
+ if (value !== null) {
271
+ preprHeaders[key] = value;
272
+ }
273
+ };
274
+ for (const key of PREPR_HEADER_KEYS) {
275
+ copy(key);
276
+ }
277
+ return preprHeaders;
278
+ }
279
+ function validatePreprToken(token) {
280
+ if (!token) {
281
+ throw new PreprError(
282
+ "Token is required",
283
+ "MISSING_TOKEN",
284
+ "validatePreprToken"
285
+ );
286
+ }
287
+ if (!token.startsWith("https://")) {
288
+ throw new PreprError(
289
+ "Token must be a valid HTTPS URL",
290
+ "INVALID_TOKEN",
291
+ "validatePreprToken"
292
+ );
293
+ }
294
+ }
295
+ function extractAccessToken(graphqlUrl) {
296
+ let url;
297
+ try {
298
+ url = new URL(graphqlUrl);
299
+ } catch (error) {
300
+ throw new PreprError(
301
+ "Token must be a valid URL",
302
+ "INVALID_TOKEN",
303
+ "extractAccessToken",
304
+ error instanceof Error ? error : new Error(String(error))
305
+ );
306
+ }
307
+ if (url.hostname !== "graphql.prepr.io") {
308
+ throw new PreprError(
309
+ "Token must be a graphql.prepr.io URL",
310
+ "INVALID_TOKEN",
311
+ "extractAccessToken"
312
+ );
313
+ }
314
+ const pathParts = url.pathname.split("/");
315
+ const token = pathParts[pathParts.length - 1];
316
+ if (!token) {
317
+ throw new PreprError(
318
+ "Token URL is missing an access token segment",
319
+ "INVALID_TOKEN",
320
+ "extractAccessToken"
321
+ );
322
+ }
323
+ return token;
324
+ }
325
+ async function getPreprEnvironmentSegments(token) {
326
+ validatePreprToken(token);
327
+ try {
328
+ const response = await fetch(token, {
329
+ headers: {
330
+ "Prepr-Package": `@preprio/toolkit@${VERSION}`,
331
+ // Duplicates the version in Prepr-Package. It keeps the User-Agent
332
+ // format used by `@preprio/prepr-nextjs`, for Prepr API consumers that
333
+ // still identify the toolbar by that string.
334
+ "User-Agent": `Prepr-Preview-Bar/${VERSION}`,
335
+ "Content-Type": "application/json"
336
+ },
337
+ method: "POST",
338
+ body: JSON.stringify({
339
+ query: `{
340
+ _Segments {
341
+ _id
342
+ name
343
+ }
344
+ }`
345
+ })
346
+ });
347
+ if (!response.ok) {
348
+ throw new PreprError(
349
+ `HTTP ${response.status}: ${response.statusText}`,
350
+ "HTTP_ERROR",
351
+ "getPreprEnvironmentSegments"
352
+ );
353
+ }
354
+ const json = await response.json();
355
+ if (!json || !json.data || !json.data._Segments) {
356
+ throw new PreprError(
357
+ "Invalid response format from Prepr API",
358
+ "INVALID_RESPONSE",
359
+ "getPreprEnvironmentSegments"
360
+ );
361
+ }
362
+ return json.data._Segments;
363
+ } catch (error) {
364
+ if (error instanceof PreprError) {
365
+ throw error;
366
+ }
367
+ throw new PreprError(
368
+ "Failed to fetch segments from Prepr API",
369
+ "FETCH_ERROR",
370
+ "getPreprEnvironmentSegments",
371
+ error instanceof Error ? error : new Error(String(error))
372
+ );
373
+ }
374
+ }
375
+ async function getToolbarPropsFromHeaders(headers, token, features) {
376
+ const resolved = resolveFeatures(features);
377
+ let segments = [];
378
+ if (resolved.segments) {
379
+ try {
380
+ segments = await getPreprEnvironmentSegments(token);
381
+ } catch {
382
+ segments = [];
383
+ }
384
+ }
385
+ return {
386
+ activeSegment: resolved.segments ? getActiveSegmentFromHeaders(headers) : null,
387
+ activeVariant: resolved.abTesting ? getActiveVariantFromHeaders(headers) : null,
388
+ segments,
389
+ data: segments
390
+ };
391
+ }
392
+
393
+ // src/core/personalization.ts
394
+ var PERSONALIZED_VARY = /\bPrepr-(Segments|ABTesting)/i;
395
+ function isPersonalizedResponse(source) {
396
+ const headers = "headers" in source ? source.headers : source;
397
+ return PERSONALIZED_VARY.test(headers.get("vary") ?? "");
398
+ }
399
+
400
+ export {
401
+ PREPR_LOCALS_KEY,
402
+ preprHandle,
403
+ getPreprHeadersFromLocals,
404
+ PreprError,
405
+ getPreprUUIDFromHeaders,
406
+ getActiveSegmentFromHeaders,
407
+ getActiveVariantFromHeaders,
408
+ getPreprHeadersFromHeaders,
409
+ validatePreprToken,
410
+ extractAccessToken,
411
+ getToolbarPropsFromHeaders,
412
+ isPersonalizedResponse
413
+ };