@preprio/toolkit 0.6.0-alpha.9 → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +111 -1363
  2. package/dist/astro/index.cjs +1555 -182
  3. package/dist/astro/index.d.cts +201 -1
  4. package/dist/astro/index.d.ts +201 -1
  5. package/dist/astro/index.js +1557 -29
  6. package/dist/{chunk-5QIWVDP2.js → chunk-33GWVTRJ.js} +1 -1
  7. package/dist/chunk-A2J7R4LR.js +256 -0
  8. package/dist/{chunk-WQBKQG4R.js → chunk-DSJ22P6J.js} +6 -1
  9. package/dist/chunk-KM2GME62.js +1255 -0
  10. package/dist/chunk-UTKH7DOI.js +58 -0
  11. package/dist/chunk-V7MCHPE7.js +85 -0
  12. package/dist/{chunk-J66UOCK6.js → chunk-WBMN4L7G.js} +1680 -579
  13. package/dist/chunk-Y7JWV7WV.js +374 -0
  14. package/dist/codegen/index.cjs +82 -0
  15. package/dist/codegen/index.d.cts +70 -0
  16. package/dist/codegen/index.d.ts +70 -0
  17. package/dist/codegen/index.js +64 -0
  18. package/dist/index.cjs +3729 -553
  19. package/dist/index.d.cts +403 -19
  20. package/dist/index.d.ts +403 -19
  21. package/dist/index.js +345 -24
  22. package/dist/live-preview-HCBNBC6C.js +19 -0
  23. package/dist/nextjs/components.cjs +1872 -754
  24. package/dist/nextjs/components.d.cts +5 -51
  25. package/dist/nextjs/components.d.ts +5 -51
  26. package/dist/nextjs/components.js +8 -299
  27. package/dist/nextjs/index.cjs +1228 -181
  28. package/dist/nextjs/index.d.cts +247 -92
  29. package/dist/nextjs/index.d.ts +247 -92
  30. package/dist/nextjs/index.js +1629 -111
  31. package/dist/nextjs/live-action.cjs +298 -0
  32. package/dist/nextjs/live-action.d.cts +12 -0
  33. package/dist/nextjs/live-action.d.ts +12 -0
  34. package/dist/nextjs/live-action.js +68 -0
  35. package/dist/nextjs/live.cjs +2010 -0
  36. package/dist/nextjs/live.d.cts +54 -0
  37. package/dist/nextjs/live.d.ts +54 -0
  38. package/dist/nextjs/live.js +287 -0
  39. package/dist/nuxt/chunk-5RBZPRQN.js +350 -0
  40. package/dist/nuxt/chunk-LUKVPOJ2.js +32 -0
  41. package/dist/nuxt/index.cjs +15 -16
  42. package/dist/nuxt/index.d.cts +167 -6
  43. package/dist/nuxt/index.d.ts +167 -6
  44. package/dist/nuxt/index.js +402 -15
  45. package/dist/nuxt/live-preview-KO4IKWTX.js +1234 -0
  46. package/dist/nuxt/live.cjs +1928 -0
  47. package/dist/nuxt/live.d.cts +45 -0
  48. package/dist/nuxt/live.d.ts +45 -0
  49. package/dist/nuxt/live.js +216 -0
  50. package/dist/{types-BYH9XqmN.d.cts → pixel-DqU7NvgW.d.cts} +102 -5
  51. package/dist/{types-BYH9XqmN.d.ts → pixel-DqU7NvgW.d.ts} +102 -5
  52. package/dist/react/components.cjs +1865 -480
  53. package/dist/react/components.d.cts +43 -8
  54. package/dist/react/components.d.ts +43 -8
  55. package/dist/react/components.js +1865 -480
  56. package/dist/sveltekit/chunk-5RBZPRQN.js +350 -0
  57. package/dist/sveltekit/chunk-LUKVPOJ2.js +32 -0
  58. package/dist/sveltekit/index.cjs +15 -16
  59. package/dist/sveltekit/index.d.cts +111 -10
  60. package/dist/sveltekit/index.d.ts +111 -10
  61. package/dist/sveltekit/index.js +398 -15
  62. package/dist/sveltekit/live-preview-KO4IKWTX.js +1234 -0
  63. package/dist/sveltekit/live.cjs +1940 -0
  64. package/dist/sveltekit/live.d.cts +61 -0
  65. package/dist/sveltekit/live.d.ts +61 -0
  66. package/dist/sveltekit/live.js +220 -0
  67. package/package.json +132 -71
  68. package/src/astro/PreprToolbar.astro +7 -1
  69. package/src/astro/PreprTrackingPixel.astro +2 -4
  70. package/src/nuxt/PreprToolbar.vue +12 -1
  71. package/src/nuxt/PreprTrackingPixel.vue +2 -4
  72. package/src/sveltekit/PreprToolbar.svelte +17 -2
  73. package/src/sveltekit/PreprTrackingPixel.svelte +2 -4
  74. package/dist/astro/chunk-UN4JADNU.js +0 -173
  75. package/dist/astro/graphql.cjs +0 -1078
  76. package/dist/astro/graphql.d.cts +0 -300
  77. package/dist/astro/graphql.d.ts +0 -300
  78. package/dist/astro/graphql.js +0 -984
  79. package/dist/astro/index-XT_z-RYT.d.cts +0 -130
  80. package/dist/astro/index-XT_z-RYT.d.ts +0 -130
  81. package/dist/chunk-3NCEVJJ3.js +0 -10
  82. package/dist/chunk-S5RWVMDJ.js +0 -148
  83. package/dist/chunk-XL4Y7FGW.js +0 -499
  84. package/dist/graphql/codegen.cjs +0 -557
  85. package/dist/graphql/codegen.d.cts +0 -23
  86. package/dist/graphql/codegen.d.ts +0 -23
  87. package/dist/graphql/codegen.js +0 -99
  88. package/dist/graphql.cjs +0 -1020
  89. package/dist/graphql.d.cts +0 -335
  90. package/dist/graphql.d.ts +0 -335
  91. package/dist/graphql.js +0 -448
  92. package/dist/nextjs/chunk-CMV6ZP6E.js +0 -549
  93. package/dist/nextjs/graphql.cjs +0 -1836
  94. package/dist/nextjs/graphql.d.cts +0 -498
  95. package/dist/nextjs/graphql.d.ts +0 -498
  96. package/dist/nextjs/graphql.js +0 -1422
  97. package/dist/nextjs/server-BL-sqZvu.d.cts +0 -156
  98. package/dist/nextjs/server-BL-sqZvu.d.ts +0 -156
  99. package/dist/nuxt/chunk-XWOABVMW.js +0 -417
  100. package/dist/nuxt/graphql.cjs +0 -1085
  101. package/dist/nuxt/graphql.d.cts +0 -297
  102. package/dist/nuxt/graphql.d.ts +0 -297
  103. package/dist/nuxt/graphql.js +0 -985
  104. package/dist/nuxt/server-8v6OHbsw.d.cts +0 -158
  105. package/dist/nuxt/server-8v6OHbsw.d.ts +0 -158
  106. package/dist/pixel-DwW7cXJm.d.cts +0 -49
  107. package/dist/pixel-DwW7cXJm.d.ts +0 -49
  108. package/dist/server-Brr1UgtW.d.ts +0 -59
  109. package/dist/server-DJuS3YU0.d.cts +0 -59
  110. package/dist/sveltekit/chunk-3S5RA6G5.js +0 -413
  111. package/dist/sveltekit/graphql.cjs +0 -1091
  112. package/dist/sveltekit/graphql.d.cts +0 -302
  113. package/dist/sveltekit/graphql.d.ts +0 -302
  114. package/dist/sveltekit/graphql.js +0 -991
  115. package/dist/sveltekit/server-CO847mEV.d.cts +0 -98
  116. package/dist/sveltekit/server-CO847mEV.d.ts +0 -98
