@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
@@ -29,13 +29,14 @@ __export(sveltekit_exports, {
29
29
  getPreprHeadersFromLocals: () => getPreprHeadersFromLocals,
30
30
  getPreprUUID: () => getPreprUUID,
31
31
  getToolbarProps: () => getToolbarProps,
32
+ isPersonalizedResponse: () => isPersonalizedResponse,
32
33
  preprHandle: () => preprHandle,
33
34
  validatePreprToken: () => validatePreprToken
34
35
  });
35
36
  module.exports = __toCommonJS(sveltekit_exports);
36
37
 
37
38
  // src/version.ts
38
- var VERSION = "0.5.0-rc.2";
39
+ var VERSION = "0.6.0-alpha.1";
39
40
 
40
41
  // src/core/constants.ts
41
42
  var COOKIE_PREVIEW_MODE = "Prepr-Preview-Mode";
@@ -229,6 +230,10 @@ function processFrameworkRequest(request, opts, framework) {
229
230
  });
230
231
  }
231
232
  }
233
+ if (requestHeaders.has("Prepr-Segments")) {
234
+ requestHeaders.delete("Prepr-Customer-Id");
235
+ requestHeaders.delete("Prepr-Customer-Id-Created");
236
+ }
232
237
  return { requestHeaders, responseCookies };
233
238
  }
234
239
 
