@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.
- package/README.md +111 -1363
- package/dist/astro/index.cjs +1555 -182
- package/dist/astro/index.d.cts +201 -1
- package/dist/astro/index.d.ts +201 -1
- package/dist/astro/index.js +1557 -29
- package/dist/{chunk-5QIWVDP2.js → chunk-33GWVTRJ.js} +1 -1
- package/dist/chunk-A2J7R4LR.js +256 -0
- package/dist/{chunk-WQBKQG4R.js → chunk-DSJ22P6J.js} +6 -1
- package/dist/chunk-KM2GME62.js +1255 -0
- package/dist/chunk-UTKH7DOI.js +58 -0
- package/dist/chunk-V7MCHPE7.js +85 -0
- package/dist/{chunk-J66UOCK6.js → chunk-WBMN4L7G.js} +1680 -579
- package/dist/chunk-Y7JWV7WV.js +374 -0
- package/dist/codegen/index.cjs +82 -0
- package/dist/codegen/index.d.cts +70 -0
- package/dist/codegen/index.d.ts +70 -0
- package/dist/codegen/index.js +64 -0
- package/dist/index.cjs +3729 -553
- package/dist/index.d.cts +403 -19
- package/dist/index.d.ts +403 -19
- package/dist/index.js +345 -24
- package/dist/live-preview-HCBNBC6C.js +19 -0
- package/dist/nextjs/components.cjs +1872 -754
- package/dist/nextjs/components.d.cts +5 -51
- package/dist/nextjs/components.d.ts +5 -51
- package/dist/nextjs/components.js +8 -299
- package/dist/nextjs/index.cjs +1228 -181
- package/dist/nextjs/index.d.cts +247 -92
- package/dist/nextjs/index.d.ts +247 -92
- package/dist/nextjs/index.js +1629 -111
- package/dist/nextjs/live-action.cjs +298 -0
- package/dist/nextjs/live-action.d.cts +12 -0
- package/dist/nextjs/live-action.d.ts +12 -0
- package/dist/nextjs/live-action.js +68 -0
- package/dist/nextjs/live.cjs +2010 -0
- package/dist/nextjs/live.d.cts +54 -0
- package/dist/nextjs/live.d.ts +54 -0
- package/dist/nextjs/live.js +287 -0
- package/dist/nuxt/chunk-5RBZPRQN.js +350 -0
- package/dist/nuxt/chunk-LUKVPOJ2.js +32 -0
- package/dist/nuxt/index.cjs +15 -16
- package/dist/nuxt/index.d.cts +167 -6
- package/dist/nuxt/index.d.ts +167 -6
- package/dist/nuxt/index.js +402 -15
- package/dist/nuxt/live-preview-KO4IKWTX.js +1234 -0
- package/dist/nuxt/live.cjs +1928 -0
- package/dist/nuxt/live.d.cts +45 -0
- package/dist/nuxt/live.d.ts +45 -0
- package/dist/nuxt/live.js +216 -0
- package/dist/{types-BYH9XqmN.d.cts → pixel-DqU7NvgW.d.cts} +102 -5
- package/dist/{types-BYH9XqmN.d.ts → pixel-DqU7NvgW.d.ts} +102 -5
- package/dist/react/components.cjs +1865 -480
- package/dist/react/components.d.cts +43 -8
- package/dist/react/components.d.ts +43 -8
- package/dist/react/components.js +1865 -480
- package/dist/sveltekit/chunk-5RBZPRQN.js +350 -0
- package/dist/sveltekit/chunk-LUKVPOJ2.js +32 -0
- package/dist/sveltekit/index.cjs +15 -16
- package/dist/sveltekit/index.d.cts +111 -10
- package/dist/sveltekit/index.d.ts +111 -10
- package/dist/sveltekit/index.js +398 -15
- package/dist/sveltekit/live-preview-KO4IKWTX.js +1234 -0
- package/dist/sveltekit/live.cjs +1940 -0
- package/dist/sveltekit/live.d.cts +61 -0
- package/dist/sveltekit/live.d.ts +61 -0
- package/dist/sveltekit/live.js +220 -0
- package/package.json +132 -71
- package/src/astro/PreprToolbar.astro +7 -1
- package/src/astro/PreprTrackingPixel.astro +2 -4
- package/src/nuxt/PreprToolbar.vue +12 -1
- package/src/nuxt/PreprTrackingPixel.vue +2 -4
- package/src/sveltekit/PreprToolbar.svelte +17 -2
- package/src/sveltekit/PreprTrackingPixel.svelte +2 -4
- package/dist/astro/chunk-UN4JADNU.js +0 -173
- package/dist/astro/graphql.cjs +0 -1078
- package/dist/astro/graphql.d.cts +0 -300
- package/dist/astro/graphql.d.ts +0 -300
- package/dist/astro/graphql.js +0 -984
- package/dist/astro/index-XT_z-RYT.d.cts +0 -130
- package/dist/astro/index-XT_z-RYT.d.ts +0 -130
- package/dist/chunk-3NCEVJJ3.js +0 -10
- package/dist/chunk-S5RWVMDJ.js +0 -148
- package/dist/chunk-XL4Y7FGW.js +0 -499
- package/dist/graphql/codegen.cjs +0 -557
- package/dist/graphql/codegen.d.cts +0 -23
- package/dist/graphql/codegen.d.ts +0 -23
- package/dist/graphql/codegen.js +0 -99
- package/dist/graphql.cjs +0 -1020
- package/dist/graphql.d.cts +0 -335
- package/dist/graphql.d.ts +0 -335
- package/dist/graphql.js +0 -448
- package/dist/nextjs/chunk-CMV6ZP6E.js +0 -549
- package/dist/nextjs/graphql.cjs +0 -1836
- package/dist/nextjs/graphql.d.cts +0 -498
- package/dist/nextjs/graphql.d.ts +0 -498
- package/dist/nextjs/graphql.js +0 -1422
- package/dist/nextjs/server-BL-sqZvu.d.cts +0 -156
- package/dist/nextjs/server-BL-sqZvu.d.ts +0 -156
- package/dist/nuxt/chunk-XWOABVMW.js +0 -417
- package/dist/nuxt/graphql.cjs +0 -1085
- package/dist/nuxt/graphql.d.cts +0 -297
- package/dist/nuxt/graphql.d.ts +0 -297
- package/dist/nuxt/graphql.js +0 -985
- package/dist/nuxt/server-8v6OHbsw.d.cts +0 -158
- package/dist/nuxt/server-8v6OHbsw.d.ts +0 -158
- package/dist/pixel-DwW7cXJm.d.cts +0 -49
- package/dist/pixel-DwW7cXJm.d.ts +0 -49
- package/dist/server-Brr1UgtW.d.ts +0 -59
- package/dist/server-DJuS3YU0.d.cts +0 -59
- package/dist/sveltekit/chunk-3S5RA6G5.js +0 -413
- package/dist/sveltekit/graphql.cjs +0 -1091
- package/dist/sveltekit/graphql.d.cts +0 -302
- package/dist/sveltekit/graphql.d.ts +0 -302
- package/dist/sveltekit/graphql.js +0 -991
- package/dist/sveltekit/server-CO847mEV.d.cts +0 -98
- package/dist/sveltekit/server-CO847mEV.d.ts +0 -98
package/dist/nextjs/graphql.cjs
DELETED
|
@@ -1,1836 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __create = Object.create;
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __export = (target, all) => {
|
|
9
|
-
for (var name2 in all)
|
|
10
|
-
__defProp(target, name2, { get: all[name2], enumerable: true });
|
|
11
|
-
};
|
|
12
|
-
var __copyProps = (to, from, except, desc) => {
|
|
13
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
-
for (let key of __getOwnPropNames(from))
|
|
15
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
-
}
|
|
18
|
-
return to;
|
|
19
|
-
};
|
|
20
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
-
mod
|
|
27
|
-
));
|
|
28
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
-
|
|
30
|
-
// src/nextjs/graphql.ts
|
|
31
|
-
var graphql_exports = {};
|
|
32
|
-
__export(graphql_exports, {
|
|
33
|
-
PREPR_ANY_ITEM_TAG: () => PREPR_ANY_ITEM_TAG,
|
|
34
|
-
PREPR_DEFAULT_VARIANT: () => PREPR_DEFAULT_VARIANT,
|
|
35
|
-
PreprError: () => PreprError,
|
|
36
|
-
PreprStack: () => PreprStack,
|
|
37
|
-
createPreprClient: () => createPreprClient2,
|
|
38
|
-
createPreprProxy: () => createPreprProxy,
|
|
39
|
-
decisionsFrom: () => decisionsFrom,
|
|
40
|
-
isPersonalizedResponse: () => isPersonalizedResponse,
|
|
41
|
-
loadPreprSchema: () => loadPreprSchema,
|
|
42
|
-
preprCacheTags: () => preprCacheTags,
|
|
43
|
-
preprModelTag: () => preprModelTag,
|
|
44
|
-
preprVariantProps: () => preprVariantProps,
|
|
45
|
-
resolveVariants: () => resolveVariants,
|
|
46
|
-
splitStack: () => splitStack,
|
|
47
|
-
toDecisionQuery: () => toDecisionQuery,
|
|
48
|
-
toVariantsQuery: () => toVariantsQuery
|
|
49
|
-
});
|
|
50
|
-
module.exports = __toCommonJS(graphql_exports);
|
|
51
|
-
var nextCache = __toESM(require("next/cache"), 1);
|
|
52
|
-
|
|
53
|
-
// src/core/graphql/cache-tags.ts
|
|
54
|
-
var MAX_TAGS = 128;
|
|
55
|
-
var MAX_TAG_LENGTH = 256;
|
|
56
|
-
var PREPR_ANY_ITEM_TAG = "prepr:any";
|
|
57
|
-
var PREPR_SCHEMA_TAG = "prepr:schema";
|
|
58
|
-
var preprItemTag = (id) => `prepr:${id}`;
|
|
59
|
-
var NOT_ALPHANUMERIC = /[^a-z0-9]/g;
|
|
60
|
-
var preprModelTag = (model) => `prepr:model:${model.toLowerCase().replace(NOT_ALPHANUMERIC, "")}`;
|
|
61
|
-
function preprModelTagsFor(document2, data, schema) {
|
|
62
|
-
const operation = document2.definitions.find(
|
|
63
|
-
(definition) => definition.kind === "OperationDefinition" && definition.operation === "query"
|
|
64
|
-
);
|
|
65
|
-
const root = schema.types[schema.queryType];
|
|
66
|
-
if (!operation || !root) return [];
|
|
67
|
-
const models = (type) => {
|
|
68
|
-
const members = schema.types[type]?.possibleTypes ?? [];
|
|
69
|
-
return members.length > 0 ? members : [type];
|
|
70
|
-
};
|
|
71
|
-
const tags = /* @__PURE__ */ new Set();
|
|
72
|
-
for (const selection of operation.selectionSet.selections) {
|
|
73
|
-
if (selection.kind !== "Field") continue;
|
|
74
|
-
const type = root.fields[selection.name.value]?.type;
|
|
75
|
-
const info = type ? schema.types[type] : void 0;
|
|
76
|
-
if (!type || !info) continue;
|
|
77
|
-
const items = info.fields.items?.type;
|
|
78
|
-
const key = (selection.alias ?? selection.name).value;
|
|
79
|
-
const found = typeof data === "object" && data !== null && data[key] != null;
|
|
80
|
-
const affected = items ? models(items) : found ? [] : models(type);
|
|
81
|
-
for (const model of affected) tags.add(preprModelTag(model));
|
|
82
|
-
}
|
|
83
|
-
return [...tags];
|
|
84
|
-
}
|
|
85
|
-
function preprCacheTags(data) {
|
|
86
|
-
const tags = /* @__PURE__ */ new Set();
|
|
87
|
-
const stack = [data];
|
|
88
|
-
while (stack.length > 0) {
|
|
89
|
-
const value = stack.pop();
|
|
90
|
-
if (typeof value !== "object" || value === null) continue;
|
|
91
|
-
const id = value._id;
|
|
92
|
-
if (typeof id === "string" && id !== "") {
|
|
93
|
-
const tag = preprItemTag(id);
|
|
94
|
-
if (tag.length > MAX_TAG_LENGTH) return [PREPR_ANY_ITEM_TAG];
|
|
95
|
-
tags.add(tag);
|
|
96
|
-
if (tags.size > MAX_TAGS) return [PREPR_ANY_ITEM_TAG];
|
|
97
|
-
}
|
|
98
|
-
for (const child of Object.values(value)) stack.push(child);
|
|
99
|
-
}
|
|
100
|
-
return [...tags];
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
// src/version.ts
|
|
104
|
-
var VERSION = "0.6.0-alpha.9";
|
|
105
|
-
|
|
106
|
-
// src/core/features.ts
|
|
107
|
-
function isEnabled(config) {
|
|
108
|
-
if (typeof config === "boolean") return config;
|
|
109
|
-
return config?.enabled ?? true;
|
|
110
|
-
}
|
|
111
|
-
function resolveFeatures(features) {
|
|
112
|
-
return {
|
|
113
|
-
segments: isEnabled(features?.segments),
|
|
114
|
-
abTesting: isEnabled(features?.abTesting),
|
|
115
|
-
editMode: isEnabled(features?.editMode)
|
|
116
|
-
};
|
|
117
|
-
}
|
|
118
|
-
var ALL_FEATURES_ENABLED = Object.freeze({
|
|
119
|
-
segments: true,
|
|
120
|
-
abTesting: true,
|
|
121
|
-
editMode: true
|
|
122
|
-
});
|
|
123
|
-
|
|
124
|
-
// src/core/server.ts
|
|
125
|
-
var PreprError = class extends Error {
|
|
126
|
-
constructor(message, code, context, originalError) {
|
|
127
|
-
super(message);
|
|
128
|
-
this.code = code;
|
|
129
|
-
this.context = context;
|
|
130
|
-
this.originalError = originalError;
|
|
131
|
-
this.name = "PreprError";
|
|
132
|
-
}
|
|
133
|
-
};
|
|
134
|
-
var PREPR_HEADER_KEYS = [
|
|
135
|
-
"prepr-customer-id",
|
|
136
|
-
"Prepr-Segments",
|
|
137
|
-
"Prepr-ABtesting",
|
|
138
|
-
"Prepr-Preview-Bar",
|
|
139
|
-
"Prepr-Context-utm_source",
|
|
140
|
-
"Prepr-Context-utm_medium",
|
|
141
|
-
"Prepr-Context-utm_term",
|
|
142
|
-
"Prepr-Context-utm_content",
|
|
143
|
-
"Prepr-Context-utm_campaign",
|
|
144
|
-
"Prepr-Context-initial_referral",
|
|
145
|
-
"Prepr-Visitor-IP",
|
|
146
|
-
"Prepr-Hubspot-Id",
|
|
147
|
-
"Prepr-Customer-Id-Created",
|
|
148
|
-
"User-Agent",
|
|
149
|
-
"Prepr-Package"
|
|
150
|
-
];
|
|
151
|
-
function getPreprHeadersFromHeaders(headers2) {
|
|
152
|
-
const preprHeaders = {};
|
|
153
|
-
const copy = (key) => {
|
|
154
|
-
const value = headers2.get(key);
|
|
155
|
-
if (value !== null) {
|
|
156
|
-
preprHeaders[key] = value;
|
|
157
|
-
}
|
|
158
|
-
};
|
|
159
|
-
for (const key of PREPR_HEADER_KEYS) {
|
|
160
|
-
copy(key);
|
|
161
|
-
}
|
|
162
|
-
return preprHeaders;
|
|
163
|
-
}
|
|
164
|
-
function validatePreprToken(token) {
|
|
165
|
-
if (!token) {
|
|
166
|
-
throw new PreprError(
|
|
167
|
-
"Token is required",
|
|
168
|
-
"MISSING_TOKEN",
|
|
169
|
-
"validatePreprToken"
|
|
170
|
-
);
|
|
171
|
-
}
|
|
172
|
-
if (!token.startsWith("https://")) {
|
|
173
|
-
throw new PreprError(
|
|
174
|
-
"Token must be a valid HTTPS URL",
|
|
175
|
-
"INVALID_TOKEN",
|
|
176
|
-
"validatePreprToken"
|
|
177
|
-
);
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
// src/core/variants/constants.ts
|
|
182
|
-
var PREPR_CONTEXT_ALIAS = "_preprContext";
|
|
183
|
-
var PREPR_TYPE_ALIAS = "_preprType";
|
|
184
|
-
var PREPR_DEFAULT_VARIANT = "ALL_OTHER_USERS";
|
|
185
|
-
|
|
186
|
-
// src/core/variants/ast.ts
|
|
187
|
-
var import_parser = require("graphql/language/parser.js");
|
|
188
|
-
var name = (value) => ({ kind: "Name", value });
|
|
189
|
-
function selectionSet(selections) {
|
|
190
|
-
return { kind: "SelectionSet", selections };
|
|
191
|
-
}
|
|
192
|
-
function contextField(withKey) {
|
|
193
|
-
const fields = ["kind", "group_id", "variant_id"];
|
|
194
|
-
if (withKey) fields.push("variant_key");
|
|
195
|
-
return {
|
|
196
|
-
kind: "Field",
|
|
197
|
-
alias: name(PREPR_CONTEXT_ALIAS),
|
|
198
|
-
name: name("_context"),
|
|
199
|
-
selectionSet: selectionSet(
|
|
200
|
-
fields.map(
|
|
201
|
-
(field) => ({ kind: "Field", name: name(field) })
|
|
202
|
-
)
|
|
203
|
-
)
|
|
204
|
-
};
|
|
205
|
-
}
|
|
206
|
-
function typenameField() {
|
|
207
|
-
return {
|
|
208
|
-
kind: "Field",
|
|
209
|
-
alias: name(PREPR_TYPE_ALIAS),
|
|
210
|
-
name: name("__typename")
|
|
211
|
-
};
|
|
212
|
-
}
|
|
213
|
-
function inlineFragment(typeName, selections) {
|
|
214
|
-
return {
|
|
215
|
-
kind: "InlineFragment",
|
|
216
|
-
typeCondition: { kind: "NamedType", name: name(typeName) },
|
|
217
|
-
selectionSet: selectionSet(selections)
|
|
218
|
-
};
|
|
219
|
-
}
|
|
220
|
-
function contextSelections(typeName, schema, onlyTypes, withType = true) {
|
|
221
|
-
const fields = () => withType ? [contextField(true), typenameField()] : [contextField(false)];
|
|
222
|
-
const type = schema.types[typeName];
|
|
223
|
-
if (!type) return [];
|
|
224
|
-
if (type.possibleTypes.length > 0) {
|
|
225
|
-
return type.possibleTypes.filter(
|
|
226
|
-
(member) => schema.types[member]?.hasContext && (!onlyTypes || onlyTypes.has(member))
|
|
227
|
-
).map((member) => inlineFragment(member, fields()));
|
|
228
|
-
}
|
|
229
|
-
return type.hasContext ? fields() : [];
|
|
230
|
-
}
|
|
231
|
-
function withoutPersonalizeArg(args = []) {
|
|
232
|
-
return args.filter((arg) => arg.name.value !== "personalize");
|
|
233
|
-
}
|
|
234
|
-
function documentOf(document2) {
|
|
235
|
-
if (typeof document2 === "string") return (0, import_parser.parse)(document2);
|
|
236
|
-
if (document2 instanceof String) return (0, import_parser.parse)(document2.toString());
|
|
237
|
-
return document2;
|
|
238
|
-
}
|
|
239
|
-
function collectVariables(node, used) {
|
|
240
|
-
if (!node || typeof node !== "object") return;
|
|
241
|
-
if (Array.isArray(node)) {
|
|
242
|
-
for (const item of node) collectVariables(item, used);
|
|
243
|
-
return;
|
|
244
|
-
}
|
|
245
|
-
const value = node;
|
|
246
|
-
if (value.kind === "Variable") {
|
|
247
|
-
used.add(value.name.value);
|
|
248
|
-
return;
|
|
249
|
-
}
|
|
250
|
-
for (const key of Object.keys(value)) {
|
|
251
|
-
if (key !== "loc") collectVariables(value[key], used);
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
// src/core/variants/decision-document.ts
|
|
256
|
-
function decisionSelectionSet(set, typeName, path, ctx) {
|
|
257
|
-
const selections = [];
|
|
258
|
-
for (const selection of set.selections) {
|
|
259
|
-
if (selection.kind === "FragmentSpread") {
|
|
260
|
-
const fragment = ctx.fragments[selection.name.value];
|
|
261
|
-
if (!fragment) continue;
|
|
262
|
-
const pruned = decisionSelectionSet(
|
|
263
|
-
fragment.selectionSet,
|
|
264
|
-
fragment.typeCondition.name.value,
|
|
265
|
-
path,
|
|
266
|
-
ctx
|
|
267
|
-
);
|
|
268
|
-
if (!pruned) continue;
|
|
269
|
-
if (fragment.typeCondition.name.value === typeName) {
|
|
270
|
-
selections.push(...pruned.selections);
|
|
271
|
-
} else {
|
|
272
|
-
selections.push(
|
|
273
|
-
inlineFragment(fragment.typeCondition.name.value, [
|
|
274
|
-
...pruned.selections
|
|
275
|
-
])
|
|
276
|
-
);
|
|
277
|
-
}
|
|
278
|
-
continue;
|
|
279
|
-
}
|
|
280
|
-
if (selection.kind === "InlineFragment") {
|
|
281
|
-
const condition = selection.typeCondition?.name.value ?? typeName;
|
|
282
|
-
const pruned = decisionSelectionSet(
|
|
283
|
-
selection.selectionSet,
|
|
284
|
-
condition,
|
|
285
|
-
path,
|
|
286
|
-
ctx
|
|
287
|
-
);
|
|
288
|
-
if (!pruned) continue;
|
|
289
|
-
if (condition === typeName && !selection.directives?.length) {
|
|
290
|
-
selections.push(...pruned.selections);
|
|
291
|
-
} else {
|
|
292
|
-
selections.push({ ...selection, selectionSet: pruned });
|
|
293
|
-
}
|
|
294
|
-
continue;
|
|
295
|
-
}
|
|
296
|
-
if (!selection.selectionSet) continue;
|
|
297
|
-
const field = ctx.schema.types[typeName]?.fields[selection.name.value];
|
|
298
|
-
if (!field) continue;
|
|
299
|
-
const key = selection.alias?.value ?? selection.name.value;
|
|
300
|
-
const fieldPath = path ? `${path}.${key}` : key;
|
|
301
|
-
if (ctx.paths && !ctx.paths.prefixes.has(fieldPath)) continue;
|
|
302
|
-
const child = decisionSelectionSet(
|
|
303
|
-
selection.selectionSet,
|
|
304
|
-
field.type,
|
|
305
|
-
fieldPath,
|
|
306
|
-
ctx
|
|
307
|
-
);
|
|
308
|
-
const groupTypes = ctx.paths?.groups.get(fieldPath);
|
|
309
|
-
const holdsGroups = field.personalizable && (!ctx.paths || groupTypes !== void 0);
|
|
310
|
-
if (holdsGroups) {
|
|
311
|
-
selections.push({
|
|
312
|
-
...selection,
|
|
313
|
-
arguments: withoutPersonalizeArg(selection.arguments),
|
|
314
|
-
selectionSet: selectionSet([
|
|
315
|
-
...ctx.topLevelOnly ? [] : child?.selections ?? [],
|
|
316
|
-
...contextSelections(
|
|
317
|
-
field.type,
|
|
318
|
-
ctx.schema,
|
|
319
|
-
groupTypes && !groupTypes.has("*") ? groupTypes : void 0,
|
|
320
|
-
false
|
|
321
|
-
)
|
|
322
|
-
])
|
|
323
|
-
});
|
|
324
|
-
} else if (child) {
|
|
325
|
-
selections.push({
|
|
326
|
-
...selection,
|
|
327
|
-
arguments: field.personalizable ? withoutPersonalizeArg(selection.arguments) : selection.arguments,
|
|
328
|
-
selectionSet: child
|
|
329
|
-
});
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
return selections.length > 0 ? selectionSet(selections) : null;
|
|
333
|
-
}
|
|
334
|
-
function toDecisionDocument(document2, schema, groupPaths, options) {
|
|
335
|
-
const doc = documentOf(document2);
|
|
336
|
-
const fragments = {};
|
|
337
|
-
for (const definition of doc.definitions) {
|
|
338
|
-
if (definition.kind === "FragmentDefinition") {
|
|
339
|
-
fragments[definition.name.value] = definition;
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
const operation = doc.definitions.find(
|
|
343
|
-
(definition) => definition.kind === "OperationDefinition"
|
|
344
|
-
);
|
|
345
|
-
if (!operation) return null;
|
|
346
|
-
let paths;
|
|
347
|
-
if (groupPaths) {
|
|
348
|
-
const prefixes = /* @__PURE__ */ new Set();
|
|
349
|
-
for (const groupPath of groupPaths.keys()) {
|
|
350
|
-
const parts = groupPath.split(".");
|
|
351
|
-
for (let i = 1; i <= parts.length; i++) {
|
|
352
|
-
prefixes.add(parts.slice(0, i).join("."));
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
paths = { groups: groupPaths, prefixes };
|
|
356
|
-
}
|
|
357
|
-
const pruned = decisionSelectionSet(
|
|
358
|
-
operation.selectionSet,
|
|
359
|
-
schema.queryType,
|
|
360
|
-
"",
|
|
361
|
-
{ schema, fragments, paths, topLevelOnly: options?.topLevelOnly }
|
|
362
|
-
);
|
|
363
|
-
if (!pruned) return null;
|
|
364
|
-
const used = /* @__PURE__ */ new Set();
|
|
365
|
-
collectVariables(pruned, used);
|
|
366
|
-
collectVariables(operation.directives, used);
|
|
367
|
-
const shared = sharedContextFragment(schema);
|
|
368
|
-
return {
|
|
369
|
-
kind: "Document",
|
|
370
|
-
definitions: [
|
|
371
|
-
...shared ? [shared.definition] : [],
|
|
372
|
-
{
|
|
373
|
-
...operation,
|
|
374
|
-
name: operation.name && name(`${operation.name.value}Decision`),
|
|
375
|
-
variableDefinitions: (operation.variableDefinitions ?? []).filter(
|
|
376
|
-
(definition) => used.has(definition.variable.name.value)
|
|
377
|
-
),
|
|
378
|
-
selectionSet: shared ? shared.apply(pruned) : pruned
|
|
379
|
-
}
|
|
380
|
-
]
|
|
381
|
-
};
|
|
382
|
-
}
|
|
383
|
-
function sharedContextFragment(schema) {
|
|
384
|
-
const contextTypes = new Set(
|
|
385
|
-
Object.values(schema.types).flatMap(
|
|
386
|
-
(type) => type.hasContext ? [type.fields._context.type] : []
|
|
387
|
-
)
|
|
388
|
-
);
|
|
389
|
-
if (contextTypes.size !== 1) return null;
|
|
390
|
-
const [contextType] = contextTypes;
|
|
391
|
-
const fragmentName = "c";
|
|
392
|
-
const definition = {
|
|
393
|
-
kind: "FragmentDefinition",
|
|
394
|
-
name: name(fragmentName),
|
|
395
|
-
typeCondition: { kind: "NamedType", name: name(contextType) },
|
|
396
|
-
selectionSet: selectionSet(
|
|
397
|
-
["kind", "group_id", "variant_id"].map(
|
|
398
|
-
(field) => ({ kind: "Field", name: name(field) })
|
|
399
|
-
)
|
|
400
|
-
)
|
|
401
|
-
};
|
|
402
|
-
const spread = {
|
|
403
|
-
kind: "FragmentSpread",
|
|
404
|
-
name: name(fragmentName)
|
|
405
|
-
};
|
|
406
|
-
const apply = (set) => selectionSet(
|
|
407
|
-
set.selections.map((selection) => {
|
|
408
|
-
if (selection.kind === "Field" && selection.alias?.value === PREPR_CONTEXT_ALIAS) {
|
|
409
|
-
return { ...selection, selectionSet: selectionSet([spread]) };
|
|
410
|
-
}
|
|
411
|
-
return "selectionSet" in selection && selection.selectionSet ? {
|
|
412
|
-
...selection,
|
|
413
|
-
selectionSet: apply(selection.selectionSet)
|
|
414
|
-
} : selection;
|
|
415
|
-
})
|
|
416
|
-
);
|
|
417
|
-
return { definition, apply };
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
// src/core/variants/probe-document.ts
|
|
421
|
-
function probeSelectionSet(set, fragments) {
|
|
422
|
-
const selections = [
|
|
423
|
-
{ kind: "Field", name: name("__typename") }
|
|
424
|
-
];
|
|
425
|
-
for (const selection of set.selections) {
|
|
426
|
-
if (selection.kind === "Field") {
|
|
427
|
-
if (!selection.selectionSet) continue;
|
|
428
|
-
selections.push({
|
|
429
|
-
...selection,
|
|
430
|
-
selectionSet: probeSelectionSet(selection.selectionSet, fragments)
|
|
431
|
-
});
|
|
432
|
-
continue;
|
|
433
|
-
}
|
|
434
|
-
const fragment = selection.kind === "InlineFragment" ? selection : fragments[selection.name.value];
|
|
435
|
-
if (!fragment) continue;
|
|
436
|
-
const child = probeSelectionSet(fragment.selectionSet, fragments);
|
|
437
|
-
if (child.selections.length === 1) continue;
|
|
438
|
-
selections.push({
|
|
439
|
-
kind: "InlineFragment",
|
|
440
|
-
typeCondition: fragment.typeCondition,
|
|
441
|
-
directives: selection.directives,
|
|
442
|
-
selectionSet: child
|
|
443
|
-
});
|
|
444
|
-
}
|
|
445
|
-
return selectionSet(selections);
|
|
446
|
-
}
|
|
447
|
-
function toAbProbeDocument(document2) {
|
|
448
|
-
const doc = documentOf(document2);
|
|
449
|
-
const fragments = {};
|
|
450
|
-
for (const definition of doc.definitions) {
|
|
451
|
-
if (definition.kind === "FragmentDefinition") {
|
|
452
|
-
fragments[definition.name.value] = definition;
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
const operation = doc.definitions.find(
|
|
456
|
-
(definition) => definition.kind === "OperationDefinition"
|
|
457
|
-
);
|
|
458
|
-
if (!operation) return null;
|
|
459
|
-
const probe = probeSelectionSet(operation.selectionSet, fragments);
|
|
460
|
-
const used = /* @__PURE__ */ new Set();
|
|
461
|
-
collectVariables(probe, used);
|
|
462
|
-
collectVariables(operation.directives, used);
|
|
463
|
-
return {
|
|
464
|
-
kind: "Document",
|
|
465
|
-
definitions: [
|
|
466
|
-
{
|
|
467
|
-
...operation,
|
|
468
|
-
name: operation.name && name(`${operation.name.value}AbCheck`),
|
|
469
|
-
variableDefinitions: (operation.variableDefinitions ?? []).filter(
|
|
470
|
-
(definition) => used.has(definition.variable.name.value)
|
|
471
|
-
),
|
|
472
|
-
selectionSet: probe
|
|
473
|
-
}
|
|
474
|
-
]
|
|
475
|
-
};
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
// src/core/variants/resolve.ts
|
|
479
|
-
function personalizationPaths(data) {
|
|
480
|
-
const paths = /* @__PURE__ */ new Map();
|
|
481
|
-
const walk = (value, path) => {
|
|
482
|
-
if (Array.isArray(value)) {
|
|
483
|
-
for (const item of value) {
|
|
484
|
-
if (contextOf(item)?.kind === "PERSONALIZATION") {
|
|
485
|
-
const record = item;
|
|
486
|
-
const type = record[PREPR_TYPE_ALIAS] ?? record.__typename;
|
|
487
|
-
const types = paths.get(path) ?? /* @__PURE__ */ new Set();
|
|
488
|
-
types.add(typeof type === "string" ? type : "*");
|
|
489
|
-
paths.set(path, types);
|
|
490
|
-
}
|
|
491
|
-
walk(item, path);
|
|
492
|
-
}
|
|
493
|
-
return;
|
|
494
|
-
}
|
|
495
|
-
if (!value || typeof value !== "object") return;
|
|
496
|
-
for (const [key, child] of Object.entries(value)) {
|
|
497
|
-
if (key !== PREPR_CONTEXT_ALIAS && key !== PREPR_TYPE_ALIAS)
|
|
498
|
-
walk(child, path ? `${path}.${key}` : key);
|
|
499
|
-
}
|
|
500
|
-
};
|
|
501
|
-
walk(data, "");
|
|
502
|
-
return paths;
|
|
503
|
-
}
|
|
504
|
-
function contextOf(item) {
|
|
505
|
-
if (!item || typeof item !== "object") return null;
|
|
506
|
-
const context = item[PREPR_CONTEXT_ALIAS];
|
|
507
|
-
const ctx = context;
|
|
508
|
-
return ctx?.kind && ctx.group_id ? ctx : null;
|
|
509
|
-
}
|
|
510
|
-
function decisionsFrom(data) {
|
|
511
|
-
const decisions = /* @__PURE__ */ new Map();
|
|
512
|
-
const walk = (value) => {
|
|
513
|
-
if (Array.isArray(value)) return value.forEach(walk);
|
|
514
|
-
if (!value || typeof value !== "object") return;
|
|
515
|
-
const ctx = contextOf(value);
|
|
516
|
-
if (ctx?.group_id && ctx.variant_id) {
|
|
517
|
-
const ids = decisions.get(ctx.group_id) ?? [];
|
|
518
|
-
if (!ids.includes(ctx.variant_id)) ids.push(ctx.variant_id);
|
|
519
|
-
decisions.set(ctx.group_id, ids);
|
|
520
|
-
}
|
|
521
|
-
Object.values(value).forEach(walk);
|
|
522
|
-
};
|
|
523
|
-
walk(data);
|
|
524
|
-
return decisions;
|
|
525
|
-
}
|
|
526
|
-
function chosenVariants(ctx, options) {
|
|
527
|
-
const decided = options.decisions?.get(ctx.group_id);
|
|
528
|
-
if (ctx.kind === "AB_TEST") {
|
|
529
|
-
return options.bucket ? [options.bucket] : decided ?? ["A"];
|
|
530
|
-
}
|
|
531
|
-
return decided ?? [PREPR_DEFAULT_VARIANT];
|
|
532
|
-
}
|
|
533
|
-
function resolveVariants(data, options = {}) {
|
|
534
|
-
const resolve = (value) => {
|
|
535
|
-
if (Array.isArray(value)) {
|
|
536
|
-
return value.filter((item) => {
|
|
537
|
-
const ctx = contextOf(item);
|
|
538
|
-
return !ctx || chosenVariants(ctx, options).includes(ctx.variant_id ?? "");
|
|
539
|
-
}).map(resolve);
|
|
540
|
-
}
|
|
541
|
-
if (!value || typeof value !== "object") return value;
|
|
542
|
-
const out = {};
|
|
543
|
-
for (const [key, child] of Object.entries(value)) out[key] = resolve(child);
|
|
544
|
-
return out;
|
|
545
|
-
};
|
|
546
|
-
return resolve(data);
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
// src/core/variants/schema.ts
|
|
550
|
-
var PREPR_SCHEMA_QUERY = `query PreprPersonalizationSchema {
|
|
551
|
-
__schema {
|
|
552
|
-
queryType { name }
|
|
553
|
-
types {
|
|
554
|
-
name
|
|
555
|
-
possibleTypes { name }
|
|
556
|
-
fields {
|
|
557
|
-
name
|
|
558
|
-
args { name }
|
|
559
|
-
type { name ofType { name ofType { name ofType { name ofType { name } } } } }
|
|
560
|
-
}
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
}`;
|
|
564
|
-
function namedType(ref) {
|
|
565
|
-
let current = ref;
|
|
566
|
-
while (current && !current.name) current = current.ofType;
|
|
567
|
-
return current?.name ?? "";
|
|
568
|
-
}
|
|
569
|
-
function toSchemaInfo(introspection) {
|
|
570
|
-
const types = {};
|
|
571
|
-
for (const type of introspection.__schema.types) {
|
|
572
|
-
if (type.name.startsWith("__")) continue;
|
|
573
|
-
const fields = {};
|
|
574
|
-
for (const field of type.fields ?? []) {
|
|
575
|
-
fields[field.name] = {
|
|
576
|
-
type: namedType(field.type),
|
|
577
|
-
personalizable: field.args.some((arg) => arg.name === "personalize")
|
|
578
|
-
};
|
|
579
|
-
}
|
|
580
|
-
types[type.name] = {
|
|
581
|
-
fields,
|
|
582
|
-
possibleTypes: (type.possibleTypes ?? []).map((t) => t.name),
|
|
583
|
-
hasContext: "_context" in fields
|
|
584
|
-
};
|
|
585
|
-
}
|
|
586
|
-
return { queryType: introspection.__schema.queryType.name, types };
|
|
587
|
-
}
|
|
588
|
-
|
|
589
|
-
// src/core/variants/stack.ts
|
|
590
|
-
function containsKind(value, kind) {
|
|
591
|
-
if (Array.isArray(value))
|
|
592
|
-
return value.some((item) => containsKind(item, kind));
|
|
593
|
-
if (!value || typeof value !== "object") return false;
|
|
594
|
-
if (contextOf(value)?.kind === kind) return true;
|
|
595
|
-
return Object.values(value).some((child) => containsKind(child, kind));
|
|
596
|
-
}
|
|
597
|
-
function splitStack(items) {
|
|
598
|
-
const blocks = [];
|
|
599
|
-
let position = 0;
|
|
600
|
-
const positionsOf = (block) => block.key.startsWith("group:") ? 1 : block.items.length;
|
|
601
|
-
items.forEach((item, index) => {
|
|
602
|
-
const ctx = contextOf(item);
|
|
603
|
-
const groupKey = ctx ? `group:${ctx.group_id}` : null;
|
|
604
|
-
const personalized = containsKind(item, "PERSONALIZATION");
|
|
605
|
-
const abTest = containsKind(item, "AB_TEST");
|
|
606
|
-
const last = blocks.at(-1);
|
|
607
|
-
const plain = !groupKey && !personalized && !abTest;
|
|
608
|
-
if (groupKey && last?.key === groupKey) {
|
|
609
|
-
last.personalized || (last.personalized = personalized);
|
|
610
|
-
last.abTest || (last.abTest = abTest);
|
|
611
|
-
last.items.push(item);
|
|
612
|
-
} else if (plain && last && !last.personalized && !last.abTest) {
|
|
613
|
-
last.items.push(item);
|
|
614
|
-
} else {
|
|
615
|
-
const last2 = blocks.at(-1);
|
|
616
|
-
if (last2) position = last2.index + positionsOf(last2);
|
|
617
|
-
blocks.push({
|
|
618
|
-
key: groupKey ?? `items:${index}`,
|
|
619
|
-
items: [item],
|
|
620
|
-
index: position,
|
|
621
|
-
personalized,
|
|
622
|
-
abTest
|
|
623
|
-
});
|
|
624
|
-
}
|
|
625
|
-
});
|
|
626
|
-
return blocks;
|
|
627
|
-
}
|
|
628
|
-
|
|
629
|
-
// src/core/variants/tracking.ts
|
|
630
|
-
function preprVariantProps(item) {
|
|
631
|
-
const key = contextOf(item)?.variant_key;
|
|
632
|
-
return key ? { "data-prepr-variant-key": key } : {};
|
|
633
|
-
}
|
|
634
|
-
|
|
635
|
-
// src/core/variants/variants-document.ts
|
|
636
|
-
function variantsSelectionSet(set, typeName, schema) {
|
|
637
|
-
const selections = set.selections.map((selection) => {
|
|
638
|
-
if (selection.kind === "InlineFragment") {
|
|
639
|
-
return {
|
|
640
|
-
...selection,
|
|
641
|
-
selectionSet: variantsSelectionSet(
|
|
642
|
-
selection.selectionSet,
|
|
643
|
-
selection.typeCondition?.name.value ?? typeName,
|
|
644
|
-
schema
|
|
645
|
-
)
|
|
646
|
-
};
|
|
647
|
-
}
|
|
648
|
-
if (selection.kind !== "Field" || !selection.selectionSet) return selection;
|
|
649
|
-
const field = schema.types[typeName]?.fields[selection.name.value];
|
|
650
|
-
if (!field) return selection;
|
|
651
|
-
const child = variantsSelectionSet(
|
|
652
|
-
selection.selectionSet,
|
|
653
|
-
field.type,
|
|
654
|
-
schema
|
|
655
|
-
);
|
|
656
|
-
if (!field.personalizable) return { ...selection, selectionSet: child };
|
|
657
|
-
return {
|
|
658
|
-
...selection,
|
|
659
|
-
arguments: [
|
|
660
|
-
...withoutPersonalizeArg(selection.arguments),
|
|
661
|
-
{
|
|
662
|
-
kind: "Argument",
|
|
663
|
-
name: name("personalize"),
|
|
664
|
-
value: { kind: "BooleanValue", value: false }
|
|
665
|
-
}
|
|
666
|
-
],
|
|
667
|
-
selectionSet: selectionSet([
|
|
668
|
-
...child.selections,
|
|
669
|
-
...contextSelections(field.type, schema)
|
|
670
|
-
])
|
|
671
|
-
};
|
|
672
|
-
});
|
|
673
|
-
return { ...set, selections };
|
|
674
|
-
}
|
|
675
|
-
function toVariantsDocument(document2, schema) {
|
|
676
|
-
const doc = documentOf(document2);
|
|
677
|
-
return {
|
|
678
|
-
...doc,
|
|
679
|
-
definitions: doc.definitions.map((definition) => {
|
|
680
|
-
if (definition.kind === "OperationDefinition") {
|
|
681
|
-
return {
|
|
682
|
-
...definition,
|
|
683
|
-
selectionSet: variantsSelectionSet(
|
|
684
|
-
definition.selectionSet,
|
|
685
|
-
schema.queryType,
|
|
686
|
-
schema
|
|
687
|
-
)
|
|
688
|
-
};
|
|
689
|
-
}
|
|
690
|
-
if (definition.kind === "FragmentDefinition") {
|
|
691
|
-
return {
|
|
692
|
-
...definition,
|
|
693
|
-
selectionSet: variantsSelectionSet(
|
|
694
|
-
definition.selectionSet,
|
|
695
|
-
definition.typeCondition.name.value,
|
|
696
|
-
schema
|
|
697
|
-
)
|
|
698
|
-
};
|
|
699
|
-
}
|
|
700
|
-
return definition;
|
|
701
|
-
})
|
|
702
|
-
};
|
|
703
|
-
}
|
|
704
|
-
|
|
705
|
-
// src/core/graphql/document.ts
|
|
706
|
-
var import_printer = require("graphql/language/printer.js");
|
|
707
|
-
var import_stripIgnoredCharacters = require("graphql/utilities/stripIgnoredCharacters.js");
|
|
708
|
-
var printed = /* @__PURE__ */ new WeakMap();
|
|
709
|
-
function isDocumentNode(value) {
|
|
710
|
-
return typeof value === "object" && value !== null && value.kind === "Document" && Array.isArray(value.definitions);
|
|
711
|
-
}
|
|
712
|
-
function invalidDocument(originalError) {
|
|
713
|
-
return new PreprError(
|
|
714
|
-
"Expected a GraphQL query string, TypedDocumentString or DocumentNode",
|
|
715
|
-
"INVALID_DOCUMENT",
|
|
716
|
-
"createPreprClient",
|
|
717
|
-
originalError
|
|
718
|
-
);
|
|
719
|
-
}
|
|
720
|
-
var minified = /* @__PURE__ */ new Map();
|
|
721
|
-
var MINIFIED_CACHE_LIMIT = 500;
|
|
722
|
-
function minify(query) {
|
|
723
|
-
const cached = minified.get(query);
|
|
724
|
-
if (cached !== void 0) return cached;
|
|
725
|
-
let result = query;
|
|
726
|
-
try {
|
|
727
|
-
result = (0, import_stripIgnoredCharacters.stripIgnoredCharacters)(query);
|
|
728
|
-
} catch {
|
|
729
|
-
}
|
|
730
|
-
if (minified.size < MINIFIED_CACHE_LIMIT) minified.set(query, result);
|
|
731
|
-
return result;
|
|
732
|
-
}
|
|
733
|
-
function resolveQuery(document2) {
|
|
734
|
-
if (typeof document2 === "string") return minify(document2);
|
|
735
|
-
if (document2 instanceof String) return minify(document2.toString());
|
|
736
|
-
if (!isDocumentNode(document2)) throw invalidDocument();
|
|
737
|
-
let query = printed.get(document2);
|
|
738
|
-
if (query === void 0) {
|
|
739
|
-
try {
|
|
740
|
-
query = minify((0, import_printer.print)(document2));
|
|
741
|
-
} catch (error) {
|
|
742
|
-
throw invalidDocument(error instanceof Error ? error : void 0);
|
|
743
|
-
}
|
|
744
|
-
printed.set(document2, query);
|
|
745
|
-
}
|
|
746
|
-
return query;
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
// src/core/variants/queries.ts
|
|
750
|
-
function toVariantsQuery(document2, schema) {
|
|
751
|
-
return resolveQuery(toVariantsDocument(document2, schema));
|
|
752
|
-
}
|
|
753
|
-
function toDecisionQuery(document2, schema, options = {}) {
|
|
754
|
-
const paths = options.from === void 0 ? void 0 : personalizationPaths(options.from);
|
|
755
|
-
if (paths && paths.size === 0) return null;
|
|
756
|
-
const decision = toDecisionDocument(document2, schema, paths, {
|
|
757
|
-
topLevelOnly: !paths && options.topLevelOnly
|
|
758
|
-
});
|
|
759
|
-
return decision ? resolveQuery(decision) : null;
|
|
760
|
-
}
|
|
761
|
-
|
|
762
|
-
// src/core/graphql/transport.ts
|
|
763
|
-
var import_stega2 = require("@vercel/stega");
|
|
764
|
-
|
|
765
|
-
// src/core/personalization.ts
|
|
766
|
-
var PERSONALIZED_VARY = /\bPrepr-(Segments|ABTesting)/i;
|
|
767
|
-
function isPersonalizedResponse(source) {
|
|
768
|
-
const headers2 = "headers" in source ? source.headers : source;
|
|
769
|
-
return PERSONALIZED_VARY.test(headers2.get("vary") ?? "");
|
|
770
|
-
}
|
|
771
|
-
|
|
772
|
-
// src/core/stega/clean.ts
|
|
773
|
-
var import_stega = require("@vercel/stega");
|
|
774
|
-
|
|
775
|
-
// src/core/utils.ts
|
|
776
|
-
var DebugLogger = class {
|
|
777
|
-
constructor(options) {
|
|
778
|
-
this.options = {
|
|
779
|
-
prefix: "[Prepr]",
|
|
780
|
-
...options
|
|
781
|
-
};
|
|
782
|
-
}
|
|
783
|
-
// A local `enabled` wins; otherwise defer to the global logger so scoped
|
|
784
|
-
// loggers created before initDebugLogger() still pick up the setting.
|
|
785
|
-
isEnabled() {
|
|
786
|
-
if (this.options.enabled !== void 0) {
|
|
787
|
-
return this.options.enabled;
|
|
788
|
-
}
|
|
789
|
-
return globalDebugLogger?.options?.enabled ?? false;
|
|
790
|
-
}
|
|
791
|
-
log(message, ...args) {
|
|
792
|
-
if (!this.isEnabled()) return;
|
|
793
|
-
const prefix = this.options.prefix;
|
|
794
|
-
console.log(`${prefix} ${message}`, ...args);
|
|
795
|
-
}
|
|
796
|
-
warn(message, ...args) {
|
|
797
|
-
if (!this.isEnabled()) return;
|
|
798
|
-
const prefix = this.options.prefix;
|
|
799
|
-
console.warn(`${prefix} ${message}`, ...args);
|
|
800
|
-
}
|
|
801
|
-
error(message, ...args) {
|
|
802
|
-
if (!this.isEnabled()) return;
|
|
803
|
-
const prefix = this.options.prefix;
|
|
804
|
-
console.error(`${prefix} ${message}`, ...args);
|
|
805
|
-
}
|
|
806
|
-
};
|
|
807
|
-
var globalDebugLogger = null;
|
|
808
|
-
function createScopedLogger(scopeName) {
|
|
809
|
-
return new DebugLogger({
|
|
810
|
-
prefix: `[Prepr][${scopeName}]`
|
|
811
|
-
});
|
|
812
|
-
}
|
|
813
|
-
|
|
814
|
-
// src/core/stega/clean.ts
|
|
815
|
-
var debug = createScopedLogger("stega:clean");
|
|
816
|
-
function stegaClean(text) {
|
|
817
|
-
if (!text) return text;
|
|
818
|
-
return (0, import_stega.vercelStegaClean)(text);
|
|
819
|
-
}
|
|
820
|
-
|
|
821
|
-
// src/core/graphql/transport.ts
|
|
822
|
-
var OPERATION_NAME = /\b(?:query|mutation|subscription)\s+([_A-Za-z][_0-9A-Za-z]*)/;
|
|
823
|
-
var STEGA_RAW = new RegExp(
|
|
824
|
-
import_stega2.VERCEL_STEGA_REGEX.source,
|
|
825
|
-
import_stega2.VERCEL_STEGA_REGEX.flags.replace("g", "")
|
|
826
|
-
);
|
|
827
|
-
var STEGA_ESCAPED = /\\u(?:200[bcd]|206[0-3]|feff|d834)/i;
|
|
828
|
-
var URL_KEY = /(url|slug|link|href)$/i;
|
|
829
|
-
var FASTLY_QUERY_MAX = 96 * 1024;
|
|
830
|
-
function base64(text) {
|
|
831
|
-
const bytes = new TextEncoder().encode(text);
|
|
832
|
-
let binary = "";
|
|
833
|
-
for (let i = 0; i < bytes.length; i += 32768) {
|
|
834
|
-
binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
835
|
-
}
|
|
836
|
-
return btoa(binary);
|
|
837
|
-
}
|
|
838
|
-
function cacheInit(init, noStore) {
|
|
839
|
-
const result = { ...init };
|
|
840
|
-
if (noStore) {
|
|
841
|
-
result.cache = "no-store";
|
|
842
|
-
delete result.next;
|
|
843
|
-
}
|
|
844
|
-
return result;
|
|
845
|
-
}
|
|
846
|
-
function isFrameworkSignal(error) {
|
|
847
|
-
return typeof error === "object" && error !== null && typeof error.digest === "string";
|
|
848
|
-
}
|
|
849
|
-
function mergePreprHeaders(base, extra) {
|
|
850
|
-
const merged = new Headers(base);
|
|
851
|
-
new Headers(extra).forEach((value, key) => {
|
|
852
|
-
merged.set(key, value);
|
|
853
|
-
});
|
|
854
|
-
return merged;
|
|
855
|
-
}
|
|
856
|
-
function cleanEveryString(_key, value) {
|
|
857
|
-
return typeof value === "string" ? stegaClean(value) : value;
|
|
858
|
-
}
|
|
859
|
-
function cleanUrlStrings(key, value) {
|
|
860
|
-
return typeof value === "string" && URL_KEY.test(key) ? stegaClean(value) : value;
|
|
861
|
-
}
|
|
862
|
-
function parseBody(text, stega) {
|
|
863
|
-
if (stega === "none" || !(STEGA_RAW.test(text) || STEGA_ESCAPED.test(text))) {
|
|
864
|
-
return JSON.parse(text);
|
|
865
|
-
}
|
|
866
|
-
return JSON.parse(text, stega === "all" ? cleanEveryString : cleanUrlStrings);
|
|
867
|
-
}
|
|
868
|
-
function createTransport(options) {
|
|
869
|
-
const { url, preview = false } = options;
|
|
870
|
-
const stega = options.stega ?? (preview ? "urls" : "all");
|
|
871
|
-
const clientHeaders = new Headers(options.headers);
|
|
872
|
-
return async (document2, variables, queryOptions = {}) => {
|
|
873
|
-
const query = resolveQuery(document2);
|
|
874
|
-
const operation = OPERATION_NAME.exec(query)?.[1] ?? "anonymous";
|
|
875
|
-
const headers2 = new Headers(clientHeaders);
|
|
876
|
-
for (const layer of [queryOptions.init?.headers, queryOptions.headers]) {
|
|
877
|
-
new Headers(layer).forEach((value, key) => {
|
|
878
|
-
headers2.set(key, value);
|
|
879
|
-
});
|
|
880
|
-
}
|
|
881
|
-
headers2.set("Content-Type", "application/json");
|
|
882
|
-
const perRequestHeaders = queryOptions.headers !== void 0 || queryOptions.init?.headers !== void 0;
|
|
883
|
-
const payload = JSON.stringify({ query, variables });
|
|
884
|
-
const fastly = options.fastlyQuery ? base64(payload) : null;
|
|
885
|
-
const viaGet = fastly !== null && fastly.length <= FASTLY_QUERY_MAX;
|
|
886
|
-
if (viaGet) headers2.set("Fastly-Query", fastly);
|
|
887
|
-
const init = {
|
|
888
|
-
...cacheInit(queryOptions.init, preview || perRequestHeaders),
|
|
889
|
-
method: viaGet ? "GET" : "POST",
|
|
890
|
-
headers: headers2,
|
|
891
|
-
body: viaGet ? void 0 : payload
|
|
892
|
-
};
|
|
893
|
-
const fetchImpl = queryOptions.fetch ?? options.fetch;
|
|
894
|
-
let response;
|
|
895
|
-
try {
|
|
896
|
-
response = await (fetchImpl ? fetchImpl(url, init) : fetch(url, init));
|
|
897
|
-
} catch (error) {
|
|
898
|
-
if (isFrameworkSignal(error)) throw error;
|
|
899
|
-
throw new PreprError(
|
|
900
|
-
`Prepr GraphQL request failed for ${operation}`,
|
|
901
|
-
"FETCH_ERROR",
|
|
902
|
-
operation,
|
|
903
|
-
error instanceof Error ? error : void 0
|
|
904
|
-
);
|
|
905
|
-
}
|
|
906
|
-
if (!response.ok) {
|
|
907
|
-
throw new PreprError(
|
|
908
|
-
`Prepr GraphQL HTTP ${response.status} for ${operation}${response.status === 412 ? " (Prepr rejects queries longer than 27,500 characters)" : ""}`,
|
|
909
|
-
"HTTP_ERROR",
|
|
910
|
-
operation
|
|
911
|
-
);
|
|
912
|
-
}
|
|
913
|
-
let body;
|
|
914
|
-
try {
|
|
915
|
-
body = parseBody(await response.text(), stega);
|
|
916
|
-
} catch (error) {
|
|
917
|
-
throw new PreprError(
|
|
918
|
-
`Prepr GraphQL response for ${operation} is not valid JSON`,
|
|
919
|
-
"INVALID_RESPONSE",
|
|
920
|
-
operation,
|
|
921
|
-
error instanceof Error ? error : void 0
|
|
922
|
-
);
|
|
923
|
-
}
|
|
924
|
-
if (typeof body !== "object" || body === null) {
|
|
925
|
-
throw new PreprError(
|
|
926
|
-
`Prepr GraphQL response for ${operation} is not an object`,
|
|
927
|
-
"INVALID_RESPONSE",
|
|
928
|
-
operation
|
|
929
|
-
);
|
|
930
|
-
}
|
|
931
|
-
const { data, errors } = body;
|
|
932
|
-
if (Array.isArray(errors) && errors.length > 0) {
|
|
933
|
-
const messages = errors.map((e) => String(e?.message ?? "Unknown error")).join("; ");
|
|
934
|
-
throw new PreprError(
|
|
935
|
-
`Prepr GraphQL errors for ${operation}: ${messages}`,
|
|
936
|
-
"GRAPHQL_ERROR",
|
|
937
|
-
operation
|
|
938
|
-
);
|
|
939
|
-
}
|
|
940
|
-
if (data === null || data === void 0) {
|
|
941
|
-
throw new PreprError(
|
|
942
|
-
`Prepr GraphQL response for ${operation} has no data`,
|
|
943
|
-
"INVALID_RESPONSE",
|
|
944
|
-
operation
|
|
945
|
-
);
|
|
946
|
-
}
|
|
947
|
-
return { data, personalized: isPersonalizedResponse(response) };
|
|
948
|
-
};
|
|
949
|
-
}
|
|
950
|
-
|
|
951
|
-
// src/core/graphql/probe.ts
|
|
952
|
-
var AB_TEST_VARY = /\bPrepr-ABTesting/i;
|
|
953
|
-
var SEGMENTS_VARY = /\bPrepr-Segments/i;
|
|
954
|
-
var AB_CHECK_TTL_MS = 6e4;
|
|
955
|
-
var AB_CHECK_MAX_ENTRIES = 1e3;
|
|
956
|
-
function createVaryProbe(run, options) {
|
|
957
|
-
const abProbes = /* @__PURE__ */ new Map();
|
|
958
|
-
const abChecks = /* @__PURE__ */ new Map();
|
|
959
|
-
return (document2, variables) => {
|
|
960
|
-
const key = JSON.stringify(variables ?? null);
|
|
961
|
-
let answers = abChecks.get(document2);
|
|
962
|
-
if (!answers) {
|
|
963
|
-
answers = /* @__PURE__ */ new Map();
|
|
964
|
-
abChecks.set(document2, answers);
|
|
965
|
-
}
|
|
966
|
-
const cached = answers.get(key);
|
|
967
|
-
if (cached && Date.now() - cached.at < AB_CHECK_TTL_MS) return cached.value;
|
|
968
|
-
const value = (async () => {
|
|
969
|
-
let probe = abProbes.get(document2);
|
|
970
|
-
if (probe === void 0) {
|
|
971
|
-
probe = toAbProbeDocument(document2);
|
|
972
|
-
abProbes.set(document2, probe);
|
|
973
|
-
}
|
|
974
|
-
if (!probe) return "";
|
|
975
|
-
let vary = "";
|
|
976
|
-
const send = options.fetch ?? fetch;
|
|
977
|
-
await run(probe, variables, {
|
|
978
|
-
fetch: async (input, init) => {
|
|
979
|
-
const response = await send(input, init);
|
|
980
|
-
vary = response.headers.get("vary") ?? "";
|
|
981
|
-
return response;
|
|
982
|
-
}
|
|
983
|
-
});
|
|
984
|
-
return vary;
|
|
985
|
-
})().catch((error) => {
|
|
986
|
-
if (isFrameworkSignal(error)) throw error;
|
|
987
|
-
answers.delete(key);
|
|
988
|
-
return null;
|
|
989
|
-
});
|
|
990
|
-
if (answers.size >= AB_CHECK_MAX_ENTRIES) {
|
|
991
|
-
answers.delete(answers.keys().next().value);
|
|
992
|
-
}
|
|
993
|
-
answers.set(key, { value, at: Date.now() });
|
|
994
|
-
return value;
|
|
995
|
-
};
|
|
996
|
-
}
|
|
997
|
-
|
|
998
|
-
// src/core/graphql/client.ts
|
|
999
|
-
var clientSchemas = /* @__PURE__ */ new WeakMap();
|
|
1000
|
-
function isParseableUrl(url) {
|
|
1001
|
-
try {
|
|
1002
|
-
new URL(url);
|
|
1003
|
-
return true;
|
|
1004
|
-
} catch {
|
|
1005
|
-
return false;
|
|
1006
|
-
}
|
|
1007
|
-
}
|
|
1008
|
-
function assertPreprUrl(url, source) {
|
|
1009
|
-
validatePreprToken(url);
|
|
1010
|
-
if (!isParseableUrl(url)) {
|
|
1011
|
-
throw new PreprError(
|
|
1012
|
-
"Prepr GraphQL URL is not a valid URL",
|
|
1013
|
-
"INVALID_TOKEN",
|
|
1014
|
-
source
|
|
1015
|
-
);
|
|
1016
|
-
}
|
|
1017
|
-
}
|
|
1018
|
-
function createPreprClient(options) {
|
|
1019
|
-
assertPreprUrl(options.url, "createPreprClient");
|
|
1020
|
-
const run = createTransport(options);
|
|
1021
|
-
const probeVary = createVaryProbe(run, options);
|
|
1022
|
-
let schema;
|
|
1023
|
-
const loadSchema = () => schema ?? (schema = run(
|
|
1024
|
-
PREPR_SCHEMA_QUERY,
|
|
1025
|
-
void 0,
|
|
1026
|
-
{ init: options.schemaInit }
|
|
1027
|
-
).then(
|
|
1028
|
-
(result) => toSchemaInfo(result.data),
|
|
1029
|
-
(error) => {
|
|
1030
|
-
schema = void 0;
|
|
1031
|
-
throw error;
|
|
1032
|
-
}
|
|
1033
|
-
));
|
|
1034
|
-
const variantsDocuments = /* @__PURE__ */ new Map();
|
|
1035
|
-
const decisionDocuments = /* @__PURE__ */ new Map();
|
|
1036
|
-
const client = {
|
|
1037
|
-
async query(document2, variables, queryOptions = {}) {
|
|
1038
|
-
const { variants, ...rest } = queryOptions;
|
|
1039
|
-
if (!variants) return run(document2, variables, rest);
|
|
1040
|
-
let derived = variantsDocuments.get(document2);
|
|
1041
|
-
if (!derived) {
|
|
1042
|
-
derived = toVariantsDocument(document2, await loadSchema());
|
|
1043
|
-
variantsDocuments.set(document2, derived);
|
|
1044
|
-
}
|
|
1045
|
-
return run(derived, variables, rest);
|
|
1046
|
-
},
|
|
1047
|
-
async decide(document2, variables, queryOptions = {}) {
|
|
1048
|
-
const { from, ...rest } = queryOptions;
|
|
1049
|
-
const paths = from === void 0 ? void 0 : personalizationPaths(from);
|
|
1050
|
-
if (paths && paths.size === 0) return /* @__PURE__ */ new Map();
|
|
1051
|
-
const signature = paths ? [...paths].map(([path, types]) => `${path}:${[...types].sort().join(",")}`).sort().join("|") : "*";
|
|
1052
|
-
let byPaths = decisionDocuments.get(document2);
|
|
1053
|
-
if (!byPaths) {
|
|
1054
|
-
byPaths = /* @__PURE__ */ new Map();
|
|
1055
|
-
decisionDocuments.set(document2, byPaths);
|
|
1056
|
-
}
|
|
1057
|
-
let derived = byPaths.get(signature);
|
|
1058
|
-
if (derived === void 0) {
|
|
1059
|
-
derived = toDecisionDocument(document2, await loadSchema(), paths);
|
|
1060
|
-
byPaths.set(signature, derived);
|
|
1061
|
-
}
|
|
1062
|
-
if (!derived) return /* @__PURE__ */ new Map();
|
|
1063
|
-
const { data } = await run(derived, variables, rest);
|
|
1064
|
-
return decisionsFrom(data);
|
|
1065
|
-
},
|
|
1066
|
-
hasAbTests: (document2, variables) => probeVary(document2, variables).then(
|
|
1067
|
-
(vary) => vary === null || AB_TEST_VARY.test(vary)
|
|
1068
|
-
),
|
|
1069
|
-
hasSegments: (document2, variables) => probeVary(document2, variables).then(
|
|
1070
|
-
(vary) => vary === null || SEGMENTS_VARY.test(vary)
|
|
1071
|
-
)
|
|
1072
|
-
};
|
|
1073
|
-
clientSchemas.set(client, loadSchema);
|
|
1074
|
-
return client;
|
|
1075
|
-
}
|
|
1076
|
-
|
|
1077
|
-
// src/core/graphql/schema-loader.ts
|
|
1078
|
-
var schemas = /* @__PURE__ */ new Map();
|
|
1079
|
-
async function loadPreprSchema(url, options = {}) {
|
|
1080
|
-
assertPreprUrl(url, "loadPreprSchema");
|
|
1081
|
-
let schema = schemas.get(url);
|
|
1082
|
-
if (!schema) {
|
|
1083
|
-
const run = createTransport({ url, fetch: options.fetch, stega: "none" });
|
|
1084
|
-
schema = run(
|
|
1085
|
-
PREPR_SCHEMA_QUERY
|
|
1086
|
-
).then((result) => toSchemaInfo(result.data)).catch((error) => {
|
|
1087
|
-
schemas.delete(url);
|
|
1088
|
-
if (error instanceof PreprError) throw error;
|
|
1089
|
-
throw new PreprError(
|
|
1090
|
-
"Prepr schema response is not an introspection result",
|
|
1091
|
-
"INVALID_RESPONSE",
|
|
1092
|
-
"loadPreprSchema",
|
|
1093
|
-
error instanceof Error ? error : void 0
|
|
1094
|
-
);
|
|
1095
|
-
});
|
|
1096
|
-
schemas.set(url, schema);
|
|
1097
|
-
}
|
|
1098
|
-
return schema;
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
|
-
// src/nextjs/decisions.ts
|
|
1102
|
-
var PREPR_DECIDE_HEADER = "Prepr-Decide";
|
|
1103
|
-
var DEFAULT_DECISION = "*";
|
|
1104
|
-
var DECISIONS_MAX_GROUPS = 40;
|
|
1105
|
-
var SAFE_ID = /^[\w-]+$/;
|
|
1106
|
-
function serializeDecisions(decisions) {
|
|
1107
|
-
return [...decisions].filter(([group]) => SAFE_ID.test(group)).slice(0, DECISIONS_MAX_GROUPS).map(
|
|
1108
|
-
([group, variants]) => `${group}:${variants.filter((v) => SAFE_ID.test(v)).join("|")}`
|
|
1109
|
-
).join("~");
|
|
1110
|
-
}
|
|
1111
|
-
function forwardedHeaders(request, response) {
|
|
1112
|
-
const overridden = response.headers.get("x-middleware-override-headers");
|
|
1113
|
-
if (!overridden) return getPreprHeadersFromHeaders(request.headers);
|
|
1114
|
-
const headers2 = new Headers();
|
|
1115
|
-
for (const name2 of overridden.split(",")) {
|
|
1116
|
-
const value = response.headers.get(`x-middleware-request-${name2.trim()}`);
|
|
1117
|
-
if (value !== null) headers2.set(name2.trim(), value);
|
|
1118
|
-
}
|
|
1119
|
-
return getPreprHeadersFromHeaders(headers2);
|
|
1120
|
-
}
|
|
1121
|
-
var preprClientInternals = /* @__PURE__ */ new WeakMap();
|
|
1122
|
-
async function decideView(client, headers2, page, timeoutMs = 3e3) {
|
|
1123
|
-
const init = { signal: AbortSignal.timeout(timeoutMs) };
|
|
1124
|
-
try {
|
|
1125
|
-
const decided = page.decision ? decisionsFrom(
|
|
1126
|
-
(await client.query(page.decision, page.variables, { headers: headers2, init })).data
|
|
1127
|
-
) : await client.decide(page.document, page.variables, { headers: headers2, init });
|
|
1128
|
-
return serializeDecisions(decided);
|
|
1129
|
-
} catch (error) {
|
|
1130
|
-
if (isFrameworkSignal(error)) throw error;
|
|
1131
|
-
return DEFAULT_DECISION;
|
|
1132
|
-
}
|
|
1133
|
-
}
|
|
1134
|
-
|
|
1135
|
-
// src/nextjs/server.ts
|
|
1136
|
-
var import_headers = require("next/headers");
|
|
1137
|
-
async function readHeaders() {
|
|
1138
|
-
return await (0, import_headers.headers)();
|
|
1139
|
-
}
|
|
1140
|
-
async function getPreprHeaders() {
|
|
1141
|
-
const h = await readHeaders();
|
|
1142
|
-
return getPreprHeadersFromHeaders(h);
|
|
1143
|
-
}
|
|
1144
|
-
|
|
1145
|
-
// src/nextjs/proxy.ts
|
|
1146
|
-
var import_server9 = require("next/server");
|
|
1147
|
-
|
|
1148
|
-
// src/nextjs/draft.ts
|
|
1149
|
-
var import_headers2 = require("next/headers");
|
|
1150
|
-
var import_navigation = require("next/navigation");
|
|
1151
|
-
var import_server7 = require("next/server");
|
|
1152
|
-
var DRAFT_COOKIE = "__prerender_bypass";
|
|
1153
|
-
var RETURN_PARAM = "prepr_draft";
|
|
1154
|
-
var DEFAULT_ROUTE = "/api/prepr/draft";
|
|
1155
|
-
function preprDraftRedirect(request, options) {
|
|
1156
|
-
if (!options.preview) return null;
|
|
1157
|
-
if (request.method !== "GET" && request.method !== "HEAD") return null;
|
|
1158
|
-
const url = request.nextUrl;
|
|
1159
|
-
if (url.pathname === (options.route ?? DEFAULT_ROUTE)) return null;
|
|
1160
|
-
if (request.cookies.has(DRAFT_COOKIE)) {
|
|
1161
|
-
if (!url.searchParams.has(RETURN_PARAM)) return null;
|
|
1162
|
-
const clean = url.clone();
|
|
1163
|
-
clean.searchParams.delete(RETURN_PARAM);
|
|
1164
|
-
return import_server7.NextResponse.redirect(clean, 307);
|
|
1165
|
-
}
|
|
1166
|
-
if (url.searchParams.has(RETURN_PARAM)) return null;
|
|
1167
|
-
const target = new URL(options.route ?? DEFAULT_ROUTE, request.url);
|
|
1168
|
-
target.searchParams.set("to", url.pathname + url.search);
|
|
1169
|
-
return import_server7.NextResponse.redirect(target, 307);
|
|
1170
|
-
}
|
|
1171
|
-
|
|
1172
|
-
// src/nextjs/middleware.ts
|
|
1173
|
-
var import_server8 = require("next/server");
|
|
1174
|
-
|
|
1175
|
-
// src/core/constants.ts
|
|
1176
|
-
var COOKIE_PREVIEW_MODE = "Prepr-Preview-Mode";
|
|
1177
|
-
var COOKIE_SEGMENT = "Prepr-Segments";
|
|
1178
|
-
var COOKIE_VARIANT = "Prepr-ABtesting";
|
|
1179
|
-
var COOKIE_UID = "__prepr_uid";
|
|
1180
|
-
var COOKIE_HUBSPOT = "hubspotutk";
|
|
1181
|
-
var PARAM_SEGMENT = "prepr_preview_segment";
|
|
1182
|
-
var PARAM_VARIANT = "prepr_preview_ab";
|
|
1183
|
-
var PARAM_HIDE_BAR = "prepr_hide_bar";
|
|
1184
|
-
var ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;
|
|
1185
|
-
|
|
1186
|
-
// src/core/middleware.ts
|
|
1187
|
-
var UTM_PARAMS = [
|
|
1188
|
-
"utm_source",
|
|
1189
|
-
"utm_medium",
|
|
1190
|
-
"utm_term",
|
|
1191
|
-
"utm_content",
|
|
1192
|
-
"utm_campaign"
|
|
1193
|
-
];
|
|
1194
|
-
var MAX_HEADER_VALUE_LENGTH = 2048;
|
|
1195
|
-
function sanitizeHeaderValue(value) {
|
|
1196
|
-
const stripped = value.replace(/[\u0000-\u001f\u007f]/g, "");
|
|
1197
|
-
return stripped.length > MAX_HEADER_VALUE_LENGTH ? stripped.slice(0, MAX_HEADER_VALUE_LENGTH) : stripped;
|
|
1198
|
-
}
|
|
1199
|
-
function parseCookies(request) {
|
|
1200
|
-
const cookies2 = /* @__PURE__ */ new Map();
|
|
1201
|
-
const header = request.headers.get("cookie");
|
|
1202
|
-
if (!header) return cookies2;
|
|
1203
|
-
for (const part of header.split(";")) {
|
|
1204
|
-
const eq = part.indexOf("=");
|
|
1205
|
-
if (eq === -1) continue;
|
|
1206
|
-
const name2 = part.slice(0, eq).trim();
|
|
1207
|
-
const value = part.slice(eq + 1).trim();
|
|
1208
|
-
if (!name2) continue;
|
|
1209
|
-
try {
|
|
1210
|
-
cookies2.set(name2, decodeURIComponent(value));
|
|
1211
|
-
} catch {
|
|
1212
|
-
cookies2.set(name2, value);
|
|
1213
|
-
}
|
|
1214
|
-
}
|
|
1215
|
-
return cookies2;
|
|
1216
|
-
}
|
|
1217
|
-
function processFrameworkRequest(request, opts, framework) {
|
|
1218
|
-
const requestHeaders = new Headers(request.headers);
|
|
1219
|
-
const responseCookies = [];
|
|
1220
|
-
const inboundPreprHeaders = [];
|
|
1221
|
-
requestHeaders.forEach((_value, key) => {
|
|
1222
|
-
if (key.toLowerCase().startsWith("prepr-")) {
|
|
1223
|
-
inboundPreprHeaders.push(key);
|
|
1224
|
-
}
|
|
1225
|
-
});
|
|
1226
|
-
for (const key of inboundPreprHeaders) {
|
|
1227
|
-
requestHeaders.delete(key);
|
|
1228
|
-
}
|
|
1229
|
-
const requestCookies = parseCookies(request);
|
|
1230
|
-
const url = new URL(request.url);
|
|
1231
|
-
const searchParams = url.searchParams;
|
|
1232
|
-
const forwardedProto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
|
|
1233
|
-
const isSecure = forwardedProto ? forwardedProto === "https" : url.protocol === "https:";
|
|
1234
|
-
const crossSite = isSecure ? { sameSite: "None", secure: true } : {};
|
|
1235
|
-
for (const key of UTM_PARAMS) {
|
|
1236
|
-
const value = searchParams.get(key);
|
|
1237
|
-
if (value !== null) {
|
|
1238
|
-
requestHeaders.set(`Prepr-Context-${key}`, sanitizeHeaderValue(value));
|
|
1239
|
-
}
|
|
1240
|
-
}
|
|
1241
|
-
const referer = request.headers.get("referer");
|
|
1242
|
-
if (referer) {
|
|
1243
|
-
requestHeaders.set(
|
|
1244
|
-
"Prepr-Context-initial_referral",
|
|
1245
|
-
sanitizeHeaderValue(referer)
|
|
1246
|
-
);
|
|
1247
|
-
}
|
|
1248
|
-
const userAgent = request.headers.get("user-agent");
|
|
1249
|
-
if (userAgent) {
|
|
1250
|
-
requestHeaders.set("User-Agent", sanitizeHeaderValue(userAgent));
|
|
1251
|
-
}
|
|
1252
|
-
const packageParts = [`@preprio/toolkit@${opts?.version ?? VERSION}`];
|
|
1253
|
-
if (framework) packageParts.push(`framework=${framework}`);
|
|
1254
|
-
packageParts.push(`preview=${opts?.preview ? "true" : "false"}`);
|
|
1255
|
-
requestHeaders.set("Prepr-Package", packageParts.join("; "));
|
|
1256
|
-
const ip = request.headers.get("Cf-Connecting-Ip") ?? request.headers.get("x-real-ip");
|
|
1257
|
-
if (ip) {
|
|
1258
|
-
requestHeaders.set("Prepr-Visitor-IP", sanitizeHeaderValue(ip));
|
|
1259
|
-
}
|
|
1260
|
-
const hutkCookie = requestCookies.get(COOKIE_HUBSPOT);
|
|
1261
|
-
if (hutkCookie) {
|
|
1262
|
-
requestHeaders.set("Prepr-Hubspot-Id", sanitizeHeaderValue(hutkCookie));
|
|
1263
|
-
}
|
|
1264
|
-
let uid = sanitizeHeaderValue(requestCookies.get(COOKIE_UID) ?? "");
|
|
1265
|
-
if (!uid) {
|
|
1266
|
-
uid = crypto.randomUUID();
|
|
1267
|
-
responseCookies.push({
|
|
1268
|
-
name: COOKIE_UID,
|
|
1269
|
-
value: uid,
|
|
1270
|
-
maxAge: ONE_YEAR_SECONDS,
|
|
1271
|
-
path: "/"
|
|
1272
|
-
});
|
|
1273
|
-
requestHeaders.set("Prepr-Customer-Id-Created", "true");
|
|
1274
|
-
}
|
|
1275
|
-
requestHeaders.set("Prepr-Customer-Id", uid);
|
|
1276
|
-
if (!opts?.preview) {
|
|
1277
|
-
return { requestHeaders, responseCookies };
|
|
1278
|
-
}
|
|
1279
|
-
const features = resolveFeatures(opts?.features);
|
|
1280
|
-
const hasPreviewParams = features.segments && searchParams.has(PARAM_SEGMENT) || features.abTesting && searchParams.has(PARAM_VARIANT);
|
|
1281
|
-
if (!hasPreviewParams) {
|
|
1282
|
-
const previewModeCookie = requestCookies.get(COOKIE_PREVIEW_MODE);
|
|
1283
|
-
const previewModeEnabled = previewModeCookie !== "false";
|
|
1284
|
-
if (!previewModeEnabled) {
|
|
1285
|
-
return { requestHeaders, responseCookies };
|
|
1286
|
-
}
|
|
1287
|
-
}
|
|
1288
|
-
requestHeaders.set("Prepr-Preview-Bar", "true");
|
|
1289
|
-
const isLivePreview = searchParams.get(PARAM_HIDE_BAR) === "true";
|
|
1290
|
-
if (!isLivePreview && !requestCookies.has(COOKIE_PREVIEW_MODE)) {
|
|
1291
|
-
responseCookies.push({
|
|
1292
|
-
name: COOKIE_PREVIEW_MODE,
|
|
1293
|
-
value: "true",
|
|
1294
|
-
maxAge: ONE_YEAR_SECONDS,
|
|
1295
|
-
path: "/",
|
|
1296
|
-
...crossSite
|
|
1297
|
-
});
|
|
1298
|
-
}
|
|
1299
|
-
if (!isLivePreview) {
|
|
1300
|
-
const segmentCookie = features.segments ? requestCookies.get(COOKIE_SEGMENT) : void 0;
|
|
1301
|
-
if (segmentCookie) {
|
|
1302
|
-
requestHeaders.set("Prepr-Segments", sanitizeHeaderValue(segmentCookie));
|
|
1303
|
-
}
|
|
1304
|
-
const abCookie = features.abTesting ? requestCookies.get(COOKIE_VARIANT) : void 0;
|
|
1305
|
-
if (abCookie) {
|
|
1306
|
-
requestHeaders.set("Prepr-ABtesting", sanitizeHeaderValue(abCookie));
|
|
1307
|
-
}
|
|
1308
|
-
}
|
|
1309
|
-
const previewAb = features.abTesting ? searchParams.get(PARAM_VARIANT) : null;
|
|
1310
|
-
if (previewAb !== null) {
|
|
1311
|
-
requestHeaders.set("Prepr-ABtesting", sanitizeHeaderValue(previewAb));
|
|
1312
|
-
if (!isLivePreview) {
|
|
1313
|
-
responseCookies.push({
|
|
1314
|
-
name: COOKIE_VARIANT,
|
|
1315
|
-
value: previewAb,
|
|
1316
|
-
maxAge: ONE_YEAR_SECONDS,
|
|
1317
|
-
path: "/",
|
|
1318
|
-
...crossSite
|
|
1319
|
-
});
|
|
1320
|
-
}
|
|
1321
|
-
}
|
|
1322
|
-
const previewSegment = features.segments ? searchParams.get(PARAM_SEGMENT) : null;
|
|
1323
|
-
if (previewSegment !== null) {
|
|
1324
|
-
requestHeaders.set("Prepr-Segments", sanitizeHeaderValue(previewSegment));
|
|
1325
|
-
if (!isLivePreview) {
|
|
1326
|
-
responseCookies.push({
|
|
1327
|
-
name: COOKIE_SEGMENT,
|
|
1328
|
-
value: previewSegment,
|
|
1329
|
-
maxAge: ONE_YEAR_SECONDS,
|
|
1330
|
-
path: "/",
|
|
1331
|
-
...crossSite
|
|
1332
|
-
});
|
|
1333
|
-
}
|
|
1334
|
-
}
|
|
1335
|
-
if (requestHeaders.has("Prepr-Segments")) {
|
|
1336
|
-
requestHeaders.delete("Prepr-Customer-Id");
|
|
1337
|
-
requestHeaders.delete("Prepr-Customer-Id-Created");
|
|
1338
|
-
}
|
|
1339
|
-
return { requestHeaders, responseCookies };
|
|
1340
|
-
}
|
|
1341
|
-
|
|
1342
|
-
// src/nextjs/middleware.ts
|
|
1343
|
-
function createPreprMiddleware(request, responseOrOptions, maybeOptions) {
|
|
1344
|
-
let chainedResponse;
|
|
1345
|
-
let options;
|
|
1346
|
-
if (responseOrOptions instanceof import_server8.NextResponse) {
|
|
1347
|
-
chainedResponse = responseOrOptions;
|
|
1348
|
-
options = maybeOptions;
|
|
1349
|
-
} else {
|
|
1350
|
-
options = responseOrOptions;
|
|
1351
|
-
}
|
|
1352
|
-
const { requestHeaders, responseCookies } = processFrameworkRequest(
|
|
1353
|
-
request,
|
|
1354
|
-
options,
|
|
1355
|
-
"nextjs"
|
|
1356
|
-
);
|
|
1357
|
-
const response = chainedResponse ?? import_server8.NextResponse.next({ request: { headers: requestHeaders } });
|
|
1358
|
-
if (chainedResponse) {
|
|
1359
|
-
const existing = response.headers.get("x-middleware-override-headers");
|
|
1360
|
-
const names = new Set(
|
|
1361
|
-
existing ? existing.split(",").map((name2) => name2.trim()).filter(Boolean) : []
|
|
1362
|
-
);
|
|
1363
|
-
requestHeaders.forEach((value, key) => {
|
|
1364
|
-
names.add(key);
|
|
1365
|
-
response.headers.set(`x-middleware-request-${key}`, value);
|
|
1366
|
-
});
|
|
1367
|
-
response.headers.set("x-middleware-override-headers", [...names].join(","));
|
|
1368
|
-
}
|
|
1369
|
-
for (const cookie of responseCookies) {
|
|
1370
|
-
response.cookies.set(cookie.name, cookie.value, {
|
|
1371
|
-
maxAge: cookie.maxAge,
|
|
1372
|
-
path: cookie.path,
|
|
1373
|
-
// Lower-cased: Next's cookie API expects 'none' | 'lax' | 'strict'.
|
|
1374
|
-
...cookie.sameSite ? {
|
|
1375
|
-
sameSite: cookie.sameSite.toLowerCase()
|
|
1376
|
-
} : {},
|
|
1377
|
-
...cookie.secure ? { secure: true } : {}
|
|
1378
|
-
});
|
|
1379
|
-
}
|
|
1380
|
-
return response;
|
|
1381
|
-
}
|
|
1382
|
-
|
|
1383
|
-
// src/nextjs/proxy.ts
|
|
1384
|
-
function isPagePath(pathname) {
|
|
1385
|
-
return !pathname.startsWith("/_next/") && !pathname.startsWith("/api/") && !/\.[^/]*$/.test(pathname);
|
|
1386
|
-
}
|
|
1387
|
-
function createPreprProxy(options) {
|
|
1388
|
-
const internals = preprClientInternals.get(options.client);
|
|
1389
|
-
if (!internals) {
|
|
1390
|
-
throw new PreprError(
|
|
1391
|
-
"createPreprProxy needs a client made by createPreprClient from @preprio/toolkit/nextjs/graphql",
|
|
1392
|
-
"CONTEXT_ERROR",
|
|
1393
|
-
"createPreprProxy"
|
|
1394
|
-
);
|
|
1395
|
-
}
|
|
1396
|
-
const { client } = internals;
|
|
1397
|
-
const preview = options.preview ?? false;
|
|
1398
|
-
const allowed = async (request) => {
|
|
1399
|
-
if (!options.onlyIf) return true;
|
|
1400
|
-
try {
|
|
1401
|
-
return await options.onlyIf(request);
|
|
1402
|
-
} catch {
|
|
1403
|
-
return false;
|
|
1404
|
-
}
|
|
1405
|
-
};
|
|
1406
|
-
const lookup = (target) => {
|
|
1407
|
-
try {
|
|
1408
|
-
return options.page(target) ?? null;
|
|
1409
|
-
} catch {
|
|
1410
|
-
return null;
|
|
1411
|
-
}
|
|
1412
|
-
};
|
|
1413
|
-
async function answerDecision(request, response, target) {
|
|
1414
|
-
let decision = DEFAULT_DECISION;
|
|
1415
|
-
const site = request.headers.get("sec-fetch-site");
|
|
1416
|
-
if (target && request.method === "GET" && (site === null || site === "same-origin") && await allowed(request)) {
|
|
1417
|
-
decision = await decideView(
|
|
1418
|
-
client,
|
|
1419
|
-
mergePreprHeaders(forwardedHeaders(request, response)),
|
|
1420
|
-
target,
|
|
1421
|
-
options.timeoutMs
|
|
1422
|
-
);
|
|
1423
|
-
}
|
|
1424
|
-
const answer = new import_server9.NextResponse(decision, {
|
|
1425
|
-
headers: {
|
|
1426
|
-
"Cache-Control": "private, no-store",
|
|
1427
|
-
"Content-Type": "text/plain; charset=utf-8"
|
|
1428
|
-
}
|
|
1429
|
-
});
|
|
1430
|
-
for (const cookie of response.cookies.getAll()) answer.cookies.set(cookie);
|
|
1431
|
-
return answer;
|
|
1432
|
-
}
|
|
1433
|
-
return async (request) => {
|
|
1434
|
-
const rendersPage = (request.method === "GET" || request.method === "HEAD") && isPagePath(request.nextUrl.pathname);
|
|
1435
|
-
const target = rendersPage ? lookup(request.nextUrl) : null;
|
|
1436
|
-
const decisionRequest = request.headers.has(PREPR_DECIDE_HEADER);
|
|
1437
|
-
if (target && preview && !decisionRequest) {
|
|
1438
|
-
const draft = preprDraftRedirect(request, { preview });
|
|
1439
|
-
if (draft) return draft;
|
|
1440
|
-
}
|
|
1441
|
-
const response = createPreprMiddleware(request, {
|
|
1442
|
-
preview,
|
|
1443
|
-
features: options.features
|
|
1444
|
-
});
|
|
1445
|
-
if (decisionRequest) return answerDecision(request, response, target);
|
|
1446
|
-
return response;
|
|
1447
|
-
};
|
|
1448
|
-
}
|
|
1449
|
-
|
|
1450
|
-
// src/nextjs/stack.ts
|
|
1451
|
-
var import_react = require("react");
|
|
1452
|
-
|
|
1453
|
-
// src/nextjs/decision-switch.ts
|
|
1454
|
-
function applyPreprDecisions(decision, options = {}) {
|
|
1455
|
-
const state = window;
|
|
1456
|
-
const key = location.pathname + location.search;
|
|
1457
|
-
const previous = state.__preprDecision;
|
|
1458
|
-
let value = decision;
|
|
1459
|
-
if (value !== void 0 && value !== "*" && options.refresh && previous && previous.key === key && previous.value !== "*") {
|
|
1460
|
-
const pairs = (from) => {
|
|
1461
|
-
const out = {};
|
|
1462
|
-
from.split("~").forEach((pair) => {
|
|
1463
|
-
const colon = pair.indexOf(":");
|
|
1464
|
-
if (colon > 0) out[pair.slice(0, colon)] = pair;
|
|
1465
|
-
});
|
|
1466
|
-
return out;
|
|
1467
|
-
};
|
|
1468
|
-
const before = pairs(previous.value);
|
|
1469
|
-
const after = pairs(value);
|
|
1470
|
-
document.querySelectorAll("[data-prepr-v][data-prepr-show]").forEach((element) => {
|
|
1471
|
-
const range = document.createRange();
|
|
1472
|
-
range.selectNodeContents(element);
|
|
1473
|
-
if (range.getBoundingClientRect().top >= window.innerHeight) return;
|
|
1474
|
-
(element.getAttribute("data-prepr-v") || "").split(" ").forEach((token) => {
|
|
1475
|
-
const group = token.slice(0, token.indexOf(":"));
|
|
1476
|
-
if (before[group]) after[group] = before[group];
|
|
1477
|
-
});
|
|
1478
|
-
});
|
|
1479
|
-
value = Object.keys(after).map((group) => after[group]).join("~");
|
|
1480
|
-
}
|
|
1481
|
-
if (value !== void 0) state.__preprDecision = { key, value };
|
|
1482
|
-
const current = state.__preprDecision;
|
|
1483
|
-
if (!current || current.key !== key) return false;
|
|
1484
|
-
document.querySelectorAll("[data-prepr-decision]").forEach((marker) => {
|
|
1485
|
-
marker.setAttribute("data-prepr-decided", "");
|
|
1486
|
-
});
|
|
1487
|
-
const defaults = current.value === "*";
|
|
1488
|
-
const chosen = {};
|
|
1489
|
-
current.value.split("~").forEach((pair) => {
|
|
1490
|
-
const colon = pair.indexOf(":");
|
|
1491
|
-
if (colon > 0)
|
|
1492
|
-
chosen[pair.slice(0, colon)] = pair.slice(colon + 1).split("|");
|
|
1493
|
-
});
|
|
1494
|
-
document.querySelectorAll("[data-prepr-v]").forEach((element) => {
|
|
1495
|
-
const nested = element.hasAttribute("data-prepr-nested");
|
|
1496
|
-
const show = defaults ? element.hasAttribute("data-prepr-default") : (element.getAttribute("data-prepr-v") || "").split(" ").every((token) => {
|
|
1497
|
-
const colon = token.indexOf(":");
|
|
1498
|
-
const variant = token.slice(colon + 1);
|
|
1499
|
-
const variants = chosen[token.slice(0, colon)];
|
|
1500
|
-
return !!variants && (nested ? variants[0] === variant : variants.indexOf(variant) >= 0);
|
|
1501
|
-
});
|
|
1502
|
-
if (show) element.setAttribute("data-prepr-show", "");
|
|
1503
|
-
else element.removeAttribute("data-prepr-show");
|
|
1504
|
-
});
|
|
1505
|
-
return true;
|
|
1506
|
-
}
|
|
1507
|
-
function requestPreprDecision(key, options = {}) {
|
|
1508
|
-
const fresh = 1e4;
|
|
1509
|
-
const keep = 18e5;
|
|
1510
|
-
const keepStatic = 36e5;
|
|
1511
|
-
const state = window;
|
|
1512
|
-
const asking = state.__preprAsking = state.__preprAsking || {};
|
|
1513
|
-
const read = () => {
|
|
1514
|
-
try {
|
|
1515
|
-
const all = JSON.parse(sessionStorage.getItem("prepr_decisions") || "{}");
|
|
1516
|
-
return all && typeof all === "object" ? all : {};
|
|
1517
|
-
} catch {
|
|
1518
|
-
return {};
|
|
1519
|
-
}
|
|
1520
|
-
};
|
|
1521
|
-
const ask = () => {
|
|
1522
|
-
if (!asking[key]) {
|
|
1523
|
-
asking[key] = fetch(key, {
|
|
1524
|
-
headers: { "Prepr-Decide": "1" },
|
|
1525
|
-
cache: "no-store",
|
|
1526
|
-
credentials: "same-origin",
|
|
1527
|
-
// The proxy gives up on Prepr after its own `timeoutMs`; this only
|
|
1528
|
-
// covers a proxy that never answers.
|
|
1529
|
-
signal: AbortSignal.timeout ? AbortSignal.timeout(6e3) : void 0
|
|
1530
|
-
}).then((response) => response.ok ? response.text() : "*").catch(() => "*").then((answer) => {
|
|
1531
|
-
delete asking[key];
|
|
1532
|
-
try {
|
|
1533
|
-
const all = read();
|
|
1534
|
-
const at = Date.now();
|
|
1535
|
-
Object.keys(all).forEach((stored) => {
|
|
1536
|
-
const entry = all[stored];
|
|
1537
|
-
if (!(entry && typeof entry.at === "number" && at - entry.at < keepStatic))
|
|
1538
|
-
delete all[stored];
|
|
1539
|
-
});
|
|
1540
|
-
const kept = all[key];
|
|
1541
|
-
if (answer !== "*" || !kept || kept.value === "*")
|
|
1542
|
-
all[key] = { value: answer, at };
|
|
1543
|
-
sessionStorage.setItem("prepr_decisions", JSON.stringify(all));
|
|
1544
|
-
} catch {
|
|
1545
|
-
}
|
|
1546
|
-
return answer;
|
|
1547
|
-
});
|
|
1548
|
-
}
|
|
1549
|
-
return asking[key];
|
|
1550
|
-
};
|
|
1551
|
-
const last = read()[key];
|
|
1552
|
-
const age = last && typeof last.at === "number" ? Date.now() - last.at : -1;
|
|
1553
|
-
const value = last && typeof last.value === "string" ? last.value : null;
|
|
1554
|
-
if (value !== null && !(value === "" && options.personalized) && age >= 0 && age < (value === "*" ? fresh : value === "" ? keepStatic : keep)) {
|
|
1555
|
-
if (value !== "" && age >= fresh) {
|
|
1556
|
-
ask().then((answer) => {
|
|
1557
|
-
if (answer !== "*" && answer !== value && options.onChange)
|
|
1558
|
-
options.onChange(answer);
|
|
1559
|
-
});
|
|
1560
|
-
}
|
|
1561
|
-
return { result: value, value: Promise.resolve(value) };
|
|
1562
|
-
}
|
|
1563
|
-
const pending = {
|
|
1564
|
-
value: ask()
|
|
1565
|
-
};
|
|
1566
|
-
pending.value.then((answer) => {
|
|
1567
|
-
pending.result = answer;
|
|
1568
|
-
});
|
|
1569
|
-
return pending;
|
|
1570
|
-
}
|
|
1571
|
-
function startPreprDecision() {
|
|
1572
|
-
const state = window;
|
|
1573
|
-
const key = location.pathname + location.search;
|
|
1574
|
-
const apply = (answer, refresh) => {
|
|
1575
|
-
if (location.pathname + location.search === key)
|
|
1576
|
-
state.__preprApply(answer, { refresh });
|
|
1577
|
-
};
|
|
1578
|
-
const pending = state.__preprRequest(key, {
|
|
1579
|
-
onChange: (answer) => apply(answer, true),
|
|
1580
|
-
personalized: true
|
|
1581
|
-
});
|
|
1582
|
-
if (pending.result !== void 0) apply(pending.result);
|
|
1583
|
-
else pending.value.then((answer) => apply(answer));
|
|
1584
|
-
}
|
|
1585
|
-
|
|
1586
|
-
// src/nextjs/stack.ts
|
|
1587
|
-
var import_components = require("./components.cjs");
|
|
1588
|
-
var VARIANT_ATTRIBUTE = "data-prepr-v";
|
|
1589
|
-
var DEFAULT_ATTRIBUTE = "data-prepr-default";
|
|
1590
|
-
var NESTED_ATTRIBUTE = "data-prepr-nested";
|
|
1591
|
-
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}`;
|
|
1592
|
-
var NOSCRIPT_HTML = `<style>[${VARIANT_ATTRIBUTE}][${DEFAULT_ATTRIBUTE}]{display:contents!important;visibility:visible!important}</style>`;
|
|
1593
|
-
var DECISION_SCRIPT = `window.__preprApply=${applyPreprDecisions.toString()};window.__preprRequest=${requestPreprDecision.toString()};(${startPreprDecision.toString()})();`;
|
|
1594
|
-
var APPLY_SCRIPT = "__preprApply()";
|
|
1595
|
-
function variantKeysOf(items) {
|
|
1596
|
-
return items.flatMap((item) => {
|
|
1597
|
-
const key = preprVariantProps(item)["data-prepr-variant-key"] ?? nestedKeyOf(item);
|
|
1598
|
-
return key ? [key] : [];
|
|
1599
|
-
});
|
|
1600
|
-
}
|
|
1601
|
-
function nestedKeyOf(value) {
|
|
1602
|
-
if (!value || typeof value !== "object") return void 0;
|
|
1603
|
-
for (const child of Object.values(value)) {
|
|
1604
|
-
const items = Array.isArray(child) ? child : [child];
|
|
1605
|
-
for (const item of items) {
|
|
1606
|
-
const key = contextOf(item)?.variant_key ?? (item && nestedKeyOf(item));
|
|
1607
|
-
if (key) return key;
|
|
1608
|
-
}
|
|
1609
|
-
}
|
|
1610
|
-
return void 0;
|
|
1611
|
-
}
|
|
1612
|
-
function renderItems(items, render, options) {
|
|
1613
|
-
const resolved = resolveVariants(items, {
|
|
1614
|
-
decisions: options.decisions,
|
|
1615
|
-
bucket: options.bucket
|
|
1616
|
-
});
|
|
1617
|
-
const content = render(resolved, {
|
|
1618
|
-
index: options.index,
|
|
1619
|
-
defaultVariant: options.defaultVariant
|
|
1620
|
-
});
|
|
1621
|
-
const variantKeys = options.track ? variantKeysOf(resolved) : [];
|
|
1622
|
-
return variantKeys.length > 0 ? (0, import_react.createElement)(import_components.PreprVariantTracking, { variantKeys }, content) : content;
|
|
1623
|
-
}
|
|
1624
|
-
function decidedGroups(items, bucket) {
|
|
1625
|
-
const groups = /* @__PURE__ */ new Map();
|
|
1626
|
-
const walk = (value) => {
|
|
1627
|
-
if (Array.isArray(value)) return value.forEach(walk);
|
|
1628
|
-
if (!value || typeof value !== "object") return;
|
|
1629
|
-
const ctx = contextOf(value);
|
|
1630
|
-
const decided = ctx?.kind === "PERSONALIZATION" || ctx?.kind === "AB_TEST" && !bucket;
|
|
1631
|
-
if (decided && ctx.variant_id) {
|
|
1632
|
-
const group = groups.get(ctx.group_id) ?? {
|
|
1633
|
-
variants: /* @__PURE__ */ new Set(),
|
|
1634
|
-
fallback: ctx.kind === "AB_TEST" ? "A" : PREPR_DEFAULT_VARIANT
|
|
1635
|
-
};
|
|
1636
|
-
group.variants.add(ctx.variant_id);
|
|
1637
|
-
groups.set(ctx.group_id, group);
|
|
1638
|
-
}
|
|
1639
|
-
Object.values(value).forEach(walk);
|
|
1640
|
-
};
|
|
1641
|
-
walk(items);
|
|
1642
|
-
return groups;
|
|
1643
|
-
}
|
|
1644
|
-
function renderVariants(block, groups, render, options) {
|
|
1645
|
-
const top = block.key.startsWith("group:") ? block.key.slice("group:".length) : void 0;
|
|
1646
|
-
const nested = !(top !== void 0 && groups.size === 1);
|
|
1647
|
-
const choices = [...groups].map(([group, { variants, fallback }]) => {
|
|
1648
|
-
const ids = nested ? [fallback, ...variants] : [...variants];
|
|
1649
|
-
return [...new Set(ids)].map((variant) => [group, variant]);
|
|
1650
|
-
});
|
|
1651
|
-
const combinations = choices.reduce(
|
|
1652
|
-
(all, pairs) => all.flatMap((combo) => pairs.map((p) => [...combo, p])),
|
|
1653
|
-
[[]]
|
|
1654
|
-
);
|
|
1655
|
-
return combinations.map((combination) => {
|
|
1656
|
-
const pairs = combination.map(([group, variant]) => `${group}:${variant}`);
|
|
1657
|
-
const isDefault = combination.every(
|
|
1658
|
-
([group, variant]) => variant === groups.get(group).fallback
|
|
1659
|
-
);
|
|
1660
|
-
return (0, import_react.createElement)(
|
|
1661
|
-
"div",
|
|
1662
|
-
{
|
|
1663
|
-
key: pairs.join(" "),
|
|
1664
|
-
[VARIANT_ATTRIBUTE]: pairs.join(" "),
|
|
1665
|
-
...isDefault ? { [DEFAULT_ATTRIBUTE]: "" } : {},
|
|
1666
|
-
...nested ? { [NESTED_ATTRIBUTE]: "" } : {},
|
|
1667
|
-
// The decision script marks the shown wrapper before hydration.
|
|
1668
|
-
suppressHydrationWarning: true
|
|
1669
|
-
},
|
|
1670
|
-
renderItems(block.items, render, {
|
|
1671
|
-
bucket: options.bucket,
|
|
1672
|
-
decisions: new Map(combination.map(([g, v]) => [g, [v]])),
|
|
1673
|
-
index: block.index,
|
|
1674
|
-
track: options.track,
|
|
1675
|
-
defaultVariant: isDefault
|
|
1676
|
-
})
|
|
1677
|
-
);
|
|
1678
|
-
});
|
|
1679
|
-
}
|
|
1680
|
-
function PreprStack({
|
|
1681
|
-
items,
|
|
1682
|
-
render,
|
|
1683
|
-
bucket,
|
|
1684
|
-
nonce,
|
|
1685
|
-
trackVariants = false
|
|
1686
|
-
}) {
|
|
1687
|
-
const blocks = splitStack(items).map((block) => ({
|
|
1688
|
-
...block,
|
|
1689
|
-
groups: decidedGroups(block.items, bucket)
|
|
1690
|
-
}));
|
|
1691
|
-
const varies = blocks.some((block) => block.groups.size > 0);
|
|
1692
|
-
return (0, import_react.createElement)(
|
|
1693
|
-
import_react.Fragment,
|
|
1694
|
-
null,
|
|
1695
|
-
varies && (0, import_react.createElement)(
|
|
1696
|
-
import_react.Fragment,
|
|
1697
|
-
{ key: "prepr-switch" },
|
|
1698
|
-
(0, import_react.createElement)("style", {
|
|
1699
|
-
nonce,
|
|
1700
|
-
dangerouslySetInnerHTML: { __html: GROUP_BASE_CSS }
|
|
1701
|
-
}),
|
|
1702
|
-
(0, import_react.createElement)("noscript", {
|
|
1703
|
-
dangerouslySetInnerHTML: { __html: NOSCRIPT_HTML }
|
|
1704
|
-
}),
|
|
1705
|
-
(0, import_react.createElement)("script", {
|
|
1706
|
-
nonce,
|
|
1707
|
-
dangerouslySetInnerHTML: { __html: DECISION_SCRIPT }
|
|
1708
|
-
}),
|
|
1709
|
-
(0, import_react.createElement)(import_components.PreprDecisionApplier),
|
|
1710
|
-
// Marked decided by the decision switch; never laid out.
|
|
1711
|
-
(0, import_react.createElement)("template", {
|
|
1712
|
-
"data-prepr-decision": "",
|
|
1713
|
-
suppressHydrationWarning: true
|
|
1714
|
-
})
|
|
1715
|
-
),
|
|
1716
|
-
...blocks.map((block) => {
|
|
1717
|
-
if (block.groups.size === 0) {
|
|
1718
|
-
return (0, import_react.createElement)(
|
|
1719
|
-
import_react.Fragment,
|
|
1720
|
-
{ key: block.key },
|
|
1721
|
-
renderItems(block.items, render, {
|
|
1722
|
-
bucket,
|
|
1723
|
-
index: block.index,
|
|
1724
|
-
track: trackVariants,
|
|
1725
|
-
defaultVariant: true
|
|
1726
|
-
})
|
|
1727
|
-
);
|
|
1728
|
-
}
|
|
1729
|
-
return (0, import_react.createElement)(
|
|
1730
|
-
import_react.Fragment,
|
|
1731
|
-
{ key: block.key },
|
|
1732
|
-
renderVariants(block, block.groups, render, {
|
|
1733
|
-
bucket,
|
|
1734
|
-
track: trackVariants
|
|
1735
|
-
}),
|
|
1736
|
-
(0, import_react.createElement)("script", {
|
|
1737
|
-
nonce,
|
|
1738
|
-
dangerouslySetInnerHTML: { __html: APPLY_SCRIPT }
|
|
1739
|
-
})
|
|
1740
|
-
);
|
|
1741
|
-
})
|
|
1742
|
-
);
|
|
1743
|
-
}
|
|
1744
|
-
|
|
1745
|
-
// src/nextjs/graphql.ts
|
|
1746
|
-
function createPreprClient2(options) {
|
|
1747
|
-
const { cacheTags = ["prepr"], revalidate, ...coreOptions } = options;
|
|
1748
|
-
const client = createPreprClient({
|
|
1749
|
-
// The schema introspection goes through the Data Cache: shared across
|
|
1750
|
-
// server instances, refreshed hourly and by a `schema.changed` webhook.
|
|
1751
|
-
schemaInit: {
|
|
1752
|
-
next: { tags: [...cacheTags, PREPR_SCHEMA_TAG], revalidate: 3600 }
|
|
1753
|
-
},
|
|
1754
|
-
...coreOptions
|
|
1755
|
-
});
|
|
1756
|
-
const nextClient = {
|
|
1757
|
-
async query(document2, variables, queryOptions = {}) {
|
|
1758
|
-
const { personalize = false, tagItems = false, ...rest } = queryOptions;
|
|
1759
|
-
const { next, ...init } = rest.init ?? {};
|
|
1760
|
-
if (tagItems && typeof nextCache.cacheTag !== "function") {
|
|
1761
|
-
throw new Error("tagItems requires Next.js 16 or later.");
|
|
1762
|
-
}
|
|
1763
|
-
const options2 = {
|
|
1764
|
-
...rest,
|
|
1765
|
-
// With tagItems, `next` is dropped too: tags or revalidate alongside
|
|
1766
|
-
// `no-store` are a conflict Next.js resolves by ignoring the store.
|
|
1767
|
-
// Otherwise tags are attached unconditionally; the core client drops
|
|
1768
|
-
// them again whenever the request ends up `no-store` (personalized,
|
|
1769
|
-
// per-request headers, or preview).
|
|
1770
|
-
init: tagItems ? { ...init, cache: "no-store" } : {
|
|
1771
|
-
...init,
|
|
1772
|
-
next: {
|
|
1773
|
-
...revalidate === void 0 ? {} : { revalidate },
|
|
1774
|
-
...next,
|
|
1775
|
-
// Merged, so a per-query tag never drops the client's own,
|
|
1776
|
-
// which the publish webhook relies on.
|
|
1777
|
-
tags: [...cacheTags, ...next?.tags ?? []]
|
|
1778
|
-
}
|
|
1779
|
-
}
|
|
1780
|
-
};
|
|
1781
|
-
if (personalize) {
|
|
1782
|
-
options2.headers = mergePreprHeaders(
|
|
1783
|
-
await getPreprHeaders(),
|
|
1784
|
-
rest.headers
|
|
1785
|
-
);
|
|
1786
|
-
}
|
|
1787
|
-
const result = await client.query(document2, variables, options2);
|
|
1788
|
-
if (tagItems) {
|
|
1789
|
-
let modelTags;
|
|
1790
|
-
try {
|
|
1791
|
-
modelTags = preprModelTagsFor(
|
|
1792
|
-
documentOf(document2),
|
|
1793
|
-
result.data,
|
|
1794
|
-
await clientSchemas.get(client)()
|
|
1795
|
-
);
|
|
1796
|
-
} catch {
|
|
1797
|
-
modelTags = [PREPR_ANY_ITEM_TAG];
|
|
1798
|
-
}
|
|
1799
|
-
nextCache.cacheTag(...cacheTags, ...next?.tags ?? [], ...modelTags);
|
|
1800
|
-
nextCache.cacheTag(...preprCacheTags(result.data));
|
|
1801
|
-
}
|
|
1802
|
-
return result;
|
|
1803
|
-
},
|
|
1804
|
-
async decide(document2, variables, queryOptions = {}) {
|
|
1805
|
-
return client.decide(document2, variables, {
|
|
1806
|
-
...queryOptions,
|
|
1807
|
-
headers: mergePreprHeaders(
|
|
1808
|
-
await getPreprHeaders(),
|
|
1809
|
-
queryOptions.headers
|
|
1810
|
-
)
|
|
1811
|
-
});
|
|
1812
|
-
},
|
|
1813
|
-
hasAbTests: (document2, variables) => client.hasAbTests(document2, variables)
|
|
1814
|
-
};
|
|
1815
|
-
preprClientInternals.set(nextClient, { client });
|
|
1816
|
-
return nextClient;
|
|
1817
|
-
}
|
|
1818
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
1819
|
-
0 && (module.exports = {
|
|
1820
|
-
PREPR_ANY_ITEM_TAG,
|
|
1821
|
-
PREPR_DEFAULT_VARIANT,
|
|
1822
|
-
PreprError,
|
|
1823
|
-
PreprStack,
|
|
1824
|
-
createPreprClient,
|
|
1825
|
-
createPreprProxy,
|
|
1826
|
-
decisionsFrom,
|
|
1827
|
-
isPersonalizedResponse,
|
|
1828
|
-
loadPreprSchema,
|
|
1829
|
-
preprCacheTags,
|
|
1830
|
-
preprModelTag,
|
|
1831
|
-
preprVariantProps,
|
|
1832
|
-
resolveVariants,
|
|
1833
|
-
splitStack,
|
|
1834
|
-
toDecisionQuery,
|
|
1835
|
-
toVariantsQuery
|
|
1836
|
-
});
|