@decocms/blocks 8.0.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 (220) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -82
  3. package/src/index.ts +35 -8
  4. package/src/protocol/assets.ts +124 -0
  5. package/src/protocol/canonical.ts +7 -0
  6. package/src/protocol/ciphertext.ts +6 -0
  7. package/src/protocol/client.ts +170 -0
  8. package/src/protocol/conformance/cases/assets.ts +81 -0
  9. package/src/protocol/conformance/cases/guards.ts +314 -0
  10. package/src/protocol/conformance/cases/reads.ts +168 -0
  11. package/src/protocol/conformance/cases/types.ts +9 -0
  12. package/src/protocol/conformance/cases/wire.ts +138 -0
  13. package/src/protocol/conformance/cases/writes.ts +345 -0
  14. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  15. package/src/protocol/conformance/context.ts +222 -0
  16. package/src/protocol/conformance/index.ts +140 -0
  17. package/src/protocol/errors.ts +142 -0
  18. package/src/protocol/index.ts +39 -0
  19. package/src/protocol/keys.ts +279 -0
  20. package/src/protocol/params.ts +67 -0
  21. package/src/protocol/secrets.ts +231 -0
  22. package/src/protocol/server/assets.ts +119 -0
  23. package/src/protocol/server/auth.ts +49 -0
  24. package/src/protocol/server/bodyCache.ts +84 -0
  25. package/src/protocol/server/content.ts +175 -0
  26. package/src/protocol/server/core.ts +112 -0
  27. package/src/protocol/server/handler.ts +102 -0
  28. package/src/protocol/server/http.ts +139 -0
  29. package/src/protocol/server/index.ts +11 -0
  30. package/src/protocol/server/methods/apply.ts +341 -0
  31. package/src/protocol/server/methods/read.ts +156 -0
  32. package/src/protocol/server/rpc.ts +136 -0
  33. package/src/protocol/storage/fs/hash.ts +21 -0
  34. package/src/protocol/storage/fs/index.ts +338 -0
  35. package/src/protocol/storage/fs/lock.ts +68 -0
  36. package/src/protocol/storage/fs/transaction.ts +183 -0
  37. package/src/protocol/storage/fs/unsupported.ts +15 -0
  38. package/src/protocol/storage/memory.ts +238 -0
  39. package/src/protocol/storage.ts +182 -0
  40. package/src/protocol/types.ts +172 -0
  41. package/src/v8/analytics.ts +50 -0
  42. package/src/v8/background.ts +107 -0
  43. package/src/v8/builtins/data.ts +23 -0
  44. package/src/v8/builtins/index.ts +26 -0
  45. package/src/v8/builtins/lazy.ts +23 -0
  46. package/src/v8/builtins/legacy.ts +65 -0
  47. package/src/v8/builtins/matchers.ts +31 -0
  48. package/src/v8/builtins/multivariate.ts +25 -0
  49. package/src/v8/builtins/secret.ts +82 -0
  50. package/src/v8/canonical.ts +117 -0
  51. package/src/v8/ciphertext.ts +158 -0
  52. package/src/v8/cli/builtins.ts +20 -0
  53. package/src/v8/cli/check/index.ts +774 -0
  54. package/src/v8/cli/check/messages.ts +168 -0
  55. package/src/v8/cli/content.ts +287 -0
  56. package/src/v8/cli/index.ts +17 -0
  57. package/src/v8/cli/log.ts +18 -0
  58. package/src/v8/cli/main.ts +12 -0
  59. package/src/v8/cli/root.ts +66 -0
  60. package/src/v8/cli/run.ts +236 -0
  61. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  62. package/src/v8/cli/schema/generate.ts +507 -0
  63. package/src/v8/cli/schema/index.ts +63 -0
  64. package/src/v8/cli/schema/tsProgram.ts +497 -0
  65. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  66. package/src/v8/cli/serve/server.ts +303 -0
  67. package/src/v8/cli/watch.ts +86 -0
  68. package/src/v8/client.ts +147 -0
  69. package/src/v8/cms.ts +237 -0
  70. package/src/v8/content.ts +195 -0
  71. package/src/v8/draft.ts +136 -0
  72. package/src/v8/errors.ts +59 -0
  73. package/src/v8/fetch.ts +133 -0
  74. package/src/v8/identity.ts +65 -0
  75. package/src/v8/index.ts +39 -0
  76. package/src/v8/json.ts +74 -0
  77. package/src/v8/matchRoute.ts +204 -0
  78. package/src/v8/remoteLoader.ts +282 -0
  79. package/src/v8/resolver.ts +278 -0
  80. package/src/v8/secrets.ts +17 -0
  81. package/src/v8/telemetry.ts +533 -0
  82. package/src/v8/types.ts +240 -0
  83. package/src/cms/applySectionConventions.ts +0 -124
  84. package/src/cms/blockSource.test.ts +0 -76
  85. package/src/cms/blockSource.ts +0 -191
  86. package/src/cms/client.browserBundle.test.ts +0 -44
  87. package/src/cms/client.ts +0 -80
  88. package/src/cms/draftSource.test.ts +0 -343
  89. package/src/cms/draftSource.ts +0 -362
  90. package/src/cms/index.ts +0 -151
  91. package/src/cms/layoutCacheRace.test.ts +0 -181
  92. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  93. package/src/cms/loadDecofileDirectory.ts +0 -89
  94. package/src/cms/loader.test.ts +0 -200
  95. package/src/cms/loader.ts +0 -304
  96. package/src/cms/registry.test.ts +0 -110
  97. package/src/cms/registry.ts +0 -242
  98. package/src/cms/resolve.test.ts +0 -980
  99. package/src/cms/resolve.ts +0 -2282
  100. package/src/cms/schema.test.ts +0 -356
  101. package/src/cms/schema.ts +0 -1215
  102. package/src/cms/sectionLoaderContext.test.ts +0 -111
  103. package/src/cms/sectionLoaderContext.ts +0 -113
  104. package/src/cms/sectionLoaders.test.ts +0 -533
  105. package/src/cms/sectionLoaders.ts +0 -636
  106. package/src/cms/sectionMixins.test.ts +0 -167
  107. package/src/cms/sectionMixins.ts +0 -153
  108. package/src/cms/stickyFlags.test.ts +0 -117
  109. package/src/flags/audience.ts +0 -56
  110. package/src/flags/everyone.ts +0 -29
  111. package/src/flags/flag.ts +0 -15
  112. package/src/flags/flags.test.ts +0 -148
  113. package/src/flags/multivariate/image.ts +0 -11
  114. package/src/flags/multivariate/message.ts +0 -11
  115. package/src/flags/multivariate/page.ts +0 -16
  116. package/src/flags/multivariate/section.ts +0 -16
  117. package/src/flags/multivariate.ts +0 -1
  118. package/src/flags/types.ts +0 -59
  119. package/src/flags/utils/multivariate.ts +0 -20
  120. package/src/hooks/Image.test.ts +0 -100
  121. package/src/hooks/Image.tsx +0 -250
  122. package/src/hooks/JsonLd.tsx +0 -353
  123. package/src/hooks/LazySection.tsx +0 -121
  124. package/src/hooks/LiveControls.tsx +0 -122
  125. package/src/hooks/Picture.tsx +0 -127
  126. package/src/hooks/RenderSection.test.tsx +0 -81
  127. package/src/hooks/RenderSection.tsx +0 -91
  128. package/src/hooks/SectionErrorFallback.tsx +0 -97
  129. package/src/hooks/index.ts +0 -30
  130. package/src/matchers/builtins.test.ts +0 -318
  131. package/src/matchers/builtins.ts +0 -459
  132. package/src/matchers/countryNames.ts +0 -104
  133. package/src/matchers/override.test.ts +0 -205
  134. package/src/matchers/override.ts +0 -136
  135. package/src/matchers/posthog.ts +0 -154
  136. package/src/middleware/decoState.ts +0 -55
  137. package/src/middleware/healthMetrics.ts +0 -133
  138. package/src/middleware/hydrationContext.test.ts +0 -61
  139. package/src/middleware/hydrationContext.ts +0 -79
  140. package/src/middleware/index.ts +0 -88
  141. package/src/middleware/liveness.ts +0 -21
  142. package/src/middleware/observability.test.ts +0 -242
  143. package/src/middleware/observability.ts +0 -643
  144. package/src/middleware/validateSection.test.ts +0 -147
  145. package/src/middleware/validateSection.ts +0 -100
  146. package/src/sdk/abTesting.test.ts +0 -326
  147. package/src/sdk/abTesting.ts +0 -499
  148. package/src/sdk/analytics.ts +0 -77
  149. package/src/sdk/cacheHeaders.test.ts +0 -115
  150. package/src/sdk/cacheHeaders.ts +0 -433
  151. package/src/sdk/cachedLoader.test.ts +0 -122
  152. package/src/sdk/cachedLoader.ts +0 -503
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/clx.ts +0 -5
  155. package/src/sdk/cn.test.ts +0 -34
  156. package/src/sdk/cn.ts +0 -28
  157. package/src/sdk/composite.test.ts +0 -121
  158. package/src/sdk/composite.ts +0 -114
  159. package/src/sdk/cookie.test.ts +0 -108
  160. package/src/sdk/cookie.ts +0 -129
  161. package/src/sdk/crypto.ts +0 -185
  162. package/src/sdk/csp.ts +0 -59
  163. package/src/sdk/detectDevice.ts +0 -45
  164. package/src/sdk/djb2.ts +0 -20
  165. package/src/sdk/encoding.test.ts +0 -71
  166. package/src/sdk/encoding.ts +0 -47
  167. package/src/sdk/env.test.ts +0 -33
  168. package/src/sdk/env.ts +0 -54
  169. package/src/sdk/flags.test.ts +0 -91
  170. package/src/sdk/flags.ts +0 -108
  171. package/src/sdk/http.test.ts +0 -71
  172. package/src/sdk/http.ts +0 -124
  173. package/src/sdk/index.ts +0 -90
  174. package/src/sdk/inflightTimeout.test.ts +0 -35
  175. package/src/sdk/inflightTimeout.ts +0 -53
  176. package/src/sdk/instrumentedFetch.test.ts +0 -559
  177. package/src/sdk/instrumentedFetch.ts +0 -339
  178. package/src/sdk/invoke.test.ts +0 -115
  179. package/src/sdk/invoke.ts +0 -298
  180. package/src/sdk/logger.test.ts +0 -432
  181. package/src/sdk/logger.ts +0 -304
  182. package/src/sdk/mergeCacheControl.ts +0 -150
  183. package/src/sdk/normalizeUrls.ts +0 -91
  184. package/src/sdk/observability.ts +0 -109
  185. package/src/sdk/otel.test.ts +0 -526
  186. package/src/sdk/otel.ts +0 -1012
  187. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  188. package/src/sdk/otelAdapters.test.ts +0 -89
  189. package/src/sdk/otelAdapters.ts +0 -144
  190. package/src/sdk/otelHttpLog.test.ts +0 -457
  191. package/src/sdk/otelHttpLog.ts +0 -419
  192. package/src/sdk/otelHttpMeter.test.ts +0 -292
  193. package/src/sdk/otelHttpMeter.ts +0 -506
  194. package/src/sdk/otelHttpTracer.test.ts +0 -474
  195. package/src/sdk/otelHttpTracer.ts +0 -543
  196. package/src/sdk/redirects.ts +0 -228
  197. package/src/sdk/requestContext.ts +0 -281
  198. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  199. package/src/sdk/requestContextStorage.browser.ts +0 -43
  200. package/src/sdk/requestContextStorage.ts +0 -35
  201. package/src/sdk/retry.ts +0 -45
  202. package/src/sdk/serverTimings.ts +0 -68
  203. package/src/sdk/signal.ts +0 -42
  204. package/src/sdk/sitemap.ts +0 -160
  205. package/src/sdk/urlRedaction.test.ts +0 -73
  206. package/src/sdk/urlRedaction.ts +0 -82
  207. package/src/sdk/urlUtils.ts +0 -134
  208. package/src/sdk/useDevice.test.ts +0 -130
  209. package/src/sdk/useDevice.ts +0 -89
  210. package/src/sdk/useDeviceContext.tsx +0 -108
  211. package/src/sdk/useId.ts +0 -7
  212. package/src/sdk/useScript.test.ts +0 -128
  213. package/src/sdk/useScript.ts +0 -210
  214. package/src/sdk/useSuggestions.test.ts +0 -230
  215. package/src/sdk/useSuggestions.ts +0 -188
  216. package/src/sdk/wrapCaughtErrors.ts +0 -107
  217. package/src/setup.ts +0 -120
  218. package/src/types/index.ts +0 -53
  219. package/src/types/widgets.ts +0 -14
  220. package/tsconfig.json +0 -7
