@decocms/tanstack 7.48.0 → 7.48.2

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.48.0",
3
+ "version": "7.48.2",
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.48.0",
28
- "@decocms/blocks-admin": "7.48.0",
29
- "@decocms/blocks-cli": "7.48.0",
27
+ "@decocms/blocks": "7.48.2",
28
+ "@decocms/blocks-admin": "7.48.2",
29
+ "@decocms/blocks-cli": "7.48.2",
30
30
  "@deco-cx/warp-node": "^0.3.16",
31
31
  "fast-json-patch": "^3.1.0",
32
32
  "ws": "^8.18.0"
@@ -1,5 +1,5 @@
1
1
  import { useEffect, type ReactNode } from "react";
2
- import { HeadContent, Scripts, ScriptOnce } from "@tanstack/react-router";
2
+ import { HeadContent, Scripts, ScriptOnce, useRouterState } from "@tanstack/react-router";
3
3
  import { LiveControls } from "@decocms/blocks/hooks";
4
4
  import {
5
5
  ANALYTICS_SCRIPT,
@@ -112,6 +112,28 @@ export function DecoRootLayout({
112
112
  return () => clearTimeout(id);
113
113
  }, [decoReadyDelay]);
114
114
 
115
+ // Pull the resolved CMS page's route pattern (`path` = pathTemplate) and block
116
+ // id (`blockKey`) out of the current route's loader data so LiveControls sends
117
+ // the admin the page the user is actually on — not the hardcoded "/*" fallback.
118
+ // The CMS page loader (cmsRoute) spreads both fields onto its loader data;
119
+ // we scan matches deepest-first to find the one that carries them.
120
+ const page = useRouterState({
121
+ select: (state) => {
122
+ for (let i = state.matches.length - 1; i >= 0; i--) {
123
+ const data = state.matches[i]?.loaderData as
124
+ | { path?: unknown; blockKey?: unknown }
125
+ | undefined;
126
+ if (data && typeof data.path === "string") {
127
+ return {
128
+ id: typeof data.blockKey === "string" ? data.blockKey : undefined,
129
+ pathTemplate: data.path,
130
+ };
131
+ }
132
+ }
133
+ return undefined;
134
+ },
135
+ });
136
+
115
137
  // Worker-entry option wins; prop is a per-root override. Undefined → disabled.
116
138
  const speculation = speculationRules ?? getSpeculationRules();
117
139
 
@@ -145,7 +167,7 @@ export function DecoRootLayout({
145
167
  </main>
146
168
  {children}
147
169
  <DraftPreviewIndicator />
148
- <LiveControls site={siteName} />
170
+ <LiveControls site={siteName} page={page} />
149
171
  <ScriptOnce children={ANALYTICS_SCRIPT} />
150
172
  <Scripts />
151
173
  </body>
@@ -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
- let cache: CacheEntry | null = null;
77
- let inflight: Promise<CacheEntry> | null = null;
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 = null;
81
- inflight = null;
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
- if (cache && cache.expiresAt > now) return cache;
121
- if (inflight) return inflight;
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 nulls `cache` and we re-check.
128
- cache = EMPTY_ENTRY;
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 = EMPTY_ENTRY;
146
+ cache.set(cacheKey, EMPTY_ENTRY);
135
147
  return EMPTY_ENTRY;
136
148
  }
137
149
 
138
- inflight = (async () => {
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 = entry;
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 = null;
165
+ inflight.delete(cacheKey);
154
166
  }
155
167
  })();
156
168
 
157
- return inflight;
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 = null;
221
- inflight = null;
233
+ cache.clear();
234
+ inflight.clear();
222
235
  }