@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,636 +0,0 @@
1
- /**
2
- * Section Loader Registry
3
- *
4
- * Section loaders enrich resolved CMS props with server-side data
5
- * (e.g., price simulations, device detection) that can't be done
6
- * at the CMS resolution level.
7
- *
8
- * This runs AFTER resolveDecoPage and BEFORE React rendering,
9
- * inside the TanStack Start server function.
10
- */
11
-
12
- import { RequestContext } from "@decocms/blocks/sdk/requestContext";
13
- import { getCacheProfile } from "../sdk/cacheHeaders";
14
- import { djb2 } from "../sdk/djb2";
15
- import { withInflightTimeout } from "../sdk/inflightTimeout";
16
- import { withTracing } from "../sdk/observability";
17
- import type { ResolvedSection } from "./resolve";
18
- import { buildSectionLoaderContext, type SectionLoaderContext } from "./sectionLoaderContext";
19
-
20
- export type SectionLoaderFn = (
21
- props: Record<string, unknown>,
22
- req: Request,
23
- /**
24
- * Compat context (issue #305). Optional so 2-arg loaders/mixins remain
25
- * valid — they simply ignore the extra argument. Framework-supplied at the
26
- * call site via {@link buildSectionLoaderContext}.
27
- */
28
- ctx?: SectionLoaderContext,
29
- ) => Promise<Record<string, unknown>> | Record<string, unknown>;
30
-
31
- // globalThis-backed: server function split modules need access
32
- const G = globalThis as any;
33
- if (!G.__deco) G.__deco = {};
34
- if (!G.__deco.sectionLoaderRegistry) G.__deco.sectionLoaderRegistry = new Map();
35
- if (!G.__deco.layoutSections) G.__deco.layoutSections = new Set();
36
- if (!G.__deco.cacheableSections) G.__deco.cacheableSections = new Map();
37
- if (!G.__deco.nonCriticalSections) G.__deco.nonCriticalSections = new Set();
38
-
39
- const loaderRegistry: Map<string, SectionLoaderFn> = G.__deco.sectionLoaderRegistry;
40
-
41
- // ---------------------------------------------------------------------------
42
- // Degradation tracking (anti-cache-poisoning)
43
- //
44
- // When a section loader throws, the section renders with raw (un-enriched)
45
- // props — e.g. a product shelf with no products during a VTEX outage. Today
46
- // that degraded page is emitted as a healthy 200 and the edge caches it for the
47
- // full retention window, so stale-if-error never fires and users see an empty
48
- // page for hours. We record each CRITICAL section degradation on a
49
- // request-scoped collector; the CMS route reads it and emits `X-Deco-Degraded`
50
- // so the worker refuses to cache the broken page and serves stale instead.
51
- //
52
- // Every section is critical by default (a registered loader failing means
53
- // intended data is missing). Decorative sections whose empty state is harmless
54
- // can opt out via `registerNonCriticalSections`.
55
- // ---------------------------------------------------------------------------
56
-
57
- const DEGRADED_BAG_KEY = "deco:degraded-sections";
58
- const nonCriticalSections: Set<string> = G.__deco.nonCriticalSections;
59
-
60
- /** Mark section keys whose loader failure should NOT make the page uncacheable. */
61
- export function registerNonCriticalSections(keys: string[]): void {
62
- for (const k of keys) nonCriticalSections.add(k);
63
- }
64
-
65
- /** A section is critical (its failure degrades the page) unless opted out. */
66
- export function isCriticalSection(key: string): boolean {
67
- return !nonCriticalSections.has(key);
68
- }
69
-
70
- /**
71
- * Record that a critical section rendered with raw props because its loader
72
- * threw. No-op outside a request scope or for non-critical sections.
73
- */
74
- export function markSectionDegraded(component: string): void {
75
- if (!isCriticalSection(component)) return;
76
- const set = RequestContext.getBag<Set<string>>(DEGRADED_BAG_KEY) ?? new Set<string>();
77
- set.add(component);
78
- RequestContext.setBag(DEGRADED_BAG_KEY, set);
79
- }
80
-
81
- /** Component keys of critical sections that degraded during this request. */
82
- export function getDegradedSections(): string[] {
83
- const set = RequestContext.getBag<Set<string>>(DEGRADED_BAG_KEY);
84
- return set ? [...set] : [];
85
- }
86
-
87
- // ---------------------------------------------------------------------------
88
- // Cacheable section loaders — SWR cache for section loader results
89
- // ---------------------------------------------------------------------------
90
-
91
- interface CacheableSectionConfig {
92
- maxAge: number;
93
- }
94
-
95
- export type CacheableSectionInput =
96
- | CacheableSectionConfig
97
- | import("../sdk/cacheHeaders").CacheProfileName;
98
-
99
- function resolveSectionCacheConfig(input: CacheableSectionInput): CacheableSectionConfig {
100
- if (typeof input === "string") {
101
- const profile = getCacheProfile(input);
102
- return { maxAge: profile.loader.fresh };
103
- }
104
- return input;
105
- }
106
-
107
- const cacheableSections: Map<string, CacheableSectionConfig> = G.__deco.cacheableSections;
108
-
109
- interface SectionCacheEntry {
110
- section: ResolvedSection;
111
- createdAt: number;
112
- refreshing: boolean;
113
- }
114
-
115
- const sectionLoaderCache = new Map<string, SectionCacheEntry>();
116
- const sectionLoaderInflight = new Map<string, Promise<ResolvedSection>>();
117
- const MAX_SECTION_CACHE_ENTRIES = 200;
118
-
119
- function evictSectionCacheIfNeeded() {
120
- if (sectionLoaderCache.size <= MAX_SECTION_CACHE_ENTRIES) return;
121
- const oldest = [...sectionLoaderCache.entries()].sort((a, b) => a[1].createdAt - b[1].createdAt);
122
- const toDelete = oldest.slice(0, sectionLoaderCache.size - MAX_SECTION_CACHE_ENTRIES);
123
- for (const [key] of toDelete) sectionLoaderCache.delete(key);
124
- }
125
-
126
- function sectionCacheKey(component: string, props: Record<string, unknown>): string {
127
- return `${component}::${djb2(JSON.stringify(props))}`;
128
- }
129
-
130
- /**
131
- * Register section components whose loader results should be cached.
132
- * Uses SWR (stale-while-revalidate) semantics: stale results are returned
133
- * immediately while a background refresh runs.
134
- *
135
- * Works for both eager sections (speeds up SSR) and deferred sections
136
- * (speeds up individual fetch on scroll).
137
- */
138
- export function registerCacheableSections(configs: Record<string, CacheableSectionInput>): void {
139
- for (const [key, config] of Object.entries(configs)) {
140
- cacheableSections.set(key, resolveSectionCacheConfig(config));
141
- }
142
- }
143
-
144
- function runCacheableSectionLoader(
145
- section: ResolvedSection,
146
- loader: SectionLoaderFn,
147
- request: Request,
148
- config: CacheableSectionConfig,
149
- ): Promise<ResolvedSection> {
150
- const key = sectionCacheKey(section.component, section.props as Record<string, unknown>);
151
-
152
- const existing = sectionLoaderInflight.get(key);
153
- if (existing) return existing;
154
-
155
- const entry = sectionLoaderCache.get(key);
156
- const now = Date.now();
157
- const isStale = entry ? now - entry.createdAt > config.maxAge : true;
158
-
159
- if (entry && !isStale) {
160
- return Promise.resolve(entry.section);
161
- }
162
-
163
- if (entry && isStale && !entry.refreshing) {
164
- entry.refreshing = true;
165
- void Promise.resolve(loader(section.props as Record<string, unknown>, request))
166
- .then((enrichedProps) => {
167
- const enriched = { ...section, props: enrichedProps };
168
- sectionLoaderCache.set(key, {
169
- section: enriched,
170
- createdAt: Date.now(),
171
- refreshing: false,
172
- });
173
- })
174
- .catch(() => {
175
- entry.refreshing = false;
176
- });
177
- return Promise.resolve(entry.section);
178
- }
179
-
180
- if (entry) return Promise.resolve(entry.section);
181
-
182
- const promise = withInflightTimeout(
183
- (async () => {
184
- const enrichedProps = await loader(section.props as Record<string, unknown>, request);
185
- const enriched = { ...section, props: enrichedProps };
186
- sectionLoaderCache.set(key, {
187
- section: enriched,
188
- createdAt: Date.now(),
189
- refreshing: false,
190
- });
191
- evictSectionCacheIfNeeded();
192
- return enriched;
193
- })(),
194
- `sectionLoader ${key}`,
195
- ).finally(() => sectionLoaderInflight.delete(key));
196
-
197
- sectionLoaderInflight.set(key, promise);
198
- return promise;
199
- }
200
-
201
- /**
202
- * Register a server-side loader for a specific section.
203
- * The loader receives the CMS-resolved props and a Request,
204
- * and returns enriched props.
205
- */
206
- export function registerSectionLoader(sectionKey: string, loader: SectionLoaderFn): void {
207
- loaderRegistry.set(sectionKey, loader);
208
- }
209
-
210
- /**
211
- * Register multiple section loaders at once.
212
- *
213
- * Dev-only diagnostic: when a request-dependent loader (one built from
214
- * `withDevice`/`withMobile`/`withSearchParam`, possibly through `compose`)
215
- * is registered for a section that's also in `layoutSections`, the layout
216
- * cache will serve the first visitor's variant to every viewer for
217
- * `LAYOUT_CACHE_TTL` (5 min). We log a loud warning explaining the
218
- * remediation options. See #206.
219
- */
220
- export function registerSectionLoaders(loaders: Record<string, SectionLoaderFn>): void {
221
- for (const [key, loader] of Object.entries(loaders)) {
222
- loaderRegistry.set(key, loader);
223
- }
224
- if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
225
- for (const [key, loader] of Object.entries(loaders)) {
226
- const requestDependent =
227
- (loader as SectionLoaderFn & { __requestDependent?: boolean }).__requestDependent === true;
228
- if (requestDependent && layoutSections.has(key)) {
229
- console.warn(
230
- `[SectionLoaders] "${key}" is registered as a layout section ` +
231
- `(cached for 5min by component path) but its loader is request-` +
232
- `dependent (withDevice/withMobile/withSearchParam). The first ` +
233
- `visitor's variant will be served to all users for 5min. Fix: ` +
234
- `(1) remove "export const layout = true" from the section, ` +
235
- `(2) call unregisterLayoutSections(["${key}"]) in setup.ts ` +
236
- `after applySectionConventions, or (3) move the request-` +
237
- `dependent logic out of the layout loader.`,
238
- );
239
- }
240
- }
241
- }
242
- }
243
-
244
- // ---------------------------------------------------------------------------
245
- // Layout section cache — sections whose output doesn't change per-page
246
- // (Header, Footer, Theme, etc.) are cached server-side so they aren't
247
- // re-resolved and re-enriched on every navigation.
248
- //
249
- // Uses in-flight deduplication: if two requests try to resolve the same
250
- // layout section concurrently, the second shares the first's Promise.
251
- // ---------------------------------------------------------------------------
252
-
253
- const layoutSections: Set<string> = G.__deco.layoutSections;
254
-
255
- const LAYOUT_CACHE_TTL = 5 * 60_000; // 5 minutes
256
-
257
- interface CachedSection {
258
- section: ResolvedSection;
259
- expiresAt: number;
260
- }
261
-
262
- const layoutCache = new Map<string, CachedSection>();
263
- const layoutInflight = new Map<string, Promise<ResolvedSection>>();
264
-
265
- /**
266
- * Register section keys that should be cached as layout sections.
267
- * Layout sections (Header, Footer, etc.) are cached server-side
268
- * for LAYOUT_CACHE_TTL to avoid redundant enrichment on every navigation.
269
- *
270
- * The cache key is the component path only — it does NOT include UA,
271
- * cookies, or geo. Sections whose loader depends on those signals must
272
- * not be layout-cached: see {@link unregisterLayoutSections} to opt a
273
- * section out of the auto-discovery done by `applySectionConventions`.
274
- */
275
- export function registerLayoutSections(keys: string[]): void {
276
- for (const key of keys) {
277
- layoutSections.add(key);
278
- }
279
- }
280
-
281
- /**
282
- * Remove section keys from the layout cache set. Use this to opt a section
283
- * out of caching when `applySectionConventions` auto-registered it via
284
- * `export const layout = true` but the section's loader is in fact request-
285
- * dependent (Header with `withDevice()`, geo-aware promo, etc.).
286
- *
287
- * Call after `applySectionConventions` and before the first request.
288
- *
289
- * See #206 for the contamination bug this prevents.
290
- */
291
- export function unregisterLayoutSections(keys: string[]): void {
292
- for (const key of keys) {
293
- layoutSections.delete(key);
294
- }
295
- }
296
-
297
- /** Check if a section key is registered as a layout section. */
298
- export function isLayoutSection(key: string): boolean {
299
- return layoutSections.has(key);
300
- }
301
-
302
- function getCachedLayout(component: string): ResolvedSection | null {
303
- const entry = layoutCache.get(component);
304
- if (!entry) return null;
305
- if (Date.now() > entry.expiresAt) {
306
- layoutCache.delete(component);
307
- return null;
308
- }
309
- return entry.section;
310
- }
311
-
312
- function setCachedLayout(component: string, section: ResolvedSection): void {
313
- layoutCache.set(component, {
314
- section,
315
- expiresAt: Date.now() + LAYOUT_CACHE_TTL,
316
- });
317
- }
318
-
319
- /**
320
- * Run a layout section's loader with in-flight dedup + TTL cache.
321
- */
322
- function resolveLayoutSection(
323
- section: ResolvedSection,
324
- loader: SectionLoaderFn,
325
- request: Request,
326
- ): Promise<ResolvedSection> {
327
- const key = section.component;
328
- const { index } = section;
329
-
330
- // Re-apply the caller's page-specific index onto a fresh object so the
331
- // shared cache entry never carries an index from a previous request.
332
- const withIndex = (s: ResolvedSection): ResolvedSection =>
333
- index !== undefined ? { ...s, index } : s;
334
-
335
- const cached = getCachedLayout(key);
336
- if (cached) return Promise.resolve(withIndex(cached));
337
-
338
- const existing = layoutInflight.get(key);
339
- if (existing) return existing.then(withIndex);
340
-
341
- const promise = withInflightTimeout(
342
- (async () => {
343
- const enrichedProps = await loader(section.props as Record<string, unknown>, request);
344
- const { index: _idx, ...sectionWithoutIndex } = section;
345
- const enriched = { ...sectionWithoutIndex, props: enrichedProps };
346
- setCachedLayout(key, enriched);
347
- return withIndex(enriched);
348
- })(),
349
- `layoutSection ${key}`,
350
- ).finally(() => layoutInflight.delete(key));
351
-
352
- layoutInflight.set(key, promise);
353
-
354
- return promise;
355
- }
356
-
357
- /**
358
- * Run registered section loaders against resolved sections.
359
- * Sections without a registered loader pass through unchanged.
360
- *
361
- * Layout sections use in-flight dedup + TTL cache to avoid
362
- * redundant enrichment across concurrent and sequential requests.
363
- *
364
- * Runs all loaders in parallel for performance.
365
- */
366
- export async function runSectionLoaders(
367
- sections: ResolvedSection[],
368
- request: Request,
369
- ): Promise<ResolvedSection[]> {
370
- // Dev warning: detect likely layout sections not registered via registerLayoutSections.
371
- // Without registration, Header/Footer won't be cached across navigations.
372
- if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
373
- for (const s of sections) {
374
- const key = s.component.toLowerCase();
375
- if ((key.includes("header") || key.includes("footer")) && !layoutSections.has(s.component)) {
376
- console.warn(
377
- `[SectionLoaders] "${s.component}" looks like a layout section but is not in registerLayoutSections(). ` +
378
- `Add it to registerLayoutSections() in setup.ts for consistent caching across navigations.`,
379
- );
380
- }
381
- }
382
- }
383
- return withTracing(
384
- "deco.section.loaders.batch",
385
- () => Promise.all(sections.map((section) => runSingleSectionLoader(section, request))),
386
- { "section.count": sections.length },
387
- );
388
- }
389
-
390
- /**
391
- * Inject the active request's URL and path into section props so site
392
- * loaders can read `props.__pageUrl` / `props.__pagePath` without having
393
- * to derive them from `req.url` themselves.
394
- *
395
- * The framework already injects these for commerce loaders (resolve.ts),
396
- * but section loaders (e.g. category SearchBanner, breadcrumb-aware FAQs)
397
- * also need to know the active page. Without this, callers had to wrap
398
- * `loader(...)` themselves in a custom `delegateAfter`-style helper —
399
- * forgetting it produced silent rendering bugs (empty banners, default
400
- * fallbacks).
401
- *
402
- * Existing values in `props` win — sites that already pre-populated
403
- * `__pageUrl` (e.g. via a custom mixin) keep their value untouched.
404
- *
405
- * Note: this runs only at the point we hand props to the user's loader.
406
- * The cacheable-section cache key hashes the *original* props (URL-agnostic),
407
- * so sections registered via `registerCacheableSections` keep sharing a
408
- * single cache entry across pages.
409
- */
410
- function injectPageContext(
411
- props: Record<string, unknown>,
412
- request: Request,
413
- ): Record<string, unknown> {
414
- let url: URL;
415
- try {
416
- url = new URL(request.url);
417
- } catch {
418
- return props;
419
- }
420
- const enriched = { ...props } as Record<string, unknown>;
421
- if (enriched.__pageUrl === undefined) enriched.__pageUrl = request.url;
422
- if (enriched.__pagePath === undefined) enriched.__pagePath = url.pathname;
423
- return enriched;
424
- }
425
-
426
- /**
427
- * Wrap a loader so it receives __pageUrl/__pagePath in its props AND the
428
- * 3rd-arg compat `ctx` (issue #305). This is the single choke point that all
429
- * four invocation paths (regular, layout, cacheable, SWR refresh) route
430
- * through, so building `ctx` here covers every path.
431
- */
432
- function withPageContext(loader: SectionLoaderFn): SectionLoaderFn {
433
- return (props, req) => loader(injectPageContext(props, req), req, buildSectionLoaderContext(req));
434
- }
435
-
436
- /**
437
- * Run a single section's registered loader.
438
- * Used by both `runSectionLoaders` (batch) and `loadDeferredSection` (individual).
439
- *
440
- * Respects three cache tiers:
441
- * 1. Layout sections (Header/Footer) — 5min TTL + in-flight dedup
442
- * 2. Cacheable sections (ProductShelf, FAQ) — SWR with configurable maxAge
443
- * 3. Regular sections — no cache, always fresh
444
- *
445
- * After the section's own loader runs, recursively runs loaders for any
446
- * nested sections found in its resolved props (e.g. wrapper sections with
447
- * a `sections: Section[]` prop). This eliminates the need for sites to
448
- * manually walk + invoke `runSingleSectionLoader` on children.
449
- */
450
- export async function runSingleSectionLoader(
451
- section: ResolvedSection,
452
- request: Request,
453
- ): Promise<ResolvedSection> {
454
- return withTracing("deco.section.loader", () => runSingleSectionLoaderImpl(section, request), {
455
- "deco.section": section.component,
456
- });
457
- }
458
-
459
- async function runSingleSectionLoaderImpl(
460
- section: ResolvedSection,
461
- request: Request,
462
- ): Promise<ResolvedSection> {
463
- const loader = loaderRegistry.get(section.component);
464
-
465
- let result: ResolvedSection;
466
-
467
- if (!loader) {
468
- // No own-loader, but the section may still contain nested sections in
469
- // its props (CMS-resolved children) that need their loaders run.
470
- result = section;
471
- } else {
472
- // Wrap the loader so __pageUrl/__pagePath are injected at the call site.
473
- // Cache keys (component name for layout, component+propsHash for cacheable)
474
- // are computed from the *original* section.props — keeping cache entries
475
- // URL-agnostic and shared across pages.
476
- const wrapped = withPageContext(loader);
477
-
478
- if (layoutSections.has(section.component)) {
479
- try {
480
- result = await resolveLayoutSection(section, wrapped, request);
481
- } catch (error) {
482
- console.error(`[SectionLoader] Error in layout "${section.component}":`, error);
483
- // Deliberately NOT marked degraded: layout sections (Header/Footer/Theme)
484
- // render on every page, so a flaky layout loader would flip the whole
485
- // site to X-Deco-Degraded and defeat edge caching everywhere. A failed
486
- // layout renders raw chrome, which is acceptable — page-body data
487
- // integrity (product shelves/PLP/PDP) is what the degraded signal guards.
488
- result = section;
489
- }
490
- } else {
491
- const cacheConfig = cacheableSections.get(section.component);
492
- if (cacheConfig) {
493
- try {
494
- result = await runCacheableSectionLoader(section, wrapped, request, cacheConfig);
495
- } catch (error) {
496
- console.error(`[SectionLoader] Error in cacheable "${section.component}":`, error);
497
- markSectionDegraded(section.component);
498
- result = section;
499
- }
500
- } else {
501
- try {
502
- const enrichedProps = await wrapped(section.props as Record<string, unknown>, request);
503
- result = { ...section, props: enrichedProps };
504
- } catch (error) {
505
- console.error(`[SectionLoader] Error in "${section.component}":`, error);
506
- markSectionDegraded(section.component);
507
- result = section;
508
- }
509
- }
510
- }
511
- }
512
-
513
- // Recurse into nested sections AFTER the parent's loader/cache lookup so
514
- // child sections keep their own cache TTL independent from the parent's.
515
- // For layout/cacheable parents, this means a 5-min layout cache hit still
516
- // re-evaluates child sections (whose own caches are usually shorter, e.g.
517
- // ProductShelf 60s). For leaf sections, `enrichNestedSections` returns
518
- // the same reference (no allocation, no extra work).
519
- const props = result.props as Record<string, unknown> | undefined;
520
- if (props && typeof props === "object") {
521
- const enrichedProps = await enrichNestedSections(props, request);
522
- if (enrichedProps !== props) {
523
- return { ...result, props: enrichedProps };
524
- }
525
- }
526
- return result;
527
- }
528
-
529
- // ---------------------------------------------------------------------------
530
- // Nested section loader support
531
- // ---------------------------------------------------------------------------
532
-
533
- /**
534
- * Type guard: matches the shape produced by `normalizeNestedSections` in
535
- * resolve.ts — `{ Component: string, props: object }`. This is how the CMS
536
- * resolver represents nested sections (children of wrapper sections).
537
- *
538
- * Note: the `Component` key uses capital C to match the runtime renderer's
539
- * convention (mirrors deco-cx/deco's Fresh API). Not to be confused with
540
- * the lowercase `component` on `ResolvedSection`.
541
- */
542
- function isNestedSection(
543
- value: unknown,
544
- ): value is { Component: string; props: Record<string, unknown> } {
545
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
546
- const obj = value as Record<string, unknown>;
547
- return (
548
- typeof obj.Component === "string" &&
549
- obj.props != null &&
550
- typeof obj.props === "object" &&
551
- !Array.isArray(obj.props)
552
- );
553
- }
554
-
555
- /**
556
- * Walk a props object and run section loaders for any nested sections.
557
- * Handles direct child sections AND arrays of sections (e.g.
558
- * `sections: Section[]`, `slides: Slide[]`).
559
- *
560
- * Returns the same reference if nothing changed — so leaf sections (the
561
- * vast majority) incur zero allocation overhead.
562
- *
563
- * Concurrency: all nested loader calls run in parallel via Promise.all.
564
- */
565
- async function enrichNestedSections(
566
- props: Record<string, unknown>,
567
- request: Request,
568
- ): Promise<Record<string, unknown>> {
569
- type Pending = {
570
- key: string;
571
- index?: number;
572
- promise: Promise<ResolvedSection>;
573
- };
574
- const pending: Pending[] = [];
575
-
576
- for (const [key, value] of Object.entries(props)) {
577
- if (isNestedSection(value)) {
578
- pending.push({
579
- key,
580
- promise: runSingleSectionLoader(
581
- {
582
- component: value.Component,
583
- props: value.props,
584
- key: value.Component,
585
- } as ResolvedSection,
586
- request,
587
- ),
588
- });
589
- continue;
590
- }
591
-
592
- if (Array.isArray(value)) {
593
- for (let i = 0; i < value.length; i++) {
594
- const item = value[i];
595
- if (isNestedSection(item)) {
596
- pending.push({
597
- key,
598
- index: i,
599
- promise: runSingleSectionLoader(
600
- {
601
- component: item.Component,
602
- props: item.props,
603
- key: item.Component,
604
- } as ResolvedSection,
605
- request,
606
- ),
607
- });
608
- }
609
- }
610
- }
611
- }
612
-
613
- if (pending.length === 0) return props;
614
-
615
- const results = await Promise.all(pending.map((p) => p.promise));
616
- const updated: Record<string, unknown> = { ...props };
617
-
618
- for (let i = 0; i < pending.length; i++) {
619
- const { key, index } = pending[i];
620
- const enriched = results[i];
621
- const nestedValue = { Component: enriched.component, props: enriched.props };
622
-
623
- if (index != null) {
624
- // Array item — clone the array on first mutation for this key
625
- const current = updated[key];
626
- if (current === props[key]) {
627
- updated[key] = [...(current as unknown[])];
628
- }
629
- (updated[key] as unknown[])[index] = nestedValue;
630
- } else {
631
- updated[key] = nestedValue;
632
- }
633
- }
634
-
635
- return updated;
636
- }