@@ -1,433 +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
- // ---------------------------------------------------------------------------
21
- // Types
22
- // ---------------------------------------------------------------------------
23
-
24
- export type CacheProfileName =
25
- | "static"
26
- | "product"
27
- | "listing"
28
- | "search"
29
- | "cart"
30
- | "private"
31
- | "none";
32
-
33
- /** Time windows for a single caching layer (in seconds). */
34
- export interface CacheTimingWindow {
35
- /** How long content is considered fresh — served without origin contact. */
36
- fresh: number;
37
- /** After fresh expires, serve stale while refreshing in background. */
38
- swr: number;
39
- /** After fresh expires and origin is erroring, serve stale for this long. */
40
- sie: number;
41
- }
42
-
43
- /** Unified cache profile covering all layers. */
44
- export interface CacheProfileConfig {
45
- /** Edge / CDN layer (Cloudflare Cache API). Times in seconds. */
46
- edge: CacheTimingWindow;
47
- /** Browser layer (Cache-Control header). Times in seconds. */
48
- browser: CacheTimingWindow;
49
- /** In-memory loader layer. Times in milliseconds. */
50
- loader: {
51
- fresh: number;
52
- sie: number;
53
- };
54
- /** Client-side TanStack Router. Times in milliseconds. */
55
- client: {
56
- staleTime: number;
57
- gcTime: number;
58
- };
59
- /** Whether CDN can cache this profile. False = private, never cached. */
60
- isPublic: boolean;
61
- }
62
-
63
- /**
64
- * Deep partial of CacheProfileConfig for site-level overrides.
65
- * Only the fields you specify are merged; everything else keeps its default.
66
- */
67
- export type CacheProfileOverrides = {
68
- [K in keyof CacheProfileConfig]?: CacheProfileConfig[K] extends object
69
- ? Partial<CacheProfileConfig[K]>
70
- : CacheProfileConfig[K];
71
- };
72
-
73
- // ---------------------------------------------------------------------------
74
- // Default profiles
75
- // ---------------------------------------------------------------------------
76
-
77
- const PROFILES: Record<CacheProfileName, CacheProfileConfig> = {
78
- static: {
79
- edge: { fresh: 900, swr: 7200, sie: 21600 },
80
- browser: { fresh: 120, swr: 1800, sie: 7200 },
81
- loader: { fresh: 300_000, sie: 1_800_000 },
82
- client: { staleTime: 300_000, gcTime: 1_800_000 },
83
- isPublic: true,
84
- },
85
- product: {
86
- edge: { fresh: 300, swr: 1800, sie: 7200 },
87
- browser: { fresh: 60, swr: 600, sie: 3600 },
88
- loader: { fresh: 30_000, sie: 600_000 },
89
- client: { staleTime: 60_000, gcTime: 300_000 },
90
- isPublic: true,
91
- },
92
- listing: {
93
- edge: { fresh: 120, swr: 900, sie: 3600 },
94
- browser: { fresh: 30, swr: 300, sie: 1800 },
95
- loader: { fresh: 60_000, sie: 300_000 },
96
- client: { staleTime: 60_000, gcTime: 300_000 },
97
- isPublic: true,
98
- },
99
- search: {
100
- edge: { fresh: 60, swr: 300, sie: 1800 },
101
- browser: { fresh: 0, swr: 120, sie: 600 },
102
- loader: { fresh: 60_000, sie: 180_000 },
103
- client: { staleTime: 30_000, gcTime: 120_000 },
104
- isPublic: true,
105
- },
106
- cart: {
107
- edge: { fresh: 0, swr: 0, sie: 0 },
108
- browser: { fresh: 0, swr: 0, sie: 0 },
109
- loader: { fresh: 0, sie: 0 },
110
- client: { staleTime: 0, gcTime: 0 },
111
- isPublic: false,
112
- },
113
- private: {
114
- edge: { fresh: 0, swr: 0, sie: 0 },
115
- browser: { fresh: 0, swr: 0, sie: 0 },
116
- loader: { fresh: 0, sie: 0 },
117
- client: { staleTime: 0, gcTime: 0 },
118
- isPublic: false,
119
- },
120
- none: {
121
- edge: { fresh: 0, swr: 0, sie: 0 },
122
- browser: { fresh: 0, swr: 0, sie: 0 },
123
- loader: { fresh: 0, sie: 0 },
124
- client: { staleTime: 0, gcTime: 0 },
125
- isPublic: false,
126
- },
127
- };
128
-
129
- // ---------------------------------------------------------------------------
130
- // Profile accessors
131
- // ---------------------------------------------------------------------------
132
-
133
- export function getCacheProfile(profile: CacheProfileName): CacheProfileConfig {
134
- return PROFILES[profile];
135
- }
136
-
137
- /**
138
- * Override specific values of a cache profile. Only the fields you specify
139
- * are merged; everything else keeps its default.
140
- *
141
- * @example
142
- * ```ts
143
- * setCacheProfile("product", { edge: { fresh: 600 } });
144
- * setCacheProfile("static", { loader: { sie: 3_600_000 } });
145
- * ```
146
- */
147
- export function setCacheProfile(
148
- profile: CacheProfileName,
149
- overrides: CacheProfileOverrides,
150
- ): void {
151
- const current = PROFILES[profile];
152
- PROFILES[profile] = {
153
- edge: { ...current.edge, ...overrides.edge },
154
- browser: { ...current.browser, ...overrides.browser },
155
- loader: { ...current.loader, ...overrides.loader },
156
- client: { ...current.client, ...overrides.client },
157
- isPublic: overrides.isPublic ?? current.isPublic,
158
- };
159
- }
160
-
161
- // ---------------------------------------------------------------------------
162
- // Derivation: Cache-Control headers (browser layer)
163
- // ---------------------------------------------------------------------------
164
-
165
- /**
166
- * Generate a `Cache-Control` header from a named profile.
167
- * Returns a headers object ready to spread into route `headers()`.
168
- */
169
- export function cacheHeaders(profile: CacheProfileName): Record<string, string> {
170
- const p = PROFILES[profile];
171
-
172
- if (!p.isPublic || (p.edge.fresh === 0 && p.browser.fresh === 0)) {
173
- return {
174
- "Cache-Control": "private, no-cache, no-store, must-revalidate",
175
- };
176
- }
177
-
178
- const parts: string[] = ["public"];
179
- parts.push(p.browser.fresh > 0 ? `max-age=${p.browser.fresh}` : "max-age=0");
180
- if (p.edge.fresh > 0) parts.push(`s-maxage=${p.edge.fresh}`);
181
- if (p.browser.swr > 0) parts.push(`stale-while-revalidate=${p.browser.swr}`);
182
- if (p.browser.sie > 0) parts.push(`stale-if-error=${p.browser.sie}`);
183
-
184
- return {
185
- "Cache-Control": parts.join(", "),
186
- Vary: "Accept-Encoding",
187
- };
188
- }
189
-
190
- // ---------------------------------------------------------------------------
191
- // Derivation: Edge cache config (for workerEntry SWR/SIE logic)
192
- // ---------------------------------------------------------------------------
193
-
194
- export interface EdgeCacheConfig {
195
- fresh: number;
196
- swr: number;
197
- sie: number;
198
- isPublic: boolean;
199
- }
200
-
201
- export function edgeCacheConfig(profile: CacheProfileName): EdgeCacheConfig {
202
- const p = PROFILES[profile];
203
- return { ...p.edge, isPublic: p.isPublic };
204
- }
205
-
206
- // ---------------------------------------------------------------------------
207
- // Derivation: Client-side route cache defaults (TanStack Router)
208
- // ---------------------------------------------------------------------------
209
-
210
- /**
211
- * Returns `{ staleTime, gcTime }` for a cache profile, ready to spread
212
- * into a TanStack Router route definition.
213
- *
214
- * In dev mode, uses short staleTime (5s) to keep data fresh enough for
215
- * development while avoiding redundant re-fetches.
216
- *
217
- * staleTime is always Infinity in production: TanStack Router v1 dehydrates
218
- * SSR route data with updatedAt: 0, so any finite staleTime makes SSR data
219
- * appear immediately stale on client hydration. That triggers a second
220
- * /_serverFn/loadCmsPage request — a separate Worker isolate that re-runs all
221
- * loaders (including Magento ResolveURL/GetCompleteProduct) and doubles the
222
- * origin load on every first navigation. With Infinity, TanStack Router never
223
- * time-based-refetches in-memory data; gcTime controls how long the data lives
224
- * in memory, and the Cloudflare edge cache handles actual data freshness. (#355)
225
- */
226
- export function routeCacheDefaults(profile: CacheProfileName): { staleTime: number; gcTime: number } {
227
- const env = typeof globalThis.process !== "undefined" ? globalThis.process.env : undefined;
228
- const isDev = env?.DECO_CACHE_DISABLE === "true" || env?.NODE_ENV === "development";
229
- if (isDev) return { staleTime: 5_000, gcTime: 30_000 };
230
- return { staleTime: Infinity, gcTime: PROFILES[profile].client.gcTime };
231
- }
232
-
233
- // ---------------------------------------------------------------------------
234
- // Derivation: Loader cache options (for createCachedLoader)
235
- // ---------------------------------------------------------------------------
236
-
237
- export interface LoaderCacheOptions {
238
- policy: "stale-while-revalidate";
239
- maxAge: number;
240
- staleIfError: number;
241
- }
242
-
243
- /**
244
- * Get loader-layer cache options for a profile.
245
- * Pass directly to `createCachedLoader` as the options argument.
246
- */
247
- export function loaderCacheOptions(profile: CacheProfileName): LoaderCacheOptions {
248
- const p = PROFILES[profile];
249
- return {
250
- policy: "stale-while-revalidate",
251
- maxAge: p.loader.fresh,
252
- staleIfError: p.loader.sie,
253
- };
254
- }
255
-
256
- // ---------------------------------------------------------------------------
257
- // URL-based cache profile detection
258
- // ---------------------------------------------------------------------------
259
-
260
- interface CachePattern {
261
- test: (pathname: string, searchParams: URLSearchParams) => boolean;
262
- profile: CacheProfileName;
263
- }
264
-
265
- const PRIVATE_PREFIX_RE =
266
- /^\/(cart|checkout|account|login|my-account)(\/|$)/;
267
-
268
- const builtinPatterns: CachePattern[] = [
269
- {
270
- test: (p) => PRIVATE_PREFIX_RE.test(p),
271
- profile: "private",
272
- },
273
- {
274
- test: (p) =>
275
- p.startsWith("/api/") ||
276
- p.startsWith("/deco/") ||
277
- p.startsWith("/_build"),
278
- profile: "none",
279
- },
280
- {
281
- test: (p, sp) => p === "/s" || p.startsWith("/s/") || sp.has("q"),
282
- profile: "search",
283
- },
284
- {
285
- test: (p) => p.endsWith("/p") || /\/p[?#]/.test(p),
286
- profile: "product",
287
- },
288
- {
289
- test: (p) => p === "/" || p === "",
290
- profile: "static",
291
- },
292
- ];
293
-
294
- const customPatterns: CachePattern[] = [];
295
-
296
- /**
297
- * Register additional URL-to-profile patterns. Custom patterns are evaluated
298
- * before built-in ones, so they can override defaults.
299
- */
300
- export function registerCachePattern(pattern: CachePattern): void {
301
- customPatterns.push(pattern);
302
- }
303
-
304
- /**
305
- * Detect the appropriate cache profile based on a URL.
306
- * Evaluates custom patterns first, then built-in patterns.
307
- * Falls back to "listing" for unmatched paths.
308
- */
309
- export function detectCacheProfile(pathnameOrUrl: string | URL): CacheProfileName {
310
- let pathname: string;
311
- let searchParams: URLSearchParams;
312
-
313
- if (typeof pathnameOrUrl === "string" && !pathnameOrUrl.startsWith("http")) {
314
- const qIdx = pathnameOrUrl.indexOf("?");
315
- pathname = qIdx >= 0 ? pathnameOrUrl.slice(0, qIdx) : pathnameOrUrl;
316
- searchParams = new URLSearchParams(qIdx >= 0 ? pathnameOrUrl.slice(qIdx) : "");
317
- } else {
318
- const url = pathnameOrUrl instanceof URL ? pathnameOrUrl : new URL(pathnameOrUrl);
319
- pathname = url.pathname;
320
- searchParams = url.searchParams;
321
- }
322
-
323
- for (const pattern of customPatterns) {
324
- if (pattern.test(pathname, searchParams)) return pattern.profile;
325
- }
326
- for (const pattern of builtinPatterns) {
327
- if (pattern.test(pathname, searchParams)) return pattern.profile;
328
- }
329
-
330
- return "listing";
331
- }
332
-
333
- /**
334
- * For a TanStack GET server-fn request (`/_serverFn/<hash>?payload=...`), the
335
- * page being loaded is encoded inside the serialized `payload` arg (e.g.
336
- * `loadCmsPage`'s `data` string `/product/p`). The request pathname itself is
337
- * `/_serverFn/...`, which {@link detectCacheProfile} can only classify as the
338
- * generic "listing" profile — so SPA-navigation data requests would cache under
339
- * a short TTL and rarely hit, even though the underlying page is a product
340
- * (5min) or the homepage (1 day).
341
- *
342
- * Returns the embedded page path so the data request can inherit the SAME cache
343
- * profile as its HTML document. Returns null for non-server-fn URLs or on any
344
- * parse miss, so callers fall back to URL-based detection (never worse than the
345
- * pre-existing behavior).
346
- *
347
- * The payload is TanStack's serialized envelope; rather than depend on its
348
- * exact shape, we walk the parsed JSON for the first arg-value string that
349
- * looks like a route path. `loadCmsPage` encodes exactly one such string.
350
- */
351
- export function serverFnPagePath(url: URL): string | null {
352
- if (
353
- !url.pathname.startsWith("/_serverFn/") &&
354
- !url.pathname.startsWith("/_server/")
355
- ) {
356
- return null;
357
- }
358
- const payload = url.searchParams.get("payload");
359
- if (!payload) return null;
360
- try {
361
- let found: string | null = null;
362
- const visit = (v: unknown): void => {
363
- if (found !== null) return;
364
- if (typeof v === "string") {
365
- if (v.startsWith("/") && !v.startsWith("//")) found = v;
366
- return;
367
- }
368
- if (Array.isArray(v)) {
369
- for (const x of v) visit(x);
370
- return;
371
- }
372
- if (v && typeof v === "object") {
373
- for (const x of Object.values(v)) visit(x);
374
- }
375
- };
376
- visit(JSON.parse(payload));
377
- return found;
378
- } catch {
379
- return null;
380
- }
381
- }
382
-
383
- /**
384
- * Search params that never change a CMS page's resolved server-fn response and
385
- * so must not fragment its edge cache key. `skuId`/`idsku` select a product
386
- * variant client-side (mirrors `cmsRouteConfig`'s default
387
- * `ignoreSearchParams: ["skuId"]`) — without stripping them, every PDP→PDP
388
- * navigation that carries a variant param is a unique key and always MISSes,
389
- * re-running the full page resolution (~1-2s) even though the response is
390
- * identical to the canonical `/product/p`.
391
- */
392
- export const DEFAULT_SERVERFN_CACHE_IGNORE_PARAMS = ["skuId", "idsku"];
393
-
394
- /**
395
- * Canonicalize a TanStack GET server-fn `payload` for use in the edge cache
396
- * key: re-serialize it (so equivalent requests always produce byte-identical
397
- * keys) and strip the given cache-irrelevant search params from any embedded
398
- * route path. This makes `/product/p?skuId=148940` and `/product/p` share one
399
- * cache entry, since `loadCmsPage` resolves both to the same page.
400
- *
401
- * Returns the original payload unchanged on any parse failure (fail-safe: the
402
- * caller keeps the raw payload, never worse than before).
403
- */
404
- export function canonicalizeServerFnPayloadForCacheKey(
405
- payload: string,
406
- ignoreParams: string[] = DEFAULT_SERVERFN_CACHE_IGNORE_PARAMS,
407
- ): string {
408
- try {
409
- const stripQuery = (s: string): string => {
410
- if (!s.startsWith("/") || s.startsWith("//")) return s;
411
- const qIdx = s.indexOf("?");
412
- if (qIdx < 0) return s;
413
- const path = s.slice(0, qIdx);
414
- const sp = new URLSearchParams(s.slice(qIdx + 1));
415
- for (const p of ignoreParams) sp.delete(p);
416
- const rest = sp.toString();
417
- return rest ? `${path}?${rest}` : path;
418
- };
419
- const visit = (v: unknown): unknown => {
420
- if (typeof v === "string") return stripQuery(v);
421
- if (Array.isArray(v)) return v.map(visit);
422
- if (v && typeof v === "object") {
423
- const out: Record<string, unknown> = {};
424
- for (const [k, val] of Object.entries(v)) out[k] = visit(val);
425
- return out;
426
- }
427
- return v;
428
- };
429
- return JSON.stringify(visit(JSON.parse(payload)));
430
- } catch {
431
- return payload;
432
- }
433
- }
@@ -1,122 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
- import { clearLoaderCache, createCachedLoader, getLoaderCacheStats } from "./cachedLoader";
3
-
4
- describe("createCachedLoader", () => {
5
- beforeEach(() => {
6
- clearLoaderCache();
7
- });
8
- afterEach(() => {
9
- clearLoaderCache();
10
- vi.restoreAllMocks();
11
- });
12
-
13
- it("serves a fresh entry from cache (MISS then HIT) within maxAge", async () => {
14
- const loaderFn = vi.fn(async (p: { id: number }) => ({ v: p.id }));
15
- const cached = createCachedLoader("t/basic", loaderFn, {
16
- policy: "stale-while-revalidate",
17
- maxAge: 60_000,
18
- });
19
-
20
- await cached({ id: 1 }); // MISS
21
- await cached({ id: 1 }); // HIT — same key, within maxAge
22
-
23
- expect(loaderFn).toHaveBeenCalledTimes(1);
24
- expect(getLoaderCacheStats().entries).toBe(1);
25
- });
26
-
27
- it("distinct props produce distinct entries", async () => {
28
- const loaderFn = vi.fn(async (p: { id: number }) => ({ v: p.id }));
29
- const cached = createCachedLoader("t/props", loaderFn, {
30
- policy: "stale-while-revalidate",
31
- maxAge: 60_000,
32
- });
33
-
34
- await cached({ id: 1 });
35
- await cached({ id: 2 });
36
-
37
- expect(loaderFn).toHaveBeenCalledTimes(2);
38
- expect(getLoaderCacheStats().entries).toBe(2);
39
- });
40
-
41
- it("clearLoaderCache() empties the cache so the next call is a MISS", async () => {
42
- const loaderFn = vi.fn(async (p: { id: number }) => ({ v: p.id }));
43
- const cached = createCachedLoader("t/bust", loaderFn, {
44
- policy: "stale-while-revalidate",
45
- maxAge: 60_000,
46
- });
47
-
48
- await cached({ id: 1 }); // MISS
49
- await cached({ id: 1 }); // HIT
50
- expect(loaderFn).toHaveBeenCalledTimes(1);
51
-
52
- clearLoaderCache();
53
- expect(getLoaderCacheStats().entries).toBe(0);
54
-
55
- await cached({ id: 1 }); // MISS again — cache was cleared
56
- expect(loaderFn).toHaveBeenCalledTimes(2);
57
- });
58
-
59
- it("a purge during an in-flight loader does not repopulate the cleared entry", async () => {
60
- // Loader we can resolve manually, to hold it "in flight" across the purge.
61
- let release!: (v: { v: number }) => void;
62
- const loaderFn = vi.fn(
63
- () =>
64
- new Promise<{ v: number }>((res) => {
65
- release = res;
66
- }),
67
- );
68
- const cached = createCachedLoader("t/race", loaderFn, {
69
- policy: "stale-while-revalidate",
70
- maxAge: 60_000,
71
- });
72
-
73
- const inflight = cached({ id: 1 }); // MISS — loader now pending
74
- clearLoaderCache(); // purge lands while the loader is in flight
75
- release({ v: 99 }); // loader resolves with pre-purge data
76
- await expect(inflight).resolves.toEqual({ v: 99 }); // caller still gets its value
77
-
78
- // ...but the raced result must NOT have been written back to the cache.
79
- expect(getLoaderCacheStats().entries).toBe(0);
80
- });
81
-
82
- it("warns once per loader name when maxAge is very long", async () => {
83
- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
84
- const loaderFn = vi.fn(async () => ({}));
85
-
86
- // > 10 min → warns
87
- createCachedLoader("t/long-a", loaderFn, {
88
- policy: "stale-while-revalidate",
89
- maxAge: 3_600_000,
90
- });
91
- // same name again → deduped, no second warning
92
- createCachedLoader("t/long-a", loaderFn, {
93
- policy: "stale-while-revalidate",
94
- maxAge: 3_600_000,
95
- });
96
- // short maxAge → no warning
97
- createCachedLoader("t/short", loaderFn, {
98
- policy: "stale-while-revalidate",
99
- maxAge: 60_000,
100
- });
101
-
102
- const longWarnings = warn.mock.calls.filter(
103
- (c) => typeof c[0] === "string" && c[0].includes("t/long-a"),
104
- );
105
- const shortWarnings = warn.mock.calls.filter(
106
- (c) => typeof c[0] === "string" && c[0].includes("t/short"),
107
- );
108
- expect(longWarnings).toHaveLength(1);
109
- expect(shortWarnings).toHaveLength(0);
110
- });
111
-
112
- it("no-store policy bypasses the cache entirely", async () => {
113
- const loaderFn = vi.fn(async () => ({}));
114
- const cached = createCachedLoader("t/nostore", loaderFn, { policy: "no-store" });
115
-
116
- await cached({});
117
- await cached({});
118
-
119
- expect(loaderFn).toHaveBeenCalledTimes(2);
120
- expect(getLoaderCacheStats().entries).toBe(0);
121
- });
122
- });