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