@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
package/dist/index.d.ts CHANGED
@@ -1,11 +1,13 @@
1
- import { P as PreprFeatures, R as ResolvedPreprFeatures, L as Locale, a as PreprSegment, b as PreprVariant, c as PreprToolbarProps, d as PreprPreviewOptions, e as PreprErrorCode, f as PreprHeaders } from './pixel-B3oQNbZ3.js';
2
- export { g as PreprEnvironment, h as PreprEventType, i as PreprFeatureConfig, j as PreprHeaderName, k as PreprPixelConfig, l as PreprToolbarComponentProps, m as PreprToolbarOptions, n as loadTrackingPixel, s as setTrackingParam, t as trackEvent } from './pixel-B3oQNbZ3.js';
1
+ import { b as PreprFeatures, R as ResolvedPreprFeatures, L as Locale, c as PreprSegment, d as PreprVariant, e as PreprToolbarProps, f as PreprPreviewOptions } from './types-BYH9XqmN.js';
2
+ export { g as PreprEnvironment, a as PreprErrorCode, h as PreprEventType, i as PreprFeatureConfig, j as PreprHeaderName, P as PreprHeaders, k as PreprToolbarComponentProps, l as PreprToolbarOptions } from './types-BYH9XqmN.js';
3
+ export { P as PreprError, e as extractAccessToken, g as getActiveSegmentFromHeaders, a as getActiveVariantFromHeaders, b as getPreprEnvironmentSegments, c as getPreprHeadersFromHeaders, d as getPreprUUIDFromHeaders, f as getToolbarPropsFromHeaders, i as isPersonalizedResponse, v as validatePreprToken } from './server-Brr1UgtW.js';
4
+ export { P as PreprPixelConfig, l as loadTrackingPixel, s as setTrackingParam, t as trackEvent } from './pixel-DwW7cXJm.js';
3
5
 
4
6
  /**
5
7
  * Package version; must match package.json. Lives in its own leaf module so
6
8
  * core can import it without cycling through the barrel.
7
9
  */
8
- declare const VERSION = "0.5.0-rc.2";
10
+ declare const VERSION = "0.6.0-alpha.1";
9
11
 
10
12
  /**
11
13
  * Resolve a `PreprFeatures` bag to plain booleans, defaulting every omitted key
@@ -65,6 +67,11 @@ interface CreatePreprPreviewOptions {
65
67
  props?: PreprToolbarProps;
66
68
  options?: PreprPreviewOptions;
67
69
  navigation?: PreprNavigationAdapter;
70
+ /**
71
+ * @internal Supplied by framework wrappers so stega stripping waits until
72
+ * the framework has hydrated the text it would change.
73
+ */
74
+ isHydrated?: (node: Text) => boolean;
68
75
  }
