@decocms/blocks 8.1.0-next.0 → 8.1.0-next.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 (114) hide show
  1. package/package.json +6 -92
  2. package/src/index.ts +2 -12
  3. package/src/protocol/storage/memory.ts +1 -1
  4. package/src/v8/background.ts +3 -3
  5. package/src/v8/builtins/legacy.ts +1 -1
  6. package/src/v8/cli/index.ts +1 -1
  7. package/src/v8/fetch.ts +8 -27
  8. package/src/v8/remoteLoader.ts +1 -1
  9. package/src/v8/telemetry.ts +1 -1
  10. package/src/cms/applySectionConventions.ts +0 -148
  11. package/src/cms/blockSource.ts +0 -228
  12. package/src/cms/client.ts +0 -85
  13. package/src/cms/deferredTrigger.ts +0 -58
  14. package/src/cms/draftSource.ts +0 -476
  15. package/src/cms/index.ts +0 -180
  16. package/src/cms/loadDecofileDirectory.ts +0 -89
  17. package/src/cms/loader.ts +0 -563
  18. package/src/cms/registry.ts +0 -264
  19. package/src/cms/renderJson.ts +0 -179
  20. package/src/cms/resolve.ts +0 -2583
  21. package/src/cms/schema.ts +0 -1219
  22. package/src/cms/sectionLoaderContext.ts +0 -113
  23. package/src/cms/sectionLoaders.ts +0 -686
  24. package/src/cms/sectionMixins.ts +0 -153
  25. package/src/flags/audience.ts +0 -56
  26. package/src/flags/everyone.ts +0 -29
  27. package/src/flags/flag.ts +0 -15
  28. package/src/flags/multivariate/image.ts +0 -11
  29. package/src/flags/multivariate/message.ts +0 -11
  30. package/src/flags/multivariate/page.ts +0 -16
  31. package/src/flags/multivariate/section.ts +0 -16
  32. package/src/flags/multivariate.ts +0 -1
  33. package/src/flags/types.ts +0 -59
  34. package/src/flags/utils/multivariate.ts +0 -20
  35. package/src/hooks/Image.tsx +0 -314
  36. package/src/hooks/JsonLd.tsx +0 -353
  37. package/src/hooks/LazySection.tsx +0 -121
  38. package/src/hooks/LiveControls.tsx +0 -144
  39. package/src/hooks/Picture.tsx +0 -127
  40. package/src/hooks/RenderSection.tsx +0 -91
  41. package/src/hooks/SectionErrorFallback.tsx +0 -97
  42. package/src/hooks/Stats.tsx +0 -134
  43. package/src/hooks/index.ts +0 -35
  44. package/src/hooks/useLoadMore.ts +0 -100
  45. package/src/matchers/builtins.ts +0 -459
  46. package/src/matchers/countryNames.ts +0 -104
  47. package/src/matchers/override.ts +0 -136
  48. package/src/matchers/posthog.ts +0 -154
  49. package/src/middleware/decoState.ts +0 -55
  50. package/src/middleware/healthMetrics.ts +0 -133
  51. package/src/middleware/hydrationContext.ts +0 -79
  52. package/src/middleware/index.ts +0 -88
  53. package/src/middleware/liveness.ts +0 -21
  54. package/src/middleware/observability.ts +0 -800
  55. package/src/middleware/validateSection.ts +0 -100
  56. package/src/preview/DraftPreviewBadge.tsx +0 -306
  57. package/src/preview/decoMark.ts +0 -11
  58. package/src/preview/index.ts +0 -8
  59. package/src/sdk/abTesting.ts +0 -556
  60. package/src/sdk/analytics.ts +0 -147
  61. package/src/sdk/cacheHeaders.ts +0 -633
  62. package/src/sdk/cacheStorage.ts +0 -287
  63. package/src/sdk/cachedLoader.ts +0 -556
  64. package/src/sdk/clx.ts +0 -5
  65. package/src/sdk/cn.ts +0 -28
  66. package/src/sdk/composite.ts +0 -114
  67. package/src/sdk/cookie.ts +0 -129
  68. package/src/sdk/crypto.ts +0 -199
  69. package/src/sdk/csp.ts +0 -59
  70. package/src/sdk/deepOmit.ts +0 -52
  71. package/src/sdk/detectDevice.ts +0 -45
  72. package/src/sdk/djb2.ts +0 -20
  73. package/src/sdk/encoding.ts +0 -44
  74. package/src/sdk/env.ts +0 -54
  75. package/src/sdk/experiments.ts +0 -314
  76. package/src/sdk/fetchCache.ts +0 -269
  77. package/src/sdk/fetchTimeout.ts +0 -58
  78. package/src/sdk/flags.ts +0 -138
  79. package/src/sdk/http.ts +0 -124
  80. package/src/sdk/index.ts +0 -97
  81. package/src/sdk/inflightTimeout.ts +0 -53
  82. package/src/sdk/instrumentedFetch.ts +0 -362
  83. package/src/sdk/invoke.ts +0 -298
  84. package/src/sdk/logger.ts +0 -304
  85. package/src/sdk/mergeCacheControl.ts +0 -150
  86. package/src/sdk/nonce.ts +0 -46
  87. package/src/sdk/normalizeUrls.ts +0 -91
  88. package/src/sdk/observability.ts +0 -116
  89. package/src/sdk/otel.ts +0 -1118
  90. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  91. package/src/sdk/otelAdapters.ts +0 -144
  92. package/src/sdk/otelHttpLog.ts +0 -419
  93. package/src/sdk/otelHttpMeter.ts +0 -532
  94. package/src/sdk/otelHttpTracer.ts +0 -543
  95. package/src/sdk/redirects.ts +0 -336
  96. package/src/sdk/requestContext.ts +0 -281
  97. package/src/sdk/requestContextStorage.browser.ts +0 -43
  98. package/src/sdk/requestContextStorage.ts +0 -35
  99. package/src/sdk/responseCache.ts +0 -82
  100. package/src/sdk/retry.ts +0 -45
  101. package/src/sdk/serverTimings.ts +0 -68
  102. package/src/sdk/signal.ts +0 -42
  103. package/src/sdk/sitemap.ts +0 -160
  104. package/src/sdk/urlRedaction.ts +0 -82
  105. package/src/sdk/urlUtils.ts +0 -183
  106. package/src/sdk/useDevice.ts +0 -89
  107. package/src/sdk/useDeviceContext.tsx +0 -108
  108. package/src/sdk/useId.ts +0 -7
  109. package/src/sdk/useScript.ts +0 -210
  110. package/src/sdk/useSuggestions.ts +0 -188
  111. package/src/sdk/wrapCaughtErrors.ts +0 -107
  112. package/src/setup.ts +0 -120
  113. package/src/types/index.ts +0 -53
  114. package/src/types/widgets.ts +0 -14
