@preprio/toolkit 0.5.0-rc.2 → 0.6.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +415 -27
  2. package/dist/astro/chunk-O7N6GPAH.js +173 -0
  3. package/dist/astro/graphql.cjs +1030 -0
  4. package/dist/astro/graphql.d.cts +305 -0
  5. package/dist/astro/graphql.d.ts +305 -0
  6. package/dist/astro/graphql.js +936 -0
  7. package/dist/astro/index-XT_z-RYT.d.cts +130 -0
  8. package/dist/astro/index-XT_z-RYT.d.ts +130 -0
  9. package/dist/astro/index.cjs +14 -1
  10. package/dist/astro/index.d.cts +1 -120
  11. package/dist/astro/index.d.ts +1 -120
  12. package/dist/astro/index.js +15 -153
  13. package/dist/chunk-3JLWZQ37.js +179 -0
  14. package/dist/chunk-3NCEVJJ3.js +10 -0
  15. package/dist/chunk-S5RWVMDJ.js +148 -0
  16. package/dist/chunk-TBKSBXGH.js +452 -0
  17. package/dist/{chunk-FLPNN3CV.js → chunk-VI6QZTBM.js} +73 -276
  18. package/dist/chunk-YWIKKWBR.js +26 -0
  19. package/dist/graphql/codegen.cjs +510 -0
  20. package/dist/graphql/codegen.d.cts +23 -0
  21. package/dist/graphql/codegen.d.ts +23 -0
  22. package/dist/graphql/codegen.js +99 -0
  23. package/dist/graphql.cjs +941 -0
  24. package/dist/graphql.d.cts +305 -0
  25. package/dist/graphql.d.ts +305 -0
  26. package/dist/graphql.js +419 -0
  27. package/dist/index.cjs +76 -119
  28. package/dist/index.d.cts +12 -64
  29. package/dist/index.d.ts +12 -64
  30. package/dist/index.js +27 -167
  31. package/dist/nextjs/chunk-BQ6IGSH6.js +231 -0
  32. package/dist/nextjs/components.cjs +190 -122
  33. package/dist/nextjs/components.d.cts +33 -2
  34. package/dist/nextjs/components.d.ts +33 -2
  35. package/dist/nextjs/components.js +133 -4
  36. package/dist/nextjs/graphql.cjs +1362 -0
  37. package/dist/nextjs/graphql.d.cts +435 -0
  38. package/dist/nextjs/graphql.d.ts +435 -0
  39. package/dist/nextjs/graphql.js +1261 -0
  40. package/dist/nextjs/index.cjs +126 -6
  41. package/dist/nextjs/index.d.cts +53 -147
  42. package/dist/nextjs/index.d.ts +53 -147
  43. package/dist/nextjs/index.js +113 -203
  44. package/dist/nextjs/server-CjpELYvq.d.cts +156 -0
  45. package/dist/nextjs/server-CjpELYvq.d.ts +156 -0
  46. package/dist/nuxt/chunk-IQDSBPDN.js +417 -0
  47. package/dist/nuxt/graphql.cjs +1037 -0
  48. package/dist/nuxt/graphql.d.cts +302 -0
  49. package/dist/nuxt/graphql.d.ts +302 -0
  50. package/dist/nuxt/graphql.js +937 -0
  51. package/dist/nuxt/index.cjs +14 -1
  52. package/dist/nuxt/index.d.cts +3 -148
  53. package/dist/nuxt/index.d.ts +3 -148
  54. package/dist/nuxt/index.js +15 -391
  55. package/dist/nuxt/server-8v6OHbsw.d.cts +158 -0
  56. package/dist/nuxt/server-8v6OHbsw.d.ts +158 -0
  57. package/dist/pixel-DwW7cXJm.d.cts +49 -0
  58. package/dist/pixel-DwW7cXJm.d.ts +49 -0
  59. package/dist/react/components.cjs +88 -120
  60. package/dist/react/components.d.cts +2 -8
  61. package/dist/react/components.d.ts +2 -8
  62. package/dist/react/components.js +88 -120
  63. package/dist/server-Brr1UgtW.d.ts +59 -0
  64. package/dist/server-DJuS3YU0.d.cts +59 -0
  65. package/dist/sveltekit/chunk-OKYZ6HPH.js +413 -0
  66. package/dist/sveltekit/graphql.cjs +1043 -0
  67. package/dist/sveltekit/graphql.d.cts +307 -0
  68. package/dist/sveltekit/graphql.d.ts +307 -0
  69. package/dist/sveltekit/graphql.js +943 -0
  70. package/dist/sveltekit/index.cjs +14 -1
  71. package/dist/sveltekit/index.d.cts +3 -88
  72. package/dist/sveltekit/index.d.ts +3 -88
  73. package/dist/sveltekit/index.js +15 -387
  74. package/dist/sveltekit/server-CO847mEV.d.cts +98 -0
  75. package/dist/sveltekit/server-CO847mEV.d.ts +98 -0
  76. package/dist/{pixel-B3oQNbZ3.d.cts → types-BYH9XqmN.d.cts} +4 -58
  77. package/dist/{pixel-B3oQNbZ3.d.ts → types-BYH9XqmN.d.ts} +4 -58
  78. package/package.json +36 -1