69
76
  interface PreprPreviewController {
70
77
  destroy(): void;
@@ -137,73 +144,14 @@ declare class PreprToolbarElement extends HTMLElementBase {
137
144
  /** Idempotent, including across bundles that each try to define the element. */
138
145
  declare function definePreprToolbar(): void;
139
146
 
140
- /** Which field the editor asked the preview to bring on screen. */
141
- interface ScrollToFieldMessage {
142
- field: string;
143
- id?: string;
144
- }
145
147
  interface IframeBridgeOptions {
146
148
  /**
147
149
  * Replace the `*.prepr.io` wildcard with an exact origin list. Intended for
148
- * self-hosted editors; when set, the wildcard no longer applies. `['*']`
149
- * accepts any editor origin — see `PreprPreviewOptions.allowedEditorOrigins`.
150
+ * self-hosted editors; when set, the wildcard no longer applies.
150
151
  */
151
152
  allowedEditorOrigins?: string[];
152
- /**
153
- * Called when the editor selects a field and wants the preview to scroll to
154
- * it. Only fires for messages from the handshaked editor origin. The bridge
155
- * stays free of DOM lookups: the preview runtime supplies `scrollToField`.
156
- */
157
- onScrollToField?: (message: ScrollToFieldMessage) => void;
158
153
  }
159
154
 
160
- /** Error thrown by the token helpers and the segments fetch. */
161
- declare class PreprError extends Error {
162
- readonly code: PreprErrorCode;
163
- readonly context?: string | undefined;
164
- readonly originalError?: Error | undefined;
165
- constructor(message: string, code: PreprErrorCode, context?: string | undefined, originalError?: Error | undefined);
166
- }
167
- /** Prepr Customer ID, or null if the middleware did not run for this request. */
168
- declare function getPreprUUIDFromHeaders(headers: Headers): string | null;
169
- /** Active segment ID, or null when no segment is selected. */
170
- declare function getActiveSegmentFromHeaders(headers: Headers): string | null;
171
- /** Active A/B variant (`'A'`/`'B'`), or null when no test is running. */
172
- declare function getActiveVariantFromHeaders(headers: Headers): string | null;
173
- /**
174
- * Collect the Prepr headers into a `PreprHeaders`. Lookups are case-insensitive
175
- * per the Fetch spec, but the returned keys use the declared casing.
176
- */
177
- declare function getPreprHeadersFromHeaders(headers: Headers): PreprHeaders;
178
- /**
179
- * Asserts `token` is the full `https://graphql.prepr.io/<token>` URL.
180
- * @throws PreprError if the token is missing or not an HTTPS URL.
181
- */
182
- declare function validatePreprToken(token: string): void;
183
- /**
184
- * Pulls the access token out of a GraphQL URL: `https://graphql.prepr.io/abc123`
185
- * -> `abc123`.
186
- * @throws PreprError if the URL is not a valid `graphql.prepr.io` URL.
187
- */
188
- declare function extractAccessToken(graphqlUrl: string): string;
189
- /**
190
- * Fetches the environment's segments from the Prepr API.
191
- *
192
- * `token` must be a Prepr GraphQL URL with scope 'segments'.
193
- * @throws PreprError if the token is invalid or the request fails.
194
- */
195
- declare function getPreprEnvironmentSegments(token: string): Promise<PreprSegment[]>;
196
- /**
197
- * Never throws: a failed segments fetch yields an empty list so the toolbar
198
- * still renders. The list is returned under both `segments` and the deprecated
199
- * `data` alias.
200
- *
201
- * Pass the same `features` object you give the toolbar and the middleware: with
202
- * segments disabled the `_Segments` request is skipped entirely, saving a
203
- * round-trip per page.
204
- */
205
- declare function getToolbarPropsFromHeaders(headers: Headers, token: string, features?: PreprFeatures): Promise<PreprToolbarProps>;
206
-
207
155
  interface CookieSpec {
208
156
  name: string;
209
157
  value: string;
@@ -242,4 +190,4 @@ interface PreprMiddlewareOptions {
242
190
  */
243
191
  declare function processPreprRequest(request: Request, opts?: PreprMiddlewareOptions): PreprMiddlewareResult;
244
192
 
245
- export { type CookieSpec, type CreatePreprPreviewOptions, type IframeBridgeOptions, PreprError, PreprErrorCode, PreprFeatures, PreprHeaders, type PreprMiddlewareOptions, type PreprMiddlewareResult, type PreprNavigationAdapter, type PreprPreviewController, PreprPreviewOptions, PreprSegment, PreprToolbarElement, PreprToolbarProps, PreprVariant, ResolvedPreprFeatures, type ToolbarState, type ToolbarStore, VERSION, createPreprPreview, createToolbarStore, definePreprToolbar, extractAccessToken, getActiveSegmentFromHeaders, getActiveVariantFromHeaders, getPreprEnvironmentSegments, getPreprHeadersFromHeaders, getPreprUUIDFromHeaders, getToolbarPropsFromHeaders, processPreprRequest, resolveFeatures, stegaClean, validatePreprToken };
193
+ export { type CookieSpec, type CreatePreprPreviewOptions, type IframeBridgeOptions, PreprFeatures, type PreprMiddlewareOptions, type PreprMiddlewareResult, type PreprNavigationAdapter, type PreprPreviewController, PreprPreviewOptions, PreprSegment, PreprToolbarElement, PreprToolbarProps, PreprVariant, ResolvedPreprFeatures, type ToolbarState, type ToolbarStore, VERSION, createPreprPreview, createToolbarStore, definePreprToolbar, processPreprRequest, resolveFeatures, stegaClean };
package/dist/index.js CHANGED
@@ -9,179 +9,34 @@ import {
9
9
  PARAM_SEGMENT,
10
10
  PARAM_VARIANT,
11
11
  PreprToolbarElement,
12
- VERSION,
13
12
  createPreprPreview,
14
13
  createToolbarStore,
15
14
  definePreprToolbar,
16
15
  loadTrackingPixel,
17
- resolveFeatures,
18
16
  setTrackingParam,
19
- stegaClean,
20
17
  trackEvent
21
- } from "./chunk-FLPNN3CV.js";
22
-
23
- // src/core/server.ts
24
- var PreprError = class extends Error {
25
- constructor(message, code, context, originalError) {
26
- super(message);
27
- this.code = code;
28
- this.context = context;
29
- this.originalError = originalError;
30
- this.name = "PreprError";
31
- }
32
- };
33
- function getPreprUUIDFromHeaders(headers) {
34
- return headers.get("prepr-customer-id");
35
- }
36
- function getActiveSegmentFromHeaders(headers) {
37
- return headers.get("Prepr-Segments");
38
- }
39
- function getActiveVariantFromHeaders(headers) {
40
- return headers.get("Prepr-ABtesting");
41
- }
42
- var PREPR_HEADER_KEYS = [
43
- "prepr-customer-id",
44
- "Prepr-Segments",
45
- "Prepr-ABtesting",
46
- "Prepr-Preview-Bar",
47
- "Prepr-Context-utm_source",
48
- "Prepr-Context-utm_medium",
49
- "Prepr-Context-utm_term",
50
- "Prepr-Context-utm_content",
51
- "Prepr-Context-utm_campaign",
52
- "Prepr-Context-initial_referral",
53
- "Prepr-Visitor-IP",
54
- "Prepr-Hubspot-Id",
55
- "Prepr-Customer-Id-Created",
56
- "User-Agent",
57
- "Prepr-Package"
58
- ];
59
- function getPreprHeadersFromHeaders(headers) {
60
- const preprHeaders = {};
61
- const copy = (key) => {
62
- const value = headers.get(key);
63
- if (value !== null) {
64
- preprHeaders[key] = value;
65
- }
66
- };
67
- for (const key of PREPR_HEADER_KEYS) {
68
- copy(key);
69
- }
70
- return preprHeaders;
71
- }
72
- function validatePreprToken(token) {
73
- if (!token) {
74
- throw new PreprError(
75
- "Token is required",
76
- "MISSING_TOKEN",
77
- "validatePreprToken"
78
- );
79
- }
80
- if (!token.startsWith("https://")) {
81
- throw new PreprError(
82
- "Token must be a valid HTTPS URL",
83
- "INVALID_TOKEN",
84
- "validatePreprToken"
85
- );
86
- }
87
- }
88
- function extractAccessToken(graphqlUrl) {
89
- let url;
90
- try {
91
- url = new URL(graphqlUrl);
92
- } catch (error) {
93
- throw new PreprError(
94
- "Token must be a valid URL",
95
- "INVALID_TOKEN",
96
- "extractAccessToken",
97
- error instanceof Error ? error : new Error(String(error))
98
- );
99
- }
100
- if (url.hostname !== "graphql.prepr.io") {
101
- throw new PreprError(
102
- "Token must be a graphql.prepr.io URL",
103
- "INVALID_TOKEN",
104
- "extractAccessToken"
105
- );
106
- }
107
- const pathParts = url.pathname.split("/");
108
- const token = pathParts[pathParts.length - 1];
109
- if (!token) {
110
- throw new PreprError(
111
- "Token URL is missing an access token segment",
112
- "INVALID_TOKEN",
113
- "extractAccessToken"
114
- );
115
- }
116
- return token;
117
- }
118
- async function getPreprEnvironmentSegments(token) {
119
- validatePreprToken(token);
120
- try {
121
- const response = await fetch(token, {
122
- headers: {
123
- "Prepr-Package": `@preprio/toolkit@${VERSION}`,
124
- // Duplicates the version in Prepr-Package. It keeps the User-Agent
125
- // format used by `@preprio/prepr-nextjs`, for Prepr API consumers that
126
- // still identify the toolbar by that string.
127
- "User-Agent": `Prepr-Preview-Bar/${VERSION}`,
128
- "Content-Type": "application/json"
129
- },
130
- method: "POST",
131
- body: JSON.stringify({
132
- query: `{
133
- _Segments {
134
- _id
135
- name
136
- }
137
- }`
138
- })
139
- });
140
- if (!response.ok) {
141
- throw new PreprError(
142
- `HTTP ${response.status}: ${response.statusText}`,
143
- "HTTP_ERROR",
144
- "getPreprEnvironmentSegments"
145
- );
146
- }
147
- const json = await response.json();
148
- if (!json || !json.data || !json.data._Segments) {
149
- throw new PreprError(
150
- "Invalid response format from Prepr API",
151
- "INVALID_RESPONSE",
152
- "getPreprEnvironmentSegments"
153
- );
154
- }
155
- return json.data._Segments;
156
- } catch (error) {
157
- if (error instanceof PreprError) {
158
- throw error;
159
- }
160
- throw new PreprError(
161
- "Failed to fetch segments from Prepr API",
162
- "FETCH_ERROR",
163
- "getPreprEnvironmentSegments",
164
- error instanceof Error ? error : new Error(String(error))
165
- );
166
- }
167
- }
168
- async function getToolbarPropsFromHeaders(headers, token, features) {
169
- const resolved = resolveFeatures(features);
170
- let segments = [];
171
- if (resolved.segments) {
172
- try {
173
- segments = await getPreprEnvironmentSegments(token);
174
- } catch {
175
- segments = [];
176
- }
177
- }
178
- return {
179
- activeSegment: resolved.segments ? getActiveSegmentFromHeaders(headers) : null,
180
- activeVariant: resolved.abTesting ? getActiveVariantFromHeaders(headers) : null,
181
- segments,
182
- data: segments
183
- };
184
- }
18
+ } from "./chunk-VI6QZTBM.js";
19
+ import {
20
+ isPersonalizedResponse
21
+ } from "./chunk-3NCEVJJ3.js";
22
+ import {
23
+ stegaClean
24
+ } from "./chunk-S5RWVMDJ.js";
25
+ import {
26
+ PreprError,
27
+ extractAccessToken,
28
+ getActiveSegmentFromHeaders,
29
+ getActiveVariantFromHeaders,
30
+ getPreprEnvironmentSegments,
31
+ getPreprHeadersFromHeaders,
32
+ getPreprUUIDFromHeaders,
33
+ getToolbarPropsFromHeaders,
34
+ validatePreprToken
35
+ } from "./chunk-3JLWZQ37.js";
36
+ import {
37
+ VERSION,
38
+ resolveFeatures
39
+ } from "./chunk-YWIKKWBR.js";
185
40
 
186
41
  // src/core/middleware.ts
187
42
  var UTM_PARAMS = [
@@ -335,6 +190,10 @@ function processFrameworkRequest(request, opts, framework) {
335
190
  });
336
191
  }
337
192
  }
193
+ if (requestHeaders.has("Prepr-Segments")) {
194
+ requestHeaders.delete("Prepr-Customer-Id");
195
+ requestHeaders.delete("Prepr-Customer-Id-Created");
196
+ }
338
197
  return { requestHeaders, responseCookies };
339
198
  }
