@decocms/tanstack 7.46.1 → 7.48.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decocms/tanstack",
3
- "version": "7.46.1",
3
+ "version": "7.48.0",
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.46.1",
28
- "@decocms/blocks-admin": "7.46.1",
29
- "@decocms/blocks-cli": "7.46.1",
27
+ "@decocms/blocks": "7.48.0",
28
+ "@decocms/blocks-admin": "7.48.0",
29
+ "@decocms/blocks-cli": "7.48.0",
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 { ANALYTICS_SCRIPT } from "@decocms/blocks/sdk/analytics";
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) --
@@ -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
+ }
@@ -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