@@ -1,633 +0,0 @@
1
- /**
2
- * Unified cache profile system for Deco storefronts.
3
- *
4
- * Each named profile (product, listing, search, static, etc.) defines cache
5
- * timing across ALL layers — edge, browser, loader, and client — in a single
6
- * object. This is the single source of truth for cache configuration.
7
- *
8
- * Sites override specific values via `setCacheProfile()` without touching
9
- * framework code. Derivation functions (`cacheHeaders`, `routeCacheDefaults`,
10
- * `loaderCacheOptions`, `edgeCacheConfig`) read from the profiles.
11
- *
12
- * @example
13
- * ```ts
14
- * // Site-level override (src/cache-config.ts):
15
- * import { setCacheProfile } from "@decocms/start/sdk/cacheHeaders";
16
- * setCacheProfile("product", { edge: { fresh: 600 } }); // 10min instead of 5min
17
- * ```
18
- */
19
-
20
- import { isTrackingParam } from "./urlUtils";
21
-
22
- // ---------------------------------------------------------------------------
23
- // Types
24
- // ---------------------------------------------------------------------------
25
-
26
- export type CacheProfileName =
27
- | "static"
28
- | "product"
29
- | "listing"
30
- | "search"
31
- | "cart"
32
- | "private"
33
- | "none";
34
-
35
- /** Time windows for a single caching layer (in seconds). */
36
- export interface CacheTimingWindow {
37
- /** How long content is considered fresh — served without origin contact. */
38
- fresh: number;
39
- /** After fresh expires, serve stale while refreshing in background. */
40
- swr: number;
41
- /** After fresh expires and origin is erroring, serve stale for this long. */
42
- sie: number;
43
- }
44
-
45
- /** Unified cache profile covering all layers. */
46
- export interface CacheProfileConfig {
47
- /** Edge / CDN layer (Cloudflare Cache API). Times in seconds. */
48
- edge: CacheTimingWindow;
49
- /** Browser layer (Cache-Control header). Times in seconds. */
50
- browser: CacheTimingWindow;
51
- /** In-memory loader layer. Times in milliseconds. */
52
- loader: {
53
- fresh: number;
54
- sie: number;
55
- };
56
- /** Client-side TanStack Router. Times in milliseconds. */
57
- client: {
58
- staleTime: number;
59
- gcTime: number;
60
- };
61
- /** Whether CDN can cache this profile. False = private, never cached. */
62
- isPublic: boolean;
63
- }
64
-
65
- /**
66
- * Deep partial of CacheProfileConfig for site-level overrides.
67
- * Only the fields you specify are merged; everything else keeps its default.
68
- */
69
- export type CacheProfileOverrides = {
70
- [K in keyof CacheProfileConfig]?: CacheProfileConfig[K] extends object
71
- ? Partial<CacheProfileConfig[K]>
72
- : CacheProfileConfig[K];
73
- };
74
-
75
- // ---------------------------------------------------------------------------
76
- // Default profiles
77
- // ---------------------------------------------------------------------------
78
-
79
- const PROFILES: Record<CacheProfileName, CacheProfileConfig> = {
80
- static: {
81
- edge: { fresh: 900, swr: 7200, sie: 21600 },
82
- browser: { fresh: 120, swr: 1800, sie: 7200 },
83
- loader: { fresh: 300_000, sie: 1_800_000 },
84
- client: { staleTime: 300_000, gcTime: 1_800_000 },
85
- isPublic: true,
86
- },
87
- product: {
88
- edge: { fresh: 300, swr: 1800, sie: 7200 },
89
- browser: { fresh: 60, swr: 600, sie: 3600 },
90
- loader: { fresh: 30_000, sie: 600_000 },
91
- client: { staleTime: 60_000, gcTime: 300_000 },
92
- isPublic: true,
93
- },
94
- listing: {
95
- edge: { fresh: 120, swr: 900, sie: 3600 },
96
- browser: { fresh: 30, swr: 300, sie: 1800 },
97
- loader: { fresh: 60_000, sie: 300_000 },
98
- client: { staleTime: 60_000, gcTime: 300_000 },
99
- isPublic: true,
100
- },
101
- search: {
102
- edge: { fresh: 60, swr: 300, sie: 1800 },
103
- browser: { fresh: 0, swr: 120, sie: 600 },
104
- loader: { fresh: 60_000, sie: 180_000 },
105
- client: { staleTime: 30_000, gcTime: 120_000 },
106
- isPublic: true,
107
- },
108
- cart: {
109
- edge: { fresh: 0, swr: 0, sie: 0 },
110
- browser: { fresh: 0, swr: 0, sie: 0 },
111
- loader: { fresh: 0, sie: 0 },
112
- client: { staleTime: 0, gcTime: 0 },
113
- isPublic: false,
114
- },
115
- private: {
116
- edge: { fresh: 0, swr: 0, sie: 0 },
117
- browser: { fresh: 0, swr: 0, sie: 0 },
118
- loader: { fresh: 0, sie: 0 },
119
- client: { staleTime: 0, gcTime: 0 },
120
- isPublic: false,
121
- },
122
- none: {
123
- edge: { fresh: 0, swr: 0, sie: 0 },
124
- browser: { fresh: 0, swr: 0, sie: 0 },
125
- loader: { fresh: 0, sie: 0 },
126
- client: { staleTime: 0, gcTime: 0 },
127
- isPublic: false,
128
- },
129
- };
130
-
131
- // ---------------------------------------------------------------------------
132
- // Profile accessors
133
- // ---------------------------------------------------------------------------
134
-
135
- export function getCacheProfile(profile: CacheProfileName): CacheProfileConfig {
136
- return PROFILES[profile];
137
- }
138
-
139
- /**
140
- * Override specific values of a cache profile. Only the fields you specify
141
- * are merged; everything else keeps its default.
142
- *
143
- * @example
144
- * ```ts
145
- * setCacheProfile("product", { edge: { fresh: 600 } });
146
- * setCacheProfile("static", { loader: { sie: 3_600_000 } });
147
- * ```
148
- */
149
- export function setCacheProfile(
150
- profile: CacheProfileName,
151
- overrides: CacheProfileOverrides,
152
- ): void {
153
- const current = PROFILES[profile];
154
-
155
- // `private`/`cart`/`none` are the profiles that keep authenticated pages off
156
- // the shared edge (and, once CDN caching is on, off the CDN). Flipping one to
157
- // public is how a checkout page ends up served to another visitor, so it
158
- // takes more than an `isPublic: true` in a props bag — see
159
- // `allowPublicPrivateProfile`.
160
- let isPublic = overrides.isPublic ?? current.isPublic;
161
- if (isPublic && !current.isPublic && !publicPrivateProfilesAllowed) {
162
- console.warn(
163
- `[deco] setCacheProfile("${profile}", { isPublic: true }) ignored: making a ` +
164
- `non-public profile public would let authenticated pages be shared between ` +
165
- `visitors. Call allowPublicPrivateProfile() first if this is deliberate.`,
166
- );
167
- isPublic = current.isPublic;
168
- }
169
-
170
- PROFILES[profile] = {
171
- edge: { ...current.edge, ...overrides.edge },
172
- browser: { ...current.browser, ...overrides.browser },
173
- loader: { ...current.loader, ...overrides.loader },
174
- client: { ...current.client, ...overrides.client },
175
- isPublic,
176
- };
177
- }
178
-
179
- let publicPrivateProfilesAllowed = false;
180
-
181
- /**
182
- * Opt out of the guard in `setCacheProfile` that refuses to turn a non-public
183
- * profile (`private`, `cart`, `none`) public.
184
- *
185
- * There is no legitimate storefront reason to call this. It exists so the
186
- * escape hatch has a name you have to type, rather than being a silent side
187
- * effect of passing `isPublic: true`.
188
- */
189
- export function allowPublicPrivateProfile(): void {
190
- publicPrivateProfilesAllowed = true;
191
- }
192
-
193
- // ---------------------------------------------------------------------------
194
- // Derivation: Cache-Control headers (browser layer)
195
- // ---------------------------------------------------------------------------
196
-
197
- /**
198
- * Generate a `Cache-Control` header from a named profile.
199
- * Returns a headers object ready to spread into route `headers()`.
200
- */
201
- export function cacheHeaders(profile: CacheProfileName): Record<string, string> {
202
- const p = PROFILES[profile];
203
-
204
- if (!p.isPublic || (p.edge.fresh === 0 && p.browser.fresh === 0)) {
205
- return {
206
- "Cache-Control": "private, no-cache, no-store, must-revalidate",
207
- };
208
- }
209
-
210
- const parts: string[] = ["public"];
211
- parts.push(p.browser.fresh > 0 ? `max-age=${p.browser.fresh}` : "max-age=0");
212
- if (p.edge.fresh > 0) parts.push(`s-maxage=${p.edge.fresh}`);
213
- if (p.browser.swr > 0) parts.push(`stale-while-revalidate=${p.browser.swr}`);
214
- if (p.browser.sie > 0) parts.push(`stale-if-error=${p.browser.sie}`);
215
-
216
- return {
217
- "Cache-Control": parts.join(", "),
218
- Vary: "Accept-Encoding",
219
- };
220
- }
221
-
222
- // ---------------------------------------------------------------------------
223
- // Derivation: Edge cache config (for workerEntry SWR/SIE logic)
224
- // ---------------------------------------------------------------------------
225
-
226
- export interface EdgeCacheConfig {
227
- fresh: number;
228
- swr: number;
229
- sie: number;
230
- isPublic: boolean;
231
- }
232
-
233
- export function edgeCacheConfig(profile: CacheProfileName): EdgeCacheConfig {
234
- const p = PROFILES[profile];
235
- return { ...p.edge, isPublic: p.isPublic };
236
- }
237
-
238
- // ---------------------------------------------------------------------------
239
- // Derivation: Client-side route cache defaults (TanStack Router)
240
- // ---------------------------------------------------------------------------
241
-
242
- /**
243
- * Returns `{ staleTime, gcTime }` for a cache profile, ready to spread
244
- * into a TanStack Router route definition.
245
- *
246
- * In dev mode, uses short staleTime (5s) to keep data fresh enough for
247
- * development while avoiding redundant re-fetches.
248
- *
249
- * staleTime is always Infinity in production: TanStack Router v1 dehydrates
250
- * SSR route data with updatedAt: 0, so any finite staleTime makes SSR data
251
- * appear immediately stale on client hydration. That triggers a second
252
- * /_serverFn/loadCmsPage request — a separate Worker isolate that re-runs all
253
- * loaders (including Magento ResolveURL/GetCompleteProduct) and doubles the
254
- * origin load on every first navigation. With Infinity, TanStack Router never
255
- * time-based-refetches in-memory data; gcTime controls how long the data lives
256
- * in memory, and the Cloudflare edge cache handles actual data freshness. (#355)
257
- */
258
- export function routeCacheDefaults(profile: CacheProfileName): { staleTime: number; gcTime: number } {
259
- const env = typeof globalThis.process !== "undefined" ? globalThis.process.env : undefined;
260
- const isDev = env?.DECO_CACHE_DISABLE === "true" || env?.NODE_ENV === "development";
261
- if (isDev) return { staleTime: 5_000, gcTime: 30_000 };
262
- return { staleTime: Infinity, gcTime: PROFILES[profile].client.gcTime };
263
- }
264
-
265
- // ---------------------------------------------------------------------------
266
- // Derivation: Loader cache options (for createCachedLoader)
267
- // ---------------------------------------------------------------------------
268
-
269
- export interface LoaderCacheOptions {
270
- policy: "stale-while-revalidate";
271
- maxAge: number;
272
- staleIfError: number;
273
- }
274
-
275
- /**
276
- * Get loader-layer cache options for a profile.
277
- * Pass directly to `createCachedLoader` as the options argument.
278
- */
279
- export function loaderCacheOptions(profile: CacheProfileName): LoaderCacheOptions {
280
- const p = PROFILES[profile];
281
- return {
282
- policy: "stale-while-revalidate",
283
- maxAge: p.loader.fresh,
284
- staleIfError: p.loader.sie,
285
- };
286
- }
287
-
288
- // ---------------------------------------------------------------------------
289
- // URL-based cache profile detection
290
- // ---------------------------------------------------------------------------
291
-
292
- interface CachePattern {
293
- test: (pathname: string, searchParams: URLSearchParams) => boolean;
294
- profile: CacheProfileName;
295
- }
296
-
297
- // Authenticated / per-user areas that must never be edge-cached. Anything not
298
- // matched here falls through to the cacheable `listing` default, so a missing
299
- // entry is a live content leak, not a missed optimization (see
300
- // decocms/blocks#412, which added the hyphenless `myaccount` VTEX wrapper path
301
- // and the pt-BR account routes).
302
- //
303
- // Three properties this regex must keep, each of which was a real hole:
304
- // - case-insensitive: `/Checkout` used to fall through to `listing`.
305
- // - optional locale prefix: `/pt/checkout`, `/br/minha-conta` likewise. Only
306
- // matches when followed by a private segment, so a legitimate two-letter
307
- // route can't be swallowed by it.
308
- // - wishlist / profile / signup / returns: absent until the CDN work, which
309
- // is what served a live store's `/listadedesejos` from the shared entry.
310
- const PRIVATE_SEGMENTS = [
311
- "cart",
312
- "carrinho",
313
- "checkout",
314
- "account",
315
- "myaccount",
316
- "my-account",
317
- "minha-conta",
318
- "meus-pedidos",
319
- "pedidos",
320
- "orders",
321
- "order-placed",
322
- "login",
323
- "logout",
324
- "sair",
325
- "cadastro",
326
- "signup",
327
- "register",
328
- "profile",
329
- "perfil",
330
- "wishlist",
331
- "favoritos",
332
- "listadedesejos",
333
- "lista-de-desejos",
334
- "minha-lista",
335
- "assinaturas",
336
- "subscriptions",
337
- "troca",
338
- "trocas",
339
- "devolucao",
340
- "devolucoes",
341
- ];
342
-
343
- const LOCALE_PREFIX = "(?:\\/[a-z]{2}(?:-[a-z]{2})?)?";
344
-
345
- const PRIVATE_PREFIX_RE = new RegExp(
346
- `^${LOCALE_PREFIX}\\/(?:${PRIVATE_SEGMENTS.join("|")})(?:\\/|$)`,
347
- "i",
348
- );
349
-
350
- // Site-registered private prefixes (see `registerPrivatePaths`). Kept separate
351
- // from `PRIVATE_SEGMENTS` so a site can only ever ADD to the private set.
352
- const extraPrivatePaths: string[] = [];
353
-
354
- /**
355
- * Mark additional path prefixes as private — never edge-cached, never served
356
- * from the CDN.
357
- *
358
- * This is the safe half of cache configuration: it can only restrict, never
359
- * relax. Prefer it over `registerCachePattern` (which can also make things
360
- * public, and is evaluated before the built-in private check).
361
- *
362
- * @example
363
- * ```ts
364
- * registerPrivatePaths(["/listadedesejos", "/trocas"]);
365
- * ```
366
- */
367
- export function registerPrivatePaths(paths: string[]): void {
368
- for (const path of paths) {
369
- const normalized = path.startsWith("/") ? path : `/${path}`;
370
- if (!extraPrivatePaths.includes(normalized)) extraPrivatePaths.push(normalized);
371
- }
372
- }
373
-
374
- function isPrivatePath(pathname: string): boolean {
375
- if (PRIVATE_PREFIX_RE.test(pathname)) return true;
376
- const lower = pathname.toLowerCase();
377
- return extraPrivatePaths.some((prefix) => {
378
- const p = prefix.toLowerCase();
379
- return lower === p || lower.startsWith(`${p}/`);
380
- });
381
- }
382
-
383
- const builtinPatterns: CachePattern[] = [
384
- {
385
- test: (p) => isPrivatePath(p),
386
- profile: "private",
387
- },
388
- {
389
- test: (p) =>
390
- p.startsWith("/api/") ||
391
- p.startsWith("/deco/") ||
392
- p.startsWith("/_build"),
393
- profile: "none",
394
- },
395
- {
396
- test: (p, sp) => p === "/s" || p.startsWith("/s/") || sp.has("q"),
397
- profile: "search",
398
- },
399
- {
400
- test: (p) => p.endsWith("/p") || /\/p[?#]/.test(p),
401
- profile: "product",
402
- },
403
- {
404
- test: (p) => p === "/" || p === "",
405
- profile: "static",
406
- },
407
- ];
408
-
409
- const customPatterns: CachePattern[] = [];
410
-
411
- /**
412
- * Register additional URL-to-profile patterns. Custom patterns are evaluated
413
- * before built-in ones, so they can override defaults — with one exception:
414
- * a custom pattern resolving to a PUBLIC profile cannot override the built-in
415
- * private check (see `detectCacheProfile`). A broad site pattern would
416
- * otherwise silently capture `/checkout` and make it cacheable.
417
- *
418
- * To mark routes as private, prefer {@link registerPrivatePaths} — it can only
419
- * restrict, and isn't subject to ordering rules.
420
- */
421
- export function registerCachePattern(pattern: CachePattern): void {
422
- customPatterns.push(pattern);
423
- }
424
-
425
- /**
426
- * Detect the appropriate cache profile based on a URL.
427
- * Evaluates custom patterns first, then built-in patterns.
428
- * Falls back to "listing" for unmatched paths.
429
- */
430
- export function detectCacheProfile(pathnameOrUrl: string | URL): CacheProfileName {
431
- let pathname: string;
432
- let searchParams: URLSearchParams;
433
-
434
- if (typeof pathnameOrUrl === "string" && !pathnameOrUrl.startsWith("http")) {
435
- const qIdx = pathnameOrUrl.indexOf("?");
436
- pathname = qIdx >= 0 ? pathnameOrUrl.slice(0, qIdx) : pathnameOrUrl;
437
- searchParams = new URLSearchParams(qIdx >= 0 ? pathnameOrUrl.slice(qIdx) : "");
438
- } else {
439
- const url = pathnameOrUrl instanceof URL ? pathnameOrUrl : new URL(pathnameOrUrl);
440
- pathname = url.pathname;
441
- searchParams = url.searchParams;
442
- }
443
-
444
- // A private path can never be talked into a public profile by a site pattern.
445
- // Custom patterns still win for anything non-public (a site can always make a
446
- // route MORE restricted), and for public-vs-public overrides on other paths.
447
- const privatePath = isPrivatePath(pathname);
448
-
449
- for (const pattern of customPatterns) {
450
- if (!pattern.test(pathname, searchParams)) continue;
451
- if (privatePath && PROFILES[pattern.profile].isPublic) return "private";
452
- return pattern.profile;
453
- }
454
- for (const pattern of builtinPatterns) {
455
- if (pattern.test(pathname, searchParams)) return pattern.profile;
456
- }
457
-
458
- return "listing";
459
- }
460
-
461
- /**
462
- * For a TanStack GET server-fn request (`/_serverFn/<hash>?payload=...`), the
463
- * page being loaded is encoded inside the serialized `payload` arg (e.g.
464
- * `loadCmsPage`'s `data` string `/product/p`). The request pathname itself is
465
- * `/_serverFn/...`, which {@link detectCacheProfile} can only classify as the
466
- * generic "listing" profile — so SPA-navigation data requests would cache under
467
- * a short TTL and rarely hit, even though the underlying page is a product
468
- * (5min) or the homepage (1 day).
469
- *
470
- * Returns the embedded page path so the data request can inherit the SAME cache
471
- * profile as its HTML document. Returns null for non-server-fn URLs or on any
472
- * parse miss, so callers fall back to URL-based detection (never worse than the
473
- * pre-existing behavior).
474
- *
475
- * The payload is TanStack's serialized envelope; rather than depend on its
476
- * exact shape, we walk the parsed JSON for the first arg-value string that
477
- * looks like a route path. `loadCmsPage` encodes exactly one such string.
478
- */
479
- export function serverFnPagePath(url: URL): string | null {
480
- if (
481
- !url.pathname.startsWith("/_serverFn/") &&
482
- !url.pathname.startsWith("/_server/")
483
- ) {
484
- return null;
485
- }
486
- const payload = url.searchParams.get("payload");
487
- if (!payload) return null;
488
- try {
489
- let found: string | null = null;
490
- const visit = (v: unknown): void => {
491
- if (found !== null) return;
492
- if (typeof v === "string") {
493
- if (v.startsWith("/") && !v.startsWith("//")) found = v;
494
- return;
495
- }
496
- if (Array.isArray(v)) {
497
- for (const x of v) visit(x);
498
- return;
499
- }
500
- if (v && typeof v === "object") {
501
- for (const x of Object.values(v)) visit(x);
502
- }
503
- };
504
- visit(JSON.parse(payload));
505
- return found;
506
- } catch {
507
- return null;
508
- }
509
- }
510
-
511
- /**
512
- * `true` when a server-fn payload (GET `payload` param or POST body) embeds a
513
- * route path or absolute URL carrying a tracking param — e.g. a deferred
514
- * section's `pageUrl` built from `location.href` on an ad landing. Same walk as
515
- * {@link canonicalizeServerFnPayloadForCacheKey}. Returns `false` on any parse
516
- * failure (fail-safe: the caller keeps its normal behavior).
517
- */
518
- export function payloadHasTrackingParams(payload: string): boolean {
519
- try {
520
- let found = false;
521
- const check = (s: string): void => {
522
- let search: string;
523
- if (/^https?:\/\//i.test(s)) {
524
- try {
525
- search = new URL(s).search;
526
- } catch {
527
- return;
528
- }
529
- } else if (s.startsWith("/") && !s.startsWith("//")) {
530
- const q = s.indexOf("?");
531
- if (q < 0) return;
532
- search = s.slice(q);
533
- } else {
534
- return;
535
- }
536
- for (const k of new URLSearchParams(search).keys()) {
537
- if (isTrackingParam(k)) {
538
- found = true;
539
- return;
540
- }
541
- }
542
- };
543
- const visit = (v: unknown): void => {
544
- if (found) return;
545
- if (typeof v === "string") {
546
- check(v);
547
- } else if (Array.isArray(v)) {
548
- for (const x of v) visit(x);
549
- } else if (v && typeof v === "object") {
550
- for (const x of Object.values(v)) visit(x);
551
- }
552
- };
553
- visit(JSON.parse(payload));
554
- return found;
555
- } catch {
556
- return false;
557
- }
558
- }
559
-
560
- /**
561
- * Search params that never change a CMS page's resolved server-fn response and
562
- * so must not fragment its edge cache key. `skuId`/`idsku` select a product
563
- * variant client-side (mirrors `cmsRouteConfig`'s default
564
- * `ignoreSearchParams: ["skuId"]`) — without stripping them, every PDP→PDP
565
- * navigation that carries a variant param is a unique key and always MISSes,
566
- * re-running the full page resolution (~1-2s) even though the response is
567
- * identical to the canonical `/product/p`.
568
- */
569
- export const DEFAULT_SERVERFN_CACHE_IGNORE_PARAMS = ["skuId", "idsku"];
570
-
571
- /**
572
- * Canonicalize a TanStack GET server-fn `payload` for use in the edge cache
573
- * key: re-serialize it (so equivalent requests always produce byte-identical
574
- * keys) and strip the cache-irrelevant search params — `ignoreParams` plus every
575
- * known tracking param — from any embedded route path or absolute URL. This
576
- * makes `/product/p?skuId=148940`, `/product/p?utm_source=ads` and `/product/p`
577
- * share one cache entry, since `loadCmsPage` resolves all three to the same
578
- * page.
579
- *
580
- * Returns the original payload unchanged on any parse failure (fail-safe: the
581
- * caller keeps the raw payload, never worse than before).
582
- */
583
- export function canonicalizeServerFnPayloadForCacheKey(
584
- payload: string,
585
- ignoreParams: string[] = DEFAULT_SERVERFN_CACHE_IGNORE_PARAMS,
586
- ): string {
587
- try {
588
- const drop = (sp: URLSearchParams): void => {
589
- for (const p of ignoreParams) sp.delete(p);
590
- // Tracking params never change what the server fn resolves, but they DO
591
- // change this key — so a shopper arriving from paid media mints a brand
592
- // new entry on every SPA interaction. Measured on a production
593
- // storefront: `/_serverFn/:id` at 84% MISS, 1401ms average.
594
- for (const k of [...sp.keys()]) if (isTrackingParam(k)) sp.delete(k);
595
- };
596
- const stripQuery = (s: string): string => {
597
- // Absolute URL: sites embed one in the payload (the deferred-section
598
- // `pageUrl` is built with `new URL(...)`), and it fragments the key
599
- // exactly like a relative path does — but the guard below skipped it, so
600
- // not even `skuId` was canonicalized there.
601
- if (/^https?:\/\//i.test(s)) {
602
- try {
603
- const u = new URL(s);
604
- drop(u.searchParams);
605
- return u.toString();
606
- } catch {
607
- return s;
608
- }
609
- }
610
- if (!s.startsWith("/") || s.startsWith("//")) return s;
611
- const qIdx = s.indexOf("?");
612
- if (qIdx < 0) return s;
613
- const path = s.slice(0, qIdx);
614
- const sp = new URLSearchParams(s.slice(qIdx + 1));
615
- drop(sp);
616
- const rest = sp.toString();
617
- return rest ? `${path}?${rest}` : path;
618
- };
619
- const visit = (v: unknown): unknown => {
620
- if (typeof v === "string") return stripQuery(v);
621
- if (Array.isArray(v)) return v.map(visit);
622
- if (v && typeof v === "object") {
623
- const out: Record<string, unknown> = {};
624
- for (const [k, val] of Object.entries(v)) out[k] = visit(val);
625
- return out;
626
- }
627
- return v;
628
- };
629
- return JSON.stringify(visit(JSON.parse(payload)));
630
- } catch {
631
- return payload;
632
- }
633
- }