@decocms/tanstack 7.47.0 → 7.48.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.
- package/package.json +4 -4
- package/src/hooks/DecoRootLayout.tsx +42 -1
- package/src/index.ts +9 -0
- package/src/routes/cmsRoute.ts +2 -2
- package/src/routes/withSiteGlobals.test.ts +37 -0
- package/src/routes/withSiteGlobals.ts +31 -18
- package/src/sdk/speculationRules.test.ts +82 -0
- package/src/sdk/speculationRules.ts +136 -0
- package/src/sdk/workerEntry.ts +20 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@decocms/tanstack",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.48.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Deco framework binding for TanStack Start + Cloudflare Workers",
|
|
6
6
|
"repository": {
|
|
@@ -24,9 +24,9 @@
|
|
|
24
24
|
"lint:unused": "knip"
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"@decocms/blocks": "7.
|
|
28
|
-
"@decocms/blocks-admin": "7.
|
|
29
|
-
"@decocms/blocks-cli": "7.
|
|
27
|
+
"@decocms/blocks": "7.48.1",
|
|
28
|
+
"@decocms/blocks-admin": "7.48.1",
|
|
29
|
+
"@decocms/blocks-cli": "7.48.1",
|
|
30
30
|
"@deco-cx/warp-node": "^0.3.16",
|
|
31
31
|
"fast-json-patch": "^3.1.0",
|
|
32
32
|
"ws": "^8.18.0"
|
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
import { useEffect, type ReactNode } from "react";
|
|
2
2
|
import { HeadContent, Scripts, ScriptOnce } from "@tanstack/react-router";
|
|
3
3
|
import { LiveControls } from "@decocms/blocks/hooks";
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
ANALYTICS_SCRIPT,
|
|
6
|
+
SPECULATION_DEV_WARN_SCRIPT,
|
|
7
|
+
} from "@decocms/blocks/sdk/analytics";
|
|
8
|
+
import { isDevMode } from "@decocms/blocks/sdk/env";
|
|
9
|
+
import {
|
|
10
|
+
buildSpeculationRules,
|
|
11
|
+
getSpeculationRules,
|
|
12
|
+
type SpeculationRulesConfig,
|
|
13
|
+
} from "../sdk/speculationRules";
|
|
5
14
|
import { DraftPreviewIndicator } from "./DraftPreviewIndicator";
|
|
6
15
|
import { NavigationProgress } from "./NavigationProgress";
|
|
7
16
|
import { StableOutlet } from "./StableOutlet";
|
|
@@ -50,6 +59,17 @@ export interface DecoRootLayoutProps {
|
|
|
50
59
|
bodyClassName?: string;
|
|
51
60
|
/** Delay in ms before firing deco:ready event. Default: 500 */
|
|
52
61
|
decoReadyDelay?: number;
|
|
62
|
+
/**
|
|
63
|
+
* Opt-in Speculation Rules API config override. Normally activated site-wide
|
|
64
|
+
* via `createDecoWorkerEntry({ speculationRules })` (like `asJson` /
|
|
65
|
+
* `renderJson`) and read from that shared config; pass this prop only to
|
|
66
|
+
* override it for a specific root. When set, emits a
|
|
67
|
+
* `<script type="speculationrules">` in <head> so the browser prerenders/
|
|
68
|
+
* prefetches the next document on intent. Ships DISABLED — only activate on
|
|
69
|
+
* sites whose analytics/pixel loaders are prerender-guarded.
|
|
70
|
+
* @see buildSpeculationRules
|
|
71
|
+
*/
|
|
72
|
+
speculationRules?: SpeculationRulesConfig;
|
|
53
73
|
/**
|
|
54
74
|
* Extra content rendered inside <body> after the main outlet
|
|
55
75
|
* (e.g. Toast, custom analytics components).
|
|
@@ -81,6 +101,7 @@ export function DecoRootLayout({
|
|
|
81
101
|
account,
|
|
82
102
|
bodyClassName = "bg-base-200 text-base-content",
|
|
83
103
|
decoReadyDelay = 500,
|
|
104
|
+
speculationRules,
|
|
84
105
|
children,
|
|
85
106
|
}: DecoRootLayoutProps) {
|
|
86
107
|
useEffect(() => {
|
|
@@ -91,10 +112,30 @@ export function DecoRootLayout({
|
|
|
91
112
|
return () => clearTimeout(id);
|
|
92
113
|
}, [decoReadyDelay]);
|
|
93
114
|
|
|
115
|
+
// Worker-entry option wins; prop is a per-root override. Undefined → disabled.
|
|
116
|
+
const speculation = speculationRules ?? getSpeculationRules();
|
|
117
|
+
|
|
94
118
|
return (
|
|
95
119
|
<html lang={lang} data-theme={dataTheme} suppressHydrationWarning>
|
|
96
120
|
<head>
|
|
97
121
|
<HeadContent />
|
|
122
|
+
{speculation && (
|
|
123
|
+
<script
|
|
124
|
+
type="speculationrules"
|
|
125
|
+
// JSON is inert; dangerouslySetInnerHTML avoids React escaping
|
|
126
|
+
// `>` in selectors (e.g. "nav > a"). Same pattern as JSON-LD.
|
|
127
|
+
dangerouslySetInnerHTML={{
|
|
128
|
+
__html: buildSpeculationRules(speculation),
|
|
129
|
+
}}
|
|
130
|
+
/>
|
|
131
|
+
)}
|
|
132
|
+
{/* Dev-only: console.error when analytics fire during a prerender
|
|
133
|
+
so the dev fixes unguarded loaders before shipping. */}
|
|
134
|
+
{speculation && isDevMode() && (
|
|
135
|
+
<script
|
|
136
|
+
dangerouslySetInnerHTML={{ __html: SPECULATION_DEV_WARN_SCRIPT }}
|
|
137
|
+
/>
|
|
138
|
+
)}
|
|
98
139
|
</head>
|
|
99
140
|
<body className={bodyClassName} suppressHydrationWarning>
|
|
100
141
|
<ScriptOnce children={buildDecoEventsBootstrap(account)} />
|
package/src/index.ts
CHANGED
|
@@ -29,6 +29,15 @@ export {
|
|
|
29
29
|
decoStringifySearch,
|
|
30
30
|
} from "./sdk/router";
|
|
31
31
|
export type { CreateDecoRouterOptions } from "./sdk/router";
|
|
32
|
+
export {
|
|
33
|
+
buildSpeculationRules,
|
|
34
|
+
DEFAULT_EXCLUDED_HREF_MATCHES,
|
|
35
|
+
} from "./sdk/speculationRules";
|
|
36
|
+
export type {
|
|
37
|
+
SpeculationAction,
|
|
38
|
+
SpeculationEagerness,
|
|
39
|
+
SpeculationRulesConfig,
|
|
40
|
+
} from "./sdk/speculationRules";
|
|
32
41
|
// createInvokeFn is intentionally NOT re-exported from this root barrel.
|
|
33
42
|
// Its body contains a `createServerFn(...).handler(...)` call that is not a
|
|
34
43
|
// top-level variable declarator (it's returned from a factory function) --
|
package/src/routes/cmsRoute.ts
CHANGED
|
@@ -202,7 +202,7 @@ async function loadCmsPageInternal(fullPath: string, resolveGlobals: boolean) {
|
|
|
202
202
|
// empty client-bundled `blocks.gen.ts`.
|
|
203
203
|
const [{ enrichedSections, enrichedSeoSection }, globals] = await Promise.all([
|
|
204
204
|
runSectionLoadersWithSeo(page.resolvedSections, page.seoSection, request),
|
|
205
|
-
resolveGlobals ? resolveSiteGlobals() : Promise.resolve(EMPTY_GLOBALS),
|
|
205
|
+
resolveGlobals ? resolveSiteGlobals(matcherCtx) : Promise.resolve(EMPTY_GLOBALS),
|
|
206
206
|
]);
|
|
207
207
|
|
|
208
208
|
// Page sections take precedence over globals — dedupe drops any global
|
|
@@ -332,7 +332,7 @@ export const loadCmsHomePage = createServerFn({ method: "GET" })
|
|
|
332
332
|
const flags = persistFlags(matcherCtx);
|
|
333
333
|
const [{ enrichedSections, enrichedSeoSection }, globals] = await Promise.all([
|
|
334
334
|
runSectionLoadersWithSeo(page.resolvedSections, page.seoSection, request),
|
|
335
|
-
resolveGlobals ? resolveSiteGlobals() : Promise.resolve(EMPTY_GLOBALS),
|
|
335
|
+
resolveGlobals ? resolveSiteGlobals(matcherCtx) : Promise.resolve(EMPTY_GLOBALS),
|
|
336
336
|
]);
|
|
337
337
|
|
|
338
338
|
const mergedSections: ResolvedSection[] = [
|
|
@@ -121,6 +121,43 @@ describe("withSiteGlobals", () => {
|
|
|
121
121
|
expect(mockedResolvePageSections).toHaveBeenCalledTimes(1);
|
|
122
122
|
});
|
|
123
123
|
|
|
124
|
+
it("threads matcherCtx to resolvePageSections", async () => {
|
|
125
|
+
mockedLoadBlocks.mockReturnValue({
|
|
126
|
+
site: { global: [{ __resolveType: "Alert" }] },
|
|
127
|
+
});
|
|
128
|
+
mockedResolvePageSections.mockResolvedValue([{ component: "A.tsx", props: {}, key: "k0" }]);
|
|
129
|
+
|
|
130
|
+
const ctx = { path: "/farm-etc" } as any;
|
|
131
|
+
await resolveSiteGlobals(ctx);
|
|
132
|
+
|
|
133
|
+
expect(mockedResolvePageSections).toHaveBeenCalledWith(
|
|
134
|
+
[{ __resolveType: "Alert" }],
|
|
135
|
+
ctx,
|
|
136
|
+
);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it("caches per path — different routes don't share a matched variant", async () => {
|
|
140
|
+
mockedLoadBlocks.mockReturnValue({
|
|
141
|
+
site: { global: [{ __resolveType: "Alert" }] },
|
|
142
|
+
});
|
|
143
|
+
mockedResolvePageSections
|
|
144
|
+
.mockResolvedValueOnce([{ component: "EtcAlert.tsx", props: {}, key: "etc" }])
|
|
145
|
+
.mockResolvedValueOnce([{ component: "HomeAlert.tsx", props: {}, key: "home" }]);
|
|
146
|
+
|
|
147
|
+
const etc = await resolveSiteGlobals({ path: "/farm-etc" } as any);
|
|
148
|
+
const home = await resolveSiteGlobals({ path: "/" } as any);
|
|
149
|
+
|
|
150
|
+
// Distinct paths resolve independently (no cross-route leak)...
|
|
151
|
+
expect(etc.resolvedSections[0].key).toBe("etc");
|
|
152
|
+
expect(home.resolvedSections[0].key).toBe("home");
|
|
153
|
+
expect(mockedResolvePageSections).toHaveBeenCalledTimes(2);
|
|
154
|
+
|
|
155
|
+
// ...and the same path is still served from cache.
|
|
156
|
+
const etcAgain = await resolveSiteGlobals({ path: "/farm-etc" } as any);
|
|
157
|
+
expect(etcAgain.resolvedSections[0].key).toBe("etc");
|
|
158
|
+
expect(mockedResolvePageSections).toHaveBeenCalledTimes(2);
|
|
159
|
+
});
|
|
160
|
+
|
|
124
161
|
it("invalidates cache when onChange fires", async () => {
|
|
125
162
|
mockedLoadBlocks.mockReturnValue({
|
|
126
163
|
site: { global: [{ __resolveType: "Analytics" }] },
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
* ```
|
|
26
26
|
*/
|
|
27
27
|
|
|
28
|
-
import type { ResolvedSection } from "@decocms/blocks/cms";
|
|
28
|
+
import type { MatcherContext, ResolvedSection } from "@decocms/blocks/cms";
|
|
29
29
|
import { loadBlocks, onChange, resolvePageSections } from "@decocms/blocks/cms";
|
|
30
30
|
|
|
31
31
|
// ---------------------------------------------------------------------------
|
|
@@ -73,12 +73,18 @@ interface CacheEntry {
|
|
|
73
73
|
const DEFAULT_CACHE_TTL_MS = 5 * 60_000;
|
|
74
74
|
const cacheTtlMs = DEFAULT_CACHE_TTL_MS;
|
|
75
75
|
|
|
76
|
-
|
|
77
|
-
|
|
76
|
+
// Keyed by request path — site.global/site.pageSections can contain
|
|
77
|
+
// path-dependent matchers (pathname, multi(ETC Segment), date, etc.), so a
|
|
78
|
+
// single process-wide cache entry would leak one route's matched variant onto
|
|
79
|
+
// every other route (e.g. a /section-only alert winning on "/"). Caching a
|
|
80
|
+
// resolvedSections array per path preserves the original 5-minute SWR behavior
|
|
81
|
+
// while keeping each route's matcher evaluation correct.
|
|
82
|
+
const cache = new Map<string, CacheEntry>();
|
|
83
|
+
const inflight = new Map<string, Promise<CacheEntry>>();
|
|
78
84
|
|
|
79
85
|
onChange(() => {
|
|
80
|
-
cache
|
|
81
|
-
inflight
|
|
86
|
+
cache.clear();
|
|
87
|
+
inflight.clear();
|
|
82
88
|
});
|
|
83
89
|
|
|
84
90
|
function readSiteBlock(): SiteBlock | null {
|
|
@@ -112,49 +118,56 @@ const EMPTY_ENTRY: CacheEntry = {
|
|
|
112
118
|
* Exposed as a util so sites can call it directly if they need globals
|
|
113
119
|
* outside the route loader path (rare).
|
|
114
120
|
*/
|
|
115
|
-
export async function resolveSiteGlobals(): Promise<{
|
|
121
|
+
export async function resolveSiteGlobals(matcherCtx?: MatcherContext): Promise<{
|
|
116
122
|
resolvedSections: ResolvedSection[];
|
|
117
123
|
rawRefs: SiteGlobalRef[];
|
|
118
124
|
}> {
|
|
125
|
+
// Path/date/segment matchers inside site-global sections (e.g. a multivariate
|
|
126
|
+
// `Alert` gated by a pathname matcher) must evaluate against the actual
|
|
127
|
+
// request, and the result is cached per path so routes don't share variants.
|
|
128
|
+
const cacheKey = matcherCtx?.path ?? "";
|
|
119
129
|
const now = Date.now();
|
|
120
|
-
|
|
121
|
-
if (
|
|
130
|
+
const cached = cache.get(cacheKey);
|
|
131
|
+
if (cached && cached.expiresAt > now) return cached;
|
|
132
|
+
const inflightEntry = inflight.get(cacheKey);
|
|
133
|
+
if (inflightEntry) return inflightEntry;
|
|
122
134
|
|
|
123
135
|
const site = readSiteBlock();
|
|
124
136
|
if (!site) {
|
|
125
137
|
// Cache the empty result so subsequent requests don't re-walk the
|
|
126
138
|
// block registry. `onChange` invalidation still applies — if a Site
|
|
127
|
-
// block appears later, the listener
|
|
128
|
-
cache
|
|
139
|
+
// block appears later, the listener clears `cache` and we re-check.
|
|
140
|
+
cache.set(cacheKey, EMPTY_ENTRY);
|
|
129
141
|
return EMPTY_ENTRY;
|
|
130
142
|
}
|
|
131
143
|
|
|
132
144
|
const rawRefs = gatherSectionRefs(site);
|
|
133
145
|
if (rawRefs.length === 0) {
|
|
134
|
-
cache
|
|
146
|
+
cache.set(cacheKey, EMPTY_ENTRY);
|
|
135
147
|
return EMPTY_ENTRY;
|
|
136
148
|
}
|
|
137
149
|
|
|
138
|
-
|
|
150
|
+
const p = (async () => {
|
|
139
151
|
try {
|
|
140
|
-
const resolvedSections = await resolvePageSections(rawRefs);
|
|
152
|
+
const resolvedSections = await resolvePageSections(rawRefs, matcherCtx);
|
|
141
153
|
const entry: CacheEntry = {
|
|
142
154
|
resolvedSections,
|
|
143
155
|
rawRefs,
|
|
144
156
|
expiresAt: Date.now() + cacheTtlMs,
|
|
145
157
|
};
|
|
146
|
-
cache
|
|
158
|
+
cache.set(cacheKey, entry);
|
|
147
159
|
return entry;
|
|
148
160
|
} catch (err) {
|
|
149
161
|
console.error("[site-globals] failed to resolve:", err);
|
|
150
162
|
// Don't cache failures — let the next request retry.
|
|
151
163
|
return { resolvedSections: [], rawRefs, expiresAt: 0 };
|
|
152
164
|
} finally {
|
|
153
|
-
inflight
|
|
165
|
+
inflight.delete(cacheKey);
|
|
154
166
|
}
|
|
155
167
|
})();
|
|
156
168
|
|
|
157
|
-
|
|
169
|
+
inflight.set(cacheKey, p);
|
|
170
|
+
return p;
|
|
158
171
|
}
|
|
159
172
|
|
|
160
173
|
// ---------------------------------------------------------------------------
|
|
@@ -217,6 +230,6 @@ export function withSiteGlobals<T extends { loader: AnyLoader }>(routeConfig: T)
|
|
|
217
230
|
|
|
218
231
|
/** @internal */
|
|
219
232
|
export function __resetSiteGlobalsCache() {
|
|
220
|
-
cache
|
|
221
|
-
inflight
|
|
233
|
+
cache.clear();
|
|
234
|
+
inflight.clear();
|
|
222
235
|
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
buildSpeculationRules,
|
|
4
|
+
DEFAULT_EXCLUDED_HREF_MATCHES,
|
|
5
|
+
getSpeculationRules,
|
|
6
|
+
setSpeculationRules,
|
|
7
|
+
} from "./speculationRules";
|
|
8
|
+
|
|
9
|
+
describe("buildSpeculationRules", () => {
|
|
10
|
+
it("defaults to prerender + moderate + document-wide, with safe exclusions", () => {
|
|
11
|
+
const rule = JSON.parse(buildSpeculationRules());
|
|
12
|
+
expect(rule.prerender).toHaveLength(1);
|
|
13
|
+
const entry = rule.prerender[0];
|
|
14
|
+
expect(entry.eagerness).toBe("moderate");
|
|
15
|
+
// first condition targets all internal links; rest are exclusions
|
|
16
|
+
expect(entry.where.and[0]).toEqual({ href_matches: "/*" });
|
|
17
|
+
const excluded = entry.where.and
|
|
18
|
+
.filter((c: { not?: { href_matches: string } }) => c.not)
|
|
19
|
+
.map((c: { not: { href_matches: string } }) => c.not.href_matches);
|
|
20
|
+
expect(excluded).toEqual([...DEFAULT_EXCLUDED_HREF_MATCHES]);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it("scopes to a link selector when given (excludes client-routed links)", () => {
|
|
24
|
+
const rule = JSON.parse(
|
|
25
|
+
buildSpeculationRules({ linkSelector: "[data-prerender] a[href]" }),
|
|
26
|
+
);
|
|
27
|
+
expect(rule.prerender[0].where.and[0]).toEqual({
|
|
28
|
+
selector_matches: "[data-prerender] a[href]",
|
|
29
|
+
});
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("merges extra exclusions and honors action/eagerness", () => {
|
|
33
|
+
const rule = JSON.parse(
|
|
34
|
+
buildSpeculationRules({
|
|
35
|
+
action: "prefetch",
|
|
36
|
+
eagerness: "conservative",
|
|
37
|
+
excludeHrefMatches: ["/*/p"],
|
|
38
|
+
}),
|
|
39
|
+
);
|
|
40
|
+
expect(rule.prefetch).toBeDefined();
|
|
41
|
+
expect(rule.prerender).toBeUndefined();
|
|
42
|
+
expect(rule.prefetch[0].eagerness).toBe("conservative");
|
|
43
|
+
const excluded = rule.prefetch[0].where.and
|
|
44
|
+
.filter((c: { not?: unknown }) => c.not)
|
|
45
|
+
.map((c: { not: { href_matches: string } }) => c.not.href_matches);
|
|
46
|
+
expect(excluded).toContain("/*/p");
|
|
47
|
+
expect(excluded).toContain("/checkout*");
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("can replace the default exclusions entirely", () => {
|
|
51
|
+
const rule = JSON.parse(
|
|
52
|
+
buildSpeculationRules({
|
|
53
|
+
excludeHrefMatches: ["/only-this*"],
|
|
54
|
+
overrideDefaultExclusions: true,
|
|
55
|
+
}),
|
|
56
|
+
);
|
|
57
|
+
const excluded = rule.prerender[0].where.and
|
|
58
|
+
.filter((c: { not?: unknown }) => c.not)
|
|
59
|
+
.map((c: { not: { href_matches: string } }) => c.not.href_matches);
|
|
60
|
+
expect(excluded).toEqual(["/only-this*"]);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it("emits valid JSON for selectors containing '>'", () => {
|
|
64
|
+
expect(() =>
|
|
65
|
+
JSON.parse(buildSpeculationRules({ linkSelector: "nav > a" })),
|
|
66
|
+
).not.toThrow();
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
describe("speculation rules activation singleton", () => {
|
|
71
|
+
it("is disabled by default and toggles via set/get", () => {
|
|
72
|
+
setSpeculationRules(undefined);
|
|
73
|
+
expect(getSpeculationRules()).toBeUndefined();
|
|
74
|
+
|
|
75
|
+
const cfg = { linkSelector: "[data-prerender] a[href]" };
|
|
76
|
+
setSpeculationRules(cfg);
|
|
77
|
+
expect(getSpeculationRules()).toBe(cfg);
|
|
78
|
+
|
|
79
|
+
setSpeculationRules(undefined);
|
|
80
|
+
expect(getSpeculationRules()).toBeUndefined();
|
|
81
|
+
});
|
|
82
|
+
});
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Speculation Rules API helper.
|
|
3
|
+
*
|
|
4
|
+
* Builds the JSON for a `<script type="speculationrules">` tag so the browser
|
|
5
|
+
* prerenders (or prefetches) the next document ahead of a real navigation,
|
|
6
|
+
* making it feel instant. This only helps *document* navigations — raw `<a>`
|
|
7
|
+
* links that leave the SPA (mega-menu → category, footer → institutional).
|
|
8
|
+
* Client-routed `<Link>`s are intercepted by the router and never benefit, so
|
|
9
|
+
* scope the candidates to the elements that actually do hard navigations via
|
|
10
|
+
* `linkSelector` (e.g. a header/menu container marked `[data-prerender]`).
|
|
11
|
+
*
|
|
12
|
+
* Ships DISABLED: `DecoRootLayout` emits nothing unless a site passes a
|
|
13
|
+
* `speculationRules` config. Activate per-site only once the site's own
|
|
14
|
+
* analytics/pixel loaders are prerender-guarded (see ANALYTICS_SCRIPT /
|
|
15
|
+
* gtmScript in @decocms/blocks/sdk/analytics), otherwise a prerender that
|
|
16
|
+
* never activates can double-count pageviews.
|
|
17
|
+
*
|
|
18
|
+
* @see https://developer.chrome.com/docs/web-platform/prerender-pages
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
export type SpeculationAction = "prerender" | "prefetch";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* How aggressively the browser speculates:
|
|
25
|
+
* - `immediate` — as soon as the rule is seen (use sparingly).
|
|
26
|
+
* - `eager` — on the smallest hint of interaction.
|
|
27
|
+
* - `moderate` — on hover (~200ms) / pointerdown. Good default for menus.
|
|
28
|
+
* - `conservative` — on pointerdown only (cheapest; dial down to this if
|
|
29
|
+
* speculative server load gets high).
|
|
30
|
+
*/
|
|
31
|
+
export type SpeculationEagerness =
|
|
32
|
+
| "immediate"
|
|
33
|
+
| "eager"
|
|
34
|
+
| "moderate"
|
|
35
|
+
| "conservative";
|
|
36
|
+
|
|
37
|
+
export interface SpeculationRulesConfig {
|
|
38
|
+
/**
|
|
39
|
+
* `prerender` (instant nav, runs the page's JS in a hidden document — requires
|
|
40
|
+
* prerender-safe analytics) or `prefetch` (cheaper, fetches the HTML only, no
|
|
41
|
+
* JS execution). Default: `"prerender"`.
|
|
42
|
+
*/
|
|
43
|
+
action?: SpeculationAction;
|
|
44
|
+
/** Default: `"moderate"`. */
|
|
45
|
+
eagerness?: SpeculationEagerness;
|
|
46
|
+
/**
|
|
47
|
+
* CSS selector for candidate anchors. Restricts speculation to hard-navigation
|
|
48
|
+
* links and excludes client-routed `<Link>`s by construction.
|
|
49
|
+
* Example: `"[data-prerender] a[href]"`. When omitted, all same-origin
|
|
50
|
+
* internal links (`/*`) are candidates.
|
|
51
|
+
*/
|
|
52
|
+
linkSelector?: string;
|
|
53
|
+
/**
|
|
54
|
+
* Extra pathname URLPattern strings to exclude, merged with the built-in
|
|
55
|
+
* stateful/proxy exclusions. Example: `["/*\/p"]` to skip PDPs.
|
|
56
|
+
*/
|
|
57
|
+
excludeHrefMatches?: string[];
|
|
58
|
+
/**
|
|
59
|
+
* Replace the built-in stateful/proxy exclusions instead of extending them.
|
|
60
|
+
* Only set this if you know none of the default-excluded paths exist.
|
|
61
|
+
* Default: `false` (keep the safe defaults).
|
|
62
|
+
*/
|
|
63
|
+
overrideDefaultExclusions?: boolean;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Paths that are unsafe or wasteful to speculatively load: stateful/auth pages
|
|
68
|
+
* (session side effects) and typical proxied/API routes (uncacheable, fresh-0).
|
|
69
|
+
* Mirrors the `private` cache profile.
|
|
70
|
+
*/
|
|
71
|
+
export const DEFAULT_EXCLUDED_HREF_MATCHES: readonly string[] = [
|
|
72
|
+
"/checkout*",
|
|
73
|
+
"/account*",
|
|
74
|
+
"/_secure/*",
|
|
75
|
+
"/login*",
|
|
76
|
+
"/logout*",
|
|
77
|
+
"/cart*",
|
|
78
|
+
"/api/*",
|
|
79
|
+
];
|
|
80
|
+
|
|
81
|
+
type WhereCondition =
|
|
82
|
+
| { href_matches: string }
|
|
83
|
+
| { selector_matches: string }
|
|
84
|
+
| { not: WhereCondition }
|
|
85
|
+
| { and: WhereCondition[] };
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Builds the JSON string for a `<script type="speculationrules">` tag from a
|
|
89
|
+
* typed config. Safe stateful/proxy exclusions are baked in by default.
|
|
90
|
+
*/
|
|
91
|
+
export function buildSpeculationRules(config: SpeculationRulesConfig = {}): string {
|
|
92
|
+
const {
|
|
93
|
+
action = "prerender",
|
|
94
|
+
eagerness = "moderate",
|
|
95
|
+
linkSelector,
|
|
96
|
+
excludeHrefMatches = [],
|
|
97
|
+
overrideDefaultExclusions = false,
|
|
98
|
+
} = config;
|
|
99
|
+
|
|
100
|
+
const exclusions = overrideDefaultExclusions
|
|
101
|
+
? excludeHrefMatches
|
|
102
|
+
: [...DEFAULT_EXCLUDED_HREF_MATCHES, ...excludeHrefMatches];
|
|
103
|
+
|
|
104
|
+
const conditions: WhereCondition[] = [
|
|
105
|
+
linkSelector
|
|
106
|
+
? { selector_matches: linkSelector }
|
|
107
|
+
: { href_matches: "/*" },
|
|
108
|
+
...exclusions.map((href) => ({ not: { href_matches: href } } as WhereCondition)),
|
|
109
|
+
];
|
|
110
|
+
|
|
111
|
+
return JSON.stringify({
|
|
112
|
+
[action]: [{ where: { and: conditions }, eagerness }],
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ---------------------------------------------------------------------------
|
|
117
|
+
// Site-level activation (module singleton)
|
|
118
|
+
//
|
|
119
|
+
// Set once at worker init via `createDecoWorkerEntry({ speculationRules })` —
|
|
120
|
+
// same lifecycle and isolate as setRenderShell — and read at SSR render time by
|
|
121
|
+
// DecoRootLayout. This is why activation lives in the worker-entry options
|
|
122
|
+
// (like `asJson` / `renderJson`) while the tag is still rendered in the HTML
|
|
123
|
+
// (cache-safe) instead of injected at the edge. Ships DISABLED (undefined).
|
|
124
|
+
// ---------------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
let activeConfig: SpeculationRulesConfig | undefined;
|
|
127
|
+
|
|
128
|
+
/** Enable Speculation Rules site-wide. Called by createDecoWorkerEntry. */
|
|
129
|
+
export function setSpeculationRules(config: SpeculationRulesConfig | undefined): void {
|
|
130
|
+
activeConfig = config;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Current site-wide Speculation Rules config, or undefined when disabled. */
|
|
134
|
+
export function getSpeculationRules(): SpeculationRulesConfig | undefined {
|
|
135
|
+
return activeConfig;
|
|
136
|
+
}
|
package/src/sdk/workerEntry.ts
CHANGED
|
@@ -77,6 +77,7 @@ import { reconfigureAppsOnce } from "@decocms/blocks-admin/apps/autoconfig";
|
|
|
77
77
|
import { getRenderShellConfig } from "@decocms/blocks-admin/admin/setup";
|
|
78
78
|
import { buildHtmlShell } from "@decocms/blocks-admin/sdk/htmlShell";
|
|
79
79
|
import { getAppMiddleware } from "@decocms/blocks-admin/sdk/setupApps";
|
|
80
|
+
import { setSpeculationRules, type SpeculationRulesConfig } from "./speculationRules";
|
|
80
81
|
import {
|
|
81
82
|
applyDraftCookieAndHeaders,
|
|
82
83
|
bindRequestDraft,
|
|
@@ -244,6 +245,20 @@ export interface DecoWorkerEntryOptions {
|
|
|
244
245
|
*/
|
|
245
246
|
asJson?: boolean;
|
|
246
247
|
|
|
248
|
+
/**
|
|
249
|
+
* Opt-in Speculation Rules API. When set, a `<script type="speculationrules">`
|
|
250
|
+
* is emitted in every page's <head> (via DecoRootLayout, so it's cache-safe)
|
|
251
|
+
* telling the browser to prerender/prefetch the next document on intent.
|
|
252
|
+
*
|
|
253
|
+
* Ships DISABLED (undefined). Only activate on sites whose analytics/pixel
|
|
254
|
+
* loaders are prerender-guarded (see ANALYTICS_SCRIPT / gtmScript in
|
|
255
|
+
* @decocms/blocks/sdk/analytics), otherwise a prerender can double-count.
|
|
256
|
+
* Scope candidates to hard-navigation links via `linkSelector` so client-
|
|
257
|
+
* routed `<Link>`s are excluded.
|
|
258
|
+
* @default undefined (disabled)
|
|
259
|
+
*/
|
|
260
|
+
speculationRules?: SpeculationRulesConfig;
|
|
261
|
+
|
|
247
262
|
/**
|
|
248
263
|
* Cross-origin access to the `?renderJson` response. It is public page data
|
|
249
264
|
* (secrets + request-derived keys are stripped), so it defaults to open.
|
|
@@ -951,8 +966,13 @@ export function createDecoWorkerEntry(
|
|
|
951
966
|
cdnCacheControl: cdnCacheControlOpt = "no-store",
|
|
952
967
|
observability: observabilityOpt,
|
|
953
968
|
outboundUserAgent: outboundUserAgentOpt,
|
|
969
|
+
speculationRules: speculationRulesOpt,
|
|
954
970
|
} = options;
|
|
955
971
|
|
|
972
|
+
// Speculation Rules — store the site-wide config in the shared singleton so
|
|
973
|
+
// DecoRootLayout (SSR) emits the tag in <head>. Inert unless the site opts in.
|
|
974
|
+
setSpeculationRules(speculationRulesOpt);
|
|
975
|
+
|
|
956
976
|
// Patch global fetch once so every outbound request — apps calling
|
|
957
977
|
// `fetch` directly, RequestContext.fetch, instrumentedFetch — carries a
|
|
958
978
|
// User-Agent. Workers sends none by default, which WAFs on partner
|