@@ -0,0 +1,943 @@
1
+ import {
2
+ PreprError,
3
+ getPreprHeadersFromHeaders,
4
+ getPreprHeadersFromLocals,
5
+ isPersonalizedResponse,
6
+ validatePreprToken
7
+ } from "./chunk-OKYZ6HPH.js";
8
+
9
+ // src/core/variants/constants.ts
10
+ var PREPR_CONTEXT_ALIAS = "_preprContext";
11
+ var PREPR_TYPE_ALIAS = "_preprType";
12
+ var PREPR_DEFAULT_VARIANT = "ALL_OTHER_USERS";
13
+
14
+ // src/core/variants/ast.ts
15
+ import { parse } from "graphql/language/parser.js";
16
+ var name = (value) => ({ kind: "Name", value });
17
+ function selectionSet(selections) {
18
+ return { kind: "SelectionSet", selections };
19
+ }
20
+ function contextField(withKey) {
21
+ const fields = ["kind", "group_id", "variant_id"];
22
+ if (withKey) fields.push("variant_key");
23
+ return {
24
+ kind: "Field",
25
+ alias: name(PREPR_CONTEXT_ALIAS),
26
+ name: name("_context"),
27
+ selectionSet: selectionSet(
28
+ fields.map(
29
+ (field) => ({ kind: "Field", name: name(field) })
30
+ )
31
+ )
32
+ };
33
+ }
34
+ function typenameField() {
35
+ return {
36
+ kind: "Field",
37
+ alias: name(PREPR_TYPE_ALIAS),
38
+ name: name("__typename")
39
+ };
40
+ }
41
+ function inlineFragment(typeName, selections) {
42
+ return {
43
+ kind: "InlineFragment",
44
+ typeCondition: { kind: "NamedType", name: name(typeName) },
45
+ selectionSet: selectionSet(selections)
46
+ };
47
+ }
48
+ function contextSelections(typeName, schema, onlyTypes, withType = true) {
49
+ const fields = () => withType ? [contextField(true), typenameField()] : [contextField(false)];
50
+ const type = schema.types[typeName];
51
+ if (!type) return [];
52
+ if (type.possibleTypes.length > 0) {
53
+ return type.possibleTypes.filter(
54
+ (member) => schema.types[member]?.hasContext && (!onlyTypes || onlyTypes.has(member))
55
+ ).map((member) => inlineFragment(member, fields()));
56
+ }
57
+ return type.hasContext ? fields() : [];
58
+ }
59
+ function withoutPersonalizeArg(args = []) {
60
+ return args.filter((arg) => arg.name.value !== "personalize");
61
+ }
62
+ function documentOf(document2) {
63
+ if (typeof document2 === "string") return parse(document2);
64
+ if (document2 instanceof String) return parse(document2.toString());
65
+ return document2;
66
+ }
67
+ function collectVariables(node, used) {
68
+ if (!node || typeof node !== "object") return;
69
+ if (Array.isArray(node)) {
70
+ for (const item of node) collectVariables(item, used);
71
+ return;
72
+ }
73
+ const value = node;
74
+ if (value.kind === "Variable") {
75
+ used.add(value.name.value);
76
+ return;
77
+ }
78
+ for (const key of Object.keys(value)) {
79
+ if (key !== "loc") collectVariables(value[key], used);
80
+ }
81
+ }
82
+
83
+ // src/core/variants/decision-document.ts
84
+ function decisionSelectionSet(set, typeName, path, ctx) {
85
+ const selections = [];
86
+ for (const selection of set.selections) {
87
+ if (selection.kind === "FragmentSpread") {
88
+ const fragment = ctx.fragments[selection.name.value];
89
+ if (!fragment) continue;
90
+ const pruned = decisionSelectionSet(
91
+ fragment.selectionSet,
92
+ fragment.typeCondition.name.value,
93
+ path,
94
+ ctx
95
+ );
96
+ if (pruned) {
97
+ selections.push(
98
+ inlineFragment(fragment.typeCondition.name.value, [
99
+ ...pruned.selections
100
+ ])
101
+ );
102
+ }
103
+ continue;
104
+ }
105
+ if (selection.kind === "InlineFragment") {
106
+ const pruned = decisionSelectionSet(
107
+ selection.selectionSet,
108
+ selection.typeCondition?.name.value ?? typeName,
109
+ path,
110
+ ctx
111
+ );
112
+ if (pruned) selections.push({ ...selection, selectionSet: pruned });
113
+ continue;
114
+ }
115
+ if (!selection.selectionSet) continue;
116
+ const field = ctx.schema.types[typeName]?.fields[selection.name.value];
117
+ if (!field) continue;
118
+ const key = selection.alias?.value ?? selection.name.value;
119
+ const fieldPath = path ? `${path}.${key}` : key;
120
+ if (ctx.paths && !ctx.paths.prefixes.has(fieldPath)) continue;
121
+ const child = decisionSelectionSet(
122
+ selection.selectionSet,
123
+ field.type,
124
+ fieldPath,
125
+ ctx
126
+ );
127
+ const groupTypes = ctx.paths?.groups.get(fieldPath);
128
+ const holdsGroups = field.personalizable && (!ctx.paths || groupTypes !== void 0);
129
+ if (holdsGroups) {
130
+ selections.push({
131
+ ...selection,
132
+ arguments: withoutPersonalizeArg(selection.arguments),
133
+ selectionSet: selectionSet([
134
+ ...ctx.topLevelOnly ? [] : child?.selections ?? [],
135
+ ...contextSelections(
136
+ field.type,
137
+ ctx.schema,
138
+ groupTypes && !groupTypes.has("*") ? groupTypes : void 0,
139
+ false
140
+ )
141
+ ])
142
+ });
143
+ } else if (child) {
144
+ selections.push({
145
+ ...selection,
146
+ arguments: field.personalizable ? withoutPersonalizeArg(selection.arguments) : selection.arguments,
147
+ selectionSet: child
148
+ });
149
+ }
150
+ }
151
+ return selections.length > 0 ? selectionSet(selections) : null;
152
+ }
153
+ function toDecisionDocument(document2, schema, groupPaths, options) {
154
+ const doc = documentOf(document2);
155
+ const fragments = {};
156
+ for (const definition of doc.definitions) {
157
+ if (definition.kind === "FragmentDefinition") {
158
+ fragments[definition.name.value] = definition;
159
+ }
160
+ }
161
+ const operation = doc.definitions.find(
162
+ (definition) => definition.kind === "OperationDefinition"
163
+ );
164
+ if (!operation) return null;
165
+ let paths;
166
+ if (groupPaths) {
167
+ const prefixes = /* @__PURE__ */ new Set();
168
+ for (const groupPath of groupPaths.keys()) {
169
+ const parts = groupPath.split(".");
170
+ for (let i = 1; i <= parts.length; i++) {
171
+ prefixes.add(parts.slice(0, i).join("."));
172
+ }
173
+ }
174
+ paths = { groups: groupPaths, prefixes };
175
+ }
176
+ const pruned = decisionSelectionSet(
177
+ operation.selectionSet,
178
+ schema.queryType,
179
+ "",
180
+ { schema, fragments, paths, topLevelOnly: options?.topLevelOnly }
181
+ );
182
+ if (!pruned) return null;
183
+ const used = /* @__PURE__ */ new Set();
184
+ collectVariables(pruned, used);
185
+ collectVariables(operation.directives, used);
186
+ return {
187
+ kind: "Document",
188
+ definitions: [
189
+ {
190
+ ...operation,
191
+ name: operation.name && name(`${operation.name.value}Decision`),
192
+ variableDefinitions: (operation.variableDefinitions ?? []).filter(
193
+ (definition) => used.has(definition.variable.name.value)
194
+ ),
195
+ selectionSet: pruned
196
+ }
197
+ ]
198
+ };
199
+ }
200
+
201
+ // src/core/variants/probe-document.ts
202
+ function probeSelectionSet(set, fragments) {
203
+ const selections = [
204
+ { kind: "Field", name: name("__typename") }
205
+ ];
206
+ for (const selection of set.selections) {
207
+ if (selection.kind === "Field") {
208
+ if (!selection.selectionSet) continue;
209
+ selections.push({
210
+ ...selection,
211
+ selectionSet: probeSelectionSet(selection.selectionSet, fragments)
212
+ });
213
+ continue;
214
+ }
215
+ const fragment = selection.kind === "InlineFragment" ? selection : fragments[selection.name.value];
216
+ if (!fragment) continue;
217
+ const child = probeSelectionSet(fragment.selectionSet, fragments);
218
+ if (child.selections.length === 1) continue;
219
+ selections.push({
220
+ kind: "InlineFragment",
221
+ typeCondition: fragment.typeCondition,
222
+ directives: selection.directives,
223
+ selectionSet: child
224
+ });
225
+ }
226
+ return selectionSet(selections);
227
+ }
228
+ function toAbProbeDocument(document2) {
229
+ const doc = documentOf(document2);
230
+ const fragments = {};
231
+ for (const definition of doc.definitions) {
232
+ if (definition.kind === "FragmentDefinition") {
233
+ fragments[definition.name.value] = definition;
234
+ }
235
+ }
236
+ const operation = doc.definitions.find(
237
+ (definition) => definition.kind === "OperationDefinition"
238
+ );
239
+ if (!operation) return null;
240
+ const probe = probeSelectionSet(operation.selectionSet, fragments);
241
+ const used = /* @__PURE__ */ new Set();
242
+ collectVariables(probe, used);
243
+ collectVariables(operation.directives, used);
244
+ return {
245
+ kind: "Document",
246
+ definitions: [
247
+ {
248
+ ...operation,
249
+ name: operation.name && name(`${operation.name.value}AbCheck`),
250
+ variableDefinitions: (operation.variableDefinitions ?? []).filter(
251
+ (definition) => used.has(definition.variable.name.value)
252
+ ),
253
+ selectionSet: probe
254
+ }
255
+ ]
256
+ };
257
+ }
258
+
259
+ // src/core/variants/resolve.ts
260
+ function personalizationPaths(data) {
261
+ const paths = /* @__PURE__ */ new Map();
262
+ const walk = (value, path) => {
263
+ if (Array.isArray(value)) {
264
+ for (const item of value) {
265
+ if (contextOf(item)?.kind === "PERSONALIZATION") {
266
+ const record = item;
267
+ const type = record[PREPR_TYPE_ALIAS] ?? record.__typename;
268
+ const types = paths.get(path) ?? /* @__PURE__ */ new Set();
269
+ types.add(typeof type === "string" ? type : "*");
270
+ paths.set(path, types);
271
+ }
272
+ walk(item, path);
273
+ }
274
+ return;
275
+ }
276
+ if (!value || typeof value !== "object") return;
277
+ for (const [key, child] of Object.entries(value)) {
278
+ if (key !== PREPR_CONTEXT_ALIAS && key !== PREPR_TYPE_ALIAS)
279
+ walk(child, path ? `${path}.${key}` : key);
280
+ }
281
+ };
282
+ walk(data, "");
283
+ return paths;
284
+ }
285
+ function contextOf(item) {
286
+ if (!item || typeof item !== "object") return null;
287
+ const context = item[PREPR_CONTEXT_ALIAS];
288
+ const ctx = context;
289
+ return ctx?.kind && ctx.group_id ? ctx : null;
290
+ }
291
+ function decisionsFrom(data) {
292
+ const decisions = /* @__PURE__ */ new Map();
293
+ const walk = (value) => {
294
+ if (Array.isArray(value)) return value.forEach(walk);
295
+ if (!value || typeof value !== "object") return;
296
+ const ctx = contextOf(value);
297
+ if (ctx?.group_id && ctx.variant_id) {
298
+ const ids = decisions.get(ctx.group_id) ?? [];
299
+ if (!ids.includes(ctx.variant_id)) ids.push(ctx.variant_id);
300
+ decisions.set(ctx.group_id, ids);
301
+ }
302
+ Object.values(value).forEach(walk);
303
+ };
304
+ walk(data);
305
+ return decisions;
306
+ }
307
+ function chosenVariants(ctx, options) {
308
+ const decided = options.decisions?.get(ctx.group_id);
309
+ if (ctx.kind === "AB_TEST") {
310
+ return options.bucket ? [options.bucket] : decided ?? ["A"];
311
+ }
312
+ return decided ?? [PREPR_DEFAULT_VARIANT];
313
+ }
314
+ function resolveVariants(data, options = {}) {
315
+ const resolve = (value) => {
316
+ if (Array.isArray(value)) {
317
+ return value.filter((item) => {
318
+ const ctx = contextOf(item);
319
+ return !ctx || chosenVariants(ctx, options).includes(ctx.variant_id ?? "");
320
+ }).map(resolve);
321
+ }
322
+ if (!value || typeof value !== "object") return value;
323
+ const out = {};
324
+ for (const [key, child] of Object.entries(value)) out[key] = resolve(child);
325
+ return out;
326
+ };
327
+ return resolve(data);
328
+ }
329
+
330
+ // src/core/variants/schema.ts
331
+ var PREPR_SCHEMA_QUERY = `query PreprPersonalizationSchema {
332
+ __schema {
333
+ queryType { name }
334
+ types {
335
+ name
336
+ possibleTypes { name }
337
+ fields {
338
+ name
339
+ args { name }
340
+ type { name ofType { name ofType { name ofType { name ofType { name } } } } }
341
+ }
342
+ }
343
+ }
344
+ }`;
345
+ function namedType(ref) {
346
+ let current = ref;
347
+ while (current && !current.name) current = current.ofType;
348
+ return current?.name ?? "";
349
+ }
350
+ function toSchemaInfo(introspection) {
351
+ const types = {};
352
+ for (const type of introspection.__schema.types) {
353
+ if (type.name.startsWith("__")) continue;
354
+ const fields = {};
355
+ for (const field of type.fields ?? []) {
356
+ fields[field.name] = {
357
+ type: namedType(field.type),
358
+ personalizable: field.args.some((arg) => arg.name === "personalize")
359
+ };
360
+ }
361
+ types[type.name] = {
362
+ fields,
363
+ possibleTypes: (type.possibleTypes ?? []).map((t) => t.name),
364
+ hasContext: "_context" in fields
365
+ };
366
+ }
367
+ return { queryType: introspection.__schema.queryType.name, types };
368
+ }
369
+
370
+ // src/core/variants/stack.ts
371
+ function containsKind(value, kind) {
372
+ if (Array.isArray(value))
373
+ return value.some((item) => containsKind(item, kind));
374
+ if (!value || typeof value !== "object") return false;
375
+ if (contextOf(value)?.kind === kind) return true;
376
+ return Object.values(value).some((child) => containsKind(child, kind));
377
+ }
378
+ function splitStack(items) {
379
+ const blocks = [];
380
+ let position = 0;
381
+ const positionsOf = (block) => block.key.startsWith("group:") ? 1 : block.items.length;
382
+ items.forEach((item, index) => {
383
+ const ctx = contextOf(item);
384
+ const groupKey = ctx ? `group:${ctx.group_id}` : null;
385
+ const personalized = containsKind(item, "PERSONALIZATION");
386
+ const abTest = containsKind(item, "AB_TEST");
387
+ const last = blocks.at(-1);
388
+ const plain = !groupKey && !personalized && !abTest;
389
+ if (groupKey && last?.key === groupKey) {
390
+ last.personalized || (last.personalized = personalized);
391
+ last.abTest || (last.abTest = abTest);
392
+ last.items.push(item);
393
+ } else if (plain && last && !last.personalized && !last.abTest) {
394
+ last.items.push(item);
395
+ } else {
396
+ const last2 = blocks.at(-1);
397
+ if (last2) position = last2.index + positionsOf(last2);
398
+ blocks.push({
399
+ key: groupKey ?? `items:${index}`,
400
+ items: [item],
401
+ index: position,
402
+ personalized,
403
+ abTest
404
+ });
405
+ }
406
+ });
407
+ return blocks;
408
+ }
409
+
410
+ // src/core/variants/tracking.ts
411
+ function preprVariantProps(item) {
412
+ const key = contextOf(item)?.variant_key;
413
+ return key ? { "data-prepr-variant-key": key } : {};
414
+ }
415
+
416
+ // src/core/variants/variants-document.ts
417
+ function variantsSelectionSet(set, typeName, schema) {
418
+ const selections = set.selections.map((selection) => {
419
+ if (selection.kind === "InlineFragment") {
420
+ return {
421
+ ...selection,
422
+ selectionSet: variantsSelectionSet(
423
+ selection.selectionSet,
424
+ selection.typeCondition?.name.value ?? typeName,
425
+ schema
426
+ )
427
+ };
428
+ }
429
+ if (selection.kind !== "Field" || !selection.selectionSet) return selection;
430
+ const field = schema.types[typeName]?.fields[selection.name.value];
431
+ if (!field) return selection;
432
+ const child = variantsSelectionSet(
433
+ selection.selectionSet,
434
+ field.type,
435
+ schema
436
+ );
437
+ if (!field.personalizable) return { ...selection, selectionSet: child };
438
+ return {
439
+ ...selection,
440
+ arguments: [
441
+ ...withoutPersonalizeArg(selection.arguments),
442
+ {
443
+ kind: "Argument",
444
+ name: name("personalize"),
445
+ value: { kind: "BooleanValue", value: false }
446
+ }
447
+ ],
448
+ selectionSet: selectionSet([
449
+ ...child.selections,
450
+ ...contextSelections(field.type, schema)
451
+ ])
452
+ };
453
+ });
454
+ return { ...set, selections };
455
+ }
456
+ function toVariantsDocument(document2, schema) {
457
+ const doc = documentOf(document2);
458
+ return {
459
+ ...doc,
460
+ definitions: doc.definitions.map((definition) => {
461
+ if (definition.kind === "OperationDefinition") {
462
+ return {
463
+ ...definition,
464
+ selectionSet: variantsSelectionSet(
465
+ definition.selectionSet,
466
+ schema.queryType,
467
+ schema
468
+ )
469
+ };
470
+ }
471
+ if (definition.kind === "FragmentDefinition") {
472
+ return {
473
+ ...definition,
474
+ selectionSet: variantsSelectionSet(
475
+ definition.selectionSet,
476
+ definition.typeCondition.name.value,
477
+ schema
478
+ )
479
+ };
480
+ }
481
+ return definition;
482
+ })
483
+ };
484
+ }
485
+
486
+ // src/core/graphql/document.ts
487
+ import { print } from "graphql/language/printer.js";
488
+ import { stripIgnoredCharacters } from "graphql/utilities/stripIgnoredCharacters.js";
489
+ var printed = /* @__PURE__ */ new WeakMap();
490
+ function isDocumentNode(value) {
491
+ return typeof value === "object" && value !== null && value.kind === "Document" && Array.isArray(value.definitions);
492
+ }
493
+ function invalidDocument(originalError) {
494
+ return new PreprError(
495
+ "Expected a GraphQL query string, TypedDocumentString or DocumentNode",
496
+ "INVALID_DOCUMENT",
497
+ "createPreprClient",
498
+ originalError
499
+ );
500
+ }
501
+ var minified = /* @__PURE__ */ new Map();
502
+ var MINIFIED_CACHE_LIMIT = 500;
503
+ function minify(query) {
504
+ const cached = minified.get(query);
505
+ if (cached !== void 0) return cached;
506
+ let result = query;
507
+ try {
508
+ result = stripIgnoredCharacters(query);
509
+ } catch {
510
+ }
511
+ if (minified.size < MINIFIED_CACHE_LIMIT) minified.set(query, result);
512
+ return result;
513
+ }
514
+ function resolveQuery(document2) {
515
+ if (typeof document2 === "string") return minify(document2);
516
+ if (document2 instanceof String) return minify(document2.toString());
517
+ if (!isDocumentNode(document2)) throw invalidDocument();
518
+ let query = printed.get(document2);
519
+ if (query === void 0) {
520
+ try {
521
+ query = minify(print(document2));
522
+ } catch (error) {
523
+ throw invalidDocument(error instanceof Error ? error : void 0);
524
+ }
525
+ printed.set(document2, query);
526
+ }
527
+ return query;
528
+ }
529
+
530
+ // src/core/variants/queries.ts
531
+ function toVariantsQuery(document2, schema) {
532
+ return resolveQuery(toVariantsDocument(document2, schema));
533
+ }
534
+ function toDecisionQuery(document2, schema, options = {}) {
535
+ const paths = options.from === void 0 ? void 0 : personalizationPaths(options.from);
536
+ if (paths && paths.size === 0) return null;
537
+ const decision = toDecisionDocument(document2, schema, paths, {
538
+ topLevelOnly: !paths && options.topLevelOnly
539
+ });
540
+ return decision ? resolveQuery(decision) : null;
541
+ }
542
+
543
+ // src/core/graphql/transport.ts
544
+ import { VERCEL_STEGA_REGEX } from "@vercel/stega";
545
+
546
+ // src/core/stega/clean.ts
547
+ import { vercelStegaClean, vercelStegaDecode } from "@vercel/stega";
548
+
549
+ // src/core/utils.ts
550
+ var DebugLogger = class {
551
+ constructor(options) {
552
+ this.options = {
553
+ prefix: "[Prepr]",
554
+ ...options
555
+ };
556
+ }
557
+ // A local `enabled` wins; otherwise defer to the global logger so scoped
558
+ // loggers created before initDebugLogger() still pick up the setting.
559
+ isEnabled() {
560
+ if (this.options.enabled !== void 0) {
561
+ return this.options.enabled;
562
+ }
563
+ return globalDebugLogger?.options?.enabled ?? false;
564
+ }
565
+ log(message, ...args) {
566
+ if (!this.isEnabled()) return;
567
+ const prefix = this.options.prefix;
568
+ console.log(`${prefix} ${message}`, ...args);
569
+ }
570
+ warn(message, ...args) {
571
+ if (!this.isEnabled()) return;
572
+ const prefix = this.options.prefix;
573
+ console.warn(`${prefix} ${message}`, ...args);
574
+ }
575
+ error(message, ...args) {
576
+ if (!this.isEnabled()) return;
577
+ const prefix = this.options.prefix;
578
+ console.error(`${prefix} ${message}`, ...args);
579
+ }
580
+ };
581
+ var globalDebugLogger = null;
582
+ function createScopedLogger(scopeName) {
583
+ return new DebugLogger({
584
+ prefix: `[Prepr][${scopeName}]`
585
+ });
586
+ }
587
+
588
+ // src/core/stega/clean.ts
589
+ var debug = createScopedLogger("stega:clean");
590
+ function stegaClean(text) {
591
+ if (!text) return text;
592
+ return vercelStegaClean(text);
593
+ }
594
+
595
+ // src/core/graphql/transport.ts
596
+ var OPERATION_NAME = /\b(?:query|mutation|subscription)\s+([_A-Za-z][_0-9A-Za-z]*)/;
597
+ var STEGA_RAW = new RegExp(
598
+ VERCEL_STEGA_REGEX.source,
599
+ VERCEL_STEGA_REGEX.flags.replace("g", "")
600
+ );
601
+ var STEGA_ESCAPED = /\\u(?:200[bcd]|206[0-3]|feff|d834)/i;
602
+ var URL_KEY = /(url|slug|link|href)$/i;
603
+ var FASTLY_QUERY_MAX = 96 * 1024;
604
+ function base64(text) {
605
+ const bytes = new TextEncoder().encode(text);
606
+ let binary = "";
607
+ for (let i = 0; i < bytes.length; i += 32768) {
608
+ binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
609
+ }
610
+ return btoa(binary);
611
+ }
612
+ function cacheInit(init, noStore) {
613
+ const result = { ...init };
614
+ if (noStore) {
615
+ result.cache = "no-store";
616
+ delete result.next;
617
+ }
618
+ return result;
619
+ }
620
+ function isFrameworkSignal(error) {
621
+ return typeof error === "object" && error !== null && typeof error.digest === "string";
622
+ }
623
+ function mergePreprHeaders(base, extra) {
624
+ const merged = new Headers(base);
625
+ new Headers(extra).forEach((value, key) => {
626
+ merged.set(key, value);
627
+ });
628
+ return merged;
629
+ }
630
+ function cleanEveryString(_key, value) {
631
+ return typeof value === "string" ? stegaClean(value) : value;
632
+ }
633
+ function cleanUrlStrings(key, value) {
634
+ return typeof value === "string" && URL_KEY.test(key) ? stegaClean(value) : value;
635
+ }
636
+ function parseBody(text, stega) {
637
+ if (stega === "none" || !(STEGA_RAW.test(text) || STEGA_ESCAPED.test(text))) {
638
+ return JSON.parse(text);
639
+ }
640
+ return JSON.parse(text, stega === "all" ? cleanEveryString : cleanUrlStrings);
641
+ }
642
+ function createTransport(options) {
643
+ const { url, preview = false } = options;
644
+ const stega = options.stega ?? (preview ? "urls" : "all");
645
+ const clientHeaders = new Headers(options.headers);
646
+ return async (document2, variables, queryOptions = {}) => {
647
+ const query = resolveQuery(document2);
648
+ const operation = OPERATION_NAME.exec(query)?.[1] ?? "anonymous";
649
+ const headers = new Headers(clientHeaders);
650
+ for (const layer of [queryOptions.init?.headers, queryOptions.headers]) {
651
+ new Headers(layer).forEach((value, key) => {
652
+ headers.set(key, value);
653
+ });
654
+ }
655
+ headers.set("Content-Type", "application/json");
656
+ const perRequestHeaders = queryOptions.headers !== void 0 || queryOptions.init?.headers !== void 0;
657
+ const payload = JSON.stringify({ query, variables });
658
+ const fastly = options.fastlyQuery ? base64(payload) : null;
659
+ const viaGet = fastly !== null && fastly.length <= FASTLY_QUERY_MAX;
660
+ if (viaGet) headers.set("Fastly-Query", fastly);
661
+ const init = {
662
+ ...cacheInit(queryOptions.init, preview || perRequestHeaders),
663
+ method: viaGet ? "GET" : "POST",
664
+ headers,
665
+ body: viaGet ? void 0 : payload
666
+ };
667
+ const fetchImpl = queryOptions.fetch ?? options.fetch;
668
+ let response;
669
+ try {
670
+ response = await (fetchImpl ? fetchImpl(url, init) : fetch(url, init));
671
+ } catch (error) {
672
+ if (isFrameworkSignal(error)) throw error;
673
+ throw new PreprError(
674
+ `Prepr GraphQL request failed for ${operation}`,
675
+ "FETCH_ERROR",
676
+ operation,
677
+ error instanceof Error ? error : void 0
678
+ );
679
+ }
680
+ if (!response.ok) {
681
+ throw new PreprError(
682
+ `Prepr GraphQL HTTP ${response.status} for ${operation}${response.status === 412 ? " (Prepr rejects queries longer than 27,500 characters)" : ""}`,
683
+ "HTTP_ERROR",
684
+ operation
685
+ );
686
+ }
687
+ let body;
688
+ try {
689
+ body = parseBody(await response.text(), stega);
690
+ } catch (error) {
691
+ throw new PreprError(
692
+ `Prepr GraphQL response for ${operation} is not valid JSON`,
693
+ "INVALID_RESPONSE",
694
+ operation,
695
+ error instanceof Error ? error : void 0
696
+ );
697
+ }
698
+ if (typeof body !== "object" || body === null) {
699
+ throw new PreprError(
700
+ `Prepr GraphQL response for ${operation} is not an object`,
701
+ "INVALID_RESPONSE",
702
+ operation
703
+ );
704
+ }
705
+ const { data, errors } = body;
706
+ if (Array.isArray(errors) && errors.length > 0) {
707
+ const messages = errors.map((e) => String(e?.message ?? "Unknown error")).join("; ");
708
+ throw new PreprError(
709
+ `Prepr GraphQL errors for ${operation}: ${messages}`,
710
+ "GRAPHQL_ERROR",
711
+ operation
712
+ );
713
+ }
714
+ if (data === null || data === void 0) {
715
+ throw new PreprError(
716
+ `Prepr GraphQL response for ${operation} has no data`,
717
+ "INVALID_RESPONSE",
718
+ operation
719
+ );
720
+ }
721
+ return { data, personalized: isPersonalizedResponse(response) };
722
+ };
723
+ }
724
+
725
+ // src/core/graphql/probe.ts
726
+ var AB_TEST_VARY = /\bPrepr-ABTesting/i;
727
+ var SEGMENTS_VARY = /\bPrepr-Segments/i;
728
+ var AB_CHECK_TTL_MS = 6e4;
729
+ var AB_CHECK_MAX_ENTRIES = 1e3;
730
+ function createVaryProbe(run, options) {
731
+ const abProbes = /* @__PURE__ */ new Map();
732
+ const abChecks = /* @__PURE__ */ new Map();
733
+ return (document2, variables) => {
734
+ const key = JSON.stringify(variables ?? null);
735
+ let answers = abChecks.get(document2);
736
+ if (!answers) {
737
+ answers = /* @__PURE__ */ new Map();
738
+ abChecks.set(document2, answers);
739
+ }
740
+ const cached = answers.get(key);
741
+ if (cached && Date.now() - cached.at < AB_CHECK_TTL_MS) return cached.value;
742
+ const value = (async () => {
743
+ let probe = abProbes.get(document2);
744
+ if (probe === void 0) {
745
+ probe = toAbProbeDocument(document2);
746
+ abProbes.set(document2, probe);
747
+ }
748
+ if (!probe) return "";
749
+ let vary = "";
750
+ const send = options.fetch ?? fetch;
751
+ await run(probe, variables, {
752
+ fetch: async (input, init) => {
753
+ const response = await send(input, init);
754
+ vary = response.headers.get("vary") ?? "";
755
+ return response;
756
+ }
757
+ });
758
+ return vary;
759
+ })().catch((error) => {
760
+ if (isFrameworkSignal(error)) throw error;
761
+ answers.delete(key);
762
+ return null;
763
+ });
764
+ if (answers.size >= AB_CHECK_MAX_ENTRIES) {
765
+ answers.delete(answers.keys().next().value);
766
+ }
767
+ answers.set(key, { value, at: Date.now() });
768
+ return value;
769
+ };
770
+ }
771
+
772
+ // src/core/graphql/client.ts
773
+ function isParseableUrl(url) {
774
+ try {
775
+ new URL(url);
776
+ return true;
777
+ } catch {
778
+ return false;
779
+ }
780
+ }
781
+ function assertPreprUrl(url, source) {
782
+ validatePreprToken(url);
783
+ if (!isParseableUrl(url)) {
784
+ throw new PreprError(
785
+ "Prepr GraphQL URL is not a valid URL",
786
+ "INVALID_TOKEN",
787
+ source
788
+ );
789
+ }
790
+ }
791
+ function createPreprClient(options) {
792
+ assertPreprUrl(options.url, "createPreprClient");
793
+ const run = createTransport(options);
794
+ const probeVary = createVaryProbe(run, options);
795
+ let schema;
796
+ const loadSchema = () => schema ?? (schema = run(
797
+ PREPR_SCHEMA_QUERY,
798
+ void 0,
799
+ { init: options.schemaInit }
800
+ ).then(
801
+ (result) => toSchemaInfo(result.data),
802
+ (error) => {
803
+ schema = void 0;
804
+ throw error;
805
+ }
806
+ ));
807
+ const variantsDocuments = /* @__PURE__ */ new Map();
808
+ const decisionDocuments = /* @__PURE__ */ new Map();
809
+ return {
810
+ async query(document2, variables, queryOptions = {}) {
811
+ const { variants, ...rest } = queryOptions;
812
+ if (!variants) return run(document2, variables, rest);
813
+ let derived = variantsDocuments.get(document2);
814
+ if (!derived) {
815
+ derived = toVariantsDocument(document2, await loadSchema());
816
+ variantsDocuments.set(document2, derived);
817
+ }
818
+ return run(derived, variables, rest);
819
+ },
820
+ async decide(document2, variables, queryOptions = {}) {
821
+ const { from, topLevelOnly, ...rest } = queryOptions;
822
+ const paths = from === void 0 ? void 0 : personalizationPaths(from);
823
+ if (paths && paths.size === 0) return /* @__PURE__ */ new Map();
824
+ const signature = paths ? [...paths].map(([path, types]) => `${path}:${[...types].sort().join(",")}`).sort().join("|") : topLevelOnly ? "top" : "*";
825
+ let byPaths = decisionDocuments.get(document2);
826
+ if (!byPaths) {
827
+ byPaths = /* @__PURE__ */ new Map();
828
+ decisionDocuments.set(document2, byPaths);
829
+ }
830
+ let derived = byPaths.get(signature);
831
+ if (derived === void 0) {
832
+ derived = toDecisionDocument(document2, await loadSchema(), paths, {
833
+ topLevelOnly: !paths && topLevelOnly
834
+ });
835
+ byPaths.set(signature, derived);
836
+ }
837
+ if (!derived) return /* @__PURE__ */ new Map();
838
+ const { data } = await run(derived, variables, rest);
839
+ return decisionsFrom(data);
840
+ },
841
+ hasAbTests: (document2, variables) => probeVary(document2, variables).then(
842
+ (vary) => vary === null || AB_TEST_VARY.test(vary)
843
+ ),
844
+ hasSegments: (document2, variables) => probeVary(document2, variables).then(
845
+ (vary) => vary === null || SEGMENTS_VARY.test(vary)
846
+ )
847
+ };
848
+ }
849
+
850
+ // src/core/graphql/event-client.ts
851
+ function createEventClient(options, adapter) {
852
+ const client = createPreprClient(options);
853
+ return {
854
+ async query(document2, variables, queryOptions = {}) {
855
+ const { personalize, event, ...rest } = queryOptions;
856
+ if (personalize && event === void 0) {
857
+ throw new PreprError(
858
+ "personalize: true requires the request event",
859
+ "CONTEXT_ERROR",
860
+ "createPreprClient"
861
+ );
862
+ }
863
+ const fetchImpl = rest.fetch ?? (event === void 0 ? void 0 : adapter.fetch?.(event));
864
+ const headers = personalize ? mergePreprHeaders(
865
+ getPreprHeadersFromHeaders(adapter.headers(event)),
866
+ rest.headers
867
+ ) : rest.headers;
868
+ return client.query(document2, variables, {
869
+ ...rest,
870
+ headers,
871
+ fetch: fetchImpl
872
+ });
873
+ },
874
+ async decide(document2, variables, queryOptions) {
875
+ const { event, ...rest } = queryOptions;
876
+ if (event === void 0) {
877
+ throw new PreprError(
878
+ "decide requires the request event",
879
+ "CONTEXT_ERROR",
880
+ "createPreprClient"
881
+ );
882
+ }
883
+ return client.decide(document2, variables, {
884
+ ...rest,
885
+ headers: mergePreprHeaders(
886
+ getPreprHeadersFromHeaders(adapter.headers(event)),
887
+ rest.headers
888
+ ),
889
+ fetch: rest.fetch ?? adapter.fetch?.(event)
890
+ });
891
+ }
892
+ };
893
+ }
894
+
895
+ // src/core/graphql/schema-loader.ts
896
+ var schemas = /* @__PURE__ */ new Map();
897
+ async function loadPreprSchema(url, options = {}) {
898
+ assertPreprUrl(url, "loadPreprSchema");
899
+ let schema = schemas.get(url);
900
+ if (!schema) {
901
+ const run = createTransport({ url, fetch: options.fetch, stega: "none" });
902
+ schema = run(
903
+ PREPR_SCHEMA_QUERY
904
+ ).then((result) => toSchemaInfo(result.data)).catch((error) => {
905
+ schemas.delete(url);
906
+ if (error instanceof PreprError) throw error;
907
+ throw new PreprError(
908
+ "Prepr schema response is not an introspection result",
909
+ "INVALID_RESPONSE",
910
+ "loadPreprSchema",
911
+ error instanceof Error ? error : void 0
912
+ );
913
+ });
914
+ schemas.set(url, schema);
915
+ }
916
+ return schema;
917
+ }
918
+
919
+ // src/sveltekit/graphql.ts
920
+ function createPreprClient2(options) {
921
+ return createEventClient(options, {
922
+ headers: (event) => {
923
+ const fromLocals = getPreprHeadersFromLocals(
924
+ event.locals ?? {}
925
+ );
926
+ return [...fromLocals.keys()].length > 0 ? fromLocals : event.request.headers;
927
+ },
928
+ fetch: (event) => event.fetch
929
+ });
930
+ }
931
+ export {
932
+ PREPR_DEFAULT_VARIANT,
933
+ PreprError,
934
+ createPreprClient2 as createPreprClient,
935
+ decisionsFrom,
936
+ isPersonalizedResponse,
937
+ loadPreprSchema,
938
+ preprVariantProps,
939
+ resolveVariants,
940
+ splitStack,
941
+ toDecisionQuery,
942
+ toVariantsQuery
943
+ };