340
199
  export {
@@ -351,6 +210,7 @@ export {
351
210
  getPreprHeadersFromHeaders,
352
211
  getPreprUUIDFromHeaders,
353
212
  getToolbarPropsFromHeaders,
213
+ isPersonalizedResponse,
354
214
  loadTrackingPixel,
355
215
  processPreprRequest,
356
216
  resolveFeatures,
@@ -0,0 +1,231 @@
1
+ // src/version.ts
2
+ var VERSION = "0.6.0-alpha.1";
3
+
4
+ // src/core/features.ts
5
+ function isEnabled(config) {
6
+ if (typeof config === "boolean") return config;
7
+ return config?.enabled ?? true;
8
+ }
9
+ function resolveFeatures(features) {
10
+ return {
11
+ segments: isEnabled(features?.segments),
12
+ abTesting: isEnabled(features?.abTesting),
13
+ editMode: isEnabled(features?.editMode)
14
+ };
15
+ }
16
+ var ALL_FEATURES_ENABLED = Object.freeze({
17
+ segments: true,
18
+ abTesting: true,
19
+ editMode: true
20
+ });
21
+
22
+ // src/core/server.ts
23
+ var PreprError = class extends Error {
24
+ constructor(message, code, context, originalError) {
25
+ super(message);
26
+ this.code = code;
27
+ this.context = context;
28
+ this.originalError = originalError;
29
+ this.name = "PreprError";
30
+ }
31
+ };
32
+ function getPreprUUIDFromHeaders(headers2) {
33
+ return headers2.get("prepr-customer-id");
34
+ }
35
+ function getActiveSegmentFromHeaders(headers2) {
36
+ return headers2.get("Prepr-Segments");
37
+ }
38
+ function getActiveVariantFromHeaders(headers2) {
39
+ return headers2.get("Prepr-ABtesting");
40
+ }
41
+ var PREPR_HEADER_KEYS = [
42
+ "prepr-customer-id",
43
+ "Prepr-Segments",
44
+ "Prepr-ABtesting",
45
+ "Prepr-Preview-Bar",
46
+ "Prepr-Context-utm_source",
47
+ "Prepr-Context-utm_medium",
48
+ "Prepr-Context-utm_term",
49
+ "Prepr-Context-utm_content",
50
+ "Prepr-Context-utm_campaign",
51
+ "Prepr-Context-initial_referral",
52
+ "Prepr-Visitor-IP",
53
+ "Prepr-Hubspot-Id",
54
+ "Prepr-Customer-Id-Created",
55
+ "User-Agent",
56
+ "Prepr-Package"
57
+ ];
58
+ function getPreprHeadersFromHeaders(headers2) {
59
+ const preprHeaders = {};
60
+ const copy = (key) => {
61
+ const value = headers2.get(key);
62
+ if (value !== null) {
63
+ preprHeaders[key] = value;
64
+ }
65
+ };
66
+ for (const key of PREPR_HEADER_KEYS) {
67
+ copy(key);
68
+ }
69
+ return preprHeaders;
70
+ }
71
+ function validatePreprToken(token) {
72
+ if (!token) {
73
+ throw new PreprError(
74
+ "Token is required",
75
+ "MISSING_TOKEN",
76
+ "validatePreprToken"
77
+ );
78
+ }
79
+ if (!token.startsWith("https://")) {
80
+ throw new PreprError(
81
+ "Token must be a valid HTTPS URL",
82
+ "INVALID_TOKEN",
83
+ "validatePreprToken"
84
+ );
85
+ }
86
+ }
87
+ function extractAccessToken(graphqlUrl) {
88
+ let url;
89
+ try {
90
+ url = new URL(graphqlUrl);
91
+ } catch (error) {
92
+ throw new PreprError(
93
+ "Token must be a valid URL",
94
+ "INVALID_TOKEN",
95
+ "extractAccessToken",
96
+ error instanceof Error ? error : new Error(String(error))
97
+ );
98
+ }
99
+ if (url.hostname !== "graphql.prepr.io") {
100
+ throw new PreprError(
101
+ "Token must be a graphql.prepr.io URL",
102
+ "INVALID_TOKEN",
103
+ "extractAccessToken"
104
+ );
105
+ }
106
+ const pathParts = url.pathname.split("/");
107
+ const token = pathParts[pathParts.length - 1];
108
+ if (!token) {
109
+ throw new PreprError(
110
+ "Token URL is missing an access token segment",
111
+ "INVALID_TOKEN",
112
+ "extractAccessToken"
113
+ );
114
+ }
115
+ return token;
116
+ }
117
+ async function getPreprEnvironmentSegments(token) {
118
+ validatePreprToken(token);
119
+ try {
120
+ const response = await fetch(token, {
121
+ headers: {
122
+ "Prepr-Package": `@preprio/toolkit@${VERSION}`,
123
+ // Duplicates the version in Prepr-Package. It keeps the User-Agent
124
+ // format used by `@preprio/prepr-nextjs`, for Prepr API consumers that
125
+ // still identify the toolbar by that string.
126
+ "User-Agent": `Prepr-Preview-Bar/${VERSION}`,
127
+ "Content-Type": "application/json"
128
+ },
129
+ method: "POST",
130
+ body: JSON.stringify({
131
+ query: `{
132
+ _Segments {
133
+ _id
134
+ name
135
+ }
136
+ }`
137
+ })
138
+ });
139
+ if (!response.ok) {
140
+ throw new PreprError(
141
+ `HTTP ${response.status}: ${response.statusText}`,
142
+ "HTTP_ERROR",
143
+ "getPreprEnvironmentSegments"
144
+ );
145
+ }
146
+ const json = await response.json();
147
+ if (!json || !json.data || !json.data._Segments) {
148
+ throw new PreprError(
149
+ "Invalid response format from Prepr API",
150
+ "INVALID_RESPONSE",
151
+ "getPreprEnvironmentSegments"
152
+ );
153
+ }
154
+ return json.data._Segments;
155
+ } catch (error) {
156
+ if (error instanceof PreprError) {
157
+ throw error;
158
+ }
159
+ throw new PreprError(
160
+ "Failed to fetch segments from Prepr API",
161
+ "FETCH_ERROR",
162
+ "getPreprEnvironmentSegments",
163
+ error instanceof Error ? error : new Error(String(error))
164
+ );
165
+ }
166
+ }
167
+ async function getToolbarPropsFromHeaders(headers2, token, features) {
168
+ const resolved = resolveFeatures(features);
169
+ let segments = [];
170
+ if (resolved.segments) {
171
+ try {
172
+ segments = await getPreprEnvironmentSegments(token);
173
+ } catch {
174
+ segments = [];
175
+ }
176
+ }
177
+ return {
178
+ activeSegment: resolved.segments ? getActiveSegmentFromHeaders(headers2) : null,
179
+ activeVariant: resolved.abTesting ? getActiveVariantFromHeaders(headers2) : null,
180
+ segments,
181
+ data: segments
182
+ };
183
+ }
184
+
185
+ // src/nextjs/server.ts
186
+ import { headers } from "next/headers";
187
+ async function readHeaders() {
188
+ return await headers();
189
+ }
190
+ async function getPreprUUID() {
191
+ const h = await readHeaders();
192
+ return getPreprUUIDFromHeaders(h);
193
+ }
194
+ async function getActiveSegment() {
195
+ const h = await readHeaders();
196
+ return getActiveSegmentFromHeaders(h);
197
+ }
198
+ async function getActiveVariant() {
199
+ const h = await readHeaders();
200
+ return getActiveVariantFromHeaders(h);
201
+ }
202
+ async function getPreprHeaders() {
203
+ const h = await readHeaders();
204
+ return getPreprHeadersFromHeaders(h);
205
+ }
206
+ async function getToolbarProps(token, features) {
207
+ const h = await readHeaders();
208
+ return getToolbarPropsFromHeaders(h, token, features);
209
+ }
210
+
211
+ // src/core/personalization.ts
212
+ var PERSONALIZED_VARY = /\bPrepr-(Segments|ABTesting)/i;
213
+ function isPersonalizedResponse(source) {
214
+ const headers2 = "headers" in source ? source.headers : source;
215
+ return PERSONALIZED_VARY.test(headers2.get("vary") ?? "");
216
+ }
217
+
218
+ export {
219
+ VERSION,
220
+ resolveFeatures,
221
+ PreprError,
222
+ getPreprHeadersFromHeaders,
223
+ validatePreprToken,
224
+ extractAccessToken,
225
+ getPreprUUID,
226
+ getActiveSegment,
227
+ getActiveVariant,
228
+ getPreprHeaders,
229
+ getToolbarProps,
230
+ isPersonalizedResponse
231
+ };