@decocms/tanstack 7.64.3 → 7.65.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decocms/tanstack",
3
- "version": "7.64.3",
3
+ "version": "7.65.1",
4
4
  "type": "module",
5
5
  "description": "Deco framework binding for TanStack Start + Cloudflare Workers",
6
6
  "repository": {
@@ -27,9 +27,9 @@
27
27
  "lint:unused": "knip"
28
28
  },
29
29
  "dependencies": {
30
- "@decocms/blocks": "7.64.3",
31
- "@decocms/blocks-admin": "7.64.3",
32
- "@decocms/blocks-cli": "7.64.3",
30
+ "@decocms/blocks": "7.65.1",
31
+ "@decocms/blocks-admin": "7.65.1",
32
+ "@decocms/blocks-cli": "7.65.1",
33
33
  "@deco-cx/warp-node": "^0.3.16",
34
34
  "fast-json-patch": "^3.1.0",
35
35
  "ws": "^8.18.0"
@@ -17,6 +17,8 @@
17
17
  * harmless by construction — the Worker verifies by recomputing and falls back
18
18
  * to `no-store` when it doesn't match.
19
19
  */
20
+
21
+ import { getRequestNonce } from "@decocms/blocks/sdk/nonce";
20
22
  import { RequestContext } from "@decocms/blocks/sdk/requestContext";
21
23
  import { CSEG_BAG_KEY, CSEG_GLOBAL } from "../sdk/cdnSegment";
22
24
 
@@ -25,6 +27,7 @@ export function CdnSegmentMarker() {
25
27
  if (!token) return null;
26
28
  return (
27
29
  <script
30
+ nonce={getRequestNonce()}
28
31
  // A hash this server computed, not user input. JSON.stringify keeps it
29
32
  // inert regardless.
30
33
  dangerouslySetInnerHTML={{
@@ -436,7 +436,7 @@ function DeferredSectionWrapper({
436
436
  // the skeleton subtree and mount of the resolved subtree even when the
437
437
  // section's own LoadingFallback renders the real component with reduced
438
438
  // props (a documented convention — see Footer.tsx/ETCImageContent.tsx in
439
- // the farmrio-storefront migration's T64). That unmount/remount is what
439
+ // a production storefront migration's T64). That unmount/remount is what
440
440
  // produces a hard rect-collapse-to-{0,0,0,0} layout-shift entry instead
441
441
  // of an ordinary prop-driven resize. Keeping the wrapper identical across
442
442
  // both branches lets React diff by type at the child position instead.
@@ -1,30 +1,28 @@
1
- import { CdnSegmentMarker } from "./CdnSegmentMarker";
2
- import { useEffect, type ReactNode } from "react";
3
- import { HeadContent, Scripts, ScriptOnce, useRouterState } from "@tanstack/react-router";
4
1
  import { LiveControls, Stats } from "@decocms/blocks/hooks";
5
- import {
6
- ANALYTICS_SCRIPT,
7
- SPECULATION_DEV_WARN_SCRIPT,
8
- } from "@decocms/blocks/sdk/analytics";
2
+ import { ANALYTICS_SCRIPT, SPECULATION_DEV_WARN_SCRIPT } from "@decocms/blocks/sdk/analytics";
9
3
  import { isDevMode } from "@decocms/blocks/sdk/env";
4
+ import { getRequestNonce } from "@decocms/blocks/sdk/nonce";
5
+ import { HeadContent, ScriptOnce, Scripts, useRouterState } from "@tanstack/react-router";
6
+ import { type ReactNode, useEffect } from "react";
10
7
  import {
11
- buildSpeculationRules,
12
- getSpeculationRules,
13
- type SpeculationRulesConfig,
8
+ buildSpeculationRules,
9
+ getSpeculationRules,
10
+ type SpeculationRulesConfig,
14
11
  } from "../sdk/speculationRules";
12
+ import { CdnSegmentMarker } from "./CdnSegmentMarker";
15
13
  import { DraftPreviewIndicator } from "./DraftPreviewIndicator";
16
14
  import { NavigationProgress } from "./NavigationProgress";
17
15
  import { StableOutlet } from "./StableOutlet";
18
16
 
19
17
  declare global {
20
- interface Window {
21
- __deco_ready?: boolean;
22
- }
18
+ interface Window {
19
+ __deco_ready?: boolean;
20
+ }
23
21
  }
24
22
 
25
23
  function buildDecoEventsBootstrap(account?: string): string {
26
- const accountJson = JSON.stringify(account ?? "");
27
- return `
24
+ const accountJson = JSON.stringify(account ?? "");
25
+ return `
28
26
  window.__RUNTIME__ = window.__RUNTIME__ || { account: ${accountJson} };
29
27
  window.DECO = window.DECO || {};
30
28
  window.DECO.events = window.DECO.events || {
@@ -48,34 +46,34 @@ window.dataLayer = window.dataLayer || [];
48
46
  }
49
47
 
50
48
  export interface DecoRootLayoutProps {
51
- /** Language attribute for the <html> tag. Default: "en" */
52
- lang?: string;
53
- /** DaisyUI data-theme attribute. Default: "light" */
54
- dataTheme?: string;
55
- /** Site name for LiveControls (admin iframe communication). Required. */
56
- siteName: string;
57
- /** Commerce platform account name for analytics bootstrap (e.g. VTEX account). */
58
- account?: string;
59
- /** CSS class for <body>. Default: "bg-base-200 text-base-content" */
60
- bodyClassName?: string;
61
- /** Delay in ms before firing deco:ready event. Default: 500 */
62
- decoReadyDelay?: number;
63
- /**
64
- * Opt-in Speculation Rules API config override. Normally activated site-wide
65
- * via `createDecoWorkerEntry({ speculationRules })` (like `asJson` /
66
- * `renderJson`) and read from that shared config; pass this prop only to
67
- * override it for a specific root. When set, emits a
68
- * `<script type="speculationrules">` in <head> so the browser prerenders/
69
- * prefetches the next document on intent. Ships DISABLED — only activate on
70
- * sites whose analytics/pixel loaders are prerender-guarded.
71
- * @see buildSpeculationRules
72
- */
73
- speculationRules?: SpeculationRulesConfig;
74
- /**
75
- * Extra content rendered inside <body> after the main outlet
76
- * (e.g. Toast, custom analytics components).
77
- */
78
- children?: ReactNode;
49
+ /** Language attribute for the <html> tag. Default: "en" */
50
+ lang?: string;
51
+ /** DaisyUI data-theme attribute. Default: "light" */
52
+ dataTheme?: string;
53
+ /** Site name for LiveControls (admin iframe communication). Required. */
54
+ siteName: string;
55
+ /** Commerce platform account name for analytics bootstrap (e.g. VTEX account). */
56
+ account?: string;
57
+ /** CSS class for <body>. Default: "bg-base-200 text-base-content" */
58
+ bodyClassName?: string;
59
+ /** Delay in ms before firing deco:ready event. Default: 500 */
60
+ decoReadyDelay?: number;
61
+ /**
62
+ * Opt-in Speculation Rules API config override. Normally activated site-wide
63
+ * via `createDecoWorkerEntry({ speculationRules })` (like `asJson` /
64
+ * `renderJson`) and read from that shared config; pass this prop only to
65
+ * override it for a specific root. When set, emits a
66
+ * `<script type="speculationrules">` in <head> so the browser prerenders/
67
+ * prefetches the next document on intent. Ships DISABLED — only activate on
68
+ * sites whose analytics/pixel loaders are prerender-guarded.
69
+ * @see buildSpeculationRules
70
+ */
71
+ speculationRules?: SpeculationRulesConfig;
72
+ /**
73
+ * Extra content rendered inside <body> after the main outlet
74
+ * (e.g. Toast, custom analytics components).
75
+ */
76
+ children?: ReactNode;
79
77
  }
80
78
 
81
79
  /**
@@ -96,97 +94,99 @@ export interface DecoRootLayoutProps {
96
94
  * pieces (NavigationProgress, StableOutlet, etc.) instead.
97
95
  */
98
96
  export function DecoRootLayout({
99
- lang = "en",
100
- dataTheme = "light",
101
- siteName,
102
- account,
103
- bodyClassName = "bg-base-200 text-base-content",
104
- decoReadyDelay = 500,
105
- speculationRules,
106
- children,
97
+ lang = "en",
98
+ dataTheme = "light",
99
+ siteName,
100
+ account,
101
+ bodyClassName = "bg-base-200 text-base-content",
102
+ decoReadyDelay = 500,
103
+ speculationRules,
104
+ children,
107
105
  }: DecoRootLayoutProps) {
108
- useEffect(() => {
109
- const id = setTimeout(() => {
110
- window.__deco_ready = true;
111
- document.dispatchEvent(new Event("deco:ready"));
112
- }, decoReadyDelay);
113
- return () => clearTimeout(id);
114
- }, [decoReadyDelay]);
106
+ useEffect(() => {
107
+ const id = setTimeout(() => {
108
+ window.__deco_ready = true;
109
+ document.dispatchEvent(new Event("deco:ready"));
110
+ }, decoReadyDelay);
111
+ return () => clearTimeout(id);
112
+ }, [decoReadyDelay]);
115
113
 
116
- // Pull the resolved CMS page's route pattern (`path` = pathTemplate) and block
117
- // id (`blockKey`) out of the current route's loader data so LiveControls sends
118
- // the admin the page the user is actually on — not the hardcoded "/*" fallback.
119
- // The CMS page loader (cmsRoute) spreads both fields onto its loader data;
120
- // we scan matches deepest-first to find the one that carries them.
121
- const page = useRouterState({
122
- select: (state) => {
123
- for (let i = state.matches.length - 1; i >= 0; i--) {
124
- const data = state.matches[i]?.loaderData as
125
- | { path?: unknown; blockKey?: unknown }
126
- | undefined;
127
- if (data && typeof data.path === "string") {
128
- return {
129
- id: typeof data.blockKey === "string" ? data.blockKey : undefined,
130
- pathTemplate: data.path,
131
- };
132
- }
133
- }
134
- return undefined;
135
- },
136
- });
114
+ // Pull the resolved CMS page's route pattern (`path` = pathTemplate) and block
115
+ // id (`blockKey`) out of the current route's loader data so LiveControls sends
116
+ // the admin the page the user is actually on — not the hardcoded "/*" fallback.
117
+ // The CMS page loader (cmsRoute) spreads both fields onto its loader data;
118
+ // we scan matches deepest-first to find the one that carries them.
119
+ const page = useRouterState({
120
+ select: (state) => {
121
+ for (let i = state.matches.length - 1; i >= 0; i--) {
122
+ const data = state.matches[i]?.loaderData as
123
+ | { path?: unknown; blockKey?: unknown }
124
+ | undefined;
125
+ if (data && typeof data.path === "string") {
126
+ return {
127
+ id: typeof data.blockKey === "string" ? data.blockKey : undefined,
128
+ pathTemplate: data.path,
129
+ };
130
+ }
131
+ }
132
+ return undefined;
133
+ },
134
+ });
137
135
 
138
- // Worker-entry option wins; prop is a per-root override. Undefined → disabled.
139
- const speculation = speculationRules ?? getSpeculationRules();
136
+ // Worker-entry option wins; prop is a per-root override. Undefined → disabled.
137
+ const speculation = speculationRules ?? getSpeculationRules();
140
138
 
141
- return (
142
- <html lang={lang} data-theme={dataTheme} suppressHydrationWarning>
143
- <head>
144
- <HeadContent />
145
- <CdnSegmentMarker />
146
- {speculation && (
147
- <script
148
- type="speculationrules"
149
- // JSON is inert; dangerouslySetInnerHTML avoids React escaping
150
- // `>` in selectors (e.g. "nav > a"). Same pattern as JSON-LD.
151
- dangerouslySetInnerHTML={{
152
- __html: buildSpeculationRules(speculation),
153
- }}
154
- />
155
- )}
156
- {/* Dev-only: console.error when analytics fire during a prerender
139
+ return (
140
+ <html lang={lang} data-theme={dataTheme} suppressHydrationWarning>
141
+ <head>
142
+ <HeadContent />
143
+ <CdnSegmentMarker />
144
+ {speculation && (
145
+ <script
146
+ type="speculationrules"
147
+ nonce={getRequestNonce()}
148
+ // JSON is inert; dangerouslySetInnerHTML avoids React escaping
149
+ // `>` in selectors (e.g. "nav > a"). Same pattern as JSON-LD.
150
+ dangerouslySetInnerHTML={{
151
+ __html: buildSpeculationRules(speculation),
152
+ }}
153
+ />
154
+ )}
155
+ {/* Dev-only: console.error when analytics fire during a prerender
157
156
  so the dev fixes unguarded loaders before shipping. */}
158
- {speculation && isDevMode() && (
159
- <script
160
- dangerouslySetInnerHTML={{ __html: SPECULATION_DEV_WARN_SCRIPT }}
161
- />
162
- )}
163
- </head>
164
- <body className={bodyClassName} suppressHydrationWarning>
165
- <ScriptOnce children={buildDecoEventsBootstrap(account)} />
166
- {/*
167
- * AFTER the bootstrap above, and in the body rather than the head. The collector's
168
- * deco module subscribes with `window?.DECO?.events?.subscribe?.(…)` — once,
169
- * optional-chained, with no retry. In the head it is an `async` script the parser
170
- * can reach and run before the inline bootstrap below it has defined
171
- * `DECO.events`, and the subscription would simply not happen: pageviews would
172
- * still flow while every commerce event went nowhere, with no error. Here the
173
- * parser has already executed the bootstrap.
174
- *
175
- * Rendering unconditionally is safe — the component returns null unless
176
- * DECO_ANALYTICS_ENABLED is exactly "true", which is what makes this an env-var
177
- * change for a site instead of a code change.
178
- */}
179
- <Stats />
180
- <NavigationProgress />
181
- <main>
182
- <StableOutlet />
183
- </main>
184
- {children}
185
- <DraftPreviewIndicator />
186
- <LiveControls site={siteName} page={page} />
187
- <ScriptOnce children={ANALYTICS_SCRIPT} />
188
- <Scripts />
189
- </body>
190
- </html>
191
- );
157
+ {speculation && isDevMode() && (
158
+ <script
159
+ nonce={getRequestNonce()}
160
+ dangerouslySetInnerHTML={{ __html: SPECULATION_DEV_WARN_SCRIPT }}
161
+ />
162
+ )}
163
+ </head>
164
+ <body className={bodyClassName} suppressHydrationWarning>
165
+ <ScriptOnce children={buildDecoEventsBootstrap(account)} />
166
+ {/*
167
+ * AFTER the bootstrap above, and in the body rather than the head. The collector's
168
+ * deco module subscribes with `window?.DECO?.events?.subscribe?.(…)` — once,
169
+ * optional-chained, with no retry. In the head it is an `async` script the parser
170
+ * can reach and run before the inline bootstrap below it has defined
171
+ * `DECO.events`, and the subscription would simply not happen: pageviews would
172
+ * still flow while every commerce event went nowhere, with no error. Here the
173
+ * parser has already executed the bootstrap.
174
+ *
175
+ * Rendering unconditionally is safe — the component returns null unless
176
+ * DECO_ANALYTICS_ENABLED is exactly "true", which is what makes this an env-var
177
+ * change for a site instead of a code change.
178
+ */}
179
+ <Stats />
180
+ <NavigationProgress />
181
+ <main>
182
+ <StableOutlet />
183
+ </main>
184
+ {children}
185
+ <DraftPreviewIndicator />
186
+ <LiveControls site={siteName} page={page} />
187
+ <ScriptOnce children={ANALYTICS_SCRIPT} />
188
+ <Scripts />
189
+ </body>
190
+ </html>
191
+ );
192
192
  }
@@ -28,6 +28,7 @@
28
28
  * closed), so the visible chip never participates in the hydration diff.
29
29
  */
30
30
  import { DraftPreviewBadge } from "@decocms/blocks/preview";
31
+ import { getRequestNonce } from "@decocms/blocks/sdk/nonce";
31
32
  import { RequestContext } from "@decocms/blocks/sdk/requestContext";
32
33
  import { DRAFT_POINTER_BAG_KEY, DRAFT_POINTER_GLOBAL } from "../sdk/draftShared";
33
34
 
@@ -52,6 +53,7 @@ export function DraftPreviewIndicator() {
52
53
  {/* Publishes a JSON-encoded pointer this server resolved (not user
53
54
  input) so the client's hydration render matches. See the module doc. */}
54
55
  <script
56
+ nonce={getRequestNonce()}
55
57
  dangerouslySetInnerHTML={{
56
58
  __html: `window.${DRAFT_POINTER_GLOBAL}=${JSON.stringify(pointer)}`,
57
59
  }}
@@ -4,8 +4,8 @@ import { derivePageUrl, isClientNavigation } from "./pageUrl";
4
4
  describe("derivePageUrl (#280 — client-nav request URL)", () => {
5
5
  it("SSR real page without query: rebuilds from fullPath", () => {
6
6
  expect(
7
- derivePageUrl("/granado/produto", new URL("https://o.com/granado/produto")),
8
- ).toBe("https://o.com/granado/produto");
7
+ derivePageUrl("/acme/produto", new URL("https://o.com/acme/produto")),
8
+ ).toBe("https://o.com/acme/produto");
9
9
  });
10
10
 
11
11
  it("SSR real page preserves duplicate query params from the server URL", () => {
@@ -21,10 +21,10 @@ describe("derivePageUrl (#280 — client-nav request URL)", () => {
21
21
  it("client nav without query: rebuilds from fullPath, NOT the /_serverFn URL", () => {
22
22
  // The regression guard: getRequestUrl() is the serverFn endpoint here.
23
23
  const serverUrl = new URL(
24
- "https://o.com/_serverFn/loadCmsPage?payload=%2Fgranado%2Fproduto",
24
+ "https://o.com/_serverFn/loadCmsPage?payload=%2Facme%2Fproduto",
25
25
  );
26
- expect(derivePageUrl("/granado/produto", serverUrl)).toBe(
27
- "https://o.com/granado/produto",
26
+ expect(derivePageUrl("/acme/produto", serverUrl)).toBe(
27
+ "https://o.com/acme/produto",
28
28
  );
29
29
  });
30
30
 
@@ -50,7 +50,7 @@ describe("isClientNavigation (SPA vs SSR detection)", () => {
50
50
 
51
51
  it("SSR real page without query (path matches): false", () => {
52
52
  expect(
53
- isClientNavigation("/granado/produto", new URL("https://o.com/granado/produto")),
53
+ isClientNavigation("/acme/produto", new URL("https://o.com/acme/produto")),
54
54
  ).toBe(false);
55
55
  });
56
56
 
@@ -17,8 +17,8 @@
17
17
  *
18
18
  * export const Route = createFileRoute("/$")({
19
19
  * ...withSiteGlobals(cmsRouteConfig({
20
- * siteName: "Bagaggio",
21
- * defaultTitle: "Bagaggio",
20
+ * siteName: "Acme",
21
+ * defaultTitle: "Acme",
22
22
  * })),
23
23
  * component: ...,
24
24
  * });
@@ -3,7 +3,7 @@
3
3
  * (`@decocms/tanstack/sdk/deferredSectionLoader`).
4
4
  *
5
5
  * Before 7.7 this wrapper was unreachable from any public subpath, so
6
- * migrated sites (lebiscuit, miess, granadobr, casaevideo) each carried a
6
+ * migrated production storefronts each carried a
7
7
  * byte-identical local shim wrapping the public `loadDeferredSection`
8
8
  * export. The cases below are derived from how those sites call it: it is
9
9
  * passed verbatim as `<DecoPageRenderer loadDeferredSectionFn={...} />`,
@@ -276,13 +276,13 @@ describe("installPreviewHostsFromBlocks", () => {
276
276
  it("installs previewHosts from the site block (either casing)", async () => {
277
277
  setDraftPreviewHosts([]);
278
278
  installPreviewHostsFromBlocks({
279
- Site: { previewHosts: ["fila.vtex.app"] },
279
+ Site: { previewHosts: ["acme.vtex.app"] },
280
280
  });
281
281
 
282
282
  // Verified through the wire: an allowed host now previews.
283
283
  const request = req({
284
- url: "https://fila.vtex.app/p?__draft=abc.preview-studio.decocms.com@v1",
285
- host: "fila.vtex.app",
284
+ url: "https://acme.vtex.app/p?__draft=abc.preview-studio.decocms.com@v1",
285
+ host: "acme.vtex.app",
286
286
  });
287
287
  const url = new URL(request.url);
288
288
  expect(requestCarriesDraft(request, url)).toBe(true);
@@ -291,10 +291,10 @@ describe("installPreviewHostsFromBlocks", () => {
291
291
  it("ignores blocks without previewHosts", () => {
292
292
  setDraftPreviewHosts([]);
293
293
  installPreviewHostsFromBlocks({ site: {} });
294
- const url = new URL("https://fila.vtex.app/p?__draft=x@v1");
294
+ const url = new URL("https://acme.vtex.app/p?__draft=x@v1");
295
295
  expect(
296
296
  requestCarriesDraft(
297
- req({ url: url.toString(), host: "fila.vtex.app" }),
297
+ req({ url: url.toString(), host: "acme.vtex.app" }),
298
298
  url,
299
299
  ),
300
300
  ).toBe(false);
@@ -308,13 +308,13 @@ describe("installDecoSiteHostFromEnv", () => {
308
308
 
309
309
  it("arms the deco-hosted domains from the DECO_SITE_NAME binding", () => {
310
310
  setDraftPreviewHosts([]);
311
- installDecoSiteHostFromEnv({ DECO_SITE_NAME: "casaevideo-tanstack" });
311
+ installDecoSiteHostFromEnv({ DECO_SITE_NAME: "acme-tanstack" });
312
312
 
313
313
  // Verified through the wire: both deco-operated hosts now preview, with no
314
314
  // site-block/env config at all.
315
315
  for (const host of [
316
- "casaevideo-tanstack.deco.site",
317
- "casaevideo-tanstack.deco-cx.workers.dev",
316
+ "acme-tanstack.deco.site",
317
+ "acme-tanstack.deco-cx.workers.dev",
318
318
  ]) {
319
319
  const url = new URL(
320
320
  `https://${host}/p?__draft=abc.preview-studio.decocms.com@v1`,
@@ -322,10 +322,10 @@ describe("installDecoSiteHostFromEnv", () => {
322
322
  expect(requestCarriesDraft(req({ url: url.toString(), host }), url)).toBe(true);
323
323
  }
324
324
  // A custom production domain is never inferred.
325
- const url = new URL("https://www.casaevideo.com.br/p?__draft=x@v1");
325
+ const url = new URL("https://www.acme.com.br/p?__draft=x@v1");
326
326
  expect(
327
327
  requestCarriesDraft(
328
- req({ url: url.toString(), host: "www.casaevideo.com.br" }),
328
+ req({ url: url.toString(), host: "www.acme.com.br" }),
329
329
  url,
330
330
  ),
331
331
  ).toBe(false);
package/src/sdk/draft.ts CHANGED
@@ -94,7 +94,7 @@ export function installPreviewHostsFromBlocks(blocks: Record<string, unknown> |
94
94
  /**
95
95
  * Register the deco-operated preview hosts inferred from the site name —
96
96
  * `<site>.deco.site` and `<site>.deco-cx.workers.dev` (the workers.dev deploy
97
- * URL, e.g. `casaevideo-tanstack.deco-cx.workers.dev`) — so a signed
97
+ * URL, e.g. `acme-tanstack.deco-cx.workers.dev`) — so a signed
98
98
  * `?__draft=` grant previews on deco-hosted infra with zero per-site config.
99
99
  *
100
100
  * Fed from the Workers env binding `DECO_SITE_NAME`: deploy-time configuration
package/src/sdk/router.ts CHANGED
@@ -6,61 +6,63 @@
6
6
  * filter URLs like `?filter.brand=Nike&filter.brand=Adidas` which must
7
7
  * round-trip correctly through the router's search system.
8
8
  */
9
- import { createRouter as createTanStackRouter } from "@tanstack/react-router";
9
+
10
+ import { getRequestNonce } from "@decocms/blocks/sdk/nonce";
10
11
  import type {
11
- SearchSerializer,
12
- SearchParser,
13
- AnyRoute,
14
- TrailingSlashOption,
12
+ AnyRoute,
13
+ SearchParser,
14
+ SearchSerializer,
15
+ TrailingSlashOption,
15
16
  } from "@tanstack/react-router";
17
+ import { createRouter as createTanStackRouter } from "@tanstack/react-router";
16
18
 
17
19
  export const decoParseSearch: SearchParser = (searchStr) => {
18
- const str = searchStr.startsWith("?") ? searchStr.slice(1) : searchStr;
19
- if (!str) return {};
20
+ const str = searchStr.startsWith("?") ? searchStr.slice(1) : searchStr;
21
+ if (!str) return {};
20
22
 
21
- const params = new URLSearchParams(str);
22
- const result: Record<string, string | string[]> = {};
23
+ const params = new URLSearchParams(str);
24
+ const result: Record<string, string | string[]> = {};
23
25
 
24
- for (const key of new Set(params.keys())) {
25
- const values = params.getAll(key);
26
- result[key] = values.length === 1 ? values[0] : values;
27
- }
28
- return result;
26
+ for (const key of new Set(params.keys())) {
27
+ const values = params.getAll(key);
28
+ result[key] = values.length === 1 ? values[0] : values;
29
+ }
30
+ return result;
29
31
  };
30
32
 
31
33
  export const decoStringifySearch: SearchSerializer = (search) => {
32
- const params = new URLSearchParams();
33
- for (const [key, value] of Object.entries(search)) {
34
- if (value === undefined || value === null || value === "") continue;
35
- if (Array.isArray(value)) {
36
- for (const v of value) params.append(key, String(v));
37
- } else {
38
- params.append(key, String(value));
39
- }
40
- }
41
- const str = params.toString();
42
- return str ? `?${str}` : "";
34
+ const params = new URLSearchParams();
35
+ for (const [key, value] of Object.entries(search)) {
36
+ if (value === undefined || value === null || value === "") continue;
37
+ if (Array.isArray(value)) {
38
+ for (const v of value) params.append(key, String(v));
39
+ } else {
40
+ params.append(key, String(value));
41
+ }
42
+ }
43
+ const str = params.toString();
44
+ return str ? `?${str}` : "";
43
45
  };
44
46
 
45
47
  export interface CreateDecoRouterOptions {
46
- routeTree: AnyRoute;
47
- scrollRestoration?: boolean;
48
- defaultPreload?: "intent" | "viewport" | "render" | false;
49
- trailingSlash?: TrailingSlashOption;
50
- /**
51
- * Router context — passed to all route loaders/components via routeContext.
52
- * Commonly used for { queryClient } per TanStack Query integration docs.
53
- */
54
- context?: Record<string, unknown>;
55
- /**
56
- * Non-DOM provider component to wrap the entire router.
57
- * Per TanStack docs, only non-DOM-rendering components (providers) should
58
- * be used — anything else causes hydration errors.
59
- *
60
- * Example: QueryClientProvider wrapping
61
- * Wrap: ({ children }) => <QueryClientProvider client={qc}>{children}</QueryClientProvider>
62
- */
63
- Wrap?: (props: { children: any }) => any;
48
+ routeTree: AnyRoute;
49
+ scrollRestoration?: boolean;
50
+ defaultPreload?: "intent" | "viewport" | "render" | false;
51
+ trailingSlash?: TrailingSlashOption;
52
+ /**
53
+ * Router context — passed to all route loaders/components via routeContext.
54
+ * Commonly used for { queryClient } per TanStack Query integration docs.
55
+ */
56
+ context?: Record<string, unknown>;
57
+ /**
58
+ * Non-DOM provider component to wrap the entire router.
59
+ * Per TanStack docs, only non-DOM-rendering components (providers) should
60
+ * be used — anything else causes hydration errors.
61
+ *
62
+ * Example: QueryClientProvider wrapping
63
+ * Wrap: ({ children }) => <QueryClientProvider client={qc}>{children}</QueryClientProvider>
64
+ */
65
+ Wrap?: (props: { children: any }) => any;
64
66
  }
65
67
 
66
68
  /**
@@ -70,23 +72,30 @@ export interface CreateDecoRouterOptions {
70
72
  * - Preload on intent
71
73
  */
72
74
  export function createDecoRouter(options: CreateDecoRouterOptions) {
73
- const {
74
- routeTree,
75
- scrollRestoration = true,
76
- defaultPreload = "intent",
77
- trailingSlash,
78
- context,
79
- Wrap,
80
- } = options;
75
+ const {
76
+ routeTree,
77
+ scrollRestoration = true,
78
+ defaultPreload = "intent",
79
+ trailingSlash,
80
+ context,
81
+ Wrap,
82
+ } = options;
83
+
84
+ // On the server, `getRouter()` runs per request inside `RequestContext.run`,
85
+ // so this reads the request's CSP nonce (enforce mode) — `ScriptOnce` and
86
+ // TanStack's own hydration scripts read `router.options.ssr.nonce` and stamp
87
+ // it. `undefined` in report-only mode and on the client, where it's a no-op.
88
+ const nonce = getRequestNonce();
81
89
 
82
- return createTanStackRouter({
83
- routeTree,
84
- scrollRestoration,
85
- defaultPreload,
86
- trailingSlash,
87
- context: context as any,
88
- Wrap,
89
- parseSearch: decoParseSearch,
90
- stringifySearch: decoStringifySearch,
91
- });
90
+ return createTanStackRouter({
91
+ routeTree,
92
+ scrollRestoration,
93
+ defaultPreload,
94
+ trailingSlash,
95
+ context: context as any,
96
+ Wrap,
97
+ parseSearch: decoParseSearch,
98
+ stringifySearch: decoStringifySearch,
99
+ ...(nonce ? { ssr: { nonce } } : {}),
100
+ });
92
101
  }