@@ -1,1422 +0,0 @@
1
- import {
2
- PREPR_ANY_ITEM_TAG,
3
- PREPR_SCHEMA_TAG,
4
- PreprError,
5
- createPreprMiddleware,
6
- getPreprHeaders,
7
- getPreprHeadersFromHeaders,
8
- isPersonalizedResponse,
9
- preprCacheTags,
10
- preprDraftRedirect,
11
- preprModelTag,
12
- preprModelTagsFor,
13
- validatePreprToken
14
- } from "./chunk-CMV6ZP6E.js";
15
-
16
- // src/nextjs/graphql.ts
17
- import * as nextCache from "next/cache";
18
-
19
- // src/core/variants/constants.ts
20
- var PREPR_CONTEXT_ALIAS = "_preprContext";
21
- var PREPR_TYPE_ALIAS = "_preprType";
22
- var PREPR_DEFAULT_VARIANT = "ALL_OTHER_USERS";
23
-
24
- // src/core/variants/ast.ts
25
- import { parse } from "graphql/language/parser.js";
26
- var name = (value) => ({ kind: "Name", value });
27
- function selectionSet(selections) {
28
- return { kind: "SelectionSet", selections };
29
- }
30
- function contextField(withKey) {
31
- const fields = ["kind", "group_id", "variant_id"];
32
- if (withKey) fields.push("variant_key");
33
- return {
34
- kind: "Field",
35
- alias: name(PREPR_CONTEXT_ALIAS),
36
- name: name("_context"),
37
- selectionSet: selectionSet(
38
- fields.map(
39
- (field) => ({ kind: "Field", name: name(field) })
40
- )
41
- )
42
- };
43
- }
44
- function typenameField() {
45
- return {
46
- kind: "Field",
47
- alias: name(PREPR_TYPE_ALIAS),
48
- name: name("__typename")
49
- };
50
- }
51
- function inlineFragment(typeName, selections) {
52
- return {
53
- kind: "InlineFragment",
54
- typeCondition: { kind: "NamedType", name: name(typeName) },
55
- selectionSet: selectionSet(selections)
56
- };
57
- }
58
- function contextSelections(typeName, schema, onlyTypes, withType = true) {
59
- const fields = () => withType ? [contextField(true), typenameField()] : [contextField(false)];
60
- const type = schema.types[typeName];
61
- if (!type) return [];
62
- if (type.possibleTypes.length > 0) {
63
- return type.possibleTypes.filter(
64
- (member) => schema.types[member]?.hasContext && (!onlyTypes || onlyTypes.has(member))
65
- ).map((member) => inlineFragment(member, fields()));
66
- }
67
- return type.hasContext ? fields() : [];
68
- }
69
- function withoutPersonalizeArg(args = []) {
70
- return args.filter((arg) => arg.name.value !== "personalize");
71
- }
72
- function documentOf(document2) {
73
- if (typeof document2 === "string") return parse(document2);
74
- if (document2 instanceof String) return parse(document2.toString());
75
- return document2;
76
- }
77
- function collectVariables(node, used) {
78
- if (!node || typeof node !== "object") return;
79
- if (Array.isArray(node)) {
80
- for (const item of node) collectVariables(item, used);
81
- return;
82
- }
83
- const value = node;
84
- if (value.kind === "Variable") {
85
- used.add(value.name.value);
86
- return;
87
- }
88
- for (const key of Object.keys(value)) {
89
- if (key !== "loc") collectVariables(value[key], used);
90
- }
91
- }
92
-
93
- // src/core/variants/decision-document.ts
94
- function decisionSelectionSet(set, typeName, path, ctx) {
95
- const selections = [];
96
- for (const selection of set.selections) {
97
- if (selection.kind === "FragmentSpread") {
98
- const fragment = ctx.fragments[selection.name.value];
99
- if (!fragment) continue;
100
- const pruned = decisionSelectionSet(
101
- fragment.selectionSet,
102
- fragment.typeCondition.name.value,
103
- path,
104
- ctx
105
- );
106
- if (!pruned) continue;
107
- if (fragment.typeCondition.name.value === typeName) {
108
- selections.push(...pruned.selections);
109
- } else {
110
- selections.push(
111
- inlineFragment(fragment.typeCondition.name.value, [
112
- ...pruned.selections
113
- ])
114
- );
115
- }
116
- continue;
117
- }
118
- if (selection.kind === "InlineFragment") {
119
- const condition = selection.typeCondition?.name.value ?? typeName;
120
- const pruned = decisionSelectionSet(
121
- selection.selectionSet,
122
- condition,
123
- path,
124
- ctx
125
- );
126
- if (!pruned) continue;
127
- if (condition === typeName && !selection.directives?.length) {
128
- selections.push(...pruned.selections);
129
- } else {
130
- selections.push({ ...selection, selectionSet: pruned });
131
- }
132
- continue;
133
- }
134
- if (!selection.selectionSet) continue;
135
- const field = ctx.schema.types[typeName]?.fields[selection.name.value];
136
- if (!field) continue;
137
- const key = selection.alias?.value ?? selection.name.value;
138
- const fieldPath = path ? `${path}.${key}` : key;
139
- if (ctx.paths && !ctx.paths.prefixes.has(fieldPath)) continue;
140
- const child = decisionSelectionSet(
141
- selection.selectionSet,
142
- field.type,
143
- fieldPath,
144
- ctx
145
- );
146
- const groupTypes = ctx.paths?.groups.get(fieldPath);
147
- const holdsGroups = field.personalizable && (!ctx.paths || groupTypes !== void 0);
148
- if (holdsGroups) {
149
- selections.push({
150
- ...selection,
151
- arguments: withoutPersonalizeArg(selection.arguments),
152
- selectionSet: selectionSet([
153
- ...ctx.topLevelOnly ? [] : child?.selections ?? [],
154
- ...contextSelections(
155
- field.type,
156
- ctx.schema,
157
- groupTypes && !groupTypes.has("*") ? groupTypes : void 0,
158
- false
159
- )
160
- ])
161
- });
162
- } else if (child) {
163
- selections.push({
164
- ...selection,
165
- arguments: field.personalizable ? withoutPersonalizeArg(selection.arguments) : selection.arguments,
166
- selectionSet: child
167
- });
168
- }
169
- }
170
- return selections.length > 0 ? selectionSet(selections) : null;
171
- }
172
- function toDecisionDocument(document2, schema, groupPaths, options) {
173
- const doc = documentOf(document2);
174
- const fragments = {};
175
- for (const definition of doc.definitions) {
176
- if (definition.kind === "FragmentDefinition") {
177
- fragments[definition.name.value] = definition;
178
- }
179
- }
180
- const operation = doc.definitions.find(
181
- (definition) => definition.kind === "OperationDefinition"
182
- );
183
- if (!operation) return null;
184
- let paths;
185
- if (groupPaths) {
186
- const prefixes = /* @__PURE__ */ new Set();
187
- for (const groupPath of groupPaths.keys()) {
188
- const parts = groupPath.split(".");
189
- for (let i = 1; i <= parts.length; i++) {
190
- prefixes.add(parts.slice(0, i).join("."));
191
- }
192
- }
193
- paths = { groups: groupPaths, prefixes };
194
- }
195
- const pruned = decisionSelectionSet(
196
- operation.selectionSet,
197
- schema.queryType,
198
- "",
199
- { schema, fragments, paths, topLevelOnly: options?.topLevelOnly }
200
- );
201
- if (!pruned) return null;
202
- const used = /* @__PURE__ */ new Set();
203
- collectVariables(pruned, used);
204
- collectVariables(operation.directives, used);
205
- const shared = sharedContextFragment(schema);
206
- return {
207
- kind: "Document",
208
- definitions: [
209
- ...shared ? [shared.definition] : [],
210
- {
211
- ...operation,
212
- name: operation.name && name(`${operation.name.value}Decision`),
213
- variableDefinitions: (operation.variableDefinitions ?? []).filter(
214
- (definition) => used.has(definition.variable.name.value)
215
- ),
216
- selectionSet: shared ? shared.apply(pruned) : pruned
217
- }
218
- ]
219
- };
220
- }
221
- function sharedContextFragment(schema) {
222
- const contextTypes = new Set(
223
- Object.values(schema.types).flatMap(
224
- (type) => type.hasContext ? [type.fields._context.type] : []
225
- )
226
- );
227
- if (contextTypes.size !== 1) return null;
228
- const [contextType] = contextTypes;
229
- const fragmentName = "c";
230
- const definition = {
231
- kind: "FragmentDefinition",
232
- name: name(fragmentName),
233
- typeCondition: { kind: "NamedType", name: name(contextType) },
234
- selectionSet: selectionSet(
235
- ["kind", "group_id", "variant_id"].map(
236
- (field) => ({ kind: "Field", name: name(field) })
237
- )
238
- )
239
- };
240
- const spread = {
241
- kind: "FragmentSpread",
242
- name: name(fragmentName)
243
- };
244
- const apply = (set) => selectionSet(
245
- set.selections.map((selection) => {
246
- if (selection.kind === "Field" && selection.alias?.value === PREPR_CONTEXT_ALIAS) {
247
- return { ...selection, selectionSet: selectionSet([spread]) };
248
- }
249
- return "selectionSet" in selection && selection.selectionSet ? {
250
- ...selection,
251
- selectionSet: apply(selection.selectionSet)
252
- } : selection;
253
- })
254
- );
255
- return { definition, apply };
256
- }
257
-
258
- // src/core/variants/probe-document.ts
259
- function probeSelectionSet(set, fragments) {
260
- const selections = [
261
- { kind: "Field", name: name("__typename") }
262
- ];
263
- for (const selection of set.selections) {
264
- if (selection.kind === "Field") {
265
- if (!selection.selectionSet) continue;
266
- selections.push({
267
- ...selection,
268
- selectionSet: probeSelectionSet(selection.selectionSet, fragments)
269
- });
270
- continue;
271
- }
272
- const fragment = selection.kind === "InlineFragment" ? selection : fragments[selection.name.value];
273
- if (!fragment) continue;
274
- const child = probeSelectionSet(fragment.selectionSet, fragments);
275
- if (child.selections.length === 1) continue;
276
- selections.push({
277
- kind: "InlineFragment",
278
- typeCondition: fragment.typeCondition,
279
- directives: selection.directives,
280
- selectionSet: child
281
- });
282
- }
283
- return selectionSet(selections);
284
- }
285
- function toAbProbeDocument(document2) {
286
- const doc = documentOf(document2);
287
- const fragments = {};
288
- for (const definition of doc.definitions) {
289
- if (definition.kind === "FragmentDefinition") {
290
- fragments[definition.name.value] = definition;
291
- }
292
- }
293
- const operation = doc.definitions.find(
294
- (definition) => definition.kind === "OperationDefinition"
295
- );
296
- if (!operation) return null;
297
- const probe = probeSelectionSet(operation.selectionSet, fragments);
298
- const used = /* @__PURE__ */ new Set();
299
- collectVariables(probe, used);
300
- collectVariables(operation.directives, used);
301
- return {
302
- kind: "Document",
303
- definitions: [
304
- {
305
- ...operation,
306
- name: operation.name && name(`${operation.name.value}AbCheck`),
307
- variableDefinitions: (operation.variableDefinitions ?? []).filter(
308
- (definition) => used.has(definition.variable.name.value)
309
- ),
310
- selectionSet: probe
311
- }
312
- ]
313
- };
314
- }
315
-
316
- // src/core/variants/resolve.ts
317
- function personalizationPaths(data) {
318
- const paths = /* @__PURE__ */ new Map();
319
- const walk = (value, path) => {
320
- if (Array.isArray(value)) {
321
- for (const item of value) {
322
- if (contextOf(item)?.kind === "PERSONALIZATION") {
323
- const record = item;
324
- const type = record[PREPR_TYPE_ALIAS] ?? record.__typename;
325
- const types = paths.get(path) ?? /* @__PURE__ */ new Set();
326
- types.add(typeof type === "string" ? type : "*");
327
- paths.set(path, types);
328
- }
329
- walk(item, path);
330
- }
331
- return;
332
- }
333
- if (!value || typeof value !== "object") return;
334
- for (const [key, child] of Object.entries(value)) {
335
- if (key !== PREPR_CONTEXT_ALIAS && key !== PREPR_TYPE_ALIAS)
336
- walk(child, path ? `${path}.${key}` : key);
337
- }
338
- };
339
- walk(data, "");
340
- return paths;
341
- }
342
- function contextOf(item) {
343
- if (!item || typeof item !== "object") return null;
344
- const context = item[PREPR_CONTEXT_ALIAS];
345
- const ctx = context;
346
- return ctx?.kind && ctx.group_id ? ctx : null;
347
- }
348
- function decisionsFrom(data) {
349
- const decisions = /* @__PURE__ */ new Map();
350
- const walk = (value) => {
351
- if (Array.isArray(value)) return value.forEach(walk);
352
- if (!value || typeof value !== "object") return;
353
- const ctx = contextOf(value);
354
- if (ctx?.group_id && ctx.variant_id) {
355
- const ids = decisions.get(ctx.group_id) ?? [];
356
- if (!ids.includes(ctx.variant_id)) ids.push(ctx.variant_id);
357
- decisions.set(ctx.group_id, ids);
358
- }
359
- Object.values(value).forEach(walk);
360
- };
361
- walk(data);
362
- return decisions;
363
- }
364
- function chosenVariants(ctx, options) {
365
- const decided = options.decisions?.get(ctx.group_id);
366
- if (ctx.kind === "AB_TEST") {
367
- return options.bucket ? [options.bucket] : decided ?? ["A"];
368
- }
369
- return decided ?? [PREPR_DEFAULT_VARIANT];
370
- }
371
- function resolveVariants(data, options = {}) {
372
- const resolve = (value) => {
373
- if (Array.isArray(value)) {
374
- return value.filter((item) => {
375
- const ctx = contextOf(item);
376
- return !ctx || chosenVariants(ctx, options).includes(ctx.variant_id ?? "");
377
- }).map(resolve);
378
- }
379
- if (!value || typeof value !== "object") return value;
380
- const out = {};
381
- for (const [key, child] of Object.entries(value)) out[key] = resolve(child);
382
- return out;
383
- };
384
- return resolve(data);
385
- }
386
-
387
- // src/core/variants/schema.ts
388
- var PREPR_SCHEMA_QUERY = `query PreprPersonalizationSchema {
389
- __schema {
390
- queryType { name }
391
- types {
392
- name
393
- possibleTypes { name }
394
- fields {
395
- name
396
- args { name }
397
- type { name ofType { name ofType { name ofType { name ofType { name } } } } }
398
- }
399
- }
400
- }
401
- }`;
402
- function namedType(ref) {
403
- let current = ref;
404
- while (current && !current.name) current = current.ofType;
405
- return current?.name ?? "";
406
- }
407
- function toSchemaInfo(introspection) {
408
- const types = {};
409
- for (const type of introspection.__schema.types) {
410
- if (type.name.startsWith("__")) continue;
411
- const fields = {};
412
- for (const field of type.fields ?? []) {
413
- fields[field.name] = {
414
- type: namedType(field.type),
415
- personalizable: field.args.some((arg) => arg.name === "personalize")
416
- };
417
- }
418
- types[type.name] = {
419
- fields,
420
- possibleTypes: (type.possibleTypes ?? []).map((t) => t.name),
421
- hasContext: "_context" in fields
422
- };
423
- }
424
- return { queryType: introspection.__schema.queryType.name, types };
425
- }
426
-
427
- // src/core/variants/stack.ts
428
- function containsKind(value, kind) {
429
- if (Array.isArray(value))
430
- return value.some((item) => containsKind(item, kind));
431
- if (!value || typeof value !== "object") return false;
432
- if (contextOf(value)?.kind === kind) return true;
433
- return Object.values(value).some((child) => containsKind(child, kind));
434
- }
435
- function splitStack(items) {
436
- const blocks = [];
437
- let position = 0;
438
- const positionsOf = (block) => block.key.startsWith("group:") ? 1 : block.items.length;
439
- items.forEach((item, index) => {
440
- const ctx = contextOf(item);
441
- const groupKey = ctx ? `group:${ctx.group_id}` : null;
442
- const personalized = containsKind(item, "PERSONALIZATION");
443
- const abTest = containsKind(item, "AB_TEST");
444
- const last = blocks.at(-1);
445
- const plain = !groupKey && !personalized && !abTest;
446
- if (groupKey && last?.key === groupKey) {
447
- last.personalized || (last.personalized = personalized);
448
- last.abTest || (last.abTest = abTest);
449
- last.items.push(item);
450
- } else if (plain && last && !last.personalized && !last.abTest) {
451
- last.items.push(item);
452
- } else {
453
- const last2 = blocks.at(-1);
454
- if (last2) position = last2.index + positionsOf(last2);
455
- blocks.push({
456
- key: groupKey ?? `items:${index}`,
457
- items: [item],
458
- index: position,
459
- personalized,
460
- abTest
461
- });
462
- }
463
- });
464
- return blocks;
465
- }
466
-
467
- // src/core/variants/tracking.ts
468
- function preprVariantProps(item) {
469
- const key = contextOf(item)?.variant_key;
470
- return key ? { "data-prepr-variant-key": key } : {};
471
- }
472
-
473
- // src/core/variants/variants-document.ts
474
- function variantsSelectionSet(set, typeName, schema) {
475
- const selections = set.selections.map((selection) => {
476
- if (selection.kind === "InlineFragment") {
477
- return {
478
- ...selection,
479
- selectionSet: variantsSelectionSet(
480
- selection.selectionSet,
481
- selection.typeCondition?.name.value ?? typeName,
482
- schema
483
- )
484
- };
485
- }
486
- if (selection.kind !== "Field" || !selection.selectionSet) return selection;
487
- const field = schema.types[typeName]?.fields[selection.name.value];
488
- if (!field) return selection;
489
- const child = variantsSelectionSet(
490
- selection.selectionSet,
491
- field.type,
492
- schema
493
- );
494
- if (!field.personalizable) return { ...selection, selectionSet: child };
495
- return {
496
- ...selection,
497
- arguments: [
498
- ...withoutPersonalizeArg(selection.arguments),
499
- {
500
- kind: "Argument",
501
- name: name("personalize"),
502
- value: { kind: "BooleanValue", value: false }
503
- }
504
- ],
505
- selectionSet: selectionSet([
506
- ...child.selections,
507
- ...contextSelections(field.type, schema)
508
- ])
509
- };
510
- });
511
- return { ...set, selections };
512
- }
513
- function toVariantsDocument(document2, schema) {
514
- const doc = documentOf(document2);
515
- return {
516
- ...doc,
517
- definitions: doc.definitions.map((definition) => {
518
- if (definition.kind === "OperationDefinition") {
519
- return {
520
- ...definition,
521
- selectionSet: variantsSelectionSet(
522
- definition.selectionSet,
523
- schema.queryType,
524
- schema
525
- )
526
- };
527
- }
528
- if (definition.kind === "FragmentDefinition") {
529
- return {
530
- ...definition,
531
- selectionSet: variantsSelectionSet(
532
- definition.selectionSet,
533
- definition.typeCondition.name.value,
534
- schema
535
- )
536
- };
537
- }
538
- return definition;
539
- })
540
- };
541
- }
542
-
543
- // src/core/graphql/document.ts
544
- import { print } from "graphql/language/printer.js";
545
- import { stripIgnoredCharacters } from "graphql/utilities/stripIgnoredCharacters.js";
546
- var printed = /* @__PURE__ */ new WeakMap();
547
- function isDocumentNode(value) {
548
- return typeof value === "object" && value !== null && value.kind === "Document" && Array.isArray(value.definitions);
549
- }
550
- function invalidDocument(originalError) {
551
- return new PreprError(
552
- "Expected a GraphQL query string, TypedDocumentString or DocumentNode",
553
- "INVALID_DOCUMENT",
554
- "createPreprClient",
555
- originalError
556
- );
557
- }
558
- var minified = /* @__PURE__ */ new Map();
559
- var MINIFIED_CACHE_LIMIT = 500;
560
- function minify(query) {
561
- const cached = minified.get(query);
562
- if (cached !== void 0) return cached;
563
- let result = query;
564
- try {
565
- result = stripIgnoredCharacters(query);
566
- } catch {
567
- }
568
- if (minified.size < MINIFIED_CACHE_LIMIT) minified.set(query, result);
569
- return result;
570
- }
571
- function resolveQuery(document2) {
572
- if (typeof document2 === "string") return minify(document2);
573
- if (document2 instanceof String) return minify(document2.toString());
574
- if (!isDocumentNode(document2)) throw invalidDocument();
575
- let query = printed.get(document2);
576
- if (query === void 0) {
577
- try {
578
- query = minify(print(document2));
579
- } catch (error) {
580
- throw invalidDocument(error instanceof Error ? error : void 0);
581
- }
582
- printed.set(document2, query);
583
- }
584
- return query;
585
- }
586
-
587
- // src/core/variants/queries.ts
588
- function toVariantsQuery(document2, schema) {
589
- return resolveQuery(toVariantsDocument(document2, schema));
590
- }
591
- function toDecisionQuery(document2, schema, options = {}) {
592
- const paths = options.from === void 0 ? void 0 : personalizationPaths(options.from);
593
- if (paths && paths.size === 0) return null;
594
- const decision = toDecisionDocument(document2, schema, paths, {
595
- topLevelOnly: !paths && options.topLevelOnly
596
- });
597
- return decision ? resolveQuery(decision) : null;
598
- }
599
-
600
- // src/core/graphql/transport.ts
601
- import { VERCEL_STEGA_REGEX } from "@vercel/stega";
602
-
603
- // src/core/stega/clean.ts
604
- import { vercelStegaClean, vercelStegaDecode } from "@vercel/stega";
605
-
606
- // src/core/utils.ts
607
- var DebugLogger = class {
608
- constructor(options) {
609
- this.options = {
610
- prefix: "[Prepr]",
611
- ...options
612
- };
613
- }
614
- // A local `enabled` wins; otherwise defer to the global logger so scoped
615
- // loggers created before initDebugLogger() still pick up the setting.
616
- isEnabled() {
617
- if (this.options.enabled !== void 0) {
618
- return this.options.enabled;
619
- }
620
- return globalDebugLogger?.options?.enabled ?? false;
621
- }
622
- log(message, ...args) {
623
- if (!this.isEnabled()) return;
624
- const prefix = this.options.prefix;
625
- console.log(`${prefix} ${message}`, ...args);
626
- }
627
- warn(message, ...args) {
628
- if (!this.isEnabled()) return;
629
- const prefix = this.options.prefix;
630
- console.warn(`${prefix} ${message}`, ...args);
631
- }
632
- error(message, ...args) {
633
- if (!this.isEnabled()) return;
634
- const prefix = this.options.prefix;
635
- console.error(`${prefix} ${message}`, ...args);
636
- }
637
- };
638
- var globalDebugLogger = null;
639
- function createScopedLogger(scopeName) {
640
- return new DebugLogger({
641
- prefix: `[Prepr][${scopeName}]`
642
- });
643
- }
644
-
645
- // src/core/stega/clean.ts
646
- var debug = createScopedLogger("stega:clean");
647
- function stegaClean(text) {
648
- if (!text) return text;
649
- return vercelStegaClean(text);
650
- }
651
-
652
- // src/core/graphql/transport.ts
653
- var OPERATION_NAME = /\b(?:query|mutation|subscription)\s+([_A-Za-z][_0-9A-Za-z]*)/;
654
- var STEGA_RAW = new RegExp(
655
- VERCEL_STEGA_REGEX.source,
656
- VERCEL_STEGA_REGEX.flags.replace("g", "")
657
- );
658
- var STEGA_ESCAPED = /\\u(?:200[bcd]|206[0-3]|feff|d834)/i;
659
- var URL_KEY = /(url|slug|link|href)$/i;
660
- var FASTLY_QUERY_MAX = 96 * 1024;
661
- function base64(text) {
662
- const bytes = new TextEncoder().encode(text);
663
- let binary = "";
664
- for (let i = 0; i < bytes.length; i += 32768) {
665
- binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
666
- }
667
- return btoa(binary);
668
- }
669
- function cacheInit(init, noStore) {
670
- const result = { ...init };
671
- if (noStore) {
672
- result.cache = "no-store";
673
- delete result.next;
674
- }
675
- return result;
676
- }
677
- function isFrameworkSignal(error) {
678
- return typeof error === "object" && error !== null && typeof error.digest === "string";
679
- }
680
- function mergePreprHeaders(base, extra) {
681
- const merged = new Headers(base);
682
- new Headers(extra).forEach((value, key) => {
683
- merged.set(key, value);
684
- });
685
- return merged;
686
- }
687
- function cleanEveryString(_key, value) {
688
- return typeof value === "string" ? stegaClean(value) : value;
689
- }
690
- function cleanUrlStrings(key, value) {
691
- return typeof value === "string" && URL_KEY.test(key) ? stegaClean(value) : value;
692
- }
693
- function parseBody(text, stega) {
694
- if (stega === "none" || !(STEGA_RAW.test(text) || STEGA_ESCAPED.test(text))) {
695
- return JSON.parse(text);
696
- }
697
- return JSON.parse(text, stega === "all" ? cleanEveryString : cleanUrlStrings);
698
- }
699
- function createTransport(options) {
700
- const { url, preview = false } = options;
701
- const stega = options.stega ?? (preview ? "urls" : "all");
702
- const clientHeaders = new Headers(options.headers);
703
- return async (document2, variables, queryOptions = {}) => {
704
- const query = resolveQuery(document2);
705
- const operation = OPERATION_NAME.exec(query)?.[1] ?? "anonymous";
706
- const headers = new Headers(clientHeaders);
707
- for (const layer of [queryOptions.init?.headers, queryOptions.headers]) {
708
- new Headers(layer).forEach((value, key) => {
709
- headers.set(key, value);
710
- });
711
- }
712
- headers.set("Content-Type", "application/json");
713
- const perRequestHeaders = queryOptions.headers !== void 0 || queryOptions.init?.headers !== void 0;
714
- const payload = JSON.stringify({ query, variables });
715
- const fastly = options.fastlyQuery ? base64(payload) : null;
716
- const viaGet = fastly !== null && fastly.length <= FASTLY_QUERY_MAX;
717
- if (viaGet) headers.set("Fastly-Query", fastly);
718
- const init = {
719
- ...cacheInit(queryOptions.init, preview || perRequestHeaders),
720
- method: viaGet ? "GET" : "POST",
721
- headers,
722
- body: viaGet ? void 0 : payload
723
- };
724
- const fetchImpl = queryOptions.fetch ?? options.fetch;
725
- let response;
726
- try {
727
- response = await (fetchImpl ? fetchImpl(url, init) : fetch(url, init));
728
- } catch (error) {
729
- if (isFrameworkSignal(error)) throw error;
730
- throw new PreprError(
731
- `Prepr GraphQL request failed for ${operation}`,
732
- "FETCH_ERROR",
733
- operation,
734
- error instanceof Error ? error : void 0
735
- );
736
- }
737
- if (!response.ok) {
738
- throw new PreprError(
739
- `Prepr GraphQL HTTP ${response.status} for ${operation}${response.status === 412 ? " (Prepr rejects queries longer than 27,500 characters)" : ""}`,
740
- "HTTP_ERROR",
741
- operation
742
- );
743
- }
744
- let body;
745
- try {
746
- body = parseBody(await response.text(), stega);
747
- } catch (error) {
748
- throw new PreprError(
749
- `Prepr GraphQL response for ${operation} is not valid JSON`,
750
- "INVALID_RESPONSE",
751
- operation,
752
- error instanceof Error ? error : void 0
753
- );
754
- }
755
- if (typeof body !== "object" || body === null) {
756
- throw new PreprError(
757
- `Prepr GraphQL response for ${operation} is not an object`,
758
- "INVALID_RESPONSE",
759
- operation
760
- );
761
- }
762
- const { data, errors } = body;
763
- if (Array.isArray(errors) && errors.length > 0) {
764
- const messages = errors.map((e) => String(e?.message ?? "Unknown error")).join("; ");
765
- throw new PreprError(
766
- `Prepr GraphQL errors for ${operation}: ${messages}`,
767
- "GRAPHQL_ERROR",
768
- operation
769
- );
770
- }
771
- if (data === null || data === void 0) {
772
- throw new PreprError(
773
- `Prepr GraphQL response for ${operation} has no data`,
774
- "INVALID_RESPONSE",
775
- operation
776
- );
777
- }
778
- return { data, personalized: isPersonalizedResponse(response) };
779
- };
780
- }
781
-
782
- // src/core/graphql/probe.ts
783
- var AB_TEST_VARY = /\bPrepr-ABTesting/i;
784
- var SEGMENTS_VARY = /\bPrepr-Segments/i;
785
- var AB_CHECK_TTL_MS = 6e4;
786
- var AB_CHECK_MAX_ENTRIES = 1e3;
787
- function createVaryProbe(run, options) {
788
- const abProbes = /* @__PURE__ */ new Map();
789
- const abChecks = /* @__PURE__ */ new Map();
790
- return (document2, variables) => {
791
- const key = JSON.stringify(variables ?? null);
792
- let answers = abChecks.get(document2);
793
- if (!answers) {
794
- answers = /* @__PURE__ */ new Map();
795
- abChecks.set(document2, answers);
796
- }
797
- const cached = answers.get(key);
798
- if (cached && Date.now() - cached.at < AB_CHECK_TTL_MS) return cached.value;
799
- const value = (async () => {
800
- let probe = abProbes.get(document2);
801
- if (probe === void 0) {
802
- probe = toAbProbeDocument(document2);
803
- abProbes.set(document2, probe);
804
- }
805
- if (!probe) return "";
806
- let vary = "";
807
- const send = options.fetch ?? fetch;
808
- await run(probe, variables, {
809
- fetch: async (input, init) => {
810
- const response = await send(input, init);
811
- vary = response.headers.get("vary") ?? "";
812
- return response;
813
- }
814
- });
815
- return vary;
816
- })().catch((error) => {
817
- if (isFrameworkSignal(error)) throw error;
818
- answers.delete(key);
819
- return null;
820
- });
821
- if (answers.size >= AB_CHECK_MAX_ENTRIES) {
822
- answers.delete(answers.keys().next().value);
823
- }
824
- answers.set(key, { value, at: Date.now() });
825
- return value;
826
- };
827
- }
828
-
829
- // src/core/graphql/client.ts
830
- var clientSchemas = /* @__PURE__ */ new WeakMap();
831
- function isParseableUrl(url) {
832
- try {
833
- new URL(url);
834
- return true;
835
- } catch {
836
- return false;
837
- }
838
- }
839
- function assertPreprUrl(url, source) {
840
- validatePreprToken(url);
841
- if (!isParseableUrl(url)) {
842
- throw new PreprError(
843
- "Prepr GraphQL URL is not a valid URL",
844
- "INVALID_TOKEN",
845
- source
846
- );
847
- }
848
- }
849
- function createPreprClient(options) {
850
- assertPreprUrl(options.url, "createPreprClient");
851
- const run = createTransport(options);
852
- const probeVary = createVaryProbe(run, options);
853
- let schema;
854
- const loadSchema = () => schema ?? (schema = run(
855
- PREPR_SCHEMA_QUERY,
856
- void 0,
857
- { init: options.schemaInit }
858
- ).then(
859
- (result) => toSchemaInfo(result.data),
860
- (error) => {
861
- schema = void 0;
862
- throw error;
863
- }
864
- ));
865
- const variantsDocuments = /* @__PURE__ */ new Map();
866
- const decisionDocuments = /* @__PURE__ */ new Map();
867
- const client = {
868
- async query(document2, variables, queryOptions = {}) {
869
- const { variants, ...rest } = queryOptions;
870
- if (!variants) return run(document2, variables, rest);
871
- let derived = variantsDocuments.get(document2);
872
- if (!derived) {
873
- derived = toVariantsDocument(document2, await loadSchema());
874
- variantsDocuments.set(document2, derived);
875
- }
876
- return run(derived, variables, rest);
877
- },
878
- async decide(document2, variables, queryOptions = {}) {
879
- const { from, ...rest } = queryOptions;
880
- const paths = from === void 0 ? void 0 : personalizationPaths(from);
881
- if (paths && paths.size === 0) return /* @__PURE__ */ new Map();
882
- const signature = paths ? [...paths].map(([path, types]) => `${path}:${[...types].sort().join(",")}`).sort().join("|") : "*";
883
- let byPaths = decisionDocuments.get(document2);
884
- if (!byPaths) {
885
- byPaths = /* @__PURE__ */ new Map();
886
- decisionDocuments.set(document2, byPaths);
887
- }
888
- let derived = byPaths.get(signature);
889
- if (derived === void 0) {
890
- derived = toDecisionDocument(document2, await loadSchema(), paths);
891
- byPaths.set(signature, derived);
892
- }
893
- if (!derived) return /* @__PURE__ */ new Map();
894
- const { data } = await run(derived, variables, rest);
895
- return decisionsFrom(data);
896
- },
897
- hasAbTests: (document2, variables) => probeVary(document2, variables).then(
898
- (vary) => vary === null || AB_TEST_VARY.test(vary)
899
- ),
900
- hasSegments: (document2, variables) => probeVary(document2, variables).then(
901
- (vary) => vary === null || SEGMENTS_VARY.test(vary)
902
- )
903
- };
904
- clientSchemas.set(client, loadSchema);
905
- return client;
906
- }
907
-
908
- // src/core/graphql/schema-loader.ts
909
- var schemas = /* @__PURE__ */ new Map();
910
- async function loadPreprSchema(url, options = {}) {
911
- assertPreprUrl(url, "loadPreprSchema");
912
- let schema = schemas.get(url);
913
- if (!schema) {
914
- const run = createTransport({ url, fetch: options.fetch, stega: "none" });
915
- schema = run(
916
- PREPR_SCHEMA_QUERY
917
- ).then((result) => toSchemaInfo(result.data)).catch((error) => {
918
- schemas.delete(url);
919
- if (error instanceof PreprError) throw error;
920
- throw new PreprError(
921
- "Prepr schema response is not an introspection result",
922
- "INVALID_RESPONSE",
923
- "loadPreprSchema",
924
- error instanceof Error ? error : void 0
925
- );
926
- });
927
- schemas.set(url, schema);
928
- }
929
- return schema;
930
- }
931
-
932
- // src/nextjs/decisions.ts
933
- var PREPR_DECIDE_HEADER = "Prepr-Decide";
934
- var DEFAULT_DECISION = "*";
935
- var DECISIONS_MAX_GROUPS = 40;
936
- var SAFE_ID = /^[\w-]+$/;
937
- function serializeDecisions(decisions) {
938
- return [...decisions].filter(([group]) => SAFE_ID.test(group)).slice(0, DECISIONS_MAX_GROUPS).map(
939
- ([group, variants]) => `${group}:${variants.filter((v) => SAFE_ID.test(v)).join("|")}`
940
- ).join("~");
941
- }
942
- function forwardedHeaders(request, response) {
943
- const overridden = response.headers.get("x-middleware-override-headers");
944
- if (!overridden) return getPreprHeadersFromHeaders(request.headers);
945
- const headers = new Headers();
946
- for (const name2 of overridden.split(",")) {
947
- const value = response.headers.get(`x-middleware-request-${name2.trim()}`);
948
- if (value !== null) headers.set(name2.trim(), value);
949
- }
950
- return getPreprHeadersFromHeaders(headers);
951
- }
952
- var preprClientInternals = /* @__PURE__ */ new WeakMap();
953
- async function decideView(client, headers, page, timeoutMs = 3e3) {
954
- const init = { signal: AbortSignal.timeout(timeoutMs) };
955
- try {
956
- const decided = page.decision ? decisionsFrom(
957
- (await client.query(page.decision, page.variables, { headers, init })).data
958
- ) : await client.decide(page.document, page.variables, { headers, init });
959
- return serializeDecisions(decided);
960
- } catch (error) {
961
- if (isFrameworkSignal(error)) throw error;
962
- return DEFAULT_DECISION;
963
- }
964
- }
965
-
966
- // src/nextjs/proxy.ts
967
- import { NextResponse } from "next/server";
968
- function isPagePath(pathname) {
969
- return !pathname.startsWith("/_next/") && !pathname.startsWith("/api/") && !/\.[^/]*$/.test(pathname);
970
- }
971
- function createPreprProxy(options) {
972
- const internals = preprClientInternals.get(options.client);
973
- if (!internals) {
974
- throw new PreprError(
975
- "createPreprProxy needs a client made by createPreprClient from @preprio/toolkit/nextjs/graphql",
976
- "CONTEXT_ERROR",
977
- "createPreprProxy"
978
- );
979
- }
980
- const { client } = internals;
981
- const preview = options.preview ?? false;
982
- const allowed = async (request) => {
983
- if (!options.onlyIf) return true;
984
- try {
985
- return await options.onlyIf(request);
986
- } catch {
987
- return false;
988
- }
989
- };
990
- const lookup = (target) => {
991
- try {
992
- return options.page(target) ?? null;
993
- } catch {
994
- return null;
995
- }
996
- };
997
- async function answerDecision(request, response, target) {
998
- let decision = DEFAULT_DECISION;
999
- const site = request.headers.get("sec-fetch-site");
1000
- if (target && request.method === "GET" && (site === null || site === "same-origin") && await allowed(request)) {
1001
- decision = await decideView(
1002
- client,
1003
- mergePreprHeaders(forwardedHeaders(request, response)),
1004
- target,
1005
- options.timeoutMs
1006
- );
1007
- }
1008
- const answer = new NextResponse(decision, {
1009
- headers: {
1010
- "Cache-Control": "private, no-store",
1011
- "Content-Type": "text/plain; charset=utf-8"
1012
- }
1013
- });
1014
- for (const cookie of response.cookies.getAll()) answer.cookies.set(cookie);
1015
- return answer;
1016
- }
1017
- return async (request) => {
1018
- const rendersPage = (request.method === "GET" || request.method === "HEAD") && isPagePath(request.nextUrl.pathname);
1019
- const target = rendersPage ? lookup(request.nextUrl) : null;
1020
- const decisionRequest = request.headers.has(PREPR_DECIDE_HEADER);
1021
- if (target && preview && !decisionRequest) {
1022
- const draft = preprDraftRedirect(request, { preview });
1023
- if (draft) return draft;
1024
- }
1025
- const response = createPreprMiddleware(request, {
1026
- preview,
1027
- features: options.features
1028
- });
1029
- if (decisionRequest) return answerDecision(request, response, target);
1030
- return response;
1031
- };
1032
- }
1033
-
1034
- // src/nextjs/stack.ts
1035
- import {
1036
- createElement,
1037
- Fragment
1038
- } from "react";
1039
-
1040
- // src/nextjs/decision-switch.ts
1041
- function applyPreprDecisions(decision, options = {}) {
1042
- const state = window;
1043
- const key = location.pathname + location.search;
1044
- const previous = state.__preprDecision;
1045
- let value = decision;
1046
- if (value !== void 0 && value !== "*" && options.refresh && previous && previous.key === key && previous.value !== "*") {
1047
- const pairs = (from) => {
1048
- const out = {};
1049
- from.split("~").forEach((pair) => {
1050
- const colon = pair.indexOf(":");
1051
- if (colon > 0) out[pair.slice(0, colon)] = pair;
1052
- });
1053
- return out;
1054
- };
1055
- const before = pairs(previous.value);
1056
- const after = pairs(value);
1057
- document.querySelectorAll("[data-prepr-v][data-prepr-show]").forEach((element) => {
1058
- const range = document.createRange();
1059
- range.selectNodeContents(element);
1060
- if (range.getBoundingClientRect().top >= window.innerHeight) return;
1061
- (element.getAttribute("data-prepr-v") || "").split(" ").forEach((token) => {
1062
- const group = token.slice(0, token.indexOf(":"));
1063
- if (before[group]) after[group] = before[group];
1064
- });
1065
- });
1066
- value = Object.keys(after).map((group) => after[group]).join("~");
1067
- }
1068
- if (value !== void 0) state.__preprDecision = { key, value };
1069
- const current = state.__preprDecision;
1070
- if (!current || current.key !== key) return false;
1071
- document.querySelectorAll("[data-prepr-decision]").forEach((marker) => {
1072
- marker.setAttribute("data-prepr-decided", "");
1073
- });
1074
- const defaults = current.value === "*";
1075
- const chosen = {};
1076
- current.value.split("~").forEach((pair) => {
1077
- const colon = pair.indexOf(":");
1078
- if (colon > 0)
1079
- chosen[pair.slice(0, colon)] = pair.slice(colon + 1).split("|");
1080
- });
1081
- document.querySelectorAll("[data-prepr-v]").forEach((element) => {
1082
- const nested = element.hasAttribute("data-prepr-nested");
1083
- const show = defaults ? element.hasAttribute("data-prepr-default") : (element.getAttribute("data-prepr-v") || "").split(" ").every((token) => {
1084
- const colon = token.indexOf(":");
1085
- const variant = token.slice(colon + 1);
1086
- const variants = chosen[token.slice(0, colon)];
1087
- return !!variants && (nested ? variants[0] === variant : variants.indexOf(variant) >= 0);
1088
- });
1089
- if (show) element.setAttribute("data-prepr-show", "");
1090
- else element.removeAttribute("data-prepr-show");
1091
- });
1092
- return true;
1093
- }
1094
- function requestPreprDecision(key, options = {}) {
1095
- const fresh = 1e4;
1096
- const keep = 18e5;
1097
- const keepStatic = 36e5;
1098
- const state = window;
1099
- const asking = state.__preprAsking = state.__preprAsking || {};
1100
- const read = () => {
1101
- try {
1102
- const all = JSON.parse(sessionStorage.getItem("prepr_decisions") || "{}");
1103
- return all && typeof all === "object" ? all : {};
1104
- } catch {
1105
- return {};
1106
- }
1107
- };
1108
- const ask = () => {
1109
- if (!asking[key]) {
1110
- asking[key] = fetch(key, {
1111
- headers: { "Prepr-Decide": "1" },
1112
- cache: "no-store",
1113
- credentials: "same-origin",
1114
- // The proxy gives up on Prepr after its own `timeoutMs`; this only
1115
- // covers a proxy that never answers.
1116
- signal: AbortSignal.timeout ? AbortSignal.timeout(6e3) : void 0
1117
- }).then((response) => response.ok ? response.text() : "*").catch(() => "*").then((answer) => {
1118
- delete asking[key];
1119
- try {
1120
- const all = read();
1121
- const at = Date.now();
1122
- Object.keys(all).forEach((stored) => {
1123
- const entry = all[stored];
1124
- if (!(entry && typeof entry.at === "number" && at - entry.at < keepStatic))
1125
- delete all[stored];
1126
- });
1127
- const kept = all[key];
1128
- if (answer !== "*" || !kept || kept.value === "*")
1129
- all[key] = { value: answer, at };
1130
- sessionStorage.setItem("prepr_decisions", JSON.stringify(all));
1131
- } catch {
1132
- }
1133
- return answer;
1134
- });
1135
- }
1136
- return asking[key];
1137
- };
1138
- const last = read()[key];
1139
- const age = last && typeof last.at === "number" ? Date.now() - last.at : -1;
1140
- const value = last && typeof last.value === "string" ? last.value : null;
1141
- if (value !== null && !(value === "" && options.personalized) && age >= 0 && age < (value === "*" ? fresh : value === "" ? keepStatic : keep)) {
1142
- if (value !== "" && age >= fresh) {
1143
- ask().then((answer) => {
1144
- if (answer !== "*" && answer !== value && options.onChange)
1145
- options.onChange(answer);
1146
- });
1147
- }
1148
- return { result: value, value: Promise.resolve(value) };
1149
- }
1150
- const pending = {
1151
- value: ask()
1152
- };
1153
- pending.value.then((answer) => {
1154
- pending.result = answer;
1155
- });
1156
- return pending;
1157
- }
1158
- function startPreprDecision() {
1159
- const state = window;
1160
- const key = location.pathname + location.search;
1161
- const apply = (answer, refresh) => {
1162
- if (location.pathname + location.search === key)
1163
- state.__preprApply(answer, { refresh });
1164
- };
1165
- const pending = state.__preprRequest(key, {
1166
- onChange: (answer) => apply(answer, true),
1167
- personalized: true
1168
- });
1169
- if (pending.result !== void 0) apply(pending.result);
1170
- else pending.value.then((answer) => apply(answer));
1171
- }
1172
-
1173
- // src/nextjs/stack.ts
1174
- import { PreprDecisionApplier, PreprVariantTracking } from "./components.js";
1175
- var VARIANT_ATTRIBUTE = "data-prepr-v";
1176
- var DEFAULT_ATTRIBUTE = "data-prepr-default";
1177
- var NESTED_ATTRIBUTE = "data-prepr-nested";
1178
- var GROUP_BASE_CSS = `[${VARIANT_ATTRIBUTE}]{display:none}[${VARIANT_ATTRIBUTE}][data-prepr-show]{display:contents}[data-prepr-decision]:not([data-prepr-decided])~[${VARIANT_ATTRIBUTE}][${DEFAULT_ATTRIBUTE}]{display:contents;visibility:hidden}`;
1179
- var NOSCRIPT_HTML = `<style>[${VARIANT_ATTRIBUTE}][${DEFAULT_ATTRIBUTE}]{display:contents!important;visibility:visible!important}</style>`;
1180
- var DECISION_SCRIPT = `window.__preprApply=${applyPreprDecisions.toString()};window.__preprRequest=${requestPreprDecision.toString()};(${startPreprDecision.toString()})();`;
1181
- var APPLY_SCRIPT = "__preprApply()";
1182
- function variantKeysOf(items) {
1183
- return items.flatMap((item) => {
1184
- const key = preprVariantProps(item)["data-prepr-variant-key"] ?? nestedKeyOf(item);
1185
- return key ? [key] : [];
1186
- });
1187
- }
1188
- function nestedKeyOf(value) {
1189
- if (!value || typeof value !== "object") return void 0;
1190
- for (const child of Object.values(value)) {
1191
- const items = Array.isArray(child) ? child : [child];
1192
- for (const item of items) {
1193
- const key = contextOf(item)?.variant_key ?? (item && nestedKeyOf(item));
1194
- if (key) return key;
1195
- }
1196
- }
1197
- return void 0;
1198
- }
1199
- function renderItems(items, render, options) {
1200
- const resolved = resolveVariants(items, {
1201
- decisions: options.decisions,
1202
- bucket: options.bucket
1203
- });
1204
- const content = render(resolved, {
1205
- index: options.index,
1206
- defaultVariant: options.defaultVariant
1207
- });
1208
- const variantKeys = options.track ? variantKeysOf(resolved) : [];
1209
- return variantKeys.length > 0 ? createElement(PreprVariantTracking, { variantKeys }, content) : content;
1210
- }
1211
- function decidedGroups(items, bucket) {
1212
- const groups = /* @__PURE__ */ new Map();
1213
- const walk = (value) => {
1214
- if (Array.isArray(value)) return value.forEach(walk);
1215
- if (!value || typeof value !== "object") return;
1216
- const ctx = contextOf(value);
1217
- const decided = ctx?.kind === "PERSONALIZATION" || ctx?.kind === "AB_TEST" && !bucket;
1218
- if (decided && ctx.variant_id) {
1219
- const group = groups.get(ctx.group_id) ?? {
1220
- variants: /* @__PURE__ */ new Set(),
1221
- fallback: ctx.kind === "AB_TEST" ? "A" : PREPR_DEFAULT_VARIANT
1222
- };
1223
- group.variants.add(ctx.variant_id);
1224
- groups.set(ctx.group_id, group);
1225
- }
1226
- Object.values(value).forEach(walk);
1227
- };
1228
- walk(items);
1229
- return groups;
1230
- }
1231
- function renderVariants(block, groups, render, options) {
1232
- const top = block.key.startsWith("group:") ? block.key.slice("group:".length) : void 0;
1233
- const nested = !(top !== void 0 && groups.size === 1);
1234
- const choices = [...groups].map(([group, { variants, fallback }]) => {
1235
- const ids = nested ? [fallback, ...variants] : [...variants];
1236
- return [...new Set(ids)].map((variant) => [group, variant]);
1237
- });
1238
- const combinations = choices.reduce(
1239
- (all, pairs) => all.flatMap((combo) => pairs.map((p) => [...combo, p])),
1240
- [[]]
1241
- );
1242
- return combinations.map((combination) => {
1243
- const pairs = combination.map(([group, variant]) => `${group}:${variant}`);
1244
- const isDefault = combination.every(
1245
- ([group, variant]) => variant === groups.get(group).fallback
1246
- );
1247
- return createElement(
1248
- "div",
1249
- {
1250
- key: pairs.join(" "),
1251
- [VARIANT_ATTRIBUTE]: pairs.join(" "),
1252
- ...isDefault ? { [DEFAULT_ATTRIBUTE]: "" } : {},
1253
- ...nested ? { [NESTED_ATTRIBUTE]: "" } : {},
1254
- // The decision script marks the shown wrapper before hydration.
1255
- suppressHydrationWarning: true
1256
- },
1257
- renderItems(block.items, render, {
1258
- bucket: options.bucket,
1259
- decisions: new Map(combination.map(([g, v]) => [g, [v]])),
1260
- index: block.index,
1261
- track: options.track,
1262
- defaultVariant: isDefault
1263
- })
1264
- );
1265
- });
1266
- }
1267
- function PreprStack({
1268
- items,
1269
- render,
1270
- bucket,
1271
- nonce,
1272
- trackVariants = false
1273
- }) {
1274
- const blocks = splitStack(items).map((block) => ({
1275
- ...block,
1276
- groups: decidedGroups(block.items, bucket)
1277
- }));
1278
- const varies = blocks.some((block) => block.groups.size > 0);
1279
- return createElement(
1280
- Fragment,
1281
- null,
1282
- varies && createElement(
1283
- Fragment,
1284
- { key: "prepr-switch" },
1285
- createElement("style", {
1286
- nonce,
1287
- dangerouslySetInnerHTML: { __html: GROUP_BASE_CSS }
1288
- }),
1289
- createElement("noscript", {
1290
- dangerouslySetInnerHTML: { __html: NOSCRIPT_HTML }
1291
- }),
1292
- createElement("script", {
1293
- nonce,
1294
- dangerouslySetInnerHTML: { __html: DECISION_SCRIPT }
1295
- }),
1296
- createElement(PreprDecisionApplier),
1297
- // Marked decided by the decision switch; never laid out.
1298
- createElement("template", {
1299
- "data-prepr-decision": "",
1300
- suppressHydrationWarning: true
1301
- })
1302
- ),
1303
- ...blocks.map((block) => {
1304
- if (block.groups.size === 0) {
1305
- return createElement(
1306
- Fragment,
1307
- { key: block.key },
1308
- renderItems(block.items, render, {
1309
- bucket,
1310
- index: block.index,
1311
- track: trackVariants,
1312
- defaultVariant: true
1313
- })
1314
- );
1315
- }
1316
- return createElement(
1317
- Fragment,
1318
- { key: block.key },
1319
- renderVariants(block, block.groups, render, {
1320
- bucket,
1321
- track: trackVariants
1322
- }),
1323
- createElement("script", {
1324
- nonce,
1325
- dangerouslySetInnerHTML: { __html: APPLY_SCRIPT }
1326
- })
1327
- );
1328
- })
1329
- );
1330
- }
1331
-
1332
- // src/nextjs/graphql.ts
1333
- function createPreprClient2(options) {
1334
- const { cacheTags = ["prepr"], revalidate, ...coreOptions } = options;
1335
- const client = createPreprClient({
1336
- // The schema introspection goes through the Data Cache: shared across
1337
- // server instances, refreshed hourly and by a `schema.changed` webhook.
1338
- schemaInit: {
1339
- next: { tags: [...cacheTags, PREPR_SCHEMA_TAG], revalidate: 3600 }
1340
- },
1341
- ...coreOptions
1342
- });
1343
- const nextClient = {
1344
- async query(document2, variables, queryOptions = {}) {
1345
- const { personalize = false, tagItems = false, ...rest } = queryOptions;
1346
- const { next, ...init } = rest.init ?? {};
1347
- if (tagItems && typeof nextCache.cacheTag !== "function") {
1348
- throw new Error("tagItems requires Next.js 16 or later.");
1349
- }
1350
- const options2 = {
1351
- ...rest,
1352
- // With tagItems, `next` is dropped too: tags or revalidate alongside
1353
- // `no-store` are a conflict Next.js resolves by ignoring the store.
1354
- // Otherwise tags are attached unconditionally; the core client drops
1355
- // them again whenever the request ends up `no-store` (personalized,
1356
- // per-request headers, or preview).
1357
- init: tagItems ? { ...init, cache: "no-store" } : {
1358
- ...init,
1359
- next: {
1360
- ...revalidate === void 0 ? {} : { revalidate },
1361
- ...next,
1362
- // Merged, so a per-query tag never drops the client's own,
1363
- // which the publish webhook relies on.
1364
- tags: [...cacheTags, ...next?.tags ?? []]
1365
- }
1366
- }
1367
- };
1368
- if (personalize) {
1369
- options2.headers = mergePreprHeaders(
1370
- await getPreprHeaders(),
1371
- rest.headers
1372
- );
1373
- }
1374
- const result = await client.query(document2, variables, options2);
1375
- if (tagItems) {
1376
- let modelTags;
1377
- try {
1378
- modelTags = preprModelTagsFor(
1379
- documentOf(document2),
1380
- result.data,
1381
- await clientSchemas.get(client)()
1382
- );
1383
- } catch {
1384
- modelTags = [PREPR_ANY_ITEM_TAG];
1385
- }
1386
- nextCache.cacheTag(...cacheTags, ...next?.tags ?? [], ...modelTags);
1387
- nextCache.cacheTag(...preprCacheTags(result.data));
1388
- }
1389
- return result;
1390
- },
1391
- async decide(document2, variables, queryOptions = {}) {
1392
- return client.decide(document2, variables, {
1393
- ...queryOptions,
1394
- headers: mergePreprHeaders(
1395
- await getPreprHeaders(),
1396
- queryOptions.headers
1397
- )
1398
- });
1399
- },
1400
- hasAbTests: (document2, variables) => client.hasAbTests(document2, variables)
1401
- };
1402
- preprClientInternals.set(nextClient, { client });
1403
- return nextClient;
1404
- }
1405
- export {
1406
- PREPR_ANY_ITEM_TAG,
1407
- PREPR_DEFAULT_VARIANT,
1408
- PreprError,
1409
- PreprStack,
1410
- createPreprClient2 as createPreprClient,
1411
- createPreprProxy,
1412
- decisionsFrom,
1413
- isPersonalizedResponse,
1414
- loadPreprSchema,
1415
- preprCacheTags,
1416
- preprModelTag,
1417
- preprVariantProps,
1418
- resolveVariants,
1419
- splitStack,
1420
- toDecisionQuery,
1421
- toVariantsQuery
1422
- };