-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathsegment.ts
More file actions
276 lines (247 loc) · 7.41 KB
/
Copy pathsegment.ts
File metadata and controls
276 lines (247 loc) · 7.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import { setCookie } from "std/http/mod.ts";
import { AppContext } from "../mod.ts";
import type { Segment } from "./types.ts";
import { removeNonLatin1Chars } from "../../utils/normalize.ts";
const SEGMENT_COOKIE_NAME = "vtex_segment";
const SALES_CHANNEL_COOKIE = "VTEXSC";
const SEGMENT = Symbol("segment");
const ORDER_FORM_ID = Symbol("orderFormId");
export interface WrappedSegment {
payload: Partial<Segment>;
token: string;
}
/**
* by default segment starts with null values
*/
const DEFAULT_SEGMENT: Partial<Segment> = {
utmi_campaign: null,
utmi_page: null,
utmi_part: null,
utm_campaign: null,
utm_source: null,
utm_medium: null,
channel: "1",
cultureInfo: "pt-BR",
currencyCode: "BRL",
currencySymbol: "R$",
countryCode: "BRA",
};
const isDefautSalesChannel = (ctx: AppContext, channel?: string) => {
return channel ===
(ctx.salesChannel || DEFAULT_SEGMENT.channel ||
ctx.defaultSegment?.channel);
};
export const isAnonymous = (
ctx: AppContext,
) => {
const payload = getSegmentFromBag(ctx)?.payload;
if (!payload) {
return true;
}
const {
campaigns,
utm_campaign,
utm_source,
utmi_campaign,
channel,
priceTables,
regionId,
} = payload;
return !campaigns &&
!utm_campaign &&
!utm_source &&
!utmi_campaign &&
(!channel || isDefautSalesChannel(ctx, channel)) &&
!priceTables &&
!regionId;
};
export const isCacheableSegment = (ctx: AppContext) => {
const payload = getSegmentFromBag(ctx)?.payload;
if (payload?.channelPrivacy === "private") return false;
if (!payload) return true;
const { campaigns, priceTables, regionId } = payload;
return !campaigns && !priceTables && !regionId;
};
const setSegmentInBag = (ctx: AppContext, data: WrappedSegment) =>
ctx?.bag?.set(SEGMENT, data);
export const getSegmentFromBag = (
ctx: AppContext,
): WrappedSegment => ctx?.bag?.get(SEGMENT);
export const getOrderFormIdFromBag = (
ctx: AppContext,
): Promise<string | undefined> | undefined => ctx?.bag?.get(ORDER_FORM_ID);
export const setOrderFormIdInBag = (
ctx: AppContext,
orderFormId: Promise<string | undefined>,
) => ctx?.bag?.set(ORDER_FORM_ID, orderFormId);
/**
* Creates a stable cache key from segment that only includes business-critical fields.
* Excludes marketing/tracking parameters (UTM, UTMI) to prevent cache fragmentation.
*
* Use this for cacheKey generation instead of the full segment token.
*/
export const getSegmentCacheKeyWithoutUTM = (ctx: AppContext): string => {
const segment = getSegmentFromBag(ctx)?.payload;
if (!segment) {
return "";
}
// Only include fields that affect pricing, inventory, or content
const cacheRelevantSegment = {
campaigns: segment.campaigns, // VTEX campaigns (can affect pricing)
channel: segment.channel, // Sales channel (affects inventory/pricing)
priceTables: segment.priceTables, // Price tables (affects pricing)
regionId: segment.regionId, // Region (can affect pricing/inventory)
currencyCode: segment.currencyCode, // Currency
cultureInfo: segment.cultureInfo, // Locale/language
countryCode: segment.countryCode, // Country
channelPrivacy: segment.channelPrivacy, // Privacy settings
// EXCLUDED: utm_campaign, utm_source, utm_medium (marketing only)
// EXCLUDED: utmi_campaign, utmi_page, utmi_part (VTEX tracking only)
};
// Stable serialization for consistent cache keys
return btoa(JSON.stringify(cacheRelevantSegment));
};
/**
* Stable serialization.
*
* This means that even if the attributes are in a different order, the final segment
* value will be the same. This improves cache hits
*/
const serialize = ({
campaigns,
channel,
priceTables,
regionId,
utm_campaign,
utm_source,
utm_medium,
utmi_campaign,
utmi_page,
utmi_part,
currencyCode,
currencySymbol,
countryCode,
cultureInfo,
channelPrivacy,
}: Partial<Segment>) => {
const seg = {
campaigns,
channel,
priceTables,
regionId,
utm_campaign: utm_campaign &&
removeNonLatin1Chars(utm_campaign).replace(/[\/\[\]{}()<>.]/g, ""),
utm_source: utm_source &&
removeNonLatin1Chars(utm_source).replace(/[\/\[\]{}()<>.]/g, ""),
utm_medium: utm_medium &&
removeNonLatin1Chars(utm_medium).replace(/[\/\[\]{}()<>.]/g, ""),
utmi_campaign: utmi_campaign && removeNonLatin1Chars(utmi_campaign),
utmi_page: utmi_page && removeNonLatin1Chars(utmi_page),
utmi_part: utmi_part && removeNonLatin1Chars(utmi_part),
currencyCode,
currencySymbol,
countryCode,
cultureInfo,
channelPrivacy,
};
return btoa(JSON.stringify(seg));
};
const parse = (cookie: string) => {
try {
return JSON.parse(atob(cookie));
} catch {
return null;
}
};
const SEGMENT_QUERY_PARAMS = [
"utmi_campaign" as const,
"utmi_page" as const,
"utmi_part" as const,
"utm_campaign" as const,
"utm_source" as const,
"utm_medium" as const,
];
export const buildSegmentFromRequest = (req: Request): Partial<Segment> => {
const url = new URL(req.url);
const partialSegment: Partial<Segment> = {};
for (const qs of SEGMENT_QUERY_PARAMS) {
const param = url.searchParams.get(qs);
if (param) {
partialSegment[qs] = param;
}
}
const sc = url.searchParams.get("sc");
if (sc) {
partialSegment.channel = sc;
}
return partialSegment;
};
export const withSegmentCookie = (
segment: WrappedSegment,
headers?: Headers,
) => {
const h = new Headers(headers);
if (!segment) {
return h;
}
const { token } = segment;
h.set("cookie", `${SEGMENT_COOKIE_NAME}=${token}`);
return h;
};
export const setSegmentBag = (
cookies: Record<string, string>,
req: Request,
ctx: AppContext,
) => {
const vtex_segment = cookies[SEGMENT_COOKIE_NAME];
const segmentFromCookie = vtex_segment && parse(vtex_segment);
const segmentFromSalesChannelCookie = cookies[SALES_CHANNEL_COOKIE]
? {
channel: cookies[SALES_CHANNEL_COOKIE]?.split("=")[1],
}
: {};
const segmentFromRequest = buildSegmentFromRequest(req);
const locale = {
...(ctx.defaultSegment?.countryCode && {
countryCode: ctx.defaultSegment.countryCode,
}),
...(ctx.defaultSegment?.cultureInfo && {
cultureInfo: ctx.defaultSegment.cultureInfo,
}),
};
const segment = {
channel: ctx.salesChannel,
...DEFAULT_SEGMENT,
...ctx.defaultSegment,
...segmentFromCookie,
...segmentFromSalesChannelCookie,
...segmentFromRequest,
...locale,
};
const token = serialize(segment);
setSegmentInBag(ctx, { payload: segment, token });
// Always persist sales channel when it comes from request params so the
// browser carries it across navigation. The CDN varies its cache key by
// VTEXSC, so setting this cookie does not prevent CDN caching.
if (segmentFromRequest.channel) {
setCookie(ctx.response.headers, {
value: `sc=${segmentFromRequest.channel}`,
name: SALES_CHANNEL_COOKIE,
path: "/",
secure: true,
});
}
// Only set vtex_segment on non-cacheable responses so cacheable ones (incl.
// UTM-only and non-default sales channel) stay Set-Cookie-free and CDN-
// cacheable. Mirrors the middleware's cacheability check (isCacheableSegment)
// so the cookie gate and the Cache-Control decision never disagree.
if (vtex_segment !== token && !isCacheableSegment(ctx)) {
setCookie(ctx.response.headers, {
value: token,
name: SEGMENT_COOKIE_NAME,
path: "/",
secure: true,
httpOnly: true,
});
}
};