@@ -438,6 +443,13 @@ function getPreprHeaders(headers) {
438
443
  async function getToolbarProps(headers, token, features) {
439
444
  return getToolbarPropsFromHeaders(headers, token, features);
440
445
  }
446
+
447
+ // src/core/personalization.ts
448
+ var PERSONALIZED_VARY = /\bPrepr-(Segments|ABTesting)/i;
449
+ function isPersonalizedResponse(source) {
450
+ const headers = "headers" in source ? source.headers : source;
451
+ return PERSONALIZED_VARY.test(headers.get("vary") ?? "");
452
+ }
441
453
  // Annotate the CommonJS export names for ESM import in node:
442
454
  0 && (module.exports = {
443
455
  PREPR_LOCALS_KEY,
@@ -449,6 +461,7 @@ async function getToolbarProps(headers, token, features) {
449
461
  getPreprHeadersFromLocals,
450
462
  getPreprUUID,
451
463
  getToolbarProps,
464
+ isPersonalizedResponse,
452
465
  preprHandle,
453
466
  validatePreprToken
454
467
  });
@@ -1,71 +1,5 @@
1
- interface PreprSegment {
2
- readonly _id: string;
3
- readonly name: string;
4
- }
5
- /**
6
- * Per-feature config. `false` is shorthand for `{ enabled: false }`; the object
7
- * form leaves room for per-feature options later without a breaking change.
8
- */
9
- type PreprFeatureConfig = boolean | {
10
- enabled?: boolean;
11
- };
12
- /** Toolkit features a consumer can turn off. Omitted keys stay enabled. */
13
- interface PreprFeatures {
14
- /** Segment picker, `Prepr-Segments` header and its cookie/query param. */
15
- segments?: PreprFeatureConfig;
16
- /** A/B variant switch, `Prepr-ABtesting` header and its cookie/query param. */
17
- abTesting?: PreprFeatureConfig;
18
- /**
19
- * The site's own click-to-edit: the toolbar's Edit mode control, the stega
20
- * tooltip/overlay and the close-edit pill.
21
- *
22
- * NOT a security control, and NOT the Prepr editor's live preview. When the
23
- * site is framed by the editor, `prepr:initVE` still activates edit mode —
24
- * that is the CMS operating inside its own iframe, not an affordance offered
25
- * to visitors. See iframe-bridge.ts.
26
- */
27
- editMode?: PreprFeatureConfig;
28
- }
29
- interface PreprToolbarProps {
30
- /**
31
- * Server-resolved active segment. Optional: omit it with `segments`
32
- * disabled, where there is nothing to resolve. When enabled and omitted,
33
- * the persisted cookie is used.
34
- */
35
- readonly activeSegment?: string | null;
36
- /**
37
- * Server-resolved active A/B variant. Optional: omit it with `abTesting`
38
- * disabled, where there is nothing to resolve. When enabled and omitted,
39
- * the persisted cookie is used.
40
- */
41
- readonly activeVariant?: string | null;
42
- /** Available segments to personalize on. */
43
- readonly segments?: readonly PreprSegment[];
44
- /** @deprecated Alias for `segments`. */
45
- readonly data?: readonly PreprSegment[];
46
- }
47
- type PreprVariant = 'A' | 'B';
48
- interface PreprHeaders {
49
- readonly 'prepr-customer-id'?: string;
50
- readonly 'Prepr-Segments'?: string;
51
- readonly 'Prepr-ABtesting'?: PreprVariant;
52
- readonly 'Prepr-Preview-Bar'?: 'true';
53
- readonly 'Prepr-Context-utm_source'?: string;
54
- readonly 'Prepr-Context-utm_medium'?: string;
55
- readonly 'Prepr-Context-utm_term'?: string;
56
- readonly 'Prepr-Context-utm_content'?: string;
57
- readonly 'Prepr-Context-utm_campaign'?: string;
58
- readonly 'Prepr-Context-initial_referral'?: string;
59
- readonly 'Prepr-Visitor-IP'?: string;
60
- readonly 'Prepr-Hubspot-Id'?: string;
61
- readonly 'Prepr-Customer-Id-Created'?: 'true';
62
- /** The visitor's browser User-Agent, used by the API for device detection. */
63
- readonly 'User-Agent'?: string;
64
- /** @deprecated Never populated; the visitor's value is under `User-Agent`. */
65
- readonly 'Prepr-User-Agent'?: string;
66
- readonly 'Prepr-Package'?: string;
67
- }
68
- type PreprErrorCode = 'INVALID_TOKEN' | 'MISSING_TOKEN' | 'HTTP_ERROR' | 'FETCH_ERROR' | 'INVALID_RESPONSE' | 'CONTEXT_ERROR';
1
+ import { b as PreprFeatures, P as PreprHeaders, c as PreprToolbarProps } from './server-CO847mEV.cjs';
2
+ export { a as PreprError, e as extractAccessToken, i as isPersonalizedResponse, v as validatePreprToken } from './server-CO847mEV.cjs';
69
3
 
70
4
  interface PreprMiddlewareOptions {
71
5
  /** Enable preview-mode headers (segment/AB overrides, preview bar). */
@@ -139,23 +73,4 @@ declare function getPreprHeaders(headers: Headers): PreprHeaders;
139
73
  */
140
74
  declare function getToolbarProps(headers: Headers, token: string, features?: PreprFeatures): Promise<PreprToolbarProps>;
141
75
 
142
- /** Error thrown by the token helpers and the segments fetch. */
143
- declare class PreprError extends Error {
144
- readonly code: PreprErrorCode;
145
- readonly context?: string | undefined;
146
- readonly originalError?: Error | undefined;
147
- constructor(message: string, code: PreprErrorCode, context?: string | undefined, originalError?: Error | undefined);
148
- }
149
- /**
150
- * Asserts `token` is the full `https://graphql.prepr.io/<token>` URL.
151
- * @throws PreprError if the token is missing or not an HTTPS URL.
152
- */
153
- declare function validatePreprToken(token: string): void;
154
- /**
155
- * Pulls the access token out of a GraphQL URL: `https://graphql.prepr.io/abc123`
156
- * -> `abc123`.
157
- * @throws PreprError if the URL is not a valid `graphql.prepr.io` URL.
158
- */
159
- declare function extractAccessToken(graphqlUrl: string): string;
160
-
161
- export { type Handle, PREPR_LOCALS_KEY, PreprError, type PreprMiddlewareOptions, type SvelteKitRequestEvent, type SvelteKitResolve, extractAccessToken, getActiveSegment, getActiveVariant, getPreprHeaders, getPreprHeadersFromLocals, getPreprUUID, getToolbarProps, preprHandle, validatePreprToken };
76
+ export { type Handle, PREPR_LOCALS_KEY, type PreprMiddlewareOptions, type SvelteKitRequestEvent, type SvelteKitResolve, getActiveSegment, getActiveVariant, getPreprHeaders, getPreprHeadersFromLocals, getPreprUUID, getToolbarProps, preprHandle };
@@ -1,71 +1,5 @@
1
- interface PreprSegment {
2
- readonly _id: string;
3
- readonly name: string;
4
- }
5
- /**
6
- * Per-feature config. `false` is shorthand for `{ enabled: false }`; the object
7
- * form leaves room for per-feature options later without a breaking change.
8
- */
9
- type PreprFeatureConfig = boolean | {
10
- enabled?: boolean;
11
- };
12
- /** Toolkit features a consumer can turn off. Omitted keys stay enabled. */
13
- interface PreprFeatures {
14
- /** Segment picker, `Prepr-Segments` header and its cookie/query param. */
15
- segments?: PreprFeatureConfig;
16
- /** A/B variant switch, `Prepr-ABtesting` header and its cookie/query param. */
17
- abTesting?: PreprFeatureConfig;
18
- /**
19
- * The site's own click-to-edit: the toolbar's Edit mode control, the stega
20
- * tooltip/overlay and the close-edit pill.
21
- *
22
- * NOT a security control, and NOT the Prepr editor's live preview. When the
23
- * site is framed by the editor, `prepr:initVE` still activates edit mode —
24
- * that is the CMS operating inside its own iframe, not an affordance offered
25
- * to visitors. See iframe-bridge.ts.
26
- */
27
- editMode?: PreprFeatureConfig;
28
- }
29
- interface PreprToolbarProps {
30
- /**
31
- * Server-resolved active segment. Optional: omit it with `segments`
32
- * disabled, where there is nothing to resolve. When enabled and omitted,
33
- * the persisted cookie is used.
34
- */
35
- readonly activeSegment?: string | null;
36
- /**
37
- * Server-resolved active A/B variant. Optional: omit it with `abTesting`
38
- * disabled, where there is nothing to resolve. When enabled and omitted,
39
- * the persisted cookie is used.
40
- */
41
- readonly activeVariant?: string | null;
42
- /** Available segments to personalize on. */
43
- readonly segments?: readonly PreprSegment[];
44
- /** @deprecated Alias for `segments`. */
45
- readonly data?: readonly PreprSegment[];
46
- }
47
- type PreprVariant = 'A' | 'B';
48
- interface PreprHeaders {
49
- readonly 'prepr-customer-id'?: string;
50
- readonly 'Prepr-Segments'?: string;
51
- readonly 'Prepr-ABtesting'?: PreprVariant;
52
- readonly 'Prepr-Preview-Bar'?: 'true';
53
- readonly 'Prepr-Context-utm_source'?: string;
54
- readonly 'Prepr-Context-utm_medium'?: string;
55
- readonly 'Prepr-Context-utm_term'?: string;
56
- readonly 'Prepr-Context-utm_content'?: string;
57
- readonly 'Prepr-Context-utm_campaign'?: string;
58
- readonly 'Prepr-Context-initial_referral'?: string;
59
- readonly 'Prepr-Visitor-IP'?: string;
60
- readonly 'Prepr-Hubspot-Id'?: string;
61
- readonly 'Prepr-Customer-Id-Created'?: 'true';
62
- /** The visitor's browser User-Agent, used by the API for device detection. */
63
- readonly 'User-Agent'?: string;
64
- /** @deprecated Never populated; the visitor's value is under `User-Agent`. */
65
- readonly 'Prepr-User-Agent'?: string;
66
- readonly 'Prepr-Package'?: string;
67
- }
68
- type PreprErrorCode = 'INVALID_TOKEN' | 'MISSING_TOKEN' | 'HTTP_ERROR' | 'FETCH_ERROR' | 'INVALID_RESPONSE' | 'CONTEXT_ERROR';
1
+ import { b as PreprFeatures, P as PreprHeaders, c as PreprToolbarProps } from './server-CO847mEV.js';
2
+ export { a as PreprError, e as extractAccessToken, i as isPersonalizedResponse, v as validatePreprToken } from './server-CO847mEV.js';
69
3
 
70
4
  interface PreprMiddlewareOptions {
71
5
  /** Enable preview-mode headers (segment/AB overrides, preview bar). */
@@ -139,23 +73,4 @@ declare function getPreprHeaders(headers: Headers): PreprHeaders;
139
73
  */
140
74
  declare function getToolbarProps(headers: Headers, token: string, features?: PreprFeatures): Promise<PreprToolbarProps>;
141
75
 
142
- /** Error thrown by the token helpers and the segments fetch. */
143
- declare class PreprError extends Error {
144
- readonly code: PreprErrorCode;
145
- readonly context?: string | undefined;
146
- readonly originalError?: Error | undefined;
147
- constructor(message: string, code: PreprErrorCode, context?: string | undefined, originalError?: Error | undefined);
148
- }
149
- /**
150
- * Asserts `token` is the full `https://graphql.prepr.io/<token>` URL.
151
- * @throws PreprError if the token is missing or not an HTTPS URL.
152
- */
153
- declare function validatePreprToken(token: string): void;
154
- /**
155
- * Pulls the access token out of a GraphQL URL: `https://graphql.prepr.io/abc123`
156
- * -> `abc123`.
157
- * @throws PreprError if the URL is not a valid `graphql.prepr.io` URL.
158
- */
159
- declare function extractAccessToken(graphqlUrl: string): string;
160
-
161
- export { type Handle, PREPR_LOCALS_KEY, PreprError, type PreprMiddlewareOptions, type SvelteKitRequestEvent, type SvelteKitResolve, extractAccessToken, getActiveSegment, getActiveVariant, getPreprHeaders, getPreprHeadersFromLocals, getPreprUUID, getToolbarProps, preprHandle, validatePreprToken };
76
+ export { type Handle, PREPR_LOCALS_KEY, type PreprMiddlewareOptions, type SvelteKitRequestEvent, type SvelteKitResolve, getActiveSegment, getActiveVariant, getPreprHeaders, getPreprHeadersFromLocals, getPreprUUID, getToolbarProps, preprHandle };
@@ -1,390 +1,17 @@
1
- // src/version.ts
2
- var VERSION = "0.5.0-rc.2";
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
- return { requestHeaders, responseCookies };
197
- }
198
-
199
- // src/sveltekit/hooks.ts
200
- var PREPR_LOCALS_KEY = "prepr";
201
- function preprHandle(options) {
202
- return async ({ event, resolve }) => {
203
- const { requestHeaders, responseCookies } = processFrameworkRequest(
204
- event.request,
205
- options,
206
- "sveltekit"
207
- );
208
- requestHeaders.forEach((value, key) => {
209
- event.request.headers.set(key, value);
210
- });
211
- if (event.locals) {
212
- event.locals[PREPR_LOCALS_KEY] = requestHeaders;
213
- }
214
- const response = await resolve(event);
215
- for (const cookie of responseCookies) {
216
- response.headers.append("Set-Cookie", serializeCookie(cookie));
217
- }
218
- return response;
219
- };
220
- }
221
- function getPreprHeadersFromLocals(locals) {
222
- const headers = locals[PREPR_LOCALS_KEY];
223
- return headers instanceof Headers ? headers : new Headers();
224
- }
225
-
226
- // src/core/server.ts
227
- var PreprError = class extends Error {
228
- constructor(message, code, context, originalError) {
229
- super(message);
230
- this.code = code;
231
- this.context = context;
232
- this.originalError = originalError;
233
- this.name = "PreprError";
234
- }
235
- };
236
- function getPreprUUIDFromHeaders(headers) {
237
- return headers.get("prepr-customer-id");
238
- }
239
- function getActiveSegmentFromHeaders(headers) {
240
- return headers.get("Prepr-Segments");
241
- }
242
- function getActiveVariantFromHeaders(headers) {
243
- return headers.get("Prepr-ABtesting");
244
- }
245
- var PREPR_HEADER_KEYS = [
246
- "prepr-customer-id",
247
- "Prepr-Segments",
248
- "Prepr-ABtesting",
249
- "Prepr-Preview-Bar",
250
- "Prepr-Context-utm_source",
251
- "Prepr-Context-utm_medium",
252
- "Prepr-Context-utm_term",
253
- "Prepr-Context-utm_content",
254
- "Prepr-Context-utm_campaign",
255
- "Prepr-Context-initial_referral",
256
- "Prepr-Visitor-IP",
257
- "Prepr-Hubspot-Id",
258
- "Prepr-Customer-Id-Created",
259
- "User-Agent",
260
- "Prepr-Package"
261
- ];
262
- function getPreprHeadersFromHeaders(headers) {
263
- const preprHeaders = {};
264
- const copy = (key) => {
265
- const value = headers.get(key);
266
- if (value !== null) {
267
- preprHeaders[key] = value;
268
- }
269
- };
270
- for (const key of PREPR_HEADER_KEYS) {
271
- copy(key);
272
- }
273
- return preprHeaders;
274
- }
275
- function validatePreprToken(token) {
276
- if (!token) {
277
- throw new PreprError(
278
- "Token is required",
279
- "MISSING_TOKEN",
280
- "validatePreprToken"
281
- );
282
- }
283
- if (!token.startsWith("https://")) {
284
- throw new PreprError(
285
- "Token must be a valid HTTPS URL",
286
- "INVALID_TOKEN",
287
- "validatePreprToken"
288
- );
289
- }
290
- }
291
- function extractAccessToken(graphqlUrl) {
292
- let url;
293
- try {
294
- url = new URL(graphqlUrl);
295
- } catch (error) {
296
- throw new PreprError(
297
- "Token must be a valid URL",
298
- "INVALID_TOKEN",
299
- "extractAccessToken",
300
- error instanceof Error ? error : new Error(String(error))
301
- );
302
- }
303
- if (url.hostname !== "graphql.prepr.io") {
304
- throw new PreprError(
305
- "Token must be a graphql.prepr.io URL",
306
- "INVALID_TOKEN",
307
- "extractAccessToken"
308
- );
309
- }
310
- const pathParts = url.pathname.split("/");
311
- const token = pathParts[pathParts.length - 1];
312
- if (!token) {
313
- throw new PreprError(
314
- "Token URL is missing an access token segment",
315
- "INVALID_TOKEN",
316
- "extractAccessToken"
317
- );
318
- }
319
- return token;
320
- }
321
- async function getPreprEnvironmentSegments(token) {
322
- validatePreprToken(token);
323
- try {
324
- const response = await fetch(token, {
325
- headers: {
326
- "Prepr-Package": `@preprio/toolkit@${VERSION}`,
327
- // Duplicates the version in Prepr-Package. It keeps the User-Agent
328
- // format used by `@preprio/prepr-nextjs`, for Prepr API consumers that
329
- // still identify the toolbar by that string.
330
- "User-Agent": `Prepr-Preview-Bar/${VERSION}`,
331
- "Content-Type": "application/json"
332
- },
333
- method: "POST",
334
- body: JSON.stringify({
335
- query: `{
336
- _Segments {
337
- _id
338
- name
339
- }
340
- }`
341
- })
342
- });
343
- if (!response.ok) {
344
- throw new PreprError(
345
- `HTTP ${response.status}: ${response.statusText}`,
346
- "HTTP_ERROR",
347
- "getPreprEnvironmentSegments"
348
- );
349
- }
350
- const json = await response.json();
351
- if (!json || !json.data || !json.data._Segments) {
352
- throw new PreprError(
353
- "Invalid response format from Prepr API",
354
- "INVALID_RESPONSE",
355
- "getPreprEnvironmentSegments"
356
- );
357
- }
358
- return json.data._Segments;
359
- } catch (error) {
360
- if (error instanceof PreprError) {
361
- throw error;
362
- }
363
- throw new PreprError(
364
- "Failed to fetch segments from Prepr API",
365
- "FETCH_ERROR",
366
- "getPreprEnvironmentSegments",
367
- error instanceof Error ? error : new Error(String(error))
368
- );
369
- }
370
- }
371
- async function getToolbarPropsFromHeaders(headers, token, features) {
372
- const resolved = resolveFeatures(features);
373
- let segments = [];
374
- if (resolved.segments) {
375
- try {
376
- segments = await getPreprEnvironmentSegments(token);
377
- } catch {
378
- segments = [];
379
- }
380
- }
381
- return {
382
- activeSegment: resolved.segments ? getActiveSegmentFromHeaders(headers) : null,
383
- activeVariant: resolved.abTesting ? getActiveVariantFromHeaders(headers) : null,
384
- segments,
385
- data: segments
386
- };
387
- }
1
+ import {
2
+ PREPR_LOCALS_KEY,
3
+ PreprError,
4
+ extractAccessToken,
5
+ getActiveSegmentFromHeaders,
6
+ getActiveVariantFromHeaders,
7
+ getPreprHeadersFromHeaders,
8
+ getPreprHeadersFromLocals,
9
+ getPreprUUIDFromHeaders,
10
+ getToolbarPropsFromHeaders,
11
+ isPersonalizedResponse,
12
+ preprHandle,
13
+ validatePreprToken
14
+ } from "./chunk-OKYZ6HPH.js";
388
15
 
389
16
  // src/sveltekit/server.ts
390
17
  function getPreprUUID(headers) {
@@ -412,6 +39,7 @@ export {
412
39
  getPreprHeadersFromLocals,
413
40
  getPreprUUID,
414
41
  getToolbarProps,
42
+ isPersonalizedResponse,
415
43
  preprHandle,
416
44
  validatePreprToken
417
45
  };