@decocms/tanstack 8.1.0-next.0 → 8.4.0
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.
- package/README.md +79 -0
- package/dist/draft.d.ts +33 -0
- package/dist/draft.d.ts.map +1 -0
- package/dist/draft.js +41 -0
- package/dist/draft.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/react/DecoDocument.d.ts +61 -0
- package/dist/react/DecoDocument.d.ts.map +1 -0
- package/dist/react/DecoDocument.js +96 -0
- package/dist/react/DecoDocument.js.map +1 -0
- package/dist/react/Image.d.ts +96 -0
- package/dist/react/Image.d.ts.map +1 -0
- package/dist/react/Image.js +79 -0
- package/dist/react/Image.js.map +1 -0
- package/dist/react/index.d.ts +7 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +7 -0
- package/dist/react/index.js.map +1 -0
- package/dist/react/pageValues.d.ts +10 -0
- package/dist/react/pageValues.d.ts.map +1 -0
- package/dist/react/pageValues.js +29 -0
- package/dist/react/pageValues.js.map +1 -0
- package/dist/react/scripts.d.ts +14 -0
- package/dist/react/scripts.d.ts.map +1 -0
- package/dist/react/scripts.js +96 -0
- package/dist/react/scripts.js.map +1 -0
- package/dist/router/index.d.ts +38 -0
- package/dist/router/index.d.ts.map +1 -0
- package/dist/router/index.js +60 -0
- package/dist/router/index.js.map +1 -0
- package/dist/scope/browser.d.ts +11 -0
- package/dist/scope/browser.d.ts.map +1 -0
- package/dist/scope/browser.js +8 -0
- package/dist/scope/browser.js.map +1 -0
- package/dist/scope/server.d.ts +13 -0
- package/dist/scope/server.d.ts.map +1 -0
- package/dist/scope/server.js +26 -0
- package/dist/scope/server.js.map +1 -0
- package/dist/server/index.d.ts +27 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +31 -0
- package/dist/server/index.js.map +1 -0
- package/dist/shared.d.ts +26 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +26 -0
- package/dist/shared.js.map +1 -0
- package/dist/start/index.d.ts +9 -0
- package/dist/start/index.d.ts.map +1 -0
- package/dist/start/index.js +33 -0
- package/dist/start/index.js.map +1 -0
- package/dist/studio.d.ts +28 -0
- package/dist/studio.d.ts.map +1 -0
- package/dist/studio.js +53 -0
- package/dist/studio.js.map +1 -0
- package/dist/vite/index.d.ts +15 -0
- package/dist/vite/index.d.ts.map +1 -0
- package/dist/vite/index.js +95 -0
- package/dist/vite/index.js.map +1 -0
- package/dist/worker/cacheProfiles.d.ts +43 -0
- package/dist/worker/cacheProfiles.d.ts.map +1 -0
- package/dist/worker/cacheProfiles.js +162 -0
- package/dist/worker/cacheProfiles.js.map +1 -0
- package/dist/worker/cookies.d.ts +20 -0
- package/dist/worker/cookies.d.ts.map +1 -0
- package/dist/worker/cookies.js +69 -0
- package/dist/worker/cookies.js.map +1 -0
- package/dist/worker/drafts.d.ts +59 -0
- package/dist/worker/drafts.d.ts.map +1 -0
- package/dist/worker/drafts.js +140 -0
- package/dist/worker/drafts.js.map +1 -0
- package/dist/worker/index.d.ts +107 -0
- package/dist/worker/index.d.ts.map +1 -0
- package/dist/worker/index.js +511 -0
- package/dist/worker/index.js.map +1 -0
- package/dist/worker/security.d.ts +14 -0
- package/dist/worker/security.d.ts.map +1 -0
- package/dist/worker/security.js +48 -0
- package/dist/worker/security.js.map +1 -0
- package/dist/worker/segment.d.ts +21 -0
- package/dist/worker/segment.d.ts.map +1 -0
- package/dist/worker/segment.js +43 -0
- package/dist/worker/segment.js.map +1 -0
- package/package.json +85 -37
- package/src/draft.ts +43 -0
- package/src/index.ts +8 -61
- package/src/react/DecoDocument.tsx +234 -0
- package/src/react/Image.tsx +213 -0
- package/src/react/index.ts +24 -0
- package/src/react/pageValues.ts +35 -0
- package/src/react/scripts.ts +98 -0
- package/src/router/index.ts +80 -0
- package/src/scope/browser.ts +18 -0
- package/src/scope/server.ts +37 -0
- package/src/server/index.ts +43 -0
- package/src/shared.ts +29 -0
- package/src/start/index.ts +31 -0
- package/src/studio.ts +52 -0
- package/src/vite/index.ts +105 -0
- package/src/worker/cacheProfiles.ts +180 -0
- package/src/worker/cookies.ts +65 -0
- package/src/worker/drafts.ts +157 -0
- package/src/worker/index.ts +648 -0
- package/src/worker/security.ts +63 -0
- package/src/worker/segment.ts +49 -0
- package/src/__conformance__/observability.test.ts +0 -221
- package/src/cms/kvBlockSource.test.ts +0 -82
- package/src/cms/kvBlockSource.ts +0 -68
- package/src/daemon/auth.ts +0 -204
- package/src/daemon/fs.ts +0 -238
- package/src/daemon/index.ts +0 -8
- package/src/daemon/middleware.ts +0 -156
- package/src/daemon/tunnel.ts +0 -129
- package/src/daemon/volumes.ts +0 -366
- package/src/daemon/watch.ts +0 -272
- package/src/hooks/CdnSegmentMarker.tsx +0 -38
- package/src/hooks/DecoPageRenderer.tsx +0 -750
- package/src/hooks/DecoRootLayout.tsx +0 -192
- package/src/hooks/DraftPreviewIndicator.test.tsx +0 -60
- package/src/hooks/DraftPreviewIndicator.tsx +0 -64
- package/src/hooks/NavigationProgress.test.tsx +0 -58
- package/src/hooks/NavigationProgress.tsx +0 -63
- package/src/hooks/PreviewProviders.test.tsx +0 -42
- package/src/hooks/PreviewProviders.tsx +0 -45
- package/src/hooks/StableOutlet.tsx +0 -30
- package/src/hooks/deferredObserverTiming.test.tsx +0 -91
- package/src/hooks/index.ts +0 -10
- package/src/routes/adminRoutes.test.ts +0 -99
- package/src/routes/adminRoutes.ts +0 -153
- package/src/routes/cmsRoute.test.ts +0 -267
- package/src/routes/cmsRoute.ts +0 -1053
- package/src/routes/components.tsx +0 -57
- package/src/routes/index.ts +0 -24
- package/src/routes/pageUrl.test.ts +0 -70
- package/src/routes/pageUrl.ts +0 -55
- package/src/routes/withSiteGlobals.test.ts +0 -243
- package/src/routes/withSiteGlobals.ts +0 -243
- package/src/sdk/backgroundTasks.test.ts +0 -68
- package/src/sdk/backgroundTasks.ts +0 -38
- package/src/sdk/cdnSegment.test.ts +0 -67
- package/src/sdk/cdnSegment.ts +0 -71
- package/src/sdk/cookiePassthrough.ts +0 -58
- package/src/sdk/createInvoke.ts +0 -77
- package/src/sdk/deferredSectionLoader.test.ts +0 -94
- package/src/sdk/deferredSectionLoader.ts +0 -46
- package/src/sdk/draft.test.ts +0 -341
- package/src/sdk/draft.ts +0 -277
- package/src/sdk/draftShared.ts +0 -16
- package/src/sdk/kvHydration.test.ts +0 -371
- package/src/sdk/kvHydration.ts +0 -263
- package/src/sdk/kvRedirects.test.ts +0 -132
- package/src/sdk/kvRedirects.ts +0 -125
- package/src/sdk/outboundHeaders.test.ts +0 -113
- package/src/sdk/outboundHeaders.ts +0 -81
- package/src/sdk/router.ts +0 -101
- package/src/sdk/serverFnFetch.ts +0 -59
- package/src/sdk/speculationRules.test.ts +0 -82
- package/src/sdk/speculationRules.ts +0 -136
- package/src/sdk/startEntry.ts +0 -31
- package/src/sdk/useHydrated.ts +0 -19
- package/src/sdk/workerEntry.cacheStorage.test.ts +0 -147
- package/src/sdk/workerEntry.test.ts +0 -1033
- package/src/sdk/workerEntry.trackingCache.test.ts +0 -328
- package/src/sdk/workerEntry.ts +0 -3154
- package/src/setupFastDeploy.ts +0 -13
- package/src/v8/__conformance__/delivery.test.ts +0 -100
- package/src/v8/binding.ts +0 -70
- package/src/v8/kvLoader.bundle.test.ts +0 -42
- package/src/v8/kvLoader.test.ts +0 -74
- package/src/v8/kvLoader.ts +0 -43
- package/src/vite/plugin-scaffold-gen.test.js +0 -106
- package/src/vite/plugin.js +0 -1022
- package/src/vite/plugin.test.js +0 -238
- package/src/vite/plugin.test.ts +0 -176
- package/tsconfig.json +0 -7
package/src/routes/cmsRoute.ts
DELETED
|
@@ -1,1053 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* CMS Route Helpers
|
|
3
|
-
*
|
|
4
|
-
* Reusable building blocks for CMS catch-all and homepage routes.
|
|
5
|
-
* Since TanStack Router requires routes to be file-based in the site repo,
|
|
6
|
-
* we export helper functions and config that sites use in their route files.
|
|
7
|
-
*
|
|
8
|
-
* @example Site's `src/routes/$.tsx`:
|
|
9
|
-
* ```ts
|
|
10
|
-
* import { createFileRoute, notFound } from "@tanstack/react-router";
|
|
11
|
-
* import { loadCmsPage, cmsRouteConfig } from "@decocms/start/routes";
|
|
12
|
-
* import { DecoPageRenderer } from "@decocms/start/hooks";
|
|
13
|
-
*
|
|
14
|
-
* export const Route = createFileRoute("/$")({
|
|
15
|
-
* ...cmsRouteConfig({
|
|
16
|
-
* siteName: "My Store",
|
|
17
|
-
* defaultTitle: "My Store - Best products",
|
|
18
|
-
* ignoreSearchParams: ["skuId"],
|
|
19
|
-
* }),
|
|
20
|
-
* });
|
|
21
|
-
* ```
|
|
22
|
-
*/
|
|
23
|
-
|
|
24
|
-
import type {
|
|
25
|
-
DeferredSection,
|
|
26
|
-
MatcherContext,
|
|
27
|
-
PageSeo,
|
|
28
|
-
ResolvedSection,
|
|
29
|
-
} from "@decocms/blocks/cms";
|
|
30
|
-
import {
|
|
31
|
-
extractSeoFromProps,
|
|
32
|
-
extractSeoFromSections,
|
|
33
|
-
getDeferredRawProps,
|
|
34
|
-
getDegradedSections,
|
|
35
|
-
getSiteSeo,
|
|
36
|
-
isEagerRequest,
|
|
37
|
-
preloadSectionComponents,
|
|
38
|
-
reExtractRawProps,
|
|
39
|
-
resolveDecoPage,
|
|
40
|
-
resolveDeferredSection,
|
|
41
|
-
resolveDeferredSectionFull,
|
|
42
|
-
runSectionLoaders,
|
|
43
|
-
runSingleSectionLoader,
|
|
44
|
-
} from "@decocms/blocks/cms";
|
|
45
|
-
import { withTracing } from "@decocms/blocks/middleware/observability";
|
|
46
|
-
import {
|
|
47
|
-
type CacheProfileName,
|
|
48
|
-
cacheHeaders,
|
|
49
|
-
detectCacheProfile,
|
|
50
|
-
routeCacheDefaults,
|
|
51
|
-
} from "@decocms/blocks/sdk/cacheHeaders";
|
|
52
|
-
import { takeExperimentAssignments } from "@decocms/blocks/sdk/experiments";
|
|
53
|
-
import {
|
|
54
|
-
parseSegmentCookie,
|
|
55
|
-
SEGMENT_COOKIE,
|
|
56
|
-
type StoredFlag,
|
|
57
|
-
serializeSegmentCookie,
|
|
58
|
-
} from "@decocms/blocks/sdk/flags";
|
|
59
|
-
import { normalizeUrlsInObject } from "@decocms/blocks/sdk/normalizeUrls";
|
|
60
|
-
import { type Device, detectDevice } from "@decocms/blocks/sdk/useDevice";
|
|
61
|
-
import { createServerFn } from "@tanstack/react-start";
|
|
62
|
-
import {
|
|
63
|
-
getCookies,
|
|
64
|
-
getRequest,
|
|
65
|
-
getRequestHeader,
|
|
66
|
-
getRequestUrl,
|
|
67
|
-
setCookie,
|
|
68
|
-
setResponseHeader,
|
|
69
|
-
} from "@tanstack/react-start/server";
|
|
70
|
-
import { createElement } from "react";
|
|
71
|
-
import { derivePageUrl, isClientNavigation } from "./pageUrl";
|
|
72
|
-
import { dedupeGlobals, resolveSiteGlobals } from "./withSiteGlobals";
|
|
73
|
-
import type { SiteGlobalRef } from "./withSiteGlobals";
|
|
74
|
-
|
|
75
|
-
const isServer = typeof document === "undefined";
|
|
76
|
-
|
|
77
|
-
// Section chunk manifest — maps section keys to chunk filenames.
|
|
78
|
-
// Generated by decoVitePlugin's generateBundle hook. Used to emit
|
|
79
|
-
// <link rel="modulepreload"> hints for eager sections.
|
|
80
|
-
let sectionChunkMap: Record<string, string> = {};
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* Set the section chunk manifest. Called by the site's worker entry
|
|
84
|
-
* or setup after loading the manifest.
|
|
85
|
-
*/
|
|
86
|
-
export function setSectionChunkMap(map: Record<string, string>): void {
|
|
87
|
-
sectionChunkMap = map;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
// ---------------------------------------------------------------------------
|
|
91
|
-
// Server function — loads a CMS page, runs section loaders, detects cache
|
|
92
|
-
// ---------------------------------------------------------------------------
|
|
93
|
-
|
|
94
|
-
type PageResult = Awaited<ReturnType<typeof loadCmsPageInternal>>;
|
|
95
|
-
const pageInflight = new Map<string, Promise<PageResult>>();
|
|
96
|
-
|
|
97
|
-
/** Same shape as `resolveSiteGlobals()`'s empty result — used when `resolveGlobals: false`. */
|
|
98
|
-
const EMPTY_GLOBALS: { resolvedSections: ResolvedSection[]; rawRefs: SiteGlobalRef[] } = {
|
|
99
|
-
resolvedSections: [],
|
|
100
|
-
rawRefs: [],
|
|
101
|
-
};
|
|
102
|
-
|
|
103
|
-
/** One year — the cohort is sticky; the `pct` fingerprint handles re-rolls. */
|
|
104
|
-
const SEGMENT_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
|
|
105
|
-
|
|
106
|
-
/**
|
|
107
|
-
* Persist sticky A/B decisions recorded during resolution and return them for
|
|
108
|
-
* the client (analytics).
|
|
109
|
-
*
|
|
110
|
-
* Merges the freshly recorded flags over any already in the `deco_segment`
|
|
111
|
-
* cookie (so navigating to a second A/B page doesn't drop the first page's
|
|
112
|
-
* cohort), and only re-issues the cookie when the merged value changed.
|
|
113
|
-
* Setting the cookie also makes the worker skip caching THIS response
|
|
114
|
-
* (`deco_segment` is not a "safe" cookie), so an unassigned visitor never
|
|
115
|
-
* poisons the shared entry — their next request carries the cookie and hits
|
|
116
|
-
* the per-cohort cache entry.
|
|
117
|
-
*
|
|
118
|
-
* `encode: (v) => v` keeps the raw base64 intact — @decocms/apps
|
|
119
|
-
* OneDollarStats reads the cookie with `atob()` directly.
|
|
120
|
-
*
|
|
121
|
-
* Experiment assignments (`sdk/experiments.ts`) merge in through the same
|
|
122
|
-
* writer rather than setting their own cookie — one `deco_segment`, one
|
|
123
|
-
* Set-Cookie. That is why this runs AFTER the section loaders: CMS matchers
|
|
124
|
-
* decide during page resolution, but an experiment is resolved inside a
|
|
125
|
-
* loader, so persisting before the loaders ran would drop the assignment and
|
|
126
|
-
* the visitor would re-roll on every request.
|
|
127
|
-
*/
|
|
128
|
-
function persistFlags(matcherCtx: MatcherContext, experiments: StoredFlag[] = []): StoredFlag[] {
|
|
129
|
-
const recorded = [...(matcherCtx.flags ?? []), ...experiments];
|
|
130
|
-
if (!recorded.length) return [];
|
|
131
|
-
|
|
132
|
-
const raw = matcherCtx.cookies?.[SEGMENT_COOKIE];
|
|
133
|
-
const merged = new Map<string, StoredFlag>();
|
|
134
|
-
for (const f of parseSegmentCookie(raw)) merged.set(f.name, f);
|
|
135
|
-
for (const f of recorded) merged.set(f.name, f);
|
|
136
|
-
|
|
137
|
-
const serialized = serializeSegmentCookie([...merged.values()]);
|
|
138
|
-
if (serialized !== (raw ?? "")) {
|
|
139
|
-
setCookie(SEGMENT_COOKIE, serialized, {
|
|
140
|
-
path: "/",
|
|
141
|
-
maxAge: SEGMENT_COOKIE_MAX_AGE,
|
|
142
|
-
sameSite: "lax",
|
|
143
|
-
encode: (v) => v,
|
|
144
|
-
});
|
|
145
|
-
}
|
|
146
|
-
return recorded;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/**
|
|
150
|
-
* Run the body sections' loaders and the SEO section's loader in the SAME
|
|
151
|
-
* batch (`Promise.all` via `runSectionLoaders`), instead of sequentially
|
|
152
|
-
* (body first, then `buildPageSeo` separately awaiting the SEO section).
|
|
153
|
-
*
|
|
154
|
-
* On a PDP, the SEO section (e.g. SeoPDP) commonly resolves the same
|
|
155
|
-
* product as a body section via the same commerce loader. Running them
|
|
156
|
-
* sequentially meant the SEO fetch always missed any in-flight request
|
|
157
|
-
* dedup at the fetch-cache layer (apps-vtex's fetchWithCache) — the body
|
|
158
|
-
* fetch had already completed and left the in-flight map by the time the
|
|
159
|
-
* SEO fetch started, so the origin got hit twice per navigation (#355).
|
|
160
|
-
* Batching them gives concurrent identical requests a chance to share one
|
|
161
|
-
* origin round-trip.
|
|
162
|
-
*/
|
|
163
|
-
/** @internal exported for tests */
|
|
164
|
-
export async function runSectionLoadersWithSeo(
|
|
165
|
-
resolvedSections: ResolvedSection[],
|
|
166
|
-
seoSection: ResolvedSection | null | undefined,
|
|
167
|
-
request: Request,
|
|
168
|
-
): Promise<{ enrichedSections: ResolvedSection[]; enrichedSeoSection: ResolvedSection | null | undefined }> {
|
|
169
|
-
if (!seoSection) {
|
|
170
|
-
return { enrichedSections: await runSectionLoaders(resolvedSections, request), enrichedSeoSection: seoSection };
|
|
171
|
-
}
|
|
172
|
-
const enrichedAll = await runSectionLoaders([...resolvedSections, seoSection], request);
|
|
173
|
-
return {
|
|
174
|
-
enrichedSections: enrichedAll.slice(0, -1),
|
|
175
|
-
enrichedSeoSection: enrichedAll[enrichedAll.length - 1],
|
|
176
|
-
};
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
/**
|
|
180
|
-
* Dedupe `site.global` / `site.pageSections` against the page's own sections,
|
|
181
|
-
* then run the survivors' loaders against the real per-request Request.
|
|
182
|
-
*
|
|
183
|
-
* `resolveSiteGlobals()` only resolves a global's *props* — and it SWR-caches
|
|
184
|
-
* that result for 5 minutes across every visitor. Until now nothing ever fed
|
|
185
|
-
* globals through `runSectionLoaders`, so a global section's `loader` export
|
|
186
|
-
* simply never ran: the component rendered with the raw CMS props and every
|
|
187
|
-
* loader-derived field arrived `undefined`. Sites worked around it by moving
|
|
188
|
-
* the work client-side (a `useQuery` over `/deco/invoke`), which changes both
|
|
189
|
-
* the timing and the SSR output — an analytics global that has to emit its
|
|
190
|
-
* event inline, in document order, cannot be rewritten that way at all.
|
|
191
|
-
*
|
|
192
|
-
* Loaders run per request and are NOT cached here; only the prop resolution
|
|
193
|
-
* behind `resolveSiteGlobals()` keeps its 5-minute cache. Dedupe runs first so
|
|
194
|
-
* a global that the page overrides never pays for its loader.
|
|
195
|
-
*
|
|
196
|
-
* Section-level caching still applies: a global registered via
|
|
197
|
-
* `registerLayoutSections` / `registerCacheableSections` goes through the same
|
|
198
|
-
* cache tiers as any other section inside `runSectionLoaders`.
|
|
199
|
-
*
|
|
200
|
-
* `pageSections` may be the page's RAW sections — it does not have to be the
|
|
201
|
-
* loader-enriched ones. `dedupeGlobals` reads only `section.component`, and no
|
|
202
|
-
* branch of `runSingleSectionLoaderImpl` ever rewrites `component` (every path
|
|
203
|
-
* returns `section` or `{ ...section, props }`, 1:1, never adding or dropping
|
|
204
|
-
* entries). Passing the raw list is what lets this run CONCURRENTLY with the
|
|
205
|
-
* page's own loaders instead of behind them.
|
|
206
|
-
*
|
|
207
|
-
* @internal exported for tests
|
|
208
|
-
*/
|
|
209
|
-
export async function enrichGlobals(
|
|
210
|
-
globalSections: ResolvedSection[],
|
|
211
|
-
pageSections: ResolvedSection[],
|
|
212
|
-
request: Request,
|
|
213
|
-
): Promise<ResolvedSection[]> {
|
|
214
|
-
const kept = dedupeGlobals(globalSections, pageSections);
|
|
215
|
-
if (kept.length === 0) return kept;
|
|
216
|
-
return runSectionLoaders(kept, request);
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
async function loadCmsPageInternal(fullPath: string, resolveGlobals: boolean) {
|
|
220
|
-
const [basePath] = fullPath.split("?");
|
|
221
|
-
// On client-side navigation getRequestUrl() is the /_serverFn/... endpoint,
|
|
222
|
-
// not the page being loaded — derivePageUrl rebuilds the real page URL so
|
|
223
|
-
// matcherCtx.url / __pageUrl stay consistent with __pagePath (#280).
|
|
224
|
-
const serverUrl = getRequestUrl();
|
|
225
|
-
const urlWithSearch = derivePageUrl(fullPath, serverUrl);
|
|
226
|
-
|
|
227
|
-
const originRequest = getRequest();
|
|
228
|
-
const matcherCtx: MatcherContext = {
|
|
229
|
-
userAgent: getRequestHeader("user-agent") ?? "",
|
|
230
|
-
url: urlWithSearch,
|
|
231
|
-
path: basePath,
|
|
232
|
-
cookies: getCookies(),
|
|
233
|
-
request: originRequest,
|
|
234
|
-
isClientNavigation: isClientNavigation(fullPath, serverUrl),
|
|
235
|
-
flags: [],
|
|
236
|
-
};
|
|
237
|
-
const page = await resolveDecoPage(basePath, matcherCtx);
|
|
238
|
-
if (!page) return null;
|
|
239
|
-
|
|
240
|
-
const request = new Request(urlWithSearch, {
|
|
241
|
-
headers: originRequest.headers,
|
|
242
|
-
});
|
|
243
|
-
|
|
244
|
-
// Resolve page sections (+ the SEO section, batched together — see #355)
|
|
245
|
-
// and site globals in parallel. Globals are merged into the same
|
|
246
|
-
// `resolvedSections` array so the path through this server function is
|
|
247
|
-
// identical for SSR (F5) and SPA (<Link>) navigations — see #233 for the
|
|
248
|
-
// previous SPA-breakage when `withSiteGlobals` ran client-side and saw an
|
|
249
|
-
// empty client-bundled `blocks.gen.ts`.
|
|
250
|
-
const [{ enrichedSections, enrichedSeoSection }, { globals, enrichedGlobals }] =
|
|
251
|
-
await Promise.all([
|
|
252
|
-
runSectionLoadersWithSeo(page.resolvedSections, page.seoSection, request),
|
|
253
|
-
(async () => {
|
|
254
|
-
const globals = resolveGlobals ? await resolveSiteGlobals(matcherCtx) : EMPTY_GLOBALS;
|
|
255
|
-
return {
|
|
256
|
-
globals,
|
|
257
|
-
// Deduped against the page's RAW sections on purpose — see enrichGlobals.
|
|
258
|
-
// Waiting for `enrichedSections` would put the globals' loaders behind
|
|
259
|
-
// the page's on the TTFB critical path for no benefit.
|
|
260
|
-
enrichedGlobals: await enrichGlobals(
|
|
261
|
-
globals.resolvedSections,
|
|
262
|
-
page.resolvedSections,
|
|
263
|
-
request,
|
|
264
|
-
),
|
|
265
|
-
};
|
|
266
|
-
})(),
|
|
267
|
-
]);
|
|
268
|
-
|
|
269
|
-
// After the loaders — a loader-resolved experiment assignment must be in the
|
|
270
|
-
// cookie this response sets. See persistFlags.
|
|
271
|
-
const flags = persistFlags(matcherCtx, takeExperimentAssignments());
|
|
272
|
-
|
|
273
|
-
// Page sections take precedence over globals — dedupe drops any global whose
|
|
274
|
-
// component is already rendered by the page. The survivors ran their own
|
|
275
|
-
// loaders above, concurrently with the page's (see enrichGlobals).
|
|
276
|
-
const mergedSections: ResolvedSection[] = [...enrichedGlobals, ...enrichedSections];
|
|
277
|
-
|
|
278
|
-
// Pre-import eager section modules so their default exports are cached
|
|
279
|
-
// in resolvedComponents. This ensures SSR renders with direct component
|
|
280
|
-
// refs, and the client hydration can skip React.lazy/Suspense.
|
|
281
|
-
const eagerKeys = mergedSections.map((s) => s.component);
|
|
282
|
-
await preloadSectionComponents(eagerKeys);
|
|
283
|
-
|
|
284
|
-
const cacheProfile = detectCacheProfile(basePath);
|
|
285
|
-
const ua = getRequestHeader("user-agent") ?? "";
|
|
286
|
-
const device = detectDevice(ua);
|
|
287
|
-
|
|
288
|
-
// Build SEO: merge page-level seo block (primary) with section-contributed SEO (secondary)
|
|
289
|
-
const seo = buildPageSeo(
|
|
290
|
-
page.seoSection,
|
|
291
|
-
enrichedSeoSection,
|
|
292
|
-
mergedSections,
|
|
293
|
-
isEagerRequest(matcherCtx),
|
|
294
|
-
);
|
|
295
|
-
|
|
296
|
-
// Destructure seoSection out — it's an internal artifact, not serialized to client
|
|
297
|
-
const { seoSection: _seo, ...pageData } = page;
|
|
298
|
-
|
|
299
|
-
// Anti-cache-poisoning: if a critical section loader failed, this page is
|
|
300
|
-
// rendering with raw/empty data. Flag the response so the edge refuses to
|
|
301
|
-
// cache the broken 200 and serves stale instead (see workerEntry.ts). Without
|
|
302
|
-
// this, the empty page would be cached as healthy for the whole retention
|
|
303
|
-
// window and stale-if-error would never fire.
|
|
304
|
-
const degraded = getDegradedSections();
|
|
305
|
-
if (degraded.length > 0) {
|
|
306
|
-
setResponseHeader("X-Deco-Degraded", "true");
|
|
307
|
-
console.warn(`[cms] page degraded — critical sections failed: ${degraded.join(", ")}`);
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
return {
|
|
311
|
-
...pageData,
|
|
312
|
-
resolvedSections: normalizeUrlsInObject(mergedSections),
|
|
313
|
-
deferredSections: normalizeUrlsInObject(page.deferredSections),
|
|
314
|
-
cacheProfile,
|
|
315
|
-
degraded: degraded.length > 0,
|
|
316
|
-
pageUrl: urlWithSearch,
|
|
317
|
-
pagePath: basePath,
|
|
318
|
-
seo,
|
|
319
|
-
device,
|
|
320
|
-
flags,
|
|
321
|
-
siteGlobals: { rawRefs: globals.rawRefs },
|
|
322
|
-
};
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
/** Accepted by `loadCmsPage` — a bare path (back-compat) or `{ path, resolveGlobals }`. */
|
|
326
|
-
export type LoadCmsPageInput = string | { path: string; resolveGlobals?: boolean };
|
|
327
|
-
|
|
328
|
-
/** @internal exported for tests */
|
|
329
|
-
export function parseLoadCmsPageInput(data: unknown): { path: string; resolveGlobals: boolean } {
|
|
330
|
-
if (typeof data === "string") return { path: data, resolveGlobals: true };
|
|
331
|
-
const obj = data as { path: string; resolveGlobals?: boolean };
|
|
332
|
-
return { path: obj.path, resolveGlobals: obj.resolveGlobals ?? true };
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
export const loadCmsPage = createServerFn({ method: "GET" })
|
|
336
|
-
.inputValidator((data: unknown) => data as LoadCmsPageInput)
|
|
337
|
-
.handler(async (ctx) => {
|
|
338
|
-
const { path: fullPath, resolveGlobals } = parseLoadCmsPageInput(ctx.data);
|
|
339
|
-
|
|
340
|
-
// Use the full path (including query string) as the dedup key.
|
|
341
|
-
// Using basePath only caused /s?q=a and /s?q=b to share one promise,
|
|
342
|
-
// returning wrong/empty results for search and filtered PLPs.
|
|
343
|
-
//
|
|
344
|
-
// SSR and client-nav produce the same eager/deferred split now, so the
|
|
345
|
-
// original reason for the `__nav:` bucket — a client-nav request must never
|
|
346
|
-
// inherit an SSR response's deferredSections (#277) — no longer applies. It
|
|
347
|
-
// is kept anyway, because this map is module-global and the payload it
|
|
348
|
-
// shares carries `pageUrl`, `flags`, and `device` derived from whichever
|
|
349
|
-
// request won the race. That cross-request bleed is pre-existing and wider
|
|
350
|
-
// than this bucket (two concurrent same-path requests already collide on
|
|
351
|
-
// cookies/UA/geo), but SSR and client-nav are exactly the pair whose
|
|
352
|
-
// `derivePageUrl` inputs differ most, so collapsing them would widen a
|
|
353
|
-
// known hole for no gain. `resolveGlobals` is part of the key for the same
|
|
354
|
-
// reason: a `resolveGlobals: false` request must not share a promise with a
|
|
355
|
-
// `resolveGlobals: true` one.
|
|
356
|
-
const clientNav = isClientNavigation(fullPath, getRequestUrl());
|
|
357
|
-
const inflightKey =
|
|
358
|
-
(clientNav ? `__nav:${fullPath}` : fullPath) + (resolveGlobals ? "" : "|noGlobals");
|
|
359
|
-
const existing = pageInflight.get(inflightKey);
|
|
360
|
-
if (existing) return existing;
|
|
361
|
-
|
|
362
|
-
const promise = loadCmsPageInternal(fullPath, resolveGlobals).finally(() =>
|
|
363
|
-
pageInflight.delete(inflightKey),
|
|
364
|
-
);
|
|
365
|
-
pageInflight.set(inflightKey, promise);
|
|
366
|
-
return promise;
|
|
367
|
-
});
|
|
368
|
-
|
|
369
|
-
/** Accepted by `loadCmsHomePage` — optional so existing no-arg callers keep working. */
|
|
370
|
-
export type LoadCmsHomePageInput = { resolveGlobals?: boolean } | undefined;
|
|
371
|
-
|
|
372
|
-
/** @internal exported for tests */
|
|
373
|
-
export function parseLoadCmsHomePageInput(data: unknown): { resolveGlobals: boolean } {
|
|
374
|
-
const obj = (data ?? {}) as { resolveGlobals?: boolean };
|
|
375
|
-
return { resolveGlobals: obj.resolveGlobals ?? true };
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
/**
|
|
379
|
-
* Same as loadCmsPage but hardcoded to "/" path.
|
|
380
|
-
* Avoids passing data through the server function for the homepage.
|
|
381
|
-
*/
|
|
382
|
-
export const loadCmsHomePage = createServerFn({ method: "GET" })
|
|
383
|
-
.inputValidator((data: unknown) => data as LoadCmsHomePageInput)
|
|
384
|
-
.handler(async (ctx) => {
|
|
385
|
-
const { resolveGlobals } = parseLoadCmsHomePageInput(ctx.data);
|
|
386
|
-
const request = getRequest();
|
|
387
|
-
const ua = getRequestHeader("user-agent") ?? "";
|
|
388
|
-
const serverUrl = getRequestUrl();
|
|
389
|
-
const matcherCtx: MatcherContext = {
|
|
390
|
-
userAgent: ua,
|
|
391
|
-
url: serverUrl.toString(),
|
|
392
|
-
path: "/",
|
|
393
|
-
cookies: getCookies(),
|
|
394
|
-
request,
|
|
395
|
-
isClientNavigation: isClientNavigation("/", serverUrl),
|
|
396
|
-
flags: [],
|
|
397
|
-
};
|
|
398
|
-
const page = await resolveDecoPage("/", matcherCtx);
|
|
399
|
-
if (!page) return null;
|
|
400
|
-
const [{ enrichedSections, enrichedSeoSection }, { globals, enrichedGlobals }] =
|
|
401
|
-
await Promise.all([
|
|
402
|
-
runSectionLoadersWithSeo(page.resolvedSections, page.seoSection, request),
|
|
403
|
-
(async () => {
|
|
404
|
-
const globals = resolveGlobals ? await resolveSiteGlobals(matcherCtx) : EMPTY_GLOBALS;
|
|
405
|
-
return {
|
|
406
|
-
globals,
|
|
407
|
-
enrichedGlobals: await enrichGlobals(
|
|
408
|
-
globals.resolvedSections,
|
|
409
|
-
page.resolvedSections,
|
|
410
|
-
request,
|
|
411
|
-
),
|
|
412
|
-
};
|
|
413
|
-
})(),
|
|
414
|
-
]);
|
|
415
|
-
const flags = persistFlags(matcherCtx, takeExperimentAssignments());
|
|
416
|
-
|
|
417
|
-
const mergedSections: ResolvedSection[] = [...enrichedGlobals, ...enrichedSections];
|
|
418
|
-
|
|
419
|
-
const eagerKeys = mergedSections.map((s) => s.component);
|
|
420
|
-
await preloadSectionComponents(eagerKeys);
|
|
421
|
-
|
|
422
|
-
const device = detectDevice(ua);
|
|
423
|
-
const seo = buildPageSeo(
|
|
424
|
-
page.seoSection,
|
|
425
|
-
enrichedSeoSection,
|
|
426
|
-
mergedSections,
|
|
427
|
-
isEagerRequest(matcherCtx),
|
|
428
|
-
);
|
|
429
|
-
|
|
430
|
-
const { seoSection: _seo, ...pageData } = page;
|
|
431
|
-
|
|
432
|
-
// Same anti-cache-poisoning flag as loadCmsPageInternal — the homepage is the
|
|
433
|
-
// highest-traffic, most-cached route, so it must not be exempt. The actual
|
|
434
|
-
// X-Deco-Degraded header is emitted by the route `headers:` callback from
|
|
435
|
-
// this `degraded` field (a reliable document-response channel).
|
|
436
|
-
const degraded = getDegradedSections();
|
|
437
|
-
if (degraded.length > 0) {
|
|
438
|
-
console.warn(`[cms] home degraded — critical sections failed: ${degraded.join(", ")}`);
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
return {
|
|
442
|
-
...pageData,
|
|
443
|
-
resolvedSections: normalizeUrlsInObject(mergedSections),
|
|
444
|
-
deferredSections: normalizeUrlsInObject(page.deferredSections),
|
|
445
|
-
degraded: degraded.length > 0,
|
|
446
|
-
pagePath: "/",
|
|
447
|
-
pageUrl: serverUrl.toString(),
|
|
448
|
-
seo,
|
|
449
|
-
device,
|
|
450
|
-
flags,
|
|
451
|
-
siteGlobals: { rawRefs: globals.rawRefs },
|
|
452
|
-
};
|
|
453
|
-
});
|
|
454
|
-
|
|
455
|
-
// ---------------------------------------------------------------------------
|
|
456
|
-
// Deferred section loader — resolves + enriches a single section on demand
|
|
457
|
-
// ---------------------------------------------------------------------------
|
|
458
|
-
|
|
459
|
-
/**
|
|
460
|
-
* Resolves + enriches a single deferred section on demand, server-side.
|
|
461
|
-
*
|
|
462
|
-
* This is the deferred-resolution path for BOTH the initial SSR document and
|
|
463
|
-
* client (SPA) navigations — `deferredPromises`/TanStack native streaming is
|
|
464
|
-
* SSR-only, because promises cannot cross the server-fn JSON boundary. It
|
|
465
|
-
* rebuilds `MatcherContext` from the real incoming request (url/path/cookies/
|
|
466
|
-
* request), so the second hop sees the same per-request state the first one did
|
|
467
|
-
* (the `deco_segment` cookie set by the page response is already present, so
|
|
468
|
-
* sticky A/B decisions stay consistent — `flags` is intentionally left unset
|
|
469
|
-
* here: this response must not re-roll or re-persist the cohort cookie).
|
|
470
|
-
*/
|
|
471
|
-
export const loadDeferredSection = createServerFn({ method: "POST" })
|
|
472
|
-
.inputValidator(
|
|
473
|
-
(data: unknown) =>
|
|
474
|
-
data as {
|
|
475
|
-
component: string;
|
|
476
|
-
/** @deprecated rawProps are now resolved server-side from the deferred props cache. */
|
|
477
|
-
rawProps?: Record<string, any>;
|
|
478
|
-
pagePath: string;
|
|
479
|
-
pageUrl?: string;
|
|
480
|
-
/** Original position in the page section list — preserved for correct SPA ordering. */
|
|
481
|
-
index?: number;
|
|
482
|
-
},
|
|
483
|
-
)
|
|
484
|
-
.handler(async (ctx) => {
|
|
485
|
-
const { component, rawProps: clientRawProps, pagePath, pageUrl, index } = ctx.data;
|
|
486
|
-
|
|
487
|
-
const originRequest = getRequest();
|
|
488
|
-
const serverUrl = getRequestUrl().toString();
|
|
489
|
-
const matcherCtx: MatcherContext = {
|
|
490
|
-
userAgent: getRequestHeader("user-agent") ?? "",
|
|
491
|
-
url: pageUrl || serverUrl,
|
|
492
|
-
path: pagePath,
|
|
493
|
-
cookies: getCookies(),
|
|
494
|
-
request: originRequest,
|
|
495
|
-
};
|
|
496
|
-
|
|
497
|
-
// Resolve rawProps: prefer client-provided (backward compat), then server cache,
|
|
498
|
-
// then re-extract from the page as a last resort (handles cross-isolate cache miss
|
|
499
|
-
// on Cloudflare Workers and TTL expiry for slow-scrolling users).
|
|
500
|
-
const rawProps =
|
|
501
|
-
clientRawProps ??
|
|
502
|
-
(index !== undefined ? getDeferredRawProps(pagePath, component, index) : null) ??
|
|
503
|
-
(index !== undefined
|
|
504
|
-
? await reExtractRawProps(pagePath, component, index, matcherCtx)
|
|
505
|
-
: null);
|
|
506
|
-
|
|
507
|
-
if (!rawProps) {
|
|
508
|
-
console.warn(
|
|
509
|
-
`[CMS] Deferred section cache miss: ${component} at index ${index} on ${pagePath}`,
|
|
510
|
-
);
|
|
511
|
-
return null;
|
|
512
|
-
}
|
|
513
|
-
|
|
514
|
-
const section = await withTracing(
|
|
515
|
-
"deco.section.deferred.load",
|
|
516
|
-
() => resolveDeferredSection(component, rawProps, pagePath, matcherCtx),
|
|
517
|
-
{
|
|
518
|
-
"section.name": component,
|
|
519
|
-
"page.path": pagePath,
|
|
520
|
-
...(typeof index === "number" ? { "section.index": index } : {}),
|
|
521
|
-
},
|
|
522
|
-
);
|
|
523
|
-
if (!section) return null;
|
|
524
|
-
|
|
525
|
-
// Preserve original index for correct ordering in SPA navigation merge
|
|
526
|
-
if (index !== undefined) section.index = index;
|
|
527
|
-
|
|
528
|
-
const request = new Request(pageUrl || serverUrl, {
|
|
529
|
-
headers: originRequest.headers,
|
|
530
|
-
});
|
|
531
|
-
const enriched = await runSingleSectionLoader(section, request);
|
|
532
|
-
|
|
533
|
-
// Anti-cache-poisoning: if this deferred section's loader failed (e.g. an
|
|
534
|
-
// empty product shelf during a VTEX outage), do NOT mark it cacheable —
|
|
535
|
-
// otherwise the empty shelf would be stored in serverFnCache and served to
|
|
536
|
-
// every visitor for the full retention window. Flag it degraded instead.
|
|
537
|
-
if (getDegradedSections().length > 0) {
|
|
538
|
-
setResponseHeader("X-Deco-Degraded", "true");
|
|
539
|
-
} else {
|
|
540
|
-
// Signal to the worker entry that this response is safe to edge-cache.
|
|
541
|
-
// Without this header, POST _serverFn responses are passed through
|
|
542
|
-
// without caching (checkout actions, invoke mutations, etc.).
|
|
543
|
-
setResponseHeader("X-Deco-Cacheable", "true");
|
|
544
|
-
}
|
|
545
|
-
|
|
546
|
-
return normalizeUrlsInObject(enriched);
|
|
547
|
-
});
|
|
548
|
-
|
|
549
|
-
// ---------------------------------------------------------------------------
|
|
550
|
-
// Default pending component — shown during SPA navigation while loader runs
|
|
551
|
-
// ---------------------------------------------------------------------------
|
|
552
|
-
|
|
553
|
-
export function CmsPagePendingFallback() {
|
|
554
|
-
return createElement(
|
|
555
|
-
"div",
|
|
556
|
-
{ className: "w-full min-h-[60vh] flex flex-col gap-6 py-8" },
|
|
557
|
-
createElement("div", {
|
|
558
|
-
className: "skeleton animate-pulse w-full rounded",
|
|
559
|
-
style: { aspectRatio: "1440/400", minHeight: 200 },
|
|
560
|
-
}),
|
|
561
|
-
createElement(
|
|
562
|
-
"div",
|
|
563
|
-
{ className: "px-4 lg:px-8 flex flex-col gap-4" },
|
|
564
|
-
createElement("div", { className: "skeleton animate-pulse w-48 h-8 rounded" }),
|
|
565
|
-
createElement(
|
|
566
|
-
"div",
|
|
567
|
-
{ className: "grid grid-cols-2 lg:grid-cols-4 gap-4" },
|
|
568
|
-
...Array.from({ length: 4 }, (_, i) =>
|
|
569
|
-
createElement("div", {
|
|
570
|
-
key: i,
|
|
571
|
-
className: "skeleton animate-pulse w-full h-48 lg:h-64 rounded",
|
|
572
|
-
}),
|
|
573
|
-
),
|
|
574
|
-
),
|
|
575
|
-
),
|
|
576
|
-
);
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
/**
|
|
580
|
-
* Default branded error boundary for CMS routes. Rendered when page resolution
|
|
581
|
-
* throws (as opposed to returning no match, which is a 404 / not-found path) —
|
|
582
|
-
* e.g. an uncaught throw in `resolveDecoPage` / `buildPageSeo` /
|
|
583
|
-
* `resolveSiteGlobals` during a VTEX outage. Without an `errorComponent` the
|
|
584
|
-
* loader rejection surfaces as a raw 500 white screen.
|
|
585
|
-
*
|
|
586
|
-
* This is the COLD-CACHE last resort: whenever a warm edge entry exists the
|
|
587
|
-
* worker serves it as `STALE-ERROR` before the request ever reaches here.
|
|
588
|
-
* Sites override via `cmsRouteConfig({ errorComponent })`.
|
|
589
|
-
*/
|
|
590
|
-
export function CmsPageErrorFallback(props: { reset?: () => void }) {
|
|
591
|
-
return createElement(
|
|
592
|
-
"div",
|
|
593
|
-
{ className: "min-h-[60vh] flex items-center justify-center px-4 text-center" },
|
|
594
|
-
createElement(
|
|
595
|
-
"div",
|
|
596
|
-
{ className: "max-w-md flex flex-col items-center gap-4" },
|
|
597
|
-
createElement("h1", { className: "text-2xl font-bold" }, "Estamos com uma instabilidade"),
|
|
598
|
-
createElement(
|
|
599
|
-
"p",
|
|
600
|
-
{ className: "opacity-70" },
|
|
601
|
-
"Não conseguimos carregar esta página agora. Tente novamente em instantes.",
|
|
602
|
-
),
|
|
603
|
-
createElement(
|
|
604
|
-
"button",
|
|
605
|
-
{
|
|
606
|
-
type: "button",
|
|
607
|
-
className: "btn btn-primary",
|
|
608
|
-
onClick: () => (props.reset ? props.reset() : undefined),
|
|
609
|
-
},
|
|
610
|
-
"Tentar de novo",
|
|
611
|
-
),
|
|
612
|
-
),
|
|
613
|
-
);
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
// ---------------------------------------------------------------------------
|
|
617
|
-
// Route configuration factory
|
|
618
|
-
// ---------------------------------------------------------------------------
|
|
619
|
-
|
|
620
|
-
export interface CmsRouteOptions {
|
|
621
|
-
/** Site name used in page titles (e.g. "Espaço Smart"). */
|
|
622
|
-
siteName: string;
|
|
623
|
-
/** Default page title when CMS page has no name. */
|
|
624
|
-
defaultTitle: string;
|
|
625
|
-
/** Default description for pages without section-contributed SEO. */
|
|
626
|
-
defaultDescription?: string;
|
|
627
|
-
/**
|
|
628
|
-
* Search params to exclude from loader deps.
|
|
629
|
-
* These params won't trigger a server re-fetch when they change.
|
|
630
|
-
* Defaults to `["skuId"]` — variant selection is client-side only.
|
|
631
|
-
*/
|
|
632
|
-
ignoreSearchParams?: string[];
|
|
633
|
-
/**
|
|
634
|
-
* Pending component shown during SPA navigation while the route loader runs.
|
|
635
|
-
*
|
|
636
|
-
* NO DEFAULT, deliberately. With none set, TanStack keeps the previous page on
|
|
637
|
-
* screen until the new one commits — which at the sub-second latencies this
|
|
638
|
-
* route now sees is usually the better feel. Setting one buys feedback on a
|
|
639
|
-
* slow navigation at the cost of a page → skeleton → page swap on every
|
|
640
|
-
* navigation slower than {@link pendingMs} (held for at least
|
|
641
|
-
* {@link pendingMinMs}), and this is a *catch-all* route, so one skeleton
|
|
642
|
-
* shape has to serve PDP, PLP, search, and institutional pages alike.
|
|
643
|
-
* {@link CmsPagePendingFallback} is exported as a starting point; prefer a
|
|
644
|
-
* per-shape skeleton, or `NavigationProgress` (`@decocms/tanstack`) for
|
|
645
|
-
* feedback that does not replace the page at all.
|
|
646
|
-
*/
|
|
647
|
-
pendingComponent?: (() => any) | null;
|
|
648
|
-
/**
|
|
649
|
-
* Custom error boundary rendered when the loader / page resolution throws.
|
|
650
|
-
* Defaults to {@link CmsPageErrorFallback} (branded "instability" page with a
|
|
651
|
-
* retry button) so an outage degrades gracefully instead of a raw 500.
|
|
652
|
-
* Receives TanStack Router's `{ error, reset }`.
|
|
653
|
-
*/
|
|
654
|
-
errorComponent?: (props: { error: Error; reset: () => void }) => any;
|
|
655
|
-
/**
|
|
656
|
-
* Delay (ms) before showing the pending component during SPA navigation.
|
|
657
|
-
* If the loader resolves before this threshold, no pending UI is shown.
|
|
658
|
-
* Prevents skeleton flash on fast cache-hit navigations. Default: 200.
|
|
659
|
-
* Inert unless {@link pendingComponent} is set.
|
|
660
|
-
*
|
|
661
|
-
* This is a *catch-all* route, so the same value covers a sub-100ms PLP facet
|
|
662
|
-
* toggle and a cold PDP. Raising it only DELAYS the skeleton on the slow
|
|
663
|
-
* navigation (a 1s `pendingMs` still shows it on a 2s nav) — it does not
|
|
664
|
-
* suppress it. Use {@link pendingMinMs} for the flicker case where the loader
|
|
665
|
-
* lands just after the threshold.
|
|
666
|
-
*/
|
|
667
|
-
pendingMs?: number;
|
|
668
|
-
/**
|
|
669
|
-
* Minimum display time (ms) for the pending component once shown.
|
|
670
|
-
* Prevents jarring flash when data arrives shortly after the threshold.
|
|
671
|
-
* Default: 300. Inert unless {@link pendingComponent} is set.
|
|
672
|
-
*
|
|
673
|
-
* Independent of {@link pendingMs}, and applied after it: worst-case a
|
|
674
|
-
* navigation is held for `pendingMs + pendingMinMs` of visible skeleton
|
|
675
|
-
* before the new page commits.
|
|
676
|
-
*/
|
|
677
|
-
pendingMinMs?: number;
|
|
678
|
-
/**
|
|
679
|
-
* SSR mode for this route.
|
|
680
|
-
* - `true` (default): Full SSR — loader + component render on server.
|
|
681
|
-
* - `'data-only'`: Loader runs on server, component renders on client only.
|
|
682
|
-
* Use for interactive-heavy pages (PDP with zoom/variant selector).
|
|
683
|
-
* - `false`: Everything runs on client only.
|
|
684
|
-
*/
|
|
685
|
-
ssr?: boolean | "data-only";
|
|
686
|
-
/**
|
|
687
|
-
* Resolve `site.theme + site.global + site.pageSections` (the CMS `Site`
|
|
688
|
-
* block) and merge them into every page's sections.
|
|
689
|
-
*
|
|
690
|
-
* Default: `true`. Set to `false` to restore pre-6.7.4 behavior for sites
|
|
691
|
-
* that don't use the `Site` block and don't want it silently activated
|
|
692
|
-
* (see #292) — this also skips the `Theme` section's `<style>` injection,
|
|
693
|
-
* so the site's own `:root` CSS fallbacks apply instead.
|
|
694
|
-
*/
|
|
695
|
-
resolveGlobals?: boolean;
|
|
696
|
-
}
|
|
697
|
-
|
|
698
|
-
type CmsPageLoaderData = {
|
|
699
|
-
name?: string;
|
|
700
|
-
cacheProfile?: CacheProfileName;
|
|
701
|
-
degraded?: boolean;
|
|
702
|
-
seo?: PageSeo;
|
|
703
|
-
device?: Device;
|
|
704
|
-
resolvedSections?: Array<{ component: string }>;
|
|
705
|
-
} | null;
|
|
706
|
-
|
|
707
|
-
// ---------------------------------------------------------------------------
|
|
708
|
-
// Page SEO assembly — merges page.seo block with section-contributed SEO
|
|
709
|
-
// ---------------------------------------------------------------------------
|
|
710
|
-
|
|
711
|
-
/**
|
|
712
|
-
* Process the resolved SEO section from page.seo, apply title/description
|
|
713
|
-
* templates, and merge with section-contributed SEO.
|
|
714
|
-
*
|
|
715
|
-
* `seoSection` is the raw (pre-loader) resolved section — its `props` are
|
|
716
|
-
* used for the CMS-configured `titleTemplate`/`descriptionTemplate` fields,
|
|
717
|
-
* which a loader transforming `{jsonLD} → {title, description}` may not
|
|
718
|
-
* pass through unchanged. `enrichedSeoSection` must already have gone
|
|
719
|
-
* through that registered section loader (e.g., SEOPDP transforms
|
|
720
|
-
* {jsonLD: ProductDetailsPage} → {title, description, ...}) — batched
|
|
721
|
-
* together with the body sections in `runSectionLoadersWithSeo` so a
|
|
722
|
-
* commerce loader shared by both (the same product fetched by both the PDP
|
|
723
|
-
* body section and the SeoPDP section) gets a chance to dedupe at the
|
|
724
|
-
* fetch-cache layer instead of resolving the page twice (#355). This
|
|
725
|
-
* function itself no longer runs any loader.
|
|
726
|
-
*/
|
|
727
|
-
function buildPageSeo(
|
|
728
|
-
seoSection: ResolvedSection | null | undefined,
|
|
729
|
-
enrichedSeoSection: ResolvedSection | null | undefined,
|
|
730
|
-
enrichedSections: ResolvedSection[],
|
|
731
|
-
isEager: boolean,
|
|
732
|
-
): PageSeo {
|
|
733
|
-
// Secondary source: SEO sections embedded in the sections array.
|
|
734
|
-
// `isEager` keeps structured-data suppression bot-aware: humans skip the
|
|
735
|
-
// JSON-LD when `ignoreStructuredData` is on; crawlers still get it.
|
|
736
|
-
const sectionSeo = extractSeoFromSections(enrichedSections, { isEager });
|
|
737
|
-
|
|
738
|
-
// Site-wide SEO config from the "Site" app block — mirrors ctx.seo in
|
|
739
|
-
// the original deco-cx/deco framework. Provides fallback title,
|
|
740
|
-
// description, and templates when page-level seo doesn't supply them.
|
|
741
|
-
const siteSeo = getSiteSeo();
|
|
742
|
-
|
|
743
|
-
if (!seoSection) {
|
|
744
|
-
// No page.seo block — use site-wide SEO as primary, section-contributed as secondary
|
|
745
|
-
const merged: PageSeo = { ...sectionSeo };
|
|
746
|
-
if (siteSeo.title && !merged.title) merged.title = siteSeo.title;
|
|
747
|
-
if (siteSeo.description && !merged.description) merged.description = siteSeo.description;
|
|
748
|
-
if (siteSeo.image && !merged.image) merged.image = siteSeo.image;
|
|
749
|
-
|
|
750
|
-
// Apply site-level templates even when there is no page-level seo
|
|
751
|
-
// section. Without this, pages whose title comes from a content
|
|
752
|
-
// section (e.g. <h1> + sectionSeo) or from the site default would
|
|
753
|
-
// skip `siteSeo.titleTemplate`, causing prod-vs-worker title drift.
|
|
754
|
-
const titleTemplate = effectiveTemplate(siteSeo.titleTemplate);
|
|
755
|
-
const descTemplate = effectiveTemplate(siteSeo.descriptionTemplate);
|
|
756
|
-
if (titleTemplate && merged.title) {
|
|
757
|
-
merged.title = titleTemplate.replace("%s", merged.title);
|
|
758
|
-
}
|
|
759
|
-
if (descTemplate && merged.description) {
|
|
760
|
-
merged.description = descTemplate.replace("%s", merged.description);
|
|
761
|
-
}
|
|
762
|
-
|
|
763
|
-
return merged;
|
|
764
|
-
}
|
|
765
|
-
|
|
766
|
-
// enrichedSeoSection should always be present once seoSection is, but
|
|
767
|
-
// fall back to the raw section's props (pre-loader) if the loader batch
|
|
768
|
-
// somehow dropped it — same "use the raw resolved props" resilience the
|
|
769
|
-
// old inline try/catch had around the loader call.
|
|
770
|
-
const enrichedProps = (enrichedSeoSection ?? seoSection).props;
|
|
771
|
-
const pageSeo = extractSeoFromProps(enrichedProps, { isEager });
|
|
772
|
-
|
|
773
|
-
// Replicate original SeoV2 loader logic: `_title ?? appTitle`
|
|
774
|
-
// When the page's seo block doesn't have a title/description,
|
|
775
|
-
// fall back to the Site app's seo config.
|
|
776
|
-
if (!pageSeo.title && siteSeo.title) pageSeo.title = siteSeo.title;
|
|
777
|
-
if (!pageSeo.description && siteSeo.description) pageSeo.description = siteSeo.description;
|
|
778
|
-
if (!pageSeo.image && siteSeo.image) pageSeo.image = siteSeo.image;
|
|
779
|
-
|
|
780
|
-
// Apply title/description templates.
|
|
781
|
-
// Priority: page-level template → site-level template → no-op.
|
|
782
|
-
// This mirrors the original: `(titleTemplate ?? "").trim().length === 0 ? "%s" : titleTemplate`
|
|
783
|
-
const rawProps = seoSection.props;
|
|
784
|
-
const titleTemplate =
|
|
785
|
-
effectiveTemplate(rawProps.titleTemplate as string | undefined) ??
|
|
786
|
-
effectiveTemplate(siteSeo.titleTemplate);
|
|
787
|
-
const descTemplate =
|
|
788
|
-
effectiveTemplate(rawProps.descriptionTemplate as string | undefined) ??
|
|
789
|
-
effectiveTemplate(siteSeo.descriptionTemplate);
|
|
790
|
-
|
|
791
|
-
if (titleTemplate && pageSeo.title) {
|
|
792
|
-
pageSeo.title = titleTemplate.replace("%s", pageSeo.title);
|
|
793
|
-
}
|
|
794
|
-
if (descTemplate && pageSeo.description) {
|
|
795
|
-
pageSeo.description = descTemplate.replace("%s", pageSeo.description);
|
|
796
|
-
}
|
|
797
|
-
|
|
798
|
-
// Primary source (page.seo) overrides secondary (section-contributed).
|
|
799
|
-
// Only truthy fields in pageSeo override — undefined keys don't clear sectionSeo.
|
|
800
|
-
return { ...sectionSeo, ...pageSeo };
|
|
801
|
-
}
|
|
802
|
-
|
|
803
|
-
/** Returns a non-trivial template string, or undefined for "%s" / empty / blank. */
|
|
804
|
-
function effectiveTemplate(tmpl: string | undefined): string | undefined {
|
|
805
|
-
if (!tmpl || tmpl.trim() === "" || tmpl.trim() === "%s") return undefined;
|
|
806
|
-
return tmpl;
|
|
807
|
-
}
|
|
808
|
-
|
|
809
|
-
// ---------------------------------------------------------------------------
|
|
810
|
-
// Head metadata builder
|
|
811
|
-
// ---------------------------------------------------------------------------
|
|
812
|
-
|
|
813
|
-
/**
|
|
814
|
-
* Build TanStack Router `head()` metadata from page-level and section-contributed SEO.
|
|
815
|
-
* Emits: title, description, canonical, OG tags, Twitter Card, robots directive.
|
|
816
|
-
*/
|
|
817
|
-
function buildHead(
|
|
818
|
-
loaderData: CmsPageLoaderData | undefined,
|
|
819
|
-
siteName: string,
|
|
820
|
-
defaultTitle: string,
|
|
821
|
-
defaultDescription?: string,
|
|
822
|
-
) {
|
|
823
|
-
const seo = loaderData?.seo;
|
|
824
|
-
const title = seo?.title
|
|
825
|
-
? seo.title
|
|
826
|
-
: loaderData?.name
|
|
827
|
-
? `${loaderData.name} | ${siteName}`
|
|
828
|
-
: defaultTitle;
|
|
829
|
-
const description = seo?.description || defaultDescription;
|
|
830
|
-
const image = seo?.image;
|
|
831
|
-
const canonical = seo?.canonical;
|
|
832
|
-
const noIndex = seo?.noIndexing;
|
|
833
|
-
|
|
834
|
-
const meta: Record<string, string>[] = [{ title }];
|
|
835
|
-
|
|
836
|
-
if (description) {
|
|
837
|
-
meta.push({ name: "description", content: description });
|
|
838
|
-
}
|
|
839
|
-
|
|
840
|
-
// Robots — always emit a directive so crawlers see an explicit signal
|
|
841
|
-
meta.push({
|
|
842
|
-
name: "robots",
|
|
843
|
-
content: noIndex
|
|
844
|
-
? "noindex, nofollow"
|
|
845
|
-
: "index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1",
|
|
846
|
-
});
|
|
847
|
-
|
|
848
|
-
// Open Graph
|
|
849
|
-
meta.push({ property: "og:title", content: title });
|
|
850
|
-
if (description) meta.push({ property: "og:description", content: description });
|
|
851
|
-
if (image) meta.push({ property: "og:image", content: image });
|
|
852
|
-
meta.push({ property: "og:type", content: seo?.type || "website" });
|
|
853
|
-
if (canonical) meta.push({ property: "og:url", content: canonical });
|
|
854
|
-
|
|
855
|
-
// Twitter Card
|
|
856
|
-
meta.push({ name: "twitter:card", content: image ? "summary_large_image" : "summary" });
|
|
857
|
-
meta.push({ name: "twitter:title", content: title });
|
|
858
|
-
if (description) meta.push({ name: "twitter:description", content: description });
|
|
859
|
-
if (image) meta.push({ name: "twitter:image", content: image });
|
|
860
|
-
|
|
861
|
-
const links: Record<string, string>[] = [];
|
|
862
|
-
if (canonical) {
|
|
863
|
-
links.push({ rel: "canonical", href: canonical });
|
|
864
|
-
}
|
|
865
|
-
|
|
866
|
-
// Modulepreload hints for eager section chunks
|
|
867
|
-
if (loaderData?.resolvedSections) {
|
|
868
|
-
for (const s of loaderData.resolvedSections) {
|
|
869
|
-
const chunkFile = sectionChunkMap[s.component];
|
|
870
|
-
if (chunkFile) {
|
|
871
|
-
links.push({ rel: "modulepreload", href: `/${chunkFile}` });
|
|
872
|
-
}
|
|
873
|
-
}
|
|
874
|
-
}
|
|
875
|
-
|
|
876
|
-
// JSON-LD structured data — rendered as <script type="application/ld+json"> in <head>
|
|
877
|
-
const scripts: Array<{ type: string; children: string }> = [];
|
|
878
|
-
if (seo?.jsonLDs?.length) {
|
|
879
|
-
for (const jsonLD of seo.jsonLDs) {
|
|
880
|
-
scripts.push({
|
|
881
|
-
type: "application/ld+json",
|
|
882
|
-
children: JSON.stringify(jsonLD),
|
|
883
|
-
});
|
|
884
|
-
}
|
|
885
|
-
}
|
|
886
|
-
|
|
887
|
-
return { meta, links, scripts };
|
|
888
|
-
}
|
|
889
|
-
|
|
890
|
-
/**
|
|
891
|
-
* Returns a TanStack Router route config object for a CMS catch-all route.
|
|
892
|
-
* Spread the result into your `createFileRoute("/$")({...})` call.
|
|
893
|
-
*
|
|
894
|
-
* Includes: loaderDeps, loader, headers, head (with full SEO), staleTime/gcTime.
|
|
895
|
-
* Does NOT include: component, notFoundComponent (site provides these).
|
|
896
|
-
*
|
|
897
|
-
* SEO metadata is extracted from sections registered via `registerSeoSections()`.
|
|
898
|
-
* The `head()` function emits title, description, canonical, OG tags, and robots.
|
|
899
|
-
*/
|
|
900
|
-
export function cmsRouteConfig(options: CmsRouteOptions) {
|
|
901
|
-
const {
|
|
902
|
-
siteName,
|
|
903
|
-
defaultTitle,
|
|
904
|
-
defaultDescription,
|
|
905
|
-
ignoreSearchParams = ["skuId"],
|
|
906
|
-
pendingComponent,
|
|
907
|
-
pendingMs = 200,
|
|
908
|
-
pendingMinMs = 300,
|
|
909
|
-
ssr: ssrMode,
|
|
910
|
-
errorComponent = CmsPageErrorFallback,
|
|
911
|
-
resolveGlobals,
|
|
912
|
-
} = options;
|
|
913
|
-
|
|
914
|
-
const ignoreSet = new Set(ignoreSearchParams);
|
|
915
|
-
|
|
916
|
-
return {
|
|
917
|
-
// Catch-all search validation: preserve all URL search params so they
|
|
918
|
-
// reach loaderDeps. Without this, TanStack Router may strip unknown
|
|
919
|
-
// params (e.g. ?q=, filter.*, page, sort) during SPA navigation.
|
|
920
|
-
validateSearch: (search: Record<string, unknown>) => search as Record<string, string>,
|
|
921
|
-
|
|
922
|
-
loaderDeps: ({ search }: { search: Record<string, string> }) => {
|
|
923
|
-
const filtered = Object.fromEntries(
|
|
924
|
-
Object.entries(search ?? {}).filter(([k]) => !ignoreSet.has(k)),
|
|
925
|
-
);
|
|
926
|
-
return {
|
|
927
|
-
search: Object.keys(filtered).length ? filtered : undefined,
|
|
928
|
-
};
|
|
929
|
-
},
|
|
930
|
-
|
|
931
|
-
loader: async ({
|
|
932
|
-
params,
|
|
933
|
-
deps,
|
|
934
|
-
}: {
|
|
935
|
-
params: { _splat?: string };
|
|
936
|
-
deps: { search?: Record<string, string> };
|
|
937
|
-
}) => {
|
|
938
|
-
const basePath = "/" + (params._splat || "");
|
|
939
|
-
const searchStr = deps.search
|
|
940
|
-
? "?" + new URLSearchParams(deps.search as Record<string, string>).toString()
|
|
941
|
-
: "";
|
|
942
|
-
const page = await loadCmsPage({
|
|
943
|
-
data: { path: basePath + searchStr, resolveGlobals },
|
|
944
|
-
});
|
|
945
|
-
if (!page) return page;
|
|
946
|
-
|
|
947
|
-
if (!isServer && page.resolvedSections) {
|
|
948
|
-
const keys = page.resolvedSections.map((s: ResolvedSection) => s.component);
|
|
949
|
-
await preloadSectionComponents(keys);
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
// Deferred sections use client-side IntersectionObserver loading.
|
|
953
|
-
// DecoPageRenderer renders skeletons (LoadingFallback) during SSR and
|
|
954
|
-
// loads full section content via _serverFn when scrolled into view.
|
|
955
|
-
//
|
|
956
|
-
// Previously, SSR streaming via TanStack <Await> resolved ALL deferred
|
|
957
|
-
// sections server-side and streamed them in the initial HTML. This caused
|
|
958
|
-
// the browser to load ALL product shelf images at once (~3x more image
|
|
959
|
-
// requests than the IntersectionObserver path). Client SPA navigation
|
|
960
|
-
// also blocked on await Promise.all() for all deferred sections.
|
|
961
|
-
//
|
|
962
|
-
// The IO path (DeferredSectionWrapper) only fetches section data when
|
|
963
|
-
// the skeleton scrolls into view, matching Fresh/Deno partial behavior
|
|
964
|
-
// and significantly reducing initial image load and TBT.
|
|
965
|
-
return page;
|
|
966
|
-
},
|
|
967
|
-
|
|
968
|
-
...(pendingComponent ? { pendingComponent } : {}),
|
|
969
|
-
pendingMs,
|
|
970
|
-
pendingMinMs,
|
|
971
|
-
errorComponent,
|
|
972
|
-
...(ssrMode !== undefined ? { ssr: ssrMode } : {}),
|
|
973
|
-
|
|
974
|
-
...routeCacheDefaults("product"),
|
|
975
|
-
|
|
976
|
-
headers: ({ loaderData }: { loaderData?: CmsPageLoaderData }) => {
|
|
977
|
-
const profile = loaderData?.cacheProfile ?? "listing";
|
|
978
|
-
const headers = cacheHeaders(profile);
|
|
979
|
-
// Emit the degraded flag on the DOCUMENT response via the route headers
|
|
980
|
-
// callback — the reliable channel (same one cacheHeaders rides), unlike
|
|
981
|
-
// setResponseHeader inside the server fn which may not reach the document.
|
|
982
|
-
// The worker treats a 200 + X-Deco-Degraded like a 5xx (no store, serve
|
|
983
|
-
// stale) to prevent caching an empty page during a VTEX outage.
|
|
984
|
-
if (loaderData?.degraded) headers["X-Deco-Degraded"] = "true";
|
|
985
|
-
return headers;
|
|
986
|
-
},
|
|
987
|
-
|
|
988
|
-
head: ({ loaderData }: { loaderData?: CmsPageLoaderData }) =>
|
|
989
|
-
buildHead(loaderData, siteName, defaultTitle, defaultDescription),
|
|
990
|
-
};
|
|
991
|
-
}
|
|
992
|
-
|
|
993
|
-
/**
|
|
994
|
-
* Returns a TanStack Router route config for the CMS homepage route.
|
|
995
|
-
* Spread into `createFileRoute("/")({...})`.
|
|
996
|
-
*
|
|
997
|
-
* Like `cmsRouteConfig`, emits full SEO head metadata from section-contributed data.
|
|
998
|
-
*/
|
|
999
|
-
export function cmsHomeRouteConfig(options: {
|
|
1000
|
-
defaultTitle: string;
|
|
1001
|
-
defaultDescription?: string;
|
|
1002
|
-
/** Site name for OG title composition. Defaults to defaultTitle. */
|
|
1003
|
-
siteName?: string;
|
|
1004
|
-
/** See `CmsRouteOptions.pendingComponent` — no default, deliberately. */
|
|
1005
|
-
pendingComponent?: (() => any) | null;
|
|
1006
|
-
/** Delay (ms) before showing pending component. Default: 200. */
|
|
1007
|
-
pendingMs?: number;
|
|
1008
|
-
/** Minimum display time (ms) for pending component. Default: 300. */
|
|
1009
|
-
pendingMinMs?: number;
|
|
1010
|
-
/** Error boundary for loader throws. Defaults to {@link CmsPageErrorFallback}. */
|
|
1011
|
-
errorComponent?: (props: { error: Error; reset: () => void }) => any;
|
|
1012
|
-
/** See `CmsRouteOptions.resolveGlobals` — default `true`. */
|
|
1013
|
-
resolveGlobals?: boolean;
|
|
1014
|
-
}) {
|
|
1015
|
-
const {
|
|
1016
|
-
defaultTitle,
|
|
1017
|
-
defaultDescription,
|
|
1018
|
-
siteName,
|
|
1019
|
-
pendingComponent,
|
|
1020
|
-
pendingMs = 200,
|
|
1021
|
-
pendingMinMs = 300,
|
|
1022
|
-
errorComponent = CmsPageErrorFallback,
|
|
1023
|
-
resolveGlobals,
|
|
1024
|
-
} = options;
|
|
1025
|
-
|
|
1026
|
-
return {
|
|
1027
|
-
loader: async () => {
|
|
1028
|
-
const page = await loadCmsHomePage({ data: { resolveGlobals } });
|
|
1029
|
-
if (!page) return page;
|
|
1030
|
-
|
|
1031
|
-
if (!isServer && page.resolvedSections) {
|
|
1032
|
-
const keys = page.resolvedSections.map((s: ResolvedSection) => s.component);
|
|
1033
|
-
await preloadSectionComponents(keys);
|
|
1034
|
-
}
|
|
1035
|
-
|
|
1036
|
-
// Deferred sections use client-side IntersectionObserver loading.
|
|
1037
|
-
// See cmsRouteConfig loader for rationale.
|
|
1038
|
-
return page;
|
|
1039
|
-
},
|
|
1040
|
-
...(pendingComponent ? { pendingComponent } : {}),
|
|
1041
|
-
pendingMs,
|
|
1042
|
-
pendingMinMs,
|
|
1043
|
-
errorComponent,
|
|
1044
|
-
...routeCacheDefaults("static"),
|
|
1045
|
-
headers: ({ loaderData }: { loaderData?: CmsPageLoaderData }) => {
|
|
1046
|
-
const headers = cacheHeaders("static");
|
|
1047
|
-
if (loaderData?.degraded) headers["X-Deco-Degraded"] = "true";
|
|
1048
|
-
return headers;
|
|
1049
|
-
},
|
|
1050
|
-
head: ({ loaderData }: { loaderData?: CmsPageLoaderData }) =>
|
|
1051
|
-
buildHead(loaderData, siteName ?? defaultTitle, defaultTitle, defaultDescription),
|
|
1052
|
-
};
|
|
1053
|
-
}
|