@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,2282 +0,0 @@
1
- import { getMatchersOverride, getRuleOverrideId, hasMatchersOverride } from "../matchers/override";
2
- import { getMeter, MetricNames, withTracing } from "../middleware/observability";
3
- import { djb2Hex } from "../sdk/djb2";
4
- import { parseSegmentCookie, SEGMENT_COOKIE, type StoredFlag, trafficToPct } from "../sdk/flags";
5
- import { withInflightTimeout } from "../sdk/inflightTimeout";
6
- import { normalizeUrlsInObject } from "../sdk/normalizeUrls";
7
- import { findPageByPath, loadBlocks } from "./loader";
8
- import { getOnBeforeResolveProps, getSection, registerOnBeforeResolveProps } from "./registry";
9
- import {
10
- type ActionConfig,
11
- inferLoaderTags,
12
- type LoaderConfig,
13
- registerActionSchemas,
14
- registerLoaderSchemas,
15
- } from "./schema";
16
- import { isLayoutSection, markSectionDegraded, runSingleSectionLoader } from "./sectionLoaders";
17
-
18
- // globalThis-backed: share state across Vite server function split modules
19
- const G = globalThis as any;
20
- if (!G.__deco) G.__deco = {};
21
- if (!G.__deco.commerceLoaders) G.__deco.commerceLoaders = {};
22
- if (!G.__deco.customMatchers) G.__deco.customMatchers = {};
23
- if (!G.__deco.eagerSectionKeys) G.__deco.eagerSectionKeys = new Set<string>();
24
-
25
- // ---------------------------------------------------------------------------
26
- // onBeforeResolveProps helper — eagerly loads the section module if needed
27
- // ---------------------------------------------------------------------------
28
-
29
- async function applyOnBeforeResolveProps(
30
- sectionType: string,
31
- props: Record<string, unknown>,
32
- ): Promise<Record<string, unknown>> {
33
- let fn = getOnBeforeResolveProps(sectionType);
34
- if (!fn) {
35
- const loader = getSection(sectionType);
36
- if (loader) {
37
- try {
38
- const mod = await loader();
39
- if (mod?.onBeforeResolveProps) {
40
- registerOnBeforeResolveProps(sectionType, mod.onBeforeResolveProps);
41
- fn = mod.onBeforeResolveProps;
42
- }
43
- } catch {}
44
- }
45
- }
46
- return fn ? fn(props) : props;
47
- }
48
-
49
- // ---------------------------------------------------------------------------
50
- // Well-known resolve types — extracted as constants so they're searchable
51
- // and overridable. Consumers migrating from deco-cx/deco may have blocks
52
- // with these __resolveType strings in their CMS JSON.
53
- // ---------------------------------------------------------------------------
54
-
55
- /** @internal */
56
- export const WELL_KNOWN_TYPES = {
57
- LAZY: "website/sections/Rendering/Lazy.tsx",
58
- DEFERRED: "website/sections/Rendering/Deferred.tsx",
59
- REQUEST_TO_PARAM: "website/functions/requestToParam.ts",
60
- COMMERCE_EXT_DETAILS: "commerce/loaders/product/extensions/detailsPage.ts",
61
- COMMERCE_EXT_LISTING: "commerce/loaders/product/extensions/listingPage.ts",
62
- MULTIVARIATE: "website/flags/multivariate.ts",
63
- MULTIVARIATE_SECTION: "website/flags/multivariate/section.ts",
64
- PAGE: "website/pages/Page.tsx",
65
- } as const;
66
-
67
- export type ResolvedSection = {
68
- component: string;
69
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
70
- props: Record<string, any>;
71
- key: string;
72
- /** Original position in the raw section list (used by mergeSections). */
73
- index?: number;
74
- };
75
-
76
- // ---------------------------------------------------------------------------
77
- // Deferred section — a placeholder for sections loaded on scroll
78
- // ---------------------------------------------------------------------------
79
-
80
- export interface DeferredSection {
81
- component: string;
82
- key: string;
83
- /** Position in the original page section list. */
84
- index: number;
85
- /**
86
- * Short hash of rawProps for client-side cache busting.
87
- * Keeps the serialized payload small — full rawProps are resolved
88
- * server-side from the deferred props cache or page re-resolution.
89
- */
90
- propsHash: string;
91
- /**
92
- * CMS-resolved props without section-loader enrichment.
93
- * @deprecated Stripped before serialization to reduce HTML payload.
94
- * Only present server-side in the rawProps cache.
95
- */
96
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
97
- rawProps?: Record<string, any>;
98
- }
99
-
100
- // ---------------------------------------------------------------------------
101
- // Async rendering configuration
102
- // ---------------------------------------------------------------------------
103
-
104
- export interface AsyncRenderingConfig {
105
- /**
106
- * When true, sections wrapped in `website/sections/Rendering/Lazy.tsx`
107
- * in the CMS are deferred and loaded on scroll. This respects the
108
- * editor's per-section choices made in the admin.
109
- * @default true
110
- */
111
- respectCmsLazy: boolean;
112
- /**
113
- * Fold threshold: sections at or above this flat index are DEFERRED
114
- * (rendered as a skeleton and loaded on scroll), so their resolved props are
115
- * not serialized into the SSR hydration payload. Sections below it stay
116
- * eager. This is an explicit, position-based opt-in that applies ONLY to
117
- * sections the editor did NOT mark async (⚡) in the admin — it never
118
- * overrides a CMS Lazy/Deferred wrapper.
119
- *
120
- * Defaults to {@link DEFAULT_FOLD_THRESHOLD} (`Infinity`), which disables
121
- * position-based deferral entirely so the admin ⚡ toggle is the sole source
122
- * of truth. Set a finite value per-site to also defer unmarked sections by
123
- * position.
124
- * @default {@link DEFAULT_FOLD_THRESHOLD}
125
- */
126
- foldThreshold: number;
127
- /** Section component keys that must always be rendered eagerly. */
128
- alwaysEager: Set<string>;
129
- /**
130
- * Site-wide bot-aware page SEO shortcut. When true, the page-level `seo`
131
- * block's commerce-loader-backed props (e.g. `jsonLD: { __resolveType: "PLP
132
- * Loader" }`) are SKIPPED for human (non-bot) requests — so SSR doesn't run
133
- * the heavy upstream fetch and the product payload never reaches the human
134
- * HTML. Bots still get the full SEO (JSON-LD) for indexing.
135
- *
136
- * This is a blanket, developer-set shortcut. The PRIMARY, client-facing lever
137
- * is the per-section `ignoreStructuredData` toggle in the admin (on the PLP/PDP
138
- * SEO section): it drives the exact same fetch-skip + bot-aware JSON-LD, but
139
- * per section and without a code change. This flag simply turns the behavior
140
- * on for every commerce-backed SEO block at once.
141
- *
142
- * OFF by default: the optimization removes the commerce data a human `<title>`
143
- * may derive from, so a blanket opt-in is only safe once the site provides a
144
- * lightweight title fallback (e.g. a cheap category-metadata loader). Sites
145
- * that just bump the framework keep the previous behavior (full SEO for
146
- * everyone) and are not regressed. Opt in with
147
- * `setAsyncRenderingConfig({ botAwareSeo: true })`, or leave it off and let
148
- * editors flip `ignoreStructuredData` per section.
149
- * @default false
150
- */
151
- botAwareSeo: boolean;
152
- }
153
-
154
- /**
155
- * Default fold threshold. `Infinity` disables position-based deferral entirely:
156
- * sections are deferred if and only if the editor marked them async (⚡) in the
157
- * admin (wrapped in CMS `Lazy.tsx`/`Deferred.tsx`). The admin is the source of
158
- * truth; a section's position on the page never drives the SSR-vs-deferred
159
- * decision by default.
160
- *
161
- * Sites that want to additionally defer unmarked sections by position can opt
162
- * in explicitly via `setAsyncRenderingConfig({ foldThreshold: N })` — keeping
163
- * the first N sections eager (above-the-fold LCP/SEO) and deferring the rest to
164
- * trim the SSR hydration payload. Even then, the threshold only affects
165
- * sections NOT marked ⚡; it never overrides the editor's choice.
166
- */
167
- export const DEFAULT_FOLD_THRESHOLD = Infinity;
168
-
169
- // Always read from globalThis so split-module copies see updates
170
- function getAsyncConfig(): AsyncRenderingConfig | null {
171
- return G.__deco.asyncConfig ?? null;
172
- }
173
-
174
- /**
175
- * Enable async section rendering.
176
- *
177
- * The admin is the source of truth: any section the editor marked async ⚡
178
- * (wrapped in `website/sections/Rendering/Lazy.tsx` or `Deferred.tsx`) is
179
- * deferred and loaded on scroll; every other section is rendered eagerly (SSR),
180
- * regardless of its position. `foldThreshold` defaults to
181
- * {@link DEFAULT_FOLD_THRESHOLD} (`Infinity`), so position-based deferral is
182
- * OFF by default. Pass a finite `foldThreshold: N` to additionally defer
183
- * UNMARKED sections from index N onward (an opt-in optimization that never
184
- * overrides the editor's ⚡ choice).
185
- *
186
- * When not called, all sections are resolved eagerly (backward compatible).
187
- */
188
- export function setAsyncRenderingConfig(config?: {
189
- foldThreshold?: number;
190
- alwaysEager?: string[];
191
- respectCmsLazy?: boolean;
192
- botAwareSeo?: boolean;
193
- }): void {
194
- const existing = getAsyncConfig();
195
- const merged = new Set([...(existing?.alwaysEager ?? []), ...(config?.alwaysEager ?? [])]);
196
- G.__deco.asyncConfig = {
197
- respectCmsLazy: config?.respectCmsLazy ?? existing?.respectCmsLazy ?? true,
198
- foldThreshold: config?.foldThreshold ?? existing?.foldThreshold ?? DEFAULT_FOLD_THRESHOLD,
199
- alwaysEager: merged,
200
- botAwareSeo: config?.botAwareSeo ?? existing?.botAwareSeo ?? false,
201
- };
202
- }
203
-
204
- /** Read-only access to the current config (null when disabled). */
205
- export function getAsyncRenderingConfig(): AsyncRenderingConfig | null {
206
- return getAsyncConfig();
207
- }
208
-
209
- // ---------------------------------------------------------------------------
210
- // Permanent eager section registry — survives setAsyncRenderingConfig() calls
211
- // ---------------------------------------------------------------------------
212
-
213
- /**
214
- * Register sections that declared `export const eager = true`.
215
- * This is a permanent registry that cannot be overwritten by
216
- * subsequent calls to `setAsyncRenderingConfig()`.
217
- */
218
- export function registerEagerSections(keys: string[]): void {
219
- const set: Set<string> = G.__deco.eagerSectionKeys;
220
- for (const k of keys) set.add(k);
221
- }
222
-
223
- function isEagerSection(key: string): boolean {
224
- return (G.__deco.eagerSectionKeys as Set<string>).has(key);
225
- }
226
-
227
- // ---------------------------------------------------------------------------
228
- // Permanent neverDefer section registry
229
- // ---------------------------------------------------------------------------
230
-
231
- /**
232
- * Register sections that declared `export const neverDefer = true`.
233
- * These sections are NEVER deferred regardless of fold threshold —
234
- * use for interactive components that need their props on the client
235
- * during hydration (search filters, configurators, etc.).
236
- */
237
- export function registerNeverDeferSections(keys: string[]): void {
238
- const set: Set<string> = (G.__deco.neverDeferSectionKeys ??= new Set());
239
- for (const k of keys) set.add(k);
240
- }
241
-
242
- function isNeverDeferSection(key: string): boolean {
243
- return (G.__deco.neverDeferSectionKeys as Set<string> | undefined)?.has(key) ?? false;
244
- }
245
-
246
- // ---------------------------------------------------------------------------
247
- // Deferred rawProps cache — keeps rawProps server-side to trim HTML payload
248
- // ---------------------------------------------------------------------------
249
-
250
- const DEFERRED_PROPS_TTL = 120_000; // 2 minutes
251
- const deferredRawPropsCache = new Map<string, { rawProps: Record<string, unknown>; ts: number }>();
252
-
253
- function deferredPropsCacheKey(pagePath: string, component: string, index: number): string {
254
- return `${pagePath}::${component}::${index}`;
255
- }
256
-
257
- export function cacheDeferredRawProps(
258
- pagePath: string,
259
- component: string,
260
- index: number,
261
- rawProps: Record<string, unknown>,
262
- ): void {
263
- const key = deferredPropsCacheKey(pagePath, component, index);
264
- deferredRawPropsCache.set(key, { rawProps, ts: Date.now() });
265
-
266
- // Lazy eviction: remove expired entries when cache grows
267
- if (deferredRawPropsCache.size > 500) {
268
- const now = Date.now();
269
- for (const [k, v] of deferredRawPropsCache) {
270
- if (now - v.ts > DEFERRED_PROPS_TTL) deferredRawPropsCache.delete(k);
271
- }
272
- }
273
- }
274
-
275
- export function getDeferredRawProps(
276
- pagePath: string,
277
- component: string,
278
- index: number,
279
- ): Record<string, unknown> | null {
280
- const key = deferredPropsCacheKey(pagePath, component, index);
281
- const entry = deferredRawPropsCache.get(key);
282
- if (!entry || Date.now() - entry.ts > DEFERRED_PROPS_TTL) return null;
283
- return entry.rawProps;
284
- }
285
-
286
- // ---------------------------------------------------------------------------
287
- // Bot detection — bots always receive fully eager pages for SEO
288
- // ---------------------------------------------------------------------------
289
-
290
- const botPatterns: RegExp[] = [
291
- /bot|crawl|spider|slurp|facebookexternalhit|mediapartners|google|bing|yandex|baidu|duckduck|teoma|ia_archiver|semrush|ahrefs|lighthouse/i,
292
- ];
293
-
294
- /**
295
- * Add a custom bot detection regex.
296
- * Requests matching any bot pattern receive fully eager pages for SEO.
297
- */
298
- export function registerBotPattern(pattern: RegExp): void {
299
- botPatterns.push(pattern);
300
- }
301
-
302
- export function isBot(userAgent?: string): boolean {
303
- if (!userAgent) return false;
304
- return botPatterns.some((re) => re.test(userAgent));
305
- }
306
-
307
- /**
308
- * Explicit override to force the eager (full SSR / crawler) render from a normal
309
- * browser — for QA and SEO auditing without spoofing the User-Agent. Triggered
310
- * by `?__deco_ssr=1` (alias `?__bot=1`) on the request URL.
311
- *
312
- * The flag lives in the query string, so it is part of the edge cache key: the
313
- * forced-eager response gets its own cache bucket and never contaminates the
314
- * human page. Cookies are intentionally NOT honored here — they are not in the
315
- * cache key and would risk serving a stale human entry.
316
- */
317
- function hasForceEagerParam(ctx?: MatcherContext): boolean {
318
- const url = ctx?.url;
319
- if (!url) return false;
320
- try {
321
- const sp = new URL(url, "https://localhost").searchParams;
322
- return sp.get("__deco_ssr") === "1" || sp.get("__bot") === "1";
323
- } catch {
324
- return false;
325
- }
326
- }
327
-
328
- /**
329
- * True for a programmatic, non-navigation request to a page URL — an AJAX
330
- * `fetch()`/XHR (e.g. the PLP "Ver mais"/load-more pagination), an embed, or a
331
- * server-to-server fetch. These consumers read the static SSR HTML and never
332
- * run the client-side deferred-section resolution (IntersectionObserver +
333
- * `loadDeferredSection` serverFn), so any `⚡` deferred section is invisible to
334
- * them — they only ever see its skeleton. Rendering eagerly puts the real
335
- * content in the HTML they actually parse.
336
- *
337
- * Detected via `Sec-Fetch-Dest: empty`, which a `fetch()`/XHR sends and which a
338
- * top-level browser navigation (`document`) and subresource loads
339
- * (`image`/`script`/`style`/`font`) do not — navigations stay deferred because
340
- * they CAN hydrate and resolve deferred sections. SPA navigations (TanStack
341
- * `<Link>` → `/_serverFn`) also send `empty` but set `isClientNavigation`, and
342
- * are excluded here so page-SEO commerce loaders stay off for humans
343
- * (decocms/blocks#286); their sections already render eagerly via the
344
- * `!isClientNav` branch of the `useAsync` gate.
345
- *
346
- * Like {@link hasForceEagerParam}, this must stay in lock-step with the edge
347
- * cache key: `workerEntry` keys `Sec-Fetch-Dest: empty` page requests into a
348
- * separate `__fetch=1` bucket, so the eager response never poisons the
349
- * navigation (deferred) entry, and vice-versa.
350
- */
351
- function isProgrammaticFetch(ctx?: MatcherContext): boolean {
352
- if (ctx?.isClientNavigation) return false;
353
- const dest = ctx?.request?.headers.get("sec-fetch-dest") ?? ctx?.headers?.["sec-fetch-dest"];
354
- return dest === "empty";
355
- }
356
-
357
- /**
358
- * True when the request should receive the full eager (crawler) render: real
359
- * search-engine bots (by User-Agent), an explicit `?__deco_ssr=1` override, or
360
- * a programmatic non-navigation fetch (see {@link isProgrammaticFetch}). Used
361
- * to gate both section deferral and page-SEO commerce resolution.
362
- */
363
- export function isEagerRequest(ctx?: MatcherContext): boolean {
364
- return isBot(ctx?.userAgent) || hasForceEagerParam(ctx) || isProgrammaticFetch(ctx);
365
- }
366
-
367
- /**
368
- * A loader registered against a `__resolveType` key. The runtime invokes it
369
- * through two paths:
370
- *
371
- * 1. CMS resolution (`commerceLoader(resolvedProps)`) — 1-arg call.
372
- * 2. `/deco/invoke/...` endpoint — `(props, request)` 2-arg call.
373
- *
374
- * Loaders that need the `Request` (cookies, geo, headers) declare the second
375
- * parameter; pure loaders ignore it. This shape lets a single registry serve
376
- * both invocation paths without `as any` casts at every wrapper.
377
- */
378
- export type CommerceLoader = (props: any, request?: Request) => Promise<any>;
379
-
380
- /**
381
- * Context passed through the resolution pipeline.
382
- * Includes HTTP request info for matcher evaluation and per-request memoization.
383
- */
384
- export interface MatcherContext {
385
- userAgent?: string;
386
- url?: string;
387
- path?: string;
388
- cookies?: Record<string, string>;
389
- headers?: Record<string, string>;
390
- request?: Request;
391
- /**
392
- * Sticky A/B flags recorded during resolution. The resolver appends a
393
- * {@link StoredFlag} the first time it evaluates each sticky matcher (see
394
- * `evaluateVariantRule`), reusing the decision for the rest of the request
395
- * so every resolve pass picks the same variant. Read it after resolution to
396
- * persist the `deco_flags` cookie and split the edge cache per cohort.
397
- * Pass an array in to opt into recording; leave undefined to disable.
398
- */
399
- flags?: StoredFlag[];
400
- /**
401
- * Client-side (SPA) navigation via TanStack `<Link>`. Disables section
402
- * deferral: deferral is a streaming-SSR optimization, but a client nav
403
- * receives the server-fn JSON in one shot, so deferral adds a round-trip +
404
- * skeleton with no benefit (and breaks loaders that need per-request app
405
- * context — see decocms/blocks#277). Set by the route loaders.
406
- */
407
- isClientNavigation?: boolean;
408
- }
409
-
410
- /**
411
- * Internal resolution context with memoization and error tracking.
412
- * Created once per resolveDecoPage / resolveValue call tree.
413
- */
414
- interface ResolveContext {
415
- routeParams?: Record<string, string>;
416
- matcherCtx: MatcherContext;
417
- memo: Map<string, unknown>;
418
- depth: number;
419
- }
420
-
421
- // ---------------------------------------------------------------------------
422
- // Configuration
423
- // ---------------------------------------------------------------------------
424
-
425
- const SKIP_RESOLVE_TYPES = new Set([
426
- "Deco",
427
- "htmx/sections/htmx.tsx",
428
- "website/sections/Analytics/Analytics.tsx",
429
- "algolia/sections/Analytics/Algolia.tsx",
430
- "shopify/loaders/proxy.ts",
431
- "vtex/loaders/proxy.ts",
432
- "website/loaders/pages.ts",
433
- "website/loaders/redirects.ts",
434
- "website/loaders/fonts/googleFonts.ts",
435
- "commerce/sections/Seo/SeoPDP.tsx",
436
- "commerce/sections/Seo/SeoPDPV2.tsx",
437
- "commerce/sections/Seo/SeoPLP.tsx",
438
- "commerce/sections/Seo/SeoPLPV2.tsx",
439
- "website/sections/Seo/Seo.tsx",
440
- "website/sections/Seo/SeoV2.tsx",
441
- "deco-sites/std/sections/SEO.tsx",
442
- ]);
443
-
444
- /** Add a __resolveType that should be skipped during resolution. */
445
- export function addSkipResolveType(resolveType: string) {
446
- SKIP_RESOLVE_TYPES.add(resolveType);
447
- }
448
-
449
- const MAX_RESOLVE_DEPTH = 20;
450
-
451
- // ---------------------------------------------------------------------------
452
- // Commerce loaders
453
- // ---------------------------------------------------------------------------
454
-
455
- const commerceLoaders: Record<string, CommerceLoader> = G.__deco.commerceLoaders;
456
-
457
- export function registerCommerceLoader(key: string, loader: CommerceLoader) {
458
- commerceLoaders[key] = loader;
459
- }
460
-
461
- export function registerCommerceLoaders(loaders: Record<string, CommerceLoader>) {
462
- Object.assign(commerceLoaders, loaders);
463
-
464
- // Auto-register loader + action schemas for the admin manifest.
465
- // Separate actions (keys containing "/actions/") from loaders.
466
- // These are stub registrations (isStub) — a real schema for the same key
467
- // (registered via registerAppSchemas from an app's schemas.gen.ts) always
468
- // wins, no matter which side registers first.
469
- const loaderConfigs: LoaderConfig[] = [];
470
- const actionConfigs: ActionConfig[] = [];
471
-
472
- for (const key of Object.keys(loaders)) {
473
- const namespace = key.startsWith("vtex/") ? "vtex" : "site";
474
- const schema = { type: "object" as const, additionalProperties: true };
475
-
476
- if (key.includes("/actions/")) {
477
- actionConfigs.push({ key, title: key, namespace, propsSchema: schema, isStub: true });
478
- } else {
479
- loaderConfigs.push({
480
- key,
481
- title: key,
482
- namespace,
483
- propsSchema: schema,
484
- tags: inferLoaderTags(key),
485
- isStub: true,
486
- });
487
- }
488
- }
489
-
490
- registerLoaderSchemas(loaderConfigs);
491
- registerActionSchemas(actionConfigs);
492
- }
493
-
494
- /** Delete a single commerce loader by key. No-op if key is absent. */
495
- export function unregisterCommerceLoader(key: string): void {
496
- delete commerceLoaders[key];
497
- }
498
-
499
- /** Clear all commerce loaders. Use with care — wipes site-registered entries too. */
500
- export function clearCommerceLoaders(): void {
501
- for (const key of Object.keys(commerceLoaders)) delete commerceLoaders[key];
502
- }
503
-
504
- /**
505
- * Look up a commerce loader tolerant of a legacy `.ts`/`.tsx` resolveType
506
- * suffix. Fresh/Deno decofiles reference app loaders with the file extension
507
- * (`shopify/loaders/ProductDetailsPage.ts`), but the split-package app
508
- * manifests register them WITHOUT it (`shopify/loaders/ProductDetailsPage`).
509
- * Exact key wins (so an explicitly-registered `.ts` alias — e.g. a site's
510
- * wrapped loader — still takes precedence); otherwise fall back to the
511
- * extension-stripped key so existing content keeps resolving after a migration.
512
- */
513
- export function getCommerceLoader(resolveType: string): CommerceLoader | undefined {
514
- return commerceLoaders[resolveType] ?? commerceLoaders[resolveType.replace(/\.tsx?$/, "")];
515
- }
516
-
517
- // ---------------------------------------------------------------------------
518
- // Custom matchers
519
- // ---------------------------------------------------------------------------
520
-
521
- const customMatchers: Record<
522
- string,
523
- (rule: Record<string, unknown>, ctx: MatcherContext) => boolean
524
- > = G.__deco.customMatchers;
525
-
526
- export function registerMatcher(
527
- key: string,
528
- fn: (rule: Record<string, unknown>, ctx: MatcherContext) => boolean,
529
- ) {
530
- customMatchers[key] = fn;
531
- }
532
-
533
- // ---------------------------------------------------------------------------
534
- // Built-in matchers — registered through the same API as custom matchers
535
- // ---------------------------------------------------------------------------
536
-
537
- if (!G.__deco._builtinMatchersRegistered) {
538
- G.__deco._builtinMatchersRegistered = true;
539
-
540
- const builtinMatchers: Record<
541
- string,
542
- (rule: Record<string, unknown>, ctx: MatcherContext) => boolean
543
- > = {
544
- "website/matchers/always.ts": () => true,
545
- "$live/matchers/MatchAlways.ts": () => true,
546
- "website/matchers/never.ts": () => false,
547
- "website/matchers/device.ts": (rule, ctx) => {
548
- const ua = (ctx.userAgent || "").toLowerCase();
549
- const isTablet = /ipad|android(?!.*mobile)|tablet/i.test(ua);
550
- const isMobile =
551
- !isTablet && /mobile|android|iphone|ipod|webos|blackberry|opera mini|iemobile/i.test(ua);
552
- const isDesktop = !isMobile && !isTablet;
553
- // If no flags are set, match everything (permissive default)
554
- if (!rule.mobile && !rule.tablet && !rule.desktop) return true;
555
- return (
556
- !!(rule.mobile && isMobile) || !!(rule.tablet && isTablet) || !!(rule.desktop && isDesktop)
557
- );
558
- },
559
- "website/matchers/random.ts": (rule) => {
560
- const traffic = typeof rule.traffic === "number" ? rule.traffic : 0.5;
561
- return Math.random() < traffic;
562
- },
563
- "website/matchers/date.ts": (rule) => {
564
- const now = Date.now();
565
- const start = typeof rule.start === "string" ? new Date(rule.start).getTime() : 0;
566
- const end = typeof rule.end === "string" ? new Date(rule.end).getTime() : Infinity;
567
- return now >= start && now <= end;
568
- },
569
- };
570
-
571
- for (const [key, fn] of Object.entries(builtinMatchers)) {
572
- // Only register if not already overridden by consumer
573
- if (!customMatchers[key]) {
574
- customMatchers[key] = fn;
575
- }
576
- }
577
- }
578
-
579
- // ---------------------------------------------------------------------------
580
- // Error handling
581
- // ---------------------------------------------------------------------------
582
-
583
- export type ResolveErrorHandler = (error: unknown, resolveType: string, context: string) => void;
584
-
585
- let onResolveError: ResolveErrorHandler = (error, resolveType, context) => {
586
- console.error(`[CMS] ${context} "${resolveType}" failed:`, error);
587
- };
588
-
589
- /** Configure a custom error handler for resolution failures. */
590
- export function setResolveErrorHandler(handler: ResolveErrorHandler) {
591
- onResolveError = handler;
592
- }
593
-
594
- // ---------------------------------------------------------------------------
595
- // Dangling reference handling
596
- // ---------------------------------------------------------------------------
597
-
598
- export type DanglingReferenceHandler = (resolveType: string) => unknown;
599
-
600
- let onDanglingReference: DanglingReferenceHandler = (resolveType) => {
601
- console.warn(`[CMS] Unhandled resolver: ${resolveType}`);
602
- return null;
603
- };
604
-
605
- /** Configure how unresolvable __resolveType references are handled. */
606
- export function setDanglingReferenceHandler(handler: DanglingReferenceHandler) {
607
- onDanglingReference = handler;
608
- }
609
-
610
- // ---------------------------------------------------------------------------
611
- // Init hook
612
- // ---------------------------------------------------------------------------
613
-
614
- export function onBeforeResolve(callback: () => void) {
615
- G.__deco.initCallback = callback;
616
- }
617
-
618
- function ensureInitialized() {
619
- if (!G.__deco.initialized && G.__deco.initCallback) {
620
- G.__deco.initCallback();
621
- G.__deco.initialized = true;
622
- }
623
- }
624
-
625
- // ---------------------------------------------------------------------------
626
- // Matcher evaluation
627
- // ---------------------------------------------------------------------------
628
-
629
- export function evaluateMatcher(
630
- rule: Record<string, unknown> | undefined,
631
- ctx: MatcherContext,
632
- ): boolean {
633
- if (!rule) return true;
634
-
635
- const resolveType = rule.__resolveType as string | undefined;
636
- if (!resolveType) return true;
637
-
638
- const blocks = loadBlocks();
639
-
640
- // x-deco-matchers-override — Deno resolveChain semantics: a saved matcher
641
- // block is keyed by its name; an inline rule by `<blockId>@<prop.path>`
642
- // (e.g. `pages-home-abc123@sections.2.variants.0.rule`). Checked before
643
- // the saved-block recursion below, which swaps __resolveType for the
644
- // underlying matcher type and merges into a fresh object, losing both the
645
- // block name and the rule's identity in the blocks map.
646
- if (hasMatchersOverride(ctx)) {
647
- const overrides = getMatchersOverride(ctx);
648
- const forced =
649
- (blocks[resolveType] ? overrides[resolveType] : undefined) ??
650
- overrides[getRuleOverrideId(blocks, rule) ?? ""];
651
- if (forced !== undefined) return forced;
652
- }
653
-
654
- if (blocks[resolveType]) {
655
- const resolvedRule = blocks[resolveType] as Record<string, unknown>;
656
- return evaluateMatcher(
657
- { ...resolvedRule, ...rule, __resolveType: resolvedRule.__resolveType as string },
658
- ctx,
659
- );
660
- }
661
-
662
- const matcher = customMatchers[resolveType];
663
- if (matcher) {
664
- try {
665
- return matcher(rule, ctx);
666
- } catch {
667
- return false;
668
- }
669
- }
670
-
671
- console.warn(`[CMS] Unknown matcher: ${resolveType}, defaulting to false`);
672
- return false;
673
- }
674
-
675
- // ---------------------------------------------------------------------------
676
- // Sticky matchers (A/B)
677
- // ---------------------------------------------------------------------------
678
-
679
- /**
680
- * Matcher types whose decision must stick per user instead of re-rolling every
681
- * request. Mirrors the `sticky = "session"` export on the corresponding
682
- * matchers in @decocms/apps (blocks re-implements matchers inline, so it
683
- * declares the set here rather than importing those exports).
684
- */
685
- const STICKY_MATCHER_TYPES = new Set(["website/matchers/random.ts"]);
686
-
687
- interface StickyMeta {
688
- /** Cohort identity — the named matcher block (e.g. "TestHero"). */
689
- name: string;
690
- /** Traffic share for the `true` branch. */
691
- traffic: number;
692
- /** `round(traffic * 100)` — the re-roll fingerprint. */
693
- pct: number;
694
- }
695
-
696
- /**
697
- * If `rule` points at a sticky matcher, return its cohort identity + traffic;
698
- * otherwise `null` (evaluate normally). A rule is either a named matcher block
699
- * (`{__resolveType: "TestHero"}`, dereferenced here to read its `traffic`) or
700
- * an inline matcher; the block name is the stable cohort key when present.
701
- */
702
- function stickyMatcherMeta(rule: Record<string, unknown> | undefined): StickyMeta | null {
703
- const rt = rule?.__resolveType as string | undefined;
704
- if (!rt) return null;
705
-
706
- const blocks = loadBlocks();
707
- const name = rt;
708
- let resolved = rule as Record<string, unknown>;
709
- if (blocks[rt]) {
710
- resolved = blocks[rt] as Record<string, unknown>;
711
- }
712
-
713
- const type = resolved.__resolveType as string | undefined;
714
- if (!type || !STICKY_MATCHER_TYPES.has(type)) return null;
715
-
716
- const traffic = typeof resolved.traffic === "number" ? resolved.traffic : 0.5;
717
- return { name, traffic, pct: trafficToPct(traffic) };
718
- }
719
-
720
- /**
721
- * Evaluate a variant's rule, applying sticky persistence for A/B matchers.
722
- *
723
- * For a sticky matcher: reuse the decision already recorded this request; else
724
- * honor the `deco_segment` cookie when its fingerprint still matches the current
725
- * `traffic`; else roll fresh. Every decision is recorded on `ctx.flags` (when
726
- * present) so the caller can persist the cookie and split the cache. Non-sticky
727
- * rules fall through to the plain matcher.
728
- */
729
- function evaluateVariantRule(
730
- rule: Record<string, unknown> | undefined,
731
- ctx: MatcherContext,
732
- ): boolean {
733
- const meta = stickyMatcherMeta(rule);
734
- // Admin preview forces variants via x-deco-matchers-override; defer to
735
- // evaluateMatcher so a forced decision wins. Sticky persistence is a
736
- // production concern (previews aren't cached), so skipping it here is fine.
737
- if (!meta || hasMatchersOverride(ctx)) return evaluateMatcher(rule, ctx);
738
-
739
- // Reuse a decision already made this request so every resolve pass (page,
740
- // shallow section-key, deferred) selects the same variant.
741
- const already = ctx.flags?.find((f) => f.name === meta.name && f.pct === meta.pct);
742
- if (already) return already.value;
743
-
744
- const stored = parseSegmentCookie(ctx.cookies?.[SEGMENT_COOKIE]).find(
745
- (f) => f.name === meta.name,
746
- );
747
- // pct === -1 marks a classic-deco segment without a fingerprint — honor it
748
- // (stay sticky) instead of re-rolling. A stale fingerprint re-rolls.
749
- const useStored = stored && (stored.pct === -1 || stored.pct === meta.pct);
750
- const value = useStored ? stored.value : Math.random() < meta.traffic;
751
-
752
- ctx.flags?.push({ name: meta.name, value, pct: meta.pct });
753
- return value;
754
- }
755
-
756
- // ---------------------------------------------------------------------------
757
- // Select (partial field picking)
758
- // ---------------------------------------------------------------------------
759
-
760
- function applySelect(value: unknown, select?: string[]): unknown {
761
- if (!select || !select.length || !value || typeof value !== "object") return value;
762
- if (Array.isArray(value)) return value.map((item) => applySelect(item, select));
763
-
764
- const result: Record<string, unknown> = {};
765
- for (const key of select) {
766
- if (key in (value as Record<string, unknown>)) {
767
- result[key] = (value as Record<string, unknown>)[key];
768
- }
769
- }
770
- return result;
771
- }
772
-
773
- // ---------------------------------------------------------------------------
774
- // Core resolution
775
- // ---------------------------------------------------------------------------
776
-
777
- async function resolveProps(
778
- obj: Record<string, unknown>,
779
- rctx: ResolveContext,
780
- ): Promise<Record<string, unknown>> {
781
- const entries = Object.entries(obj);
782
- const resolvedEntries = await Promise.all(
783
- entries.map(async ([k, v]) => [k, await internalResolve(v, rctx)] as const),
784
- );
785
- return Object.fromEntries(resolvedEntries);
786
- }
787
-
788
- async function internalResolve(value: unknown, rctx: ResolveContext): Promise<unknown> {
789
- if (!value || typeof value !== "object") return value;
790
- if (Array.isArray(value)) {
791
- const resolved = await Promise.all(value.map((item) => internalResolve(item, rctx)));
792
- // Drop items that resolved to "not present" (`undefined`) — e.g. a hidden
793
- // array item (a multivariate wrapped in a `never` matcher, see the admin's
794
- // hideArrayItem) where no variant matched. A `never`-gated item must vanish
795
- // from the array, NOT become a `null` hole the section then renders as an
796
- // empty card. Legitimate `null` values (a matched variant that resolved to
797
- // null, a failed loader) are kept — only the no-match sentinel is filtered.
798
- return resolved.filter((item) => item !== undefined);
799
- }
800
-
801
- const obj = value as Record<string, unknown>;
802
-
803
- if (!obj.__resolveType) {
804
- return resolveProps(obj, rctx);
805
- }
806
-
807
- const resolveType = obj.__resolveType as string;
808
-
809
- if (SKIP_RESOLVE_TYPES.has(resolveType)) return null;
810
-
811
- if (rctx.depth > MAX_RESOLVE_DEPTH) {
812
- console.error(`[CMS] Max resolution depth (${MAX_RESOLVE_DEPTH}) exceeded at: ${resolveType}`);
813
- return null;
814
- }
815
-
816
- const childCtx: ResolveContext = { ...rctx, depth: rctx.depth + 1 };
817
-
818
- // "resolved" short-circuit
819
- if (resolveType === "resolved") return obj.data ?? null;
820
-
821
- // Lazy section wrapper — unwrap single inner section
822
- if (resolveType === WELL_KNOWN_TYPES.LAZY) {
823
- return obj.section ? internalResolve(obj.section, childCtx) : null;
824
- }
825
-
826
- // Deferred section wrapper (legacy Fresh/HTMX) — unwrap inner sections array
827
- if (resolveType === WELL_KNOWN_TYPES.DEFERRED) {
828
- return obj.sections ? internalResolve(obj.sections, childCtx) : null;
829
- }
830
-
831
- // Request param extraction
832
- if (resolveType === WELL_KNOWN_TYPES.REQUEST_TO_PARAM) {
833
- const paramName = (obj as any).param as string;
834
- return rctx.routeParams?.[paramName] ?? null;
835
- }
836
-
837
- // Commerce extension wrappers — unwrap to inner data
838
- if (
839
- resolveType === WELL_KNOWN_TYPES.COMMERCE_EXT_DETAILS ||
840
- resolveType === WELL_KNOWN_TYPES.COMMERCE_EXT_LISTING
841
- ) {
842
- return obj.data ? internalResolve(obj.data, childCtx) : null;
843
- }
844
-
845
- // Multivariate flags
846
- if (
847
- resolveType === WELL_KNOWN_TYPES.MULTIVARIATE ||
848
- resolveType === WELL_KNOWN_TYPES.MULTIVARIATE_SECTION
849
- ) {
850
- const variants = obj.variants as Array<{ value: unknown; rule?: unknown }> | undefined;
851
- // No variant matched (incl. a single `never`-gated variant, i.e. a hidden
852
- // item) → resolve to `undefined`, the "not present" sentinel the array
853
- // branch filters out, rather than `null`, which would survive as a hole.
854
- if (!variants || variants.length === 0) return undefined;
855
-
856
- for (const variant of variants) {
857
- const rule = variant.rule as Record<string, unknown> | undefined;
858
- if (evaluateVariantRule(rule, rctx.matcherCtx)) {
859
- return internalResolve(variant.value, childCtx);
860
- }
861
- }
862
- return undefined;
863
- }
864
-
865
- // Commerce loaders
866
- const commerceLoader = getCommerceLoader(resolveType);
867
- if (commerceLoader) {
868
- const { __resolveType: _, ...loaderProps } = obj;
869
- const resolvedProps = await resolveProps(loaderProps, childCtx);
870
-
871
- if (rctx.matcherCtx.path) {
872
- resolvedProps.__pagePath = rctx.matcherCtx.path;
873
- }
874
- if (rctx.matcherCtx.url) {
875
- resolvedProps.__pageUrl = rctx.matcherCtx.url;
876
- // Auto-inject URL search params as top-level props so loaders that
877
- // expect `props.skuId` / `props.q` / `props.page` (the apps-start
878
- // canonical shape) get them populated on direct entry (Google
879
- // Shopping deep links, paid ads, email campaigns). Existing values
880
- // from the CMS block win — URL params are a fallback, not an
881
- // override.
882
- //
883
- // Safe re: cache fragmentation: commerce loaders run through this
884
- // path without a framework-level cache (the section/page cache
885
- // layer hashes section.props BEFORE this enrichment in
886
- // sectionLoaders.ts), so adding query params here does not
887
- // fragment any cache key.
888
- if (URL.canParse(rctx.matcherCtx.url)) {
889
- const url = new URL(rctx.matcherCtx.url);
890
- for (const [k, v] of url.searchParams.entries()) {
891
- if (resolvedProps[k] !== undefined) continue;
892
- // `page` is skipped on purpose (#391): loaders that read `page`
893
- // from `__pageUrl` themselves (e.g. VTEX's PLP loader) apply their
894
- // own 1-indexed-URL -> 0-indexed-internal conversion. Auto-injecting
895
- // the raw 1-indexed URL string here as `props.page` bypasses that
896
- // conversion and produces an off-by-one, on top of arriving as an
897
- // un-coerced string. Numeric conventional names get coerced so a
898
- // loader declaring `count?: number` doesn't receive a raw string.
899
- if (k === "page") continue;
900
- if ((k === "count" || k === "pageOffset") && Number.isFinite(Number(v))) {
901
- resolvedProps[k] = Number(v);
902
- continue;
903
- }
904
- resolvedProps[k] = v;
905
- }
906
- } else {
907
- // Loud warning instead of silent swallow: matcherCtx.url should
908
- // always be a fully-qualified URL (set from `getRequestUrl()` in
909
- // cmsRoute.ts). If we see a malformed value here, something
910
- // upstream is wrong — surface it so the caller can fix it.
911
- console.warn(
912
- `[CMS] malformed matcherCtx.url for "${resolveType}"; ` +
913
- `skipping query-param injection: ${rctx.matcherCtx.url}`,
914
- );
915
- }
916
- }
917
-
918
- try {
919
- return await commerceLoader(resolvedProps);
920
- } catch (error) {
921
- onResolveError(error, resolveType, "Commerce loader");
922
- // Commerce loaders (VTEX product/PLP/PDP data) are the primary source of
923
- // page-body data — this is exactly the layer that fails during a VTEX
924
- // outage. Flag the page degraded so the edge won't cache the empty
925
- // result as a healthy 200 (see X-Deco-Degraded in cmsRoute/workerEntry).
926
- markSectionDegraded(resolveType);
927
- return null;
928
- }
929
- }
930
-
931
- // Preview handler — admin sends { __resolveType: "preview", block: "BlockName", ...props }
932
- // to preview a named block. Redirect resolution to the named block.
933
- if (resolveType === "preview") {
934
- const blockName = obj.block as string | undefined;
935
- if (!blockName) return null;
936
- const { __resolveType: _, block: _b, ...overrideProps } = obj;
937
- return internalResolve({ __resolveType: blockName, ...overrideProps }, childCtx);
938
- }
939
-
940
- // Named block reference (memoized)
941
- const blocks = loadBlocks();
942
- if (blocks[resolveType]) {
943
- const memoKey = JSON.stringify(obj);
944
- if (rctx.memo.has(memoKey)) {
945
- return rctx.memo.get(memoKey);
946
- }
947
-
948
- const referencedBlock = blocks[resolveType] as Record<string, unknown>;
949
- const { __resolveType: _rt, ...restOverrides } = obj;
950
- const resultPromise = internalResolve({ ...referencedBlock, ...restOverrides }, childCtx);
951
- rctx.memo.set(memoKey, resultPromise);
952
-
953
- const result = await resultPromise;
954
- rctx.memo.set(memoKey, result);
955
- return result;
956
- }
957
-
958
- // Dangling reference — unresolvable __resolveType
959
- if (resolveType.includes("/loaders/") || resolveType.includes("/actions/")) {
960
- return onDanglingReference(resolveType);
961
- }
962
-
963
- // Unknown type — resolve props but preserve __resolveType (it's a section)
964
- const { __resolveType: _, ...rest } = obj;
965
-
966
- // onBeforeResolveProps: let sections transform raw props before resolution.
967
- // This runs with unresolved props (containing __resolveType refs) so sections
968
- // can extract metadata that would be lost after resolution (e.g., collection IDs).
969
- const propsToResolve = await applyOnBeforeResolveProps(resolveType, rest);
970
-
971
- const resolvedRest = await resolveProps(propsToResolve, childCtx);
972
- return { __resolveType: resolveType, ...resolvedRest };
973
- }
974
-
975
- // ---------------------------------------------------------------------------
976
- // Nested section normalization
977
- // ---------------------------------------------------------------------------
978
-
979
- /**
980
- * Recursively walks resolved props and converts nested sections
981
- * from `{ __resolveType: "site/sections/...", ...props }` to
982
- * `{ component: "site/sections/...", props: {...} }`.
983
- *
984
- * This preserves the same `{ Component, props }` shape used by deco-cx/deco (Fresh)
985
- * so that section code can be ported without API changes. In TanStack, `Component`
986
- * is the registry key string (not a function ref), and the renderer does the lookup.
987
- */
988
- function normalizeNestedSections(value: unknown): unknown {
989
- if (!value || typeof value !== "object") return value;
990
-
991
- if (Array.isArray(value)) {
992
- return value.map(normalizeNestedSections);
993
- }
994
-
995
- const obj = value as Record<string, unknown>;
996
- const rt = obj.__resolveType as string | undefined;
997
-
998
- if (rt && getSection(rt)) {
999
- const { __resolveType: _, ...rest } = obj;
1000
- const normalizedProps: Record<string, unknown> = {};
1001
- for (const [k, v] of Object.entries(rest)) {
1002
- normalizedProps[k] = normalizeNestedSections(v);
1003
- }
1004
- return { Component: rt, props: normalizedProps };
1005
- }
1006
-
1007
- const result: Record<string, unknown> = {};
1008
- for (const [k, v] of Object.entries(obj)) {
1009
- result[k] = normalizeNestedSections(v);
1010
- }
1011
- return result;
1012
- }
1013
-
1014
- // ---------------------------------------------------------------------------
1015
- // Public API
1016
- // ---------------------------------------------------------------------------
1017
-
1018
- /**
1019
- * Resolve a value by recursively processing __resolveType references.
1020
- * Supports memoization, commerce loaders, matchers, and flags.
1021
- */
1022
- export async function resolveValue(
1023
- value: unknown,
1024
- routeParams?: Record<string, string>,
1025
- matcherCtx?: MatcherContext,
1026
- options?: { select?: string[] },
1027
- ): Promise<unknown> {
1028
- const rctx: ResolveContext = {
1029
- routeParams,
1030
- matcherCtx: matcherCtx ?? {},
1031
- memo: new Map(),
1032
- depth: 0,
1033
- };
1034
- const result = await internalResolve(value, rctx);
1035
- return options?.select ? applySelect(result, options.select) : result;
1036
- }
1037
-
1038
- // ---------------------------------------------------------------------------
1039
- // Layout section CMS-resolve cache
1040
- // Caches the fully-resolved CMS output for layout sections so that
1041
- // commerce loaders (intelligent-search, cross-selling, etc.) inside
1042
- // Header/Footer blocks aren't re-executed on every page navigation.
1043
- // ---------------------------------------------------------------------------
1044
-
1045
- const RESOLVE_CACHE_TTL = 5 * 60_000;
1046
-
1047
- interface ResolvedSectionsCache {
1048
- sections: ResolvedSection[];
1049
- expiresAt: number;
1050
- }
1051
-
1052
- const resolvedLayoutCache = new Map<string, ResolvedSectionsCache>();
1053
- const resolvedLayoutInflight = new Map<string, Promise<ResolvedSection[]>>();
1054
-
1055
- function getCachedResolvedLayout(blockKey: string): ResolvedSection[] | null {
1056
- const entry = resolvedLayoutCache.get(blockKey);
1057
- if (!entry) return null;
1058
- if (Date.now() > entry.expiresAt) {
1059
- resolvedLayoutCache.delete(blockKey);
1060
- return null;
1061
- }
1062
- return entry.sections;
1063
- }
1064
-
1065
- function setCachedResolvedLayout(blockKey: string, sections: ResolvedSection[]): void {
1066
- resolvedLayoutCache.set(blockKey, {
1067
- sections,
1068
- expiresAt: Date.now() + RESOLVE_CACHE_TTL,
1069
- });
1070
- }
1071
-
1072
- /**
1073
- * Resolves a raw section block to ResolvedSection[].
1074
- * Used for both layout and non-layout sections.
1075
- */
1076
- async function resolveRawSection(
1077
- section: unknown,
1078
- rctx: ResolveContext,
1079
- ): Promise<ResolvedSection[]> {
1080
- const resolved = await internalResolve(section, rctx);
1081
- if (!resolved || typeof resolved !== "object") return [];
1082
-
1083
- const items = Array.isArray(resolved) ? resolved : [resolved];
1084
- const results: ResolvedSection[] = [];
1085
-
1086
- for (const item of items) {
1087
- if (!item || typeof item !== "object") continue;
1088
- const obj = item as Record<string, unknown>;
1089
- if (!obj.__resolveType) continue;
1090
-
1091
- const resolveType = obj.__resolveType as string;
1092
- const sectionLoader = getSection(resolveType);
1093
- if (!sectionLoader) {
1094
- console.warn(`[CMS] No component registered for: ${resolveType}`);
1095
- continue;
1096
- }
1097
-
1098
- const { __resolveType: _, ...rawProps } = obj;
1099
- const props = normalizeNestedSections(rawProps) as Record<string, unknown>;
1100
- results.push({
1101
- component: resolveType,
1102
- props,
1103
- key: resolveType,
1104
- });
1105
- }
1106
-
1107
- return results;
1108
- }
1109
-
1110
- // ---------------------------------------------------------------------------
1111
- // Page-level SEO block resolution
1112
- // ---------------------------------------------------------------------------
1113
-
1114
- /**
1115
- * Resolve the page-level `seo` field from the CMS page JSON.
1116
- *
1117
- * The CMS stores SEO config in `page.seo` as a separate field from
1118
- * `page.sections`. This field is typically a SeoV2.tsx block (homepage)
1119
- * or a site SEO section like SEOPDP.tsx wrapped in Lazy (PDP).
1120
- *
1121
- * This function always resolves eagerly — SEO metadata must never be
1122
- * deferred because search engine crawlers need it in the initial HTML.
1123
- * Lazy/Deferred wrappers are unwrapped, block references are followed,
1124
- * and commerce loader refs (e.g. PDP jsonLD) are resolved.
1125
- *
1126
- * Returns a ResolvedSection with the final component key and resolved props,
1127
- * or null if the seo field is absent/unresolvable.
1128
- */
1129
- export async function resolvePageSeoBlock(
1130
- seoBlock: Record<string, unknown> | undefined,
1131
- rctx: ResolveContext,
1132
- ): Promise<ResolvedSection | null> {
1133
- if (!seoBlock || typeof seoBlock !== "object") return null;
1134
-
1135
- // Bot-aware SEO: crawlers get the SEO block fully resolved (e.g. a
1136
- // ProductListingPage for JSON-LD ItemList) — that content exists for indexing;
1137
- // humans get only the lightweight metadata, with SEO props backed by a commerce
1138
- // loader skipped (see `stripCommerceLoaderProps`) so SSR doesn't block on the
1139
- // heavy upstream call and the bulky payload never reaches the human HTML.
1140
- //
1141
- // The skip is driven per-section by the editor's `ignoreStructuredData` toggle
1142
- // (the primary, client-facing lever — see `sectionIgnoresStructuredData`), OR
1143
- // site-wide by the legacy `setAsyncRenderingConfig({ botAwareSeo: true })`
1144
- // shortcut. When neither is set, resolve fully for EVERYONE (the previous
1145
- // default) so sites without a lightweight title fallback are not regressed to
1146
- // a generic `<title>`. The final decision is made at the terminal section
1147
- // below, where the section's raw props are known.
1148
- const isEagerReq = isEagerRequest(rctx.matcherCtx);
1149
- const globalBotAware = getAsyncConfig()?.botAwareSeo ?? false;
1150
-
1151
- const blocks = loadBlocks();
1152
- let current = seoBlock;
1153
-
1154
- for (let depth = 0; depth < 10; depth++) {
1155
- const rt = current.__resolveType as string | undefined;
1156
- if (!rt) return null;
1157
-
1158
- // Lazy wrapper — always unwrap for SEO (never defer)
1159
- if (rt === "website/sections/Rendering/Lazy.tsx") {
1160
- const inner = current.section;
1161
- if (!inner || typeof inner !== "object") return null;
1162
- current = inner as Record<string, unknown>;
1163
- continue;
1164
- }
1165
-
1166
- // Deferred wrapper — unwrap
1167
- if (rt === "website/sections/Rendering/Deferred.tsx") {
1168
- const inner = current.sections;
1169
- if (!inner || typeof inner !== "object") return null;
1170
- if (Array.isArray(inner) && inner.length === 1 && inner[0] && typeof inner[0] === "object") {
1171
- current = inner[0] as Record<string, unknown>;
1172
- continue;
1173
- }
1174
- return null;
1175
- }
1176
-
1177
- // Multivariate flag — evaluate matcher and follow matched variant
1178
- if (rt === "website/flags/multivariate.ts" || rt === "website/flags/multivariate/section.ts") {
1179
- const variants = current.variants as Array<{ value: unknown; rule?: unknown }> | undefined;
1180
- if (!variants?.length) return null;
1181
- let matched: unknown = null;
1182
- for (const variant of variants) {
1183
- const rule = variant.rule as Record<string, unknown> | undefined;
1184
- if (evaluateVariantRule(rule, rctx.matcherCtx)) {
1185
- matched = variant.value;
1186
- break;
1187
- }
1188
- }
1189
- if (!matched || typeof matched !== "object") return null;
1190
- current = matched as Record<string, unknown>;
1191
- continue;
1192
- }
1193
-
1194
- // Named block reference — follow the chain
1195
- const block = blocks[rt] as Record<string, unknown> | undefined;
1196
- if (block) {
1197
- const { __resolveType: _, ...overrides } = current;
1198
- current = { ...block, ...overrides };
1199
- continue;
1200
- }
1201
-
1202
- // Terminal section (site section or framework SEO type).
1203
- // Resolve all nested prop __resolveType refs (commerce loaders, etc.).
1204
- const { __resolveType: _, ...rawProps } = current;
1205
- // For humans, drop SEO props whose value resolves to a commerce loader
1206
- // (e.g. `jsonLD: { __resolveType: "PLP Loader" }`). This avoids the heavy
1207
- // SSR fetch and keeps the product payload out of the human HTML. Bots keep
1208
- // the full props so JSON-LD/rich metadata is still emitted for indexing.
1209
- // Skip only when the editor turned on `ignoreStructuredData` for this
1210
- // section, or the site-wide `botAwareSeo` shortcut is enabled.
1211
- const skipCommerceForHuman =
1212
- !isEagerReq && (globalBotAware || sectionIgnoresStructuredData(rawProps));
1213
- const propsToResolve = skipCommerceForHuman ? stripCommerceLoaderProps(rawProps) : rawProps;
1214
- try {
1215
- const resolvedProps = await resolveProps(propsToResolve, rctx);
1216
- return {
1217
- component: rt,
1218
- props: resolvedProps as Record<string, unknown>,
1219
- key: `seo:${rt}`,
1220
- };
1221
- } catch (e) {
1222
- onResolveError(e, rt, "Page SEO resolution");
1223
- return null;
1224
- }
1225
- }
1226
-
1227
- return null;
1228
- }
1229
-
1230
- /**
1231
- * Does resolving `value` invoke a commerce loader (a heavy upstream data
1232
- * fetch)? Walks named block references, Lazy/Deferred wrappers, commerce
1233
- * extension wrappers, and multivariate flags to find a terminal
1234
- * `__resolveType` registered in `commerceLoaders`.
1235
- *
1236
- * Used to keep commerce-backed SEO props (product listings/details for
1237
- * JSON-LD) out of the human SSR path while preserving them for bots.
1238
- */
1239
- function resolvesToCommerceLoader(value: unknown, depth = 0): boolean {
1240
- if (depth > 10 || !value || typeof value !== "object" || Array.isArray(value)) return false;
1241
- const obj = value as Record<string, unknown>;
1242
- const rt = obj.__resolveType as string | undefined;
1243
- if (!rt) return false;
1244
-
1245
- if (getCommerceLoader(rt)) return true;
1246
-
1247
- if (rt === WELL_KNOWN_TYPES.LAZY) return resolvesToCommerceLoader(obj.section, depth + 1);
1248
- if (rt === WELL_KNOWN_TYPES.DEFERRED) {
1249
- const inner = obj.sections;
1250
- const one = Array.isArray(inner) ? inner[0] : inner;
1251
- return resolvesToCommerceLoader(one, depth + 1);
1252
- }
1253
- if (
1254
- rt === WELL_KNOWN_TYPES.COMMERCE_EXT_DETAILS ||
1255
- rt === WELL_KNOWN_TYPES.COMMERCE_EXT_LISTING
1256
- ) {
1257
- // Extension wrappers carry their inner loader in `data`; they're commerce
1258
- // by definition, but guard the recursion for clarity.
1259
- return obj.data ? resolvesToCommerceLoader(obj.data, depth + 1) : true;
1260
- }
1261
- if (rt === WELL_KNOWN_TYPES.MULTIVARIATE || rt === WELL_KNOWN_TYPES.MULTIVARIATE_SECTION) {
1262
- const variants = obj.variants as Array<{ value?: unknown }> | undefined;
1263
- return Array.isArray(variants)
1264
- ? variants.some((v) => resolvesToCommerceLoader(v?.value, depth + 1))
1265
- : false;
1266
- }
1267
-
1268
- // Named block reference — follow one level of the chain.
1269
- const block = loadBlocks()[rt] as Record<string, unknown> | undefined;
1270
- if (block) return resolvesToCommerceLoader(block, depth + 1);
1271
-
1272
- return false;
1273
- }
1274
-
1275
- /**
1276
- * True when a commerce SEO section's props carry the editor's "Ignore Structured
1277
- * Data" toggle. This is the primary, client-facing lever for bot-aware SEO: with
1278
- * it on, humans receive no JSON-LD (and, on the page's SEO block, skip the heavy
1279
- * commerce fetch) while crawlers still get the full structured data.
1280
- *
1281
- * Two shapes, mirroring the Studio schema: top-level `ignoreStructuredData` on
1282
- * the PDP section, and nested under `configJsonLD` on the PLP section. Shared by
1283
- * the fetch-skip path (`resolvePageSeoBlock`, pre-resolution) and the
1284
- * output-strip path (`deriveCommerceSeoFromJsonLD`, post-resolution) so the two
1285
- * decisions can never read the toggle differently.
1286
- */
1287
- function sectionIgnoresStructuredData(props: Record<string, unknown>): boolean {
1288
- if (props.ignoreStructuredData === true) return true;
1289
- const configJsonLD = props.configJsonLD as { ignoreStructuredData?: boolean } | undefined;
1290
- return configJsonLD?.ignoreStructuredData === true;
1291
- }
1292
-
1293
- /**
1294
- * Return a copy of `rawProps` with every top-level field that resolves to a
1295
- * commerce loader removed. Applied to page SEO props for human (non-bot)
1296
- * requests so the heavy commerce fetch is skipped and its payload is never
1297
- * serialized into the HTML. Lightweight literal props (title, description,
1298
- * canonical, …) are preserved.
1299
- */
1300
- function stripCommerceLoaderProps(rawProps: Record<string, unknown>): Record<string, unknown> {
1301
- const out: Record<string, unknown> = {};
1302
- for (const [k, v] of Object.entries(rawProps)) {
1303
- if (resolvesToCommerceLoader(v)) continue;
1304
- out[k] = v;
1305
- }
1306
- return out;
1307
- }
1308
-
1309
- /**
1310
- * Check if a raw CMS section block will produce a layout section.
1311
- * Walks the block reference chain (up to 5 levels) to find the final
1312
- * section component key. Returns the top-level block name for caching.
1313
- *
1314
- * Example: {"__resolveType": "Header - 01"} -> block has
1315
- * __resolveType "site/sections/Header/Header.tsx" -> that's a layout section
1316
- * -> returns "Header - 01" as the cache key.
1317
- */
1318
- function isRawSectionLayout(section: unknown): string | null {
1319
- if (!section || typeof section !== "object") return null;
1320
- const obj = section as Record<string, unknown>;
1321
- const topLevelRt = obj.__resolveType as string | undefined;
1322
- if (!topLevelRt) return null;
1323
-
1324
- if (isLayoutSection(topLevelRt)) return topLevelRt;
1325
-
1326
- const blocks = loadBlocks();
1327
- let currentRt: string | undefined = topLevelRt;
1328
- for (let i = 0; i < 5; i++) {
1329
- const block = blocks[currentRt] as Record<string, unknown> | undefined;
1330
- if (!block) break;
1331
- currentRt = block.__resolveType as string | undefined;
1332
- if (!currentRt) break;
1333
- if (isLayoutSection(currentRt)) return topLevelRt;
1334
- }
1335
-
1336
- return null;
1337
- }
1338
-
1339
- /**
1340
- * Resolve the final section component key by walking block references,
1341
- * unwrapping Lazy/Deferred wrappers, and evaluating multivariate flags.
1342
- * Returns null if not determinable.
1343
- */
1344
- function resolveFinalSectionKey(section: unknown, matcherCtx?: MatcherContext): string | null {
1345
- if (!section || typeof section !== "object") return null;
1346
-
1347
- const blocks = loadBlocks();
1348
- let current = section as Record<string, unknown>;
1349
-
1350
- for (let depth = 0; depth < 10; depth++) {
1351
- const rt = current.__resolveType as string | undefined;
1352
- if (!rt) return null;
1353
-
1354
- // Lazy wrapper — unwrap single inner section
1355
- if (rt === WELL_KNOWN_TYPES.LAZY) {
1356
- const inner = current.section;
1357
- if (!inner || typeof inner !== "object") return null;
1358
- current = inner as Record<string, unknown>;
1359
- continue;
1360
- }
1361
-
1362
- // Deferred wrapper (legacy) — unwrap first inner section if deterministic
1363
- if (rt === "website/sections/Rendering/Deferred.tsx") {
1364
- const inner = current.sections;
1365
- if (!inner || typeof inner !== "object") return null;
1366
- if (Array.isArray(inner)) {
1367
- if (inner.length === 1 && inner[0] && typeof inner[0] === "object") {
1368
- current = inner[0] as Record<string, unknown>;
1369
- continue;
1370
- }
1371
- return null;
1372
- }
1373
- // sections is an object (e.g. a flag) — follow it
1374
- current = inner as Record<string, unknown>;
1375
- continue;
1376
- }
1377
-
1378
- if (rt === WELL_KNOWN_TYPES.MULTIVARIATE || rt === WELL_KNOWN_TYPES.MULTIVARIATE_SECTION) {
1379
- const variants = current.variants as Array<{ value: unknown; rule?: unknown }> | undefined;
1380
- if (!variants?.length) return null;
1381
-
1382
- let matched: unknown = null;
1383
- for (const variant of variants) {
1384
- const rule = variant.rule as Record<string, unknown> | undefined;
1385
- if (evaluateVariantRule(rule, matcherCtx ?? {})) {
1386
- matched = variant.value;
1387
- break;
1388
- }
1389
- }
1390
- if (!matched || typeof matched !== "object") return null;
1391
- current = matched as Record<string, unknown>;
1392
- continue;
1393
- }
1394
-
1395
- if (getSection(rt)) return rt;
1396
-
1397
- const block = blocks[rt] as Record<string, unknown> | undefined;
1398
- if (block) {
1399
- const { __resolveType: _, ...overrides } = current;
1400
- current = { ...block, ...overrides };
1401
- continue;
1402
- }
1403
-
1404
- return rt;
1405
- }
1406
-
1407
- return null;
1408
- }
1409
-
1410
- /**
1411
- * Walk the full wrapper chain (block refs, multivariate flags, Lazy, Deferred)
1412
- * and return true if a deferral wrapper (Lazy.tsx or Deferred.tsx) is found
1413
- * at any level. This is used by shouldDeferSection to determine if the CMS
1414
- * editor intended this section to be deferred.
1415
- */
1416
- function isCmsDeferralWrapped(section: unknown, matcherCtx?: MatcherContext): boolean {
1417
- if (!section || typeof section !== "object") return false;
1418
-
1419
- const blocks = loadBlocks();
1420
- let current = section as Record<string, unknown>;
1421
-
1422
- for (let depth = 0; depth < 10; depth++) {
1423
- const rt = current.__resolveType as string | undefined;
1424
- if (!rt) return false;
1425
-
1426
- if (rt === WELL_KNOWN_TYPES.LAZY || rt === WELL_KNOWN_TYPES.DEFERRED) {
1427
- return true;
1428
- }
1429
-
1430
- // Walk through multivariate flags to check the matched variant
1431
- if (rt === WELL_KNOWN_TYPES.MULTIVARIATE || rt === WELL_KNOWN_TYPES.MULTIVARIATE_SECTION) {
1432
- const variants = current.variants as Array<{ value: unknown; rule?: unknown }> | undefined;
1433
- if (!variants?.length) return false;
1434
-
1435
- let matched: unknown = null;
1436
- for (const variant of variants) {
1437
- const rule = variant.rule as Record<string, unknown> | undefined;
1438
- if (evaluateVariantRule(rule, matcherCtx ?? {})) {
1439
- matched = variant.value;
1440
- break;
1441
- }
1442
- }
1443
- if (!matched || typeof matched !== "object") return false;
1444
- current = matched as Record<string, unknown>;
1445
- continue;
1446
- }
1447
-
1448
- // Named block reference — follow the chain
1449
- const block = blocks[rt] as Record<string, unknown> | undefined;
1450
- if (block) {
1451
- const { __resolveType: _, ...overrides } = current;
1452
- current = { ...block, ...overrides, __resolveType: block.__resolveType as string };
1453
- continue;
1454
- }
1455
-
1456
- return false;
1457
- }
1458
-
1459
- return false;
1460
- }
1461
-
1462
- /**
1463
- * Decide whether a section is deferred (rendered client-side on scroll) or
1464
- * rendered eagerly (SSR).
1465
- *
1466
- * The admin is the source of truth: a section the editor marked async ⚡
1467
- * (wrapped in CMS `Lazy.tsx`/`Deferred.tsx`) is ALWAYS deferred, and a section
1468
- * the editor left unmarked is ALWAYS eager — independent of its position on the
1469
- * page and of any `export const eager`/`neverDefer`/`alwaysEager` flag in the
1470
- * section code. The admin ⚡ check runs first and overrides every code flag.
1471
- *
1472
- * The position threshold and code-level eager flags are an explicit per-site
1473
- * opt-in: they only take effect when a site sets a finite `foldThreshold`
1474
- * (default {@link DEFAULT_FOLD_THRESHOLD} = `Infinity`, i.e. disabled), and even
1475
- * then they can only force a NON-⚡ section eager — they never override the
1476
- * editor's ⚡ choice.
1477
- *
1478
- * Exported for unit testing.
1479
- */
1480
- export function shouldDeferSection(
1481
- section: unknown,
1482
- flatIndex: number,
1483
- cfg: AsyncRenderingConfig,
1484
- isBotReq: boolean,
1485
- matcherCtx?: MatcherContext,
1486
- ): boolean {
1487
- // Crawlers always get the full page server-rendered — deferral would hide
1488
- // content from indexing. This is an SEO guarantee, not a code override of
1489
- // editorial intent: it makes ⚡ content MORE visible to bots.
1490
- if (isBotReq) return false;
1491
-
1492
- if (!section || typeof section !== "object") return false;
1493
- const obj = section as Record<string, unknown>;
1494
- const rt = obj.__resolveType as string | undefined;
1495
- if (!rt) return false;
1496
-
1497
- const finalKey = resolveFinalSectionKey(section, matcherCtx);
1498
- if (!finalKey) return false;
1499
-
1500
- // ── ADMIN IS THE SOURCE OF TRUTH ──────────────────────────────────────────
1501
- // If the editor marked the section ⚡ (wrapped in CMS Lazy/Deferred at any
1502
- // nesting level, including multivariate flags), it is deferred —
1503
- // unconditionally, overriding every code-level flag below. This is the only
1504
- // thing that drives deferral in the default configuration.
1505
- if (cfg.respectCmsLazy && isCmsDeferralWrapped(section, matcherCtx)) return true;
1506
-
1507
- // ── Everything below is OPT-IN ONLY ───────────────────────────────────────
1508
- // These checks never override the admin (handled above). They are inert with
1509
- // the default `foldThreshold = Infinity` and only matter when a site
1510
- // explicitly opts into a finite threshold — where they protect specific
1511
- // NON-⚡ sections from position-based deferral.
1512
-
1513
- // Layout sections (Header, Footer, Theme) are shared across pages and their
1514
- // resolved output is cached; deferring them would flash a skeleton on every
1515
- // navigation.
1516
- if (isLayoutSection(finalKey)) return false;
1517
-
1518
- // `export const neverDefer = true` — keep eager regardless of threshold.
1519
- if (isNeverDeferSection(finalKey)) return false;
1520
-
1521
- // `export const eager = true` / alwaysEager — keep eager within the fold.
1522
- if (flatIndex < cfg.foldThreshold) {
1523
- if (isEagerSection(finalKey)) return false;
1524
- if (cfg.alwaysEager.has(finalKey)) return false;
1525
- }
1526
-
1527
- // Position-based fallback — disabled by default (foldThreshold = Infinity).
1528
- if (flatIndex >= cfg.foldThreshold) return true;
1529
-
1530
- return false;
1531
- }
1532
-
1533
- /**
1534
- * Follow the block reference chain to find the final section component
1535
- * and collect the CMS props WITHOUT running commerce loaders.
1536
- * Resolves named block references, Lazy/Deferred wrappers, and multivariate flags.
1537
- *
1538
- * For Deferred.tsx with a single inner section, the inner section is returned.
1539
- * For Deferred.tsx with multiple inner sections, returns null (falls back to eager).
1540
- */
1541
- function resolveSectionShallow(
1542
- section: unknown,
1543
- matcherCtx?: MatcherContext,
1544
- ): DeferredSection | null {
1545
- if (!section || typeof section !== "object") return null;
1546
-
1547
- const blocks = loadBlocks();
1548
- let current = section as Record<string, unknown>;
1549
- const MAX_DEPTH = 10;
1550
-
1551
- for (let depth = 0; depth < MAX_DEPTH; depth++) {
1552
- const rt = current.__resolveType as string | undefined;
1553
- if (!rt) return null;
1554
-
1555
- if (SKIP_RESOLVE_TYPES.has(rt)) return null;
1556
-
1557
- // Lazy wrapper — unwrap to the inner section
1558
- if (rt === WELL_KNOWN_TYPES.LAZY) {
1559
- const inner = current.section;
1560
- if (!inner || typeof inner !== "object") return null;
1561
- current = inner as Record<string, unknown>;
1562
- continue;
1563
- }
1564
-
1565
- // Deferred wrapper (legacy) — unwrap if it contains a single section
1566
- if (rt === "website/sections/Rendering/Deferred.tsx") {
1567
- const inner = current.sections;
1568
- if (!inner || typeof inner !== "object") return null;
1569
- if (Array.isArray(inner)) {
1570
- if (inner.length === 1 && inner[0] && typeof inner[0] === "object") {
1571
- current = inner[0] as Record<string, unknown>;
1572
- continue;
1573
- }
1574
- // Multiple inner sections can't be represented as a single DeferredSection
1575
- return null;
1576
- }
1577
- // sections is an object (e.g. a flag) — follow it
1578
- current = inner as Record<string, unknown>;
1579
- continue;
1580
- }
1581
-
1582
- // Multivariate flags — evaluate matchers and continue with matched variant
1583
- if (rt === WELL_KNOWN_TYPES.MULTIVARIATE || rt === WELL_KNOWN_TYPES.MULTIVARIATE_SECTION) {
1584
- const variants = current.variants as Array<{ value: unknown; rule?: unknown }> | undefined;
1585
- if (!variants?.length) return null;
1586
-
1587
- let matched: unknown = null;
1588
- for (const variant of variants) {
1589
- const rule = variant.rule as Record<string, unknown> | undefined;
1590
- if (evaluateVariantRule(rule, matcherCtx ?? {})) {
1591
- matched = variant.value;
1592
- break;
1593
- }
1594
- }
1595
- if (!matched || typeof matched !== "object") return null;
1596
- current = matched as Record<string, unknown>;
1597
- continue;
1598
- }
1599
-
1600
- // Check if this is a registered section — we found it
1601
- if (getSection(rt)) {
1602
- const { __resolveType: _, ...rawProps } = current;
1603
- return {
1604
- component: rt,
1605
- key: rt,
1606
- index: -1,
1607
- propsHash: djb2Hex(JSON.stringify(rawProps)),
1608
- rawProps: rawProps as Record<string, unknown>,
1609
- };
1610
- }
1611
-
1612
- // Named block reference — follow the chain
1613
- const block = blocks[rt] as Record<string, unknown> | undefined;
1614
- if (block) {
1615
- const { __resolveType: _rtOuter, ...overrides } = current;
1616
- current = { ...block, ...overrides };
1617
- continue;
1618
- }
1619
-
1620
- return null;
1621
- }
1622
-
1623
- return null;
1624
- }
1625
-
1626
- /**
1627
- * Resolve outer wrappers (flags, block references) around the sections list
1628
- * to get the raw section array without resolving each individual section.
1629
- * This allows the eager/deferred split to happen before section resolution.
1630
- */
1631
- export async function resolveSectionsList(
1632
- value: unknown,
1633
- rctx: ResolveContext,
1634
- depth = 0,
1635
- ): Promise<unknown[]> {
1636
- if (depth > MAX_RESOLVE_DEPTH) return [];
1637
- if (!value || typeof value !== "object") return [];
1638
- if (Array.isArray(value)) return value;
1639
-
1640
- const obj = value as Record<string, unknown>;
1641
- const rt = obj.__resolveType as string | undefined;
1642
-
1643
- // Page-level variant wrapper without __resolveType
1644
- // (CMS admin wraps ALL sections in a variant object with { variants: [...] })
1645
- if (!rt && Array.isArray(obj.variants)) {
1646
- const variants = obj.variants as Array<{ value: unknown; rule?: unknown }>;
1647
- for (const variant of variants) {
1648
- const rule = variant.rule as Record<string, unknown> | undefined;
1649
- if (evaluateVariantRule(rule, rctx.matcherCtx)) {
1650
- return resolveSectionsList(variant.value, rctx, depth + 1);
1651
- }
1652
- }
1653
- return [];
1654
- }
1655
-
1656
- if (!rt) return [];
1657
-
1658
- // Multivariate flags — evaluate matchers and recurse into matched variant
1659
- if (rt === WELL_KNOWN_TYPES.MULTIVARIATE || rt === WELL_KNOWN_TYPES.MULTIVARIATE_SECTION) {
1660
- const variants = obj.variants as Array<{ value: unknown; rule?: unknown }> | undefined;
1661
- if (!variants?.length) return [];
1662
- for (const variant of variants) {
1663
- const rule = variant.rule as Record<string, unknown> | undefined;
1664
- if (evaluateVariantRule(rule, rctx.matcherCtx)) {
1665
- return resolveSectionsList(variant.value, rctx, depth + 1);
1666
- }
1667
- }
1668
- return [];
1669
- }
1670
-
1671
- // Named block reference — follow the chain
1672
- const blocks = loadBlocks();
1673
- if (blocks[rt]) {
1674
- const referencedBlock = blocks[rt] as Record<string, unknown>;
1675
- const { __resolveType: _rtOuter, ...restOverrides } = obj;
1676
- return resolveSectionsList({ ...referencedBlock, ...restOverrides }, rctx, depth + 1);
1677
- }
1678
-
1679
- // Resolved — unwrap
1680
- if (rt === "resolved") {
1681
- const data = obj.data;
1682
- if (Array.isArray(data)) return data;
1683
- return [];
1684
- }
1685
-
1686
- return [];
1687
- }
1688
-
1689
- // ---------------------------------------------------------------------------
1690
- // Page-level SEO — extracted from registered SEO sections after resolution
1691
- // ---------------------------------------------------------------------------
1692
-
1693
- export interface PageSeo {
1694
- title?: string;
1695
- description?: string;
1696
- canonical?: string;
1697
- image?: string;
1698
- noIndexing?: boolean;
1699
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1700
- jsonLDs?: Record<string, any>[];
1701
- /** Open Graph type — "website" (default), "product", etc. */
1702
- type?: string;
1703
- }
1704
-
1705
- const seoSectionKeys: Set<string> = G.__deco.seoSections ?? (G.__deco.seoSections = new Set());
1706
-
1707
- /**
1708
- * Register section component keys whose resolved props contribute page-level
1709
- * SEO metadata (title, description, canonical, image, jsonLDs, noIndexing).
1710
- *
1711
- * After section loaders run, the framework scans these sections and extracts
1712
- * their SEO fields into `DecoPageResult.seo`, which `cmsRouteConfig` uses
1713
- * to generate `<head>` metadata (meta tags, OG, canonical, robots).
1714
- *
1715
- * JSON-LD structured data stays in the section props for the section
1716
- * component to render as `<script type="application/ld+json">`.
1717
- */
1718
- export function registerSeoSections(keys: string[]): void {
1719
- for (const k of keys) seoSectionKeys.add(k);
1720
- }
1721
-
1722
- /** Check if a section key is registered as an SEO section. */
1723
- export function isSeoSection(key: string): boolean {
1724
- return seoSectionKeys.has(key);
1725
- }
1726
-
1727
- /**
1728
- * Canonical URL from a schema.org BreadcrumbList — the `item` of its
1729
- * highest-position entry. Inlined from `@decocms/apps-commerce/utils/canonical`
1730
- * because `blocks` cannot depend on `apps-commerce` (apps-commerce depends on
1731
- * blocks, so the edge would be circular).
1732
- */
1733
- function canonicalFromBreadcrumb(breadcrumb: unknown): string | undefined {
1734
- const items = (
1735
- breadcrumb as { itemListElement?: { position: number; item: string }[] } | undefined
1736
- )?.itemListElement;
1737
- if (!Array.isArray(items) || items.length === 0) return undefined;
1738
- return items.reduce((acc, curr) => (acc.position < curr.position ? curr : acc)).item;
1739
- }
1740
-
1741
- /**
1742
- * Shallow-prune a commerce `jsonLD` before emitting it as structured data.
1743
- * Clones only when a prune option is set (the common path emits as-is), so a
1744
- * jsonLD shared with a body section is never mutated out from under it.
1745
- */
1746
- function pruneCommerceJsonLD(
1747
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1748
- jsonLD: Record<string, any>,
1749
- opts: { removeVideos: boolean; omitVariants: boolean },
1750
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1751
- ): Record<string, any> {
1752
- if (!opts.removeVideos && !opts.omitVariants) return jsonLD;
1753
- const clone = structuredClone(jsonLD);
1754
- if (opts.removeVideos && Array.isArray(clone.products)) {
1755
- for (const product of clone.products) {
1756
- product.video = undefined;
1757
- for (const variant of product.isVariantOf?.hasVariant ?? []) variant.video = undefined;
1758
- }
1759
- }
1760
- if (opts.omitVariants && clone.product?.isVariantOf?.hasVariant) {
1761
- clone.product.isVariantOf.hasVariant = [];
1762
- }
1763
- return clone;
1764
- }
1765
-
1766
- /**
1767
- * Derive SEO metadata from a commerce `jsonLD` data source (a resolved
1768
- * ProductListingPage / ProductDetailsPage), mirroring the deco-cx
1769
- * `commerce/sections/Seo/Seo{PLP,PDP}V2.tsx` section loaders.
1770
- *
1771
- * Those legacy sections have no component in @decocms/start (the commerce apps
1772
- * ship loaders/types, not sections), so nothing else runs this transform.
1773
- * Without it, PLP/PDP pages whose `page.seo` points at those types emit a
1774
- * <title>/canonical (from top-level override props) but NO schema.org
1775
- * structured data — the casaevideo.com.br/eletroportateis regression.
1776
- *
1777
- * Manual override fields already read into `seo` always win; this only fills
1778
- * gaps and appends the JSON-LD. The caller guards on `seo.jsonLDs` so a real
1779
- * site SEO section that already computed structured data is never touched.
1780
- */
1781
- function deriveCommerceSeoFromJsonLD(
1782
- seo: PageSeo,
1783
- props: Record<string, unknown>,
1784
- isEager: boolean,
1785
- ): void {
1786
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1787
- const jsonLD = props.jsonLD as Record<string, any> | undefined;
1788
- if (!jsonLD) return;
1789
- const type = jsonLD["@type"];
1790
- if (type !== "ProductListingPage" && type !== "ProductDetailsPage") return;
1791
-
1792
- const jsonLDSeo = jsonLD.seo as
1793
- | { title?: string; description?: string; canonical?: string; noIndexing?: boolean }
1794
- | null
1795
- | undefined;
1796
-
1797
- if (!seo.title && jsonLDSeo?.title) seo.title = jsonLDSeo.title;
1798
- if (!seo.description && jsonLDSeo?.description) seo.description = jsonLDSeo.description;
1799
- if (!seo.canonical) {
1800
- seo.canonical =
1801
- jsonLDSeo?.canonical ||
1802
- canonicalFromBreadcrumb(
1803
- type === "ProductListingPage" ? jsonLD.breadcrumb : jsonLD.breadcrumbList,
1804
- );
1805
- }
1806
- if (type === "ProductDetailsPage" && !seo.image) {
1807
- seo.image = jsonLD.product?.image?.[0]?.url;
1808
- }
1809
-
1810
- const isEmpty =
1811
- type === "ProductListingPage"
1812
- ? !Array.isArray(jsonLD.products) || jsonLD.products.length === 0
1813
- : !jsonLD.product;
1814
- if (seo.noIndexing === undefined) {
1815
- seo.noIndexing = isEmpty || jsonLDSeo?.noIndexing || false;
1816
- }
1817
-
1818
- // Structured data — opt out via `ignoreStructuredData` (top-level on PDP,
1819
- // under `configJsonLD` on PLP). Bot-aware: the toggle suppresses JSON-LD for
1820
- // humans only; crawlers (and the `?__deco_ssr=1` audit override) still get it
1821
- // so indexing/rich results are unaffected. An empty page contributes no
1822
- // ItemList regardless.
1823
- const configJsonLD = props.configJsonLD as
1824
- | { ignoreStructuredData?: boolean; removeVideos?: boolean }
1825
- | undefined;
1826
- const ignore = sectionIgnoresStructuredData(props);
1827
- if ((ignore && !isEager) || isEmpty) return;
1828
-
1829
- seo.jsonLDs = [
1830
- pruneCommerceJsonLD(jsonLD, {
1831
- removeVideos: configJsonLD?.removeVideos === true,
1832
- omitVariants: props.omitVariants === true,
1833
- }),
1834
- ];
1835
- }
1836
-
1837
- /**
1838
- * Pick standard SEO fields from a props object.
1839
- * Works for both framework SEO types (SeoV2) and site SEO sections (SEOPDP).
1840
- */
1841
- export function extractSeoFromProps(
1842
- props: Record<string, unknown>,
1843
- opts?: { isEager?: boolean },
1844
- ): PageSeo {
1845
- const isEager = opts?.isEager ?? false;
1846
- const seo: PageSeo = {};
1847
- if (props.title) seo.title = props.title as string;
1848
- if (props.description) seo.description = props.description as string;
1849
- if (props.canonical) seo.canonical = props.canonical as string;
1850
- if (props.image) seo.image = props.image as string;
1851
- if (props.noIndexing !== undefined) seo.noIndexing = props.noIndexing as boolean;
1852
- if (props.type) seo.type = props.type as string;
1853
- if (Array.isArray(props.jsonLDs) && props.jsonLDs.length) {
1854
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1855
- seo.jsonLDs = props.jsonLDs as Record<string, any>[];
1856
- }
1857
- // Legacy commerce PLP/PDP sections carry a `jsonLD` data source with no
1858
- // component to turn it into structured data — derive it here (only when a
1859
- // real SEO section hasn't already emitted `jsonLDs`).
1860
- if (!seo.jsonLDs) deriveCommerceSeoFromJsonLD(seo, props, isEager);
1861
- return seo;
1862
- }
1863
-
1864
- /**
1865
- * Extract SEO metadata from resolved sections registered via
1866
- * `registerSeoSections`. Later sections override earlier ones
1867
- * (e.g., a PDP SEO section overrides a generic page SEO).
1868
- */
1869
- export function extractSeoFromSections(
1870
- sections: ResolvedSection[],
1871
- opts?: { isEager?: boolean },
1872
- ): PageSeo {
1873
- const seo: PageSeo = {};
1874
- for (const section of sections) {
1875
- if (!seoSectionKeys.has(section.component)) continue;
1876
- const extracted = extractSeoFromProps(section.props, opts);
1877
- if (extracted.jsonLDs) {
1878
- extracted.jsonLDs = [...(seo.jsonLDs ?? []), ...extracted.jsonLDs];
1879
- }
1880
- Object.assign(seo, extracted);
1881
- }
1882
- return seo;
1883
- }
1884
-
1885
- export interface DecoPageResult {
1886
- name: string;
1887
- path: string;
1888
- params: Record<string, string>;
1889
- /** CMS block key, e.g. "pages-Lista de cupons [APP]-397629" */
1890
- blockKey?: string;
1891
- resolvedSections: ResolvedSection[];
1892
- deferredSections: DeferredSection[];
1893
- /**
1894
- * Resolved SEO block from the page-level `seo` field in the CMS JSON.
1895
- * Contains the section component key and resolved props (with commerce
1896
- * loader data already fetched). Needs section loader enrichment in
1897
- * cmsRoute before SEO fields can be extracted.
1898
- */
1899
- seoSection?: ResolvedSection | null;
1900
- }
1901
-
1902
- export async function resolveDecoPage(
1903
- targetPath: string,
1904
- matcherCtx?: MatcherContext,
1905
- ): Promise<DecoPageResult | null> {
1906
- const startedAt = performance.now();
1907
- return withTracing(
1908
- "deco.cms.resolvePage",
1909
- async () => {
1910
- const result = await resolveDecoPageImpl(targetPath, matcherCtx);
1911
- try {
1912
- // No path label: resolve duration is a per-service latency signal, and
1913
- // the request path is unbounded cardinality (one histogram series per
1914
- // URL — product pages, search, facets) that made this the single
1915
- // biggest series in ClickHouse. Per-route latency lives on the span
1916
- // below (raw deco.route), which is sampled — the right place for it.
1917
- getMeter()?.histogramRecord?.(
1918
- MetricNames.RESOLVE_DURATION,
1919
- (performance.now() - startedAt) / 1000,
1920
- );
1921
- } catch {
1922
- /* observability never fails the request */
1923
- }
1924
- return result;
1925
- },
1926
- { "deco.route": targetPath },
1927
- );
1928
- }
1929
-
1930
- async function resolveDecoPageImpl(
1931
- targetPath: string,
1932
- matcherCtx?: MatcherContext,
1933
- ): Promise<DecoPageResult | null> {
1934
- ensureInitialized();
1935
-
1936
- const match = findPageByPath(targetPath);
1937
- if (!match) {
1938
- console.warn(`[CMS] No page found for path: ${targetPath}`);
1939
- return null;
1940
- }
1941
-
1942
- const { page, params, blockKey } = match;
1943
- const ctx: MatcherContext = { ...matcherCtx, path: targetPath };
1944
- const rctx: ResolveContext = { routeParams: params, matcherCtx: ctx, memo: new Map(), depth: 0 };
1945
-
1946
- let rawSections: unknown[];
1947
- if (Array.isArray(page.sections)) {
1948
- rawSections = page.sections;
1949
- } else {
1950
- // Resolve outer flag/wrapper to get the section array
1951
- // without recursively resolving each individual section.
1952
- const resolved = await resolveSectionsList(page.sections, rctx);
1953
- rawSections = resolved;
1954
- }
1955
-
1956
- const isBotReq = isEagerRequest(matcherCtx);
1957
- // SPA navigation (TanStack <Link>) receives the server-fn JSON in one shot —
1958
- // there is no HTTP streaming, so deferral adds a round-trip + skeleton with
1959
- // no benefit (and breaks loaders that need per-request app context, #277).
1960
- // Resolve everything eagerly on client nav; SSR/bots keep deferral.
1961
- const isClientNav = matcherCtx?.isClientNavigation ?? false;
1962
- const currentAsyncConfig = getAsyncConfig();
1963
- const useAsync = currentAsyncConfig !== null && !isBotReq && !isClientNav;
1964
-
1965
- const eagerResults: (ResolvedSection[] | Promise<ResolvedSection[]>)[] = [];
1966
- const deferredSections: DeferredSection[] = [];
1967
- let flatIndex = 0;
1968
-
1969
- for (const section of rawSections) {
1970
- const currentFlatIndex = flatIndex;
1971
-
1972
- const shouldDefer =
1973
- useAsync && shouldDeferSection(section, currentFlatIndex, currentAsyncConfig!, isBotReq, ctx);
1974
-
1975
- if (shouldDefer) {
1976
- let deferredOk = false;
1977
- try {
1978
- const deferred = resolveSectionShallow(section, ctx);
1979
- if (deferred) {
1980
- // Skip sections whose scheduling window has already closed (or
1981
- // hasn't opened yet). Without this check a LoadingFallback
1982
- // skeleton is rendered and immediately replaced by nothing once
1983
- // the component's own scheduling guard returns null — producing
1984
- // the "skeleton flashes then disappears" effect.
1985
- const sched = deferred.rawProps?.scheduling as
1986
- | { start?: string; end?: string }
1987
- | undefined;
1988
- if (sched) {
1989
- const now = Date.now();
1990
- if (sched.end && now > new Date(sched.end).getTime()) {
1991
- flatIndex++;
1992
- continue;
1993
- }
1994
- if (sched.start && now < new Date(sched.start).getTime()) {
1995
- flatIndex++;
1996
- continue;
1997
- }
1998
- }
1999
-
2000
- deferred.index = currentFlatIndex;
2001
-
2002
- // Cache rawProps server-side and strip from the deferred object
2003
- // so they are NOT serialized into the HTML payload.
2004
- if (deferred.rawProps) {
2005
- cacheDeferredRawProps(
2006
- targetPath,
2007
- deferred.component,
2008
- currentFlatIndex,
2009
- deferred.rawProps,
2010
- );
2011
- delete deferred.rawProps;
2012
- }
2013
-
2014
- deferredSections.push(deferred);
2015
- deferredOk = true;
2016
- }
2017
- } catch (e) {
2018
- onResolveError(e, "section", "Deferred section resolution");
2019
- }
2020
-
2021
- if (!deferredOk) {
2022
- // Shallow resolution failed — fall back to eager resolution
2023
- const idx = currentFlatIndex;
2024
- eagerResults.push(
2025
- // Clone the wrappers before stamping `index` — layout sections may
2026
- // be backed by the shared resolved-layout cache, and mutating
2027
- // `s.index` in place would corrupt that shared object across
2028
- // concurrent requests (causing sections to sort into the wrong
2029
- // position, e.g. the footer jumping above other sections).
2030
- resolveRawSection(section, rctx).then((sections) =>
2031
- sections.map((s) => ({ ...s, index: idx })),
2032
- ),
2033
- );
2034
- }
2035
- flatIndex++;
2036
- } else {
2037
- // Eager: full resolution (existing logic)
2038
- const promise = (async (): Promise<ResolvedSection[]> => {
2039
- try {
2040
- const layoutKey = isRawSectionLayout(section);
2041
-
2042
- if (layoutKey) {
2043
- const cached = getCachedResolvedLayout(layoutKey);
2044
- if (cached) return cached;
2045
-
2046
- const inflight = resolvedLayoutInflight.get(layoutKey);
2047
- if (inflight) return inflight;
2048
-
2049
- const p = withInflightTimeout(
2050
- resolveRawSection(section, rctx).then((results) => {
2051
- setCachedResolvedLayout(layoutKey, results);
2052
- return results;
2053
- }),
2054
- `resolvedLayout ${layoutKey}`,
2055
- ).finally(() => resolvedLayoutInflight.delete(layoutKey));
2056
- resolvedLayoutInflight.set(layoutKey, p);
2057
- return p;
2058
- }
2059
-
2060
- return resolveRawSection(section, rctx);
2061
- } catch (e) {
2062
- onResolveError(e, "section", "Section resolution");
2063
- return [];
2064
- }
2065
- })();
2066
-
2067
- const idx = currentFlatIndex;
2068
- eagerResults.push(
2069
- // Clone the wrappers before stamping `index`. `promise` may resolve to
2070
- // the shared resolved-layout cache array (line ~1491 `return cached`)
2071
- // or the shared in-flight array; mutating `s.index` in place would
2072
- // corrupt that shared object across concurrent requests, scrambling
2073
- // section order (e.g. the footer swapping position with top sections).
2074
- promise.then((sections) => sections.map((s) => ({ ...s, index: idx }))),
2075
- );
2076
- flatIndex++;
2077
- }
2078
- }
2079
-
2080
- const allResults = await Promise.all(eagerResults);
2081
-
2082
- // Resolve page-level SEO block (page.seo field) — always eager.
2083
- // Runs after sections to benefit from memoized commerce loader results.
2084
- let seoSection: ResolvedSection | null = null;
2085
- if (page.seo) {
2086
- try {
2087
- seoSection = await resolvePageSeoBlock(page.seo as Record<string, unknown>, rctx);
2088
- } catch (e) {
2089
- onResolveError(e, "page.seo", "Page SEO block resolution");
2090
- }
2091
- }
2092
-
2093
- return {
2094
- name: page.name,
2095
- path: page.path || targetPath,
2096
- params,
2097
- blockKey,
2098
- resolvedSections: allResults.flat(),
2099
- deferredSections,
2100
- seoSection,
2101
- };
2102
- }
2103
-
2104
- /**
2105
- * Resolve a raw sections array into ResolvedSection[] with the same
2106
- * optimizations as resolveDecoPage: parallel resolution, layout caching,
2107
- * in-flight dedup, and memoization.
2108
- *
2109
- * Unlike resolveDecoPage, this does NOT look up a page by path — the
2110
- * caller provides the raw section array directly. Used by the admin
2111
- * preview renderer where page data comes from the POST body.
2112
- *
2113
- * All sections are resolved eagerly (no deferred/async split) since
2114
- * admin previews need the full rendered output.
2115
- */
2116
- export async function resolvePageSections(
2117
- rawSectionsInput: unknown,
2118
- matcherCtx?: MatcherContext,
2119
- ): Promise<ResolvedSection[]> {
2120
- ensureInitialized();
2121
-
2122
- const ctx: MatcherContext = matcherCtx ?? {};
2123
- const rctx: ResolveContext = { matcherCtx: ctx, memo: new Map(), depth: 0 };
2124
-
2125
- let rawSections: unknown[];
2126
- if (Array.isArray(rawSectionsInput)) {
2127
- rawSections = rawSectionsInput;
2128
- } else {
2129
- rawSections = await resolveSectionsList(rawSectionsInput, rctx);
2130
- }
2131
-
2132
- const eagerResults: Promise<ResolvedSection[]>[] = [];
2133
-
2134
- for (const section of rawSections) {
2135
- const promise = (async (): Promise<ResolvedSection[]> => {
2136
- try {
2137
- const layoutKey = isRawSectionLayout(section);
2138
-
2139
- if (layoutKey) {
2140
- const cached = getCachedResolvedLayout(layoutKey);
2141
- if (cached) return cached;
2142
-
2143
- const inflight = resolvedLayoutInflight.get(layoutKey);
2144
- if (inflight) return inflight;
2145
-
2146
- const p = withInflightTimeout(
2147
- resolveRawSection(section, rctx).then((results) => {
2148
- setCachedResolvedLayout(layoutKey, results);
2149
- return results;
2150
- }),
2151
- `resolvedLayout ${layoutKey}`,
2152
- ).finally(() => resolvedLayoutInflight.delete(layoutKey));
2153
- resolvedLayoutInflight.set(layoutKey, p);
2154
- return p;
2155
- }
2156
-
2157
- return resolveRawSection(section, rctx);
2158
- } catch (e) {
2159
- onResolveError(e, "section", "Preview section resolution");
2160
- return [];
2161
- }
2162
- })();
2163
-
2164
- eagerResults.push(promise);
2165
- }
2166
-
2167
- const allResults = await Promise.all(eagerResults);
2168
- return allResults.flat();
2169
- }
2170
-
2171
- /**
2172
- * Resolve a single deferred section's raw props into a fully resolved section.
2173
- * Called by the loadDeferredSection server function when a section scrolls into view.
2174
- *
2175
- * This runs the full resolution pipeline on the raw CMS props:
2176
- * - Resolves nested __resolveType references (commerce loaders, block refs, flags)
2177
- * - Normalizes nested sections to { Component, props } shape
2178
- *
2179
- * After this, the section goes through runSingleSectionLoader for final enrichment.
2180
- */
2181
- export async function resolveDeferredSection(
2182
- component: string,
2183
- rawProps: Record<string, unknown>,
2184
- pagePath: string,
2185
- matcherCtx?: MatcherContext,
2186
- ): Promise<ResolvedSection | null> {
2187
- ensureInitialized();
2188
-
2189
- const ctx: MatcherContext = { ...matcherCtx, path: pagePath };
2190
- // Recover routeParams from the page match so nested `requestToParam`
2191
- // resolvers (e.g. `:slug` on PDPs) return the right value.
2192
- const match = findPageByPath(pagePath);
2193
- const rctx: ResolveContext = {
2194
- routeParams: match?.params,
2195
- matcherCtx: ctx,
2196
- memo: new Map(),
2197
- depth: 0,
2198
- };
2199
-
2200
- // onBeforeResolveProps: let sections transform raw props before resolution.
2201
- const propsToResolve = await applyOnBeforeResolveProps(component, rawProps);
2202
-
2203
- const resolvedProps = await resolveProps(propsToResolve, rctx);
2204
- const normalizedProps = normalizeNestedSections(resolvedProps) as Record<string, unknown>;
2205
-
2206
- return {
2207
- component,
2208
- props: normalizedProps,
2209
- key: component,
2210
- };
2211
- }
2212
-
2213
- /**
2214
- * Resolve AND enrich a deferred section in one call.
2215
- * Combines CMS prop resolution (resolveDeferredSection) with section loader
2216
- * enrichment (runSingleSectionLoader) and URL normalization.
2217
- *
2218
- * Used by the route loader to create streaming promises for TanStack's
2219
- * native deferred data pattern — each deferred section becomes an unawaited
2220
- * promise that TanStack streams via SSR.
2221
- */
2222
- export async function resolveDeferredSectionFull(
2223
- ds: DeferredSection,
2224
- pagePath: string,
2225
- request: Request,
2226
- matcherCtx?: MatcherContext,
2227
- ): Promise<ResolvedSection | null> {
2228
- // rawProps may be stripped from the client payload — resolve from cache or page
2229
- const rawProps =
2230
- ds.rawProps ??
2231
- getDeferredRawProps(pagePath, ds.component, ds.index) ??
2232
- (await reExtractRawProps(pagePath, ds.component, ds.index, matcherCtx));
2233
-
2234
- if (!rawProps) return null;
2235
-
2236
- const section = await resolveDeferredSection(ds.component, rawProps, pagePath, matcherCtx);
2237
- if (!section) return null;
2238
- section.index = ds.index;
2239
- const enriched = await runSingleSectionLoader(section, request);
2240
- return normalizeUrlsInObject(enriched);
2241
- }
2242
-
2243
- /**
2244
- * Fallback for deferred rawProps cache miss: re-resolve the page and extract
2245
- * rawProps for the section at the given index. Expensive but ensures correctness
2246
- * when the in-memory cache has been evicted (different isolate, TTL expired).
2247
- */
2248
- export async function reExtractRawProps(
2249
- pagePath: string,
2250
- component: string,
2251
- sectionIndex: number,
2252
- matcherCtx?: MatcherContext,
2253
- ): Promise<Record<string, unknown> | null> {
2254
- ensureInitialized();
2255
-
2256
- const match = findPageByPath(pagePath);
2257
- if (!match) return null;
2258
-
2259
- const { page } = match;
2260
- const ctx: MatcherContext = { ...matcherCtx, path: pagePath };
2261
-
2262
- let rawSections: unknown[];
2263
- if (Array.isArray(page.sections)) {
2264
- rawSections = page.sections;
2265
- } else {
2266
- const rctx: ResolveContext = { matcherCtx: ctx, memo: new Map(), depth: 0 };
2267
- rawSections = await resolveSectionsList(page.sections, rctx);
2268
- }
2269
-
2270
- if (sectionIndex < 0 || sectionIndex >= rawSections.length) return null;
2271
-
2272
- const section = rawSections[sectionIndex];
2273
- const shallow = resolveSectionShallow(section, ctx);
2274
- if (!shallow || shallow.component !== component) return null;
2275
-
2276
- // Cache for subsequent requests
2277
- if (shallow.rawProps) {
2278
- cacheDeferredRawProps(pagePath, component, sectionIndex, shallow.rawProps);
2279
- }
2280
-
2281
- return shallow.rawProps ?? null;
2282
- }