@decocms/tanstack 8.0.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.
Files changed (150) hide show
  1. package/README.md +79 -0
  2. package/dist/draft.d.ts +33 -0
  3. package/dist/draft.d.ts.map +1 -0
  4. package/dist/draft.js +41 -0
  5. package/dist/draft.js.map +1 -0
  6. package/dist/index.d.ts +9 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +9 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/react/DecoDocument.d.ts +61 -0
  11. package/dist/react/DecoDocument.d.ts.map +1 -0
  12. package/dist/react/DecoDocument.js +96 -0
  13. package/dist/react/DecoDocument.js.map +1 -0
  14. package/dist/react/Image.d.ts +96 -0
  15. package/dist/react/Image.d.ts.map +1 -0
  16. package/dist/react/Image.js +79 -0
  17. package/dist/react/Image.js.map +1 -0
  18. package/dist/react/index.d.ts +7 -0
  19. package/dist/react/index.d.ts.map +1 -0
  20. package/dist/react/index.js +7 -0
  21. package/dist/react/index.js.map +1 -0
  22. package/dist/react/pageValues.d.ts +10 -0
  23. package/dist/react/pageValues.d.ts.map +1 -0
  24. package/dist/react/pageValues.js +29 -0
  25. package/dist/react/pageValues.js.map +1 -0
  26. package/dist/react/scripts.d.ts +14 -0
  27. package/dist/react/scripts.d.ts.map +1 -0
  28. package/dist/react/scripts.js +96 -0
  29. package/dist/react/scripts.js.map +1 -0
  30. package/dist/router/index.d.ts +38 -0
  31. package/dist/router/index.d.ts.map +1 -0
  32. package/dist/router/index.js +60 -0
  33. package/dist/router/index.js.map +1 -0
  34. package/dist/scope/browser.d.ts +11 -0
  35. package/dist/scope/browser.d.ts.map +1 -0
  36. package/dist/scope/browser.js +8 -0
  37. package/dist/scope/browser.js.map +1 -0
  38. package/dist/scope/server.d.ts +13 -0
  39. package/dist/scope/server.d.ts.map +1 -0
  40. package/dist/scope/server.js +26 -0
  41. package/dist/scope/server.js.map +1 -0
  42. package/dist/server/index.d.ts +27 -0
  43. package/dist/server/index.d.ts.map +1 -0
  44. package/dist/server/index.js +31 -0
  45. package/dist/server/index.js.map +1 -0
  46. package/dist/shared.d.ts +26 -0
  47. package/dist/shared.d.ts.map +1 -0
  48. package/dist/shared.js +26 -0
  49. package/dist/shared.js.map +1 -0
  50. package/dist/start/index.d.ts +9 -0
  51. package/dist/start/index.d.ts.map +1 -0
  52. package/dist/start/index.js +33 -0
  53. package/dist/start/index.js.map +1 -0
  54. package/dist/studio.d.ts +28 -0
  55. package/dist/studio.d.ts.map +1 -0
  56. package/dist/studio.js +53 -0
  57. package/dist/studio.js.map +1 -0
  58. package/dist/vite/index.d.ts +15 -0
  59. package/dist/vite/index.d.ts.map +1 -0
  60. package/dist/vite/index.js +95 -0
  61. package/dist/vite/index.js.map +1 -0
  62. package/dist/worker/cacheProfiles.d.ts +43 -0
  63. package/dist/worker/cacheProfiles.d.ts.map +1 -0
  64. package/dist/worker/cacheProfiles.js +162 -0
  65. package/dist/worker/cacheProfiles.js.map +1 -0
  66. package/dist/worker/cookies.d.ts +20 -0
  67. package/dist/worker/cookies.d.ts.map +1 -0
  68. package/dist/worker/cookies.js +69 -0
  69. package/dist/worker/cookies.js.map +1 -0
  70. package/dist/worker/drafts.d.ts +59 -0
  71. package/dist/worker/drafts.d.ts.map +1 -0
  72. package/dist/worker/drafts.js +140 -0
  73. package/dist/worker/drafts.js.map +1 -0
  74. package/dist/worker/index.d.ts +107 -0
  75. package/dist/worker/index.d.ts.map +1 -0
  76. package/dist/worker/index.js +511 -0
  77. package/dist/worker/index.js.map +1 -0
  78. package/dist/worker/security.d.ts +14 -0
  79. package/dist/worker/security.d.ts.map +1 -0
  80. package/dist/worker/security.js +48 -0
  81. package/dist/worker/security.js.map +1 -0
  82. package/dist/worker/segment.d.ts +21 -0
  83. package/dist/worker/segment.d.ts.map +1 -0
  84. package/dist/worker/segment.js +43 -0
  85. package/dist/worker/segment.js.map +1 -0
  86. package/package.json +86 -31
  87. package/src/draft.ts +43 -0
  88. package/src/index.ts +8 -44
  89. package/src/react/DecoDocument.tsx +234 -0
  90. package/src/react/Image.tsx +213 -0
  91. package/src/react/index.ts +24 -0
  92. package/src/react/pageValues.ts +35 -0
  93. package/src/react/scripts.ts +98 -0
  94. package/src/router/index.ts +80 -0
  95. package/src/scope/browser.ts +18 -0
  96. package/src/scope/server.ts +37 -0
  97. package/src/server/index.ts +43 -0
  98. package/src/shared.ts +29 -0
  99. package/src/start/index.ts +31 -0
  100. package/src/studio.ts +52 -0
  101. package/src/vite/index.ts +105 -0
  102. package/src/worker/cacheProfiles.ts +180 -0
  103. package/src/worker/cookies.ts +65 -0
  104. package/src/worker/drafts.ts +157 -0
  105. package/src/worker/index.ts +648 -0
  106. package/src/worker/security.ts +63 -0
  107. package/src/worker/segment.ts +49 -0
  108. package/src/cms/kvBlockSource.test.ts +0 -82
  109. package/src/cms/kvBlockSource.ts +0 -68
  110. package/src/daemon/auth.ts +0 -204
  111. package/src/daemon/fs.ts +0 -238
  112. package/src/daemon/index.ts +0 -8
  113. package/src/daemon/middleware.ts +0 -156
  114. package/src/daemon/tunnel.ts +0 -129
  115. package/src/daemon/volumes.ts +0 -366
  116. package/src/daemon/watch.ts +0 -272
  117. package/src/hooks/DecoPageRenderer.tsx +0 -688
  118. package/src/hooks/DecoRootLayout.tsx +0 -111
  119. package/src/hooks/NavigationProgress.tsx +0 -21
  120. package/src/hooks/PreviewProviders.tsx +0 -26
  121. package/src/hooks/StableOutlet.tsx +0 -30
  122. package/src/hooks/index.ts +0 -9
  123. package/src/routes/adminRoutes.test.ts +0 -99
  124. package/src/routes/adminRoutes.ts +0 -153
  125. package/src/routes/cmsRoute.test.ts +0 -100
  126. package/src/routes/cmsRoute.ts +0 -944
  127. package/src/routes/components.tsx +0 -57
  128. package/src/routes/index.ts +0 -24
  129. package/src/routes/pageUrl.test.ts +0 -70
  130. package/src/routes/pageUrl.ts +0 -54
  131. package/src/routes/withSiteGlobals.test.ts +0 -206
  132. package/src/routes/withSiteGlobals.ts +0 -222
  133. package/src/sdk/cookiePassthrough.ts +0 -58
  134. package/src/sdk/createInvoke.ts +0 -77
  135. package/src/sdk/deferredSectionLoader.test.ts +0 -94
  136. package/src/sdk/deferredSectionLoader.ts +0 -46
  137. package/src/sdk/kvHydration.test.ts +0 -215
  138. package/src/sdk/kvHydration.ts +0 -193
  139. package/src/sdk/outboundHeaders.test.ts +0 -113
  140. package/src/sdk/outboundHeaders.ts +0 -81
  141. package/src/sdk/router.ts +0 -92
  142. package/src/sdk/useHydrated.ts +0 -19
  143. package/src/sdk/workerEntry.test.ts +0 -495
  144. package/src/sdk/workerEntry.ts +0 -2307
  145. package/src/setupFastDeploy.ts +0 -13
  146. package/src/vite/plugin-scaffold-gen.test.js +0 -106
  147. package/src/vite/plugin.js +0 -850
  148. package/src/vite/plugin.test.js +0 -113
  149. package/src/vite/plugin.test.ts +0 -52
  150. package/tsconfig.json +0 -7
@@ -1,111 +0,0 @@
1
- import { useEffect, type ReactNode } from "react";
2
- import { HeadContent, Scripts, ScriptOnce } from "@tanstack/react-router";
3
- import { LiveControls } from "@decocms/blocks/hooks";
4
- import { ANALYTICS_SCRIPT } from "@decocms/blocks/sdk/analytics";
5
- import { NavigationProgress } from "./NavigationProgress";
6
- import { StableOutlet } from "./StableOutlet";
7
-
8
- declare global {
9
- interface Window {
10
- __deco_ready?: boolean;
11
- }
12
- }
13
-
14
- function buildDecoEventsBootstrap(account?: string): string {
15
- const accountJson = JSON.stringify(account ?? "");
16
- return `
17
- window.__RUNTIME__ = window.__RUNTIME__ || { account: ${accountJson} };
18
- window.DECO = window.DECO || {};
19
- window.DECO.events = window.DECO.events || {
20
- _q: [],
21
- _subs: [],
22
- dispatch: function(e) {
23
- this._q.push(e);
24
- for (var i = 0; i < this._subs.length; i++) {
25
- try { this._subs[i](e); } catch(err) { console.error('[DECO.events]', err); }
26
- }
27
- },
28
- subscribe: function(fn) {
29
- this._subs.push(fn);
30
- for (var i = 0; i < this._q.length; i++) {
31
- try { fn(this._q[i]); } catch(err) {}
32
- }
33
- }
34
- };
35
- window.dataLayer = window.dataLayer || [];
36
- `;
37
- }
38
-
39
- export interface DecoRootLayoutProps {
40
- /** Language attribute for the <html> tag. Default: "en" */
41
- lang?: string;
42
- /** DaisyUI data-theme attribute. Default: "light" */
43
- dataTheme?: string;
44
- /** Site name for LiveControls (admin iframe communication). Required. */
45
- siteName: string;
46
- /** Commerce platform account name for analytics bootstrap (e.g. VTEX account). */
47
- account?: string;
48
- /** CSS class for <body>. Default: "bg-base-200 text-base-content" */
49
- bodyClassName?: string;
50
- /** Delay in ms before firing deco:ready event. Default: 500 */
51
- decoReadyDelay?: number;
52
- /**
53
- * Extra content rendered inside <body> after the main outlet
54
- * (e.g. Toast, custom analytics components).
55
- */
56
- children?: ReactNode;
57
- }
58
-
59
- /**
60
- * Standard Deco root layout component for use in __root.tsx.
61
- *
62
- * Provides:
63
- * - NavigationProgress (loading bar during SPA nav)
64
- * - StableOutlet (height-preserved content area)
65
- * - DECO.events bootstrap (via ScriptOnce — runs before hydration, once)
66
- * - LiveControls for admin
67
- * - Analytics script (via ScriptOnce)
68
- * - deco:ready hydration signal
69
- *
70
- * QueryClientProvider should be configured via createDecoRouter's `Wrap` option
71
- * (per TanStack docs — non-DOM providers go on the router, not in components).
72
- *
73
- * Sites that need full control should compose from the individual exported
74
- * pieces (NavigationProgress, StableOutlet, etc.) instead.
75
- */
76
- export function DecoRootLayout({
77
- lang = "en",
78
- dataTheme = "light",
79
- siteName,
80
- account,
81
- bodyClassName = "bg-base-200 text-base-content",
82
- decoReadyDelay = 500,
83
- children,
84
- }: DecoRootLayoutProps) {
85
- useEffect(() => {
86
- const id = setTimeout(() => {
87
- window.__deco_ready = true;
88
- document.dispatchEvent(new Event("deco:ready"));
89
- }, decoReadyDelay);
90
- return () => clearTimeout(id);
91
- }, [decoReadyDelay]);
92
-
93
- return (
94
- <html lang={lang} data-theme={dataTheme} suppressHydrationWarning>
95
- <head>
96
- <HeadContent />
97
- </head>
98
- <body className={bodyClassName} suppressHydrationWarning>
99
- <ScriptOnce children={buildDecoEventsBootstrap(account)} />
100
- <NavigationProgress />
101
- <main>
102
- <StableOutlet />
103
- </main>
104
- {children}
105
- <LiveControls site={siteName} />
106
- <ScriptOnce children={ANALYTICS_SCRIPT} />
107
- <Scripts />
108
- </body>
109
- </html>
110
- );
111
- }
@@ -1,21 +0,0 @@
1
- import { useRouterState } from "@tanstack/react-router";
2
-
3
- const PROGRESS_CSS = `
4
- @keyframes progressSlide { from { transform: translateX(-100%); } to { transform: translateX(100%); } }
5
- .nav-progress-bar { animation: progressSlide 1s ease-in-out infinite; }
6
- `;
7
-
8
- /**
9
- * Top-of-page loading bar that appears during SPA navigation.
10
- * Uses the router's isLoading state — no extra dependencies.
11
- */
12
- export function NavigationProgress() {
13
- const isLoading = useRouterState({ select: (s) => s.isLoading });
14
- if (!isLoading) return null;
15
- return (
16
- <div className="fixed top-0 left-0 right-0 z-[9999] h-1 bg-brand-primary-500/20 overflow-hidden">
17
- <style dangerouslySetInnerHTML={{ __html: PROGRESS_CSS }} />
18
- <div className="nav-progress-bar h-full w-1/3 bg-brand-primary-500 rounded-full" />
19
- </div>
20
- );
21
- }
@@ -1,26 +0,0 @@
1
- import {
2
- createMemoryHistory,
3
- createRootRoute,
4
- createRouter,
5
- RouterContextProvider,
6
- } from "@tanstack/react-router";
7
- import type { ReactNode } from "react";
8
-
9
- const rootRoute = createRootRoute();
10
-
11
- const previewRouter = createRouter({
12
- // TanStack Router's RootRoute/Route generic inference rejects bare rootRoute
13
- // at the type level (works at runtime). `as any` avoids leaking the mismatch
14
- // into consumer sites that typecheck framework source via npm link.
15
- routeTree: rootRoute as any,
16
- history: createMemoryHistory({ initialEntries: ["/"] }),
17
- });
18
-
19
- /**
20
- * Default preview wrapper for admin iframe rendering.
21
- * Provides a TanStack Router context with memory history so components
22
- * that depend on router hooks (Link, useNavigate, etc.) work in previews.
23
- */
24
- export default function PreviewProviders({ children }: { children: ReactNode }) {
25
- return <RouterContextProvider router={previewRouter as any}>{children}</RouterContextProvider>;
26
- }
@@ -1,30 +0,0 @@
1
- import { useEffect, useRef, useState } from "react";
2
- import { Outlet, useRouterState } from "@tanstack/react-router";
3
-
4
- /**
5
- * Preserves the content area height during SPA navigation so the
6
- * footer doesn't jump up while the new page is loading.
7
- */
8
- export function StableOutlet() {
9
- const isLoading = useRouterState({ select: (s) => s.isLoading });
10
- const ref = useRef<HTMLDivElement>(null);
11
- // State (not a ref) so clearing the height when navigation completes
12
- // triggers a re-render that removes the min-height. With a ref the reset
13
- // never re-rendered, so the previous (taller) page's height stayed pinned
14
- // — leaving a large gap below the footer on tall→short navigation (#279).
15
- const [savedHeight, setSavedHeight] = useState<number | undefined>(undefined);
16
-
17
- useEffect(() => {
18
- if (isLoading && ref.current) {
19
- setSavedHeight(ref.current.offsetHeight);
20
- } else if (!isLoading) {
21
- setSavedHeight(undefined);
22
- }
23
- }, [isLoading]);
24
-
25
- return (
26
- <div ref={ref} style={savedHeight ? { minHeight: savedHeight } : undefined}>
27
- <Outlet />
28
- </div>
29
- );
30
- }
@@ -1,9 +0,0 @@
1
- export {
2
- DecoPageRenderer,
3
- SectionList,
4
- SectionRenderer,
5
- } from "./DecoPageRenderer";
6
- export { DecoRootLayout, type DecoRootLayoutProps } from "./DecoRootLayout";
7
- export { NavigationProgress } from "./NavigationProgress";
8
- export { StableOutlet } from "./StableOutlet";
9
- export { default as PreviewProviders } from "./PreviewProviders";
@@ -1,99 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
-
3
- vi.mock("@decocms/blocks-admin", () => ({
4
- corsHeaders: vi.fn(() => ({})),
5
- handleInvoke: vi.fn(),
6
- handleMeta: vi.fn(),
7
- handleRender: vi.fn(),
8
- }));
9
-
10
- vi.mock("@decocms/blocks/middleware/observability", () => ({
11
- withTracing: vi.fn((_name: string, fn: () => unknown) => fn()),
12
- }));
13
-
14
- import * as adminRoutes from "./adminRoutes";
15
- import { decoInvokeRouteConfig, decoMetaRouteConfig, decoRenderRouteConfig } from "./adminRoutes";
16
-
17
- /**
18
- * Regression guard for the dev-HMR brick:
19
- *
20
- * TanStack router-core's `BaseRoute.update()` mutates the options object it
21
- * is handed (`Object.assign(this.options, options)` — injecting `id`/`path`).
22
- * Before 7.10.0 this module exported shared module-scope literals
23
- * (`decoMetaRoute`/`decoRenderRoute`/`decoInvokeRoute`); a site passing one
24
- * by reference polluted it on first execution, and on any HMR re-execution
25
- * the route constructor threw
26
- * `Route cannot have both an 'id' and a 'path' option` — every route 500ed
27
- * until dev restart.
28
- *
29
- * The `*RouteConfig()` factories must therefore return a FRESH object on
30
- * every call, and the shared literals must never be (re-)exported.
31
- */
32
- describe("admin route config factories", () => {
33
- const cases = [
34
- {
35
- name: "decoMetaRouteConfig",
36
- factory: decoMetaRouteConfig,
37
- methods: ["GET", "OPTIONS"],
38
- },
39
- {
40
- name: "decoRenderRouteConfig",
41
- factory: decoRenderRouteConfig,
42
- methods: ["GET", "POST", "OPTIONS"],
43
- },
44
- {
45
- name: "decoInvokeRouteConfig",
46
- factory: decoInvokeRouteConfig,
47
- methods: ["GET", "POST", "OPTIONS"],
48
- },
49
- ] as const;
50
-
51
- for (const { name, factory, methods } of cases) {
52
- describe(name, () => {
53
- it("returns a new object on every call", () => {
54
- expect(factory()).not.toBe(factory());
55
- });
56
-
57
- it("returns structurally equal configs across calls", () => {
58
- expect(factory()).toEqual(factory());
59
- });
60
-
61
- it(`exposes server handlers for ${methods.join("/")}`, () => {
62
- const config = factory() as {
63
- server: { handlers: Record<string, unknown> };
64
- };
65
- expect(Object.keys(config.server.handlers).sort()).toEqual([...methods].sort());
66
- for (const method of methods) {
67
- expect(config.server.handlers[method]).toBeTypeOf("function");
68
- }
69
- });
70
-
71
- it("survives router-core-style mutation without polluting later calls", () => {
72
- // Simulate BaseRoute.update(): Object.assign(this.options, options)
73
- // pollutes whatever object createFileRoute was handed.
74
- const options = factory() as Record<string, unknown>;
75
- Object.assign(options, { id: "/deco/x", path: "/deco/x" });
76
-
77
- // The next module execution (HMR) gets a clean object again.
78
- const next = factory();
79
- expect(next).not.toHaveProperty("id");
80
- expect(next).not.toHaveProperty("path");
81
- });
82
- });
83
- }
84
-
85
- it("does NOT export the removed pre-7.10.0 literals (dev-HMR footgun)", () => {
86
- // The shared module-scope literals were removed in 7.10.0. Re-exporting
87
- // them would reintroduce the HMR brick for any site passing them by
88
- // reference to createFileRoute.
89
- const removed = ["decoMetaRoute", "decoRenderRoute", "decoInvokeRoute"];
90
- for (const name of removed) {
91
- expect(adminRoutes, `"${name}" must not be exported`).not.toHaveProperty(name);
92
- }
93
- expect(Object.keys(adminRoutes).sort()).toEqual([
94
- "decoInvokeRouteConfig",
95
- "decoMetaRouteConfig",
96
- "decoRenderRouteConfig",
97
- ]);
98
- });
99
- });
@@ -1,153 +0,0 @@
1
- /**
2
- * Admin Route Helpers
3
- *
4
- * Pre-built server handler config factories for the Deco admin protocol
5
- * routes. Sites call these in their `createFileRoute` definitions to avoid
6
- * repeating the same CORS + handler boilerplate.
7
- *
8
- * @example Site's `src/routes/deco/meta.ts`:
9
- * ```ts
10
- * import { createFileRoute } from "@tanstack/react-router";
11
- * import { decoMetaRouteConfig } from "@decocms/tanstack";
12
- *
13
- * export const Route = createFileRoute("/deco/meta")(decoMetaRouteConfig());
14
- * ```
15
- *
16
- * ## Why factories and not shared config objects? (dev-HMR footgun)
17
- *
18
- * TanStack router-core's `BaseRoute.update()` MUTATES the options object it
19
- * receives (`Object.assign(this.options, options)` — injecting `id` and
20
- * `path`). Before 7.10.0 this module exported the configs as module-scope
21
- * LITERALS (`decoMetaRoute` / `decoRenderRoute` / `decoInvokeRoute`); a site
22
- * passing one by reference (`createFileRoute("/deco/meta")(decoMetaRoute)`)
23
- * polluted the shared literal on first execution, and any dev-server HMR
24
- * partial re-execution then re-ran the route file against the still-cached,
25
- * now-polluted literal — the route constructor threw
26
- * `Route cannot have both an 'id' and a 'path' option` and every route 500ed
27
- * until the dev server restarted. The factories hand each `createFileRoute`
28
- * call its own fresh object, so the mutation is harmless. The base configs
29
- * below are module-private and deliberately NOT exported.
30
- */
31
- import { corsHeaders, handleInvoke, handleMeta, handleRender } from "@decocms/blocks-admin";
32
- import { withTracing } from "@decocms/blocks/middleware/observability";
33
-
34
- function invokeAttrs(request: Request): Record<string, string | boolean> {
35
- const url = new URL(request.url);
36
- const invokeKey = url.pathname.split("/deco/invoke/")[1] ?? "";
37
- return {
38
- "invoke.key": invokeKey || "(batch)",
39
- "invoke.batch": invokeKey === "",
40
- };
41
- }
42
-
43
- function renderAttrs(request: Request): Record<string, string> {
44
- const url = new URL(request.url);
45
- const pathComponent = url.pathname.split("/deco/render/")[1] ?? "";
46
- return { "cms.component": pathComponent || "(page)" };
47
- }
48
-
49
- type HandlerFn = (ctx: { request: Request }) => Promise<Response> | Response;
50
-
51
- function withCors(handler: HandlerFn): HandlerFn {
52
- return async (ctx) => {
53
- const response = await handler(ctx);
54
- const headers = new Headers(response.headers);
55
- for (const [k, v] of Object.entries(corsHeaders(ctx.request))) {
56
- headers.set(k, v);
57
- }
58
- return new Response(response.body, {
59
- status: response.status,
60
- headers,
61
- });
62
- };
63
- }
64
-
65
- function optionsHandler(ctx: { request: Request }): Response {
66
- return new Response(null, {
67
- status: 204,
68
- headers: corsHeaders(ctx.request),
69
- });
70
- }
71
-
72
- // ---------------------------------------------------------------------------
73
- // Base configs — module-PRIVATE. Never export these: router-core's update()
74
- // mutates whatever object createFileRoute is handed (injects id/path), so a
75
- // shared exported literal bricks dev HMR (see module doc above). Sites get
76
- // fresh copies via the *RouteConfig() factories below.
77
- // ---------------------------------------------------------------------------
78
-
79
- /** Base config for `/deco/meta` — serves JSON Schema + manifest. */
80
- const decoMetaRoute = {
81
- server: {
82
- handlers: {
83
- GET: withCors(({ request }) =>
84
- withTracing("deco.admin.meta", async () => handleMeta(request)),
85
- ),
86
- OPTIONS: optionsHandler,
87
- },
88
- },
89
- };
90
-
91
- /** Base config for `/deco/render` — section/page preview in iframe. */
92
- const decoRenderRoute = {
93
- server: {
94
- handlers: {
95
- GET: withCors(({ request }) =>
96
- withTracing(
97
- "deco.admin.render",
98
- () => Promise.resolve(handleRender(request)),
99
- renderAttrs(request),
100
- ),
101
- ),
102
- POST: withCors(({ request }) =>
103
- withTracing(
104
- "deco.admin.render",
105
- () => Promise.resolve(handleRender(request)),
106
- renderAttrs(request),
107
- ),
108
- ),
109
- OPTIONS: optionsHandler,
110
- },
111
- },
112
- };
113
-
114
- /** Base config for `/deco/invoke/$` — loader/action execution. */
115
- const decoInvokeRoute = {
116
- server: {
117
- handlers: {
118
- GET: withCors(({ request }) =>
119
- withTracing("deco.admin.invoke", () => handleInvoke(request), invokeAttrs(request)),
120
- ),
121
- POST: withCors(({ request }) =>
122
- withTracing("deco.admin.invoke", () => handleInvoke(request), invokeAttrs(request)),
123
- ),
124
- OPTIONS: optionsHandler,
125
- },
126
- },
127
- };
128
-
129
- // ---------------------------------------------------------------------------
130
- // Factories — dev-HMR-safe route configs (fresh object per call)
131
- // ---------------------------------------------------------------------------
132
- // Mirrors the `cmsRouteConfig()` / `cmsHomeRouteConfig()` convention in
133
- // cmsRoute.ts: a function returning a fresh options object, so router-core's
134
- // mutating `update()` can never pollute shared module state across HMR
135
- // re-executions.
136
-
137
- /**
138
- * Returns a fresh route config for `/deco/meta` — serves JSON Schema + manifest.
139
- * Use as `createFileRoute("/deco/meta")(decoMetaRouteConfig())`.
140
- */
141
- export const decoMetaRouteConfig = () => ({ ...decoMetaRoute });
142
-
143
- /**
144
- * Returns a fresh route config for `/deco/render` — section/page preview in iframe.
145
- * Use as `createFileRoute("/deco/render")(decoRenderRouteConfig())`.
146
- */
147
- export const decoRenderRouteConfig = () => ({ ...decoRenderRoute });
148
-
149
- /**
150
- * Returns a fresh route config for `/deco/invoke/$` — loader/action execution.
151
- * Use as `createFileRoute("/deco/invoke/$")(decoInvokeRouteConfig())`.
152
- */
153
- export const decoInvokeRouteConfig = () => ({ ...decoInvokeRoute });
@@ -1,100 +0,0 @@
1
- import { registerCacheableSections, registerSectionLoader } from "@decocms/blocks/cms";
2
- import type { ResolvedSection } from "@decocms/blocks/cms";
3
- import { describe, expect, it } from "vitest";
4
- import {
5
- parseLoadCmsHomePageInput,
6
- parseLoadCmsPageInput,
7
- runSectionLoadersWithSeo,
8
- } from "./cmsRoute";
9
-
10
- describe("parseLoadCmsPageInput (#292)", () => {
11
- it("treats a bare string as the path with resolveGlobals defaulting to true (back-compat)", () => {
12
- expect(parseLoadCmsPageInput("/produto/tenis")).toEqual({
13
- path: "/produto/tenis",
14
- resolveGlobals: true,
15
- });
16
- });
17
-
18
- it("accepts { path, resolveGlobals } and preserves an explicit false", () => {
19
- expect(parseLoadCmsPageInput({ path: "/produto/tenis", resolveGlobals: false })).toEqual({
20
- path: "/produto/tenis",
21
- resolveGlobals: false,
22
- });
23
- });
24
-
25
- it("defaults resolveGlobals to true when omitted from the object form", () => {
26
- expect(parseLoadCmsPageInput({ path: "/produto/tenis" })).toEqual({
27
- path: "/produto/tenis",
28
- resolveGlobals: true,
29
- });
30
- });
31
- });
32
-
33
- describe("parseLoadCmsHomePageInput (#292)", () => {
34
- it("defaults resolveGlobals to true when called with no data (back-compat)", () => {
35
- expect(parseLoadCmsHomePageInput(undefined)).toEqual({ resolveGlobals: true });
36
- });
37
-
38
- it("preserves an explicit resolveGlobals: false", () => {
39
- expect(parseLoadCmsHomePageInput({ resolveGlobals: false })).toEqual({ resolveGlobals: false });
40
- });
41
- });
42
-
43
- /**
44
- * Regression guard for #355: body sections and the SEO section used to be
45
- * resolved sequentially (`runSectionLoaders` for the body, then a separate
46
- * `runSingleSectionLoader` call for the SEO section inside `buildPageSeo`).
47
- * On a PDP, both commonly resolve the SAME product via the SAME commerce
48
- * loader — sequential calls always missed the fetch-cache layer's in-flight
49
- * dedup (the body call had already completed by the time the SEO call
50
- * started). Batching them into one `runSectionLoaders` call (this file's
51
- * `runSectionLoadersWithSeo`) lets identical concurrent requests share one
52
- * origin round-trip.
53
- *
54
- * This test proves the batching by registering a *cacheable* section loader
55
- * (the same SWR + in-flight-dedup mechanism real commerce loaders use) and
56
- * asserting it's invoked only once when the body section and SEO section
57
- * share the same component + props.
58
- */
59
- describe("runSectionLoadersWithSeo (#355)", () => {
60
- it("dedupes a same-component/same-props SEO section against a body section via the cacheable-section in-flight cache", async () => {
61
- const component = `test/sections/DedupCheck-${Date.now()}.tsx`;
62
- let calls = 0;
63
-
64
- registerCacheableSections({ [component]: { maxAge: 60_000 } });
65
- registerSectionLoader(component, async (props) => {
66
- calls++;
67
- await new Promise((r) => setTimeout(r, 5));
68
- return { ...props, loaded: true };
69
- });
70
-
71
- const bodySection: ResolvedSection = { component, props: { sku: "123" }, key: component, index: 0 };
72
- const seoSection: ResolvedSection = { component, props: { sku: "123" }, key: `${component}-seo`, index: -1 };
73
-
74
- const request = new Request("https://store.com/produto/123");
75
- const { enrichedSections, enrichedSeoSection } = await runSectionLoadersWithSeo(
76
- [bodySection],
77
- seoSection,
78
- request,
79
- );
80
-
81
- expect(calls).toBe(1);
82
- expect((enrichedSections[0].props as any).loaded).toBe(true);
83
- expect((enrichedSeoSection?.props as any).loaded).toBe(true);
84
- });
85
-
86
- it("runs plain runSectionLoaders when there is no SEO section", async () => {
87
- const component = `test/sections/NoSeo-${Date.now()}.tsx`;
88
- registerSectionLoader(component, async (props) => ({ ...props, loaded: true }));
89
-
90
- const bodySection: ResolvedSection = { component, props: {}, key: component, index: 0 };
91
- const { enrichedSections, enrichedSeoSection } = await runSectionLoadersWithSeo(
92
- [bodySection],
93
- null,
94
- new Request("https://store.com/"),
95
- );
96
-
97
- expect((enrichedSections[0].props as any).loaded).toBe(true);
98
- expect(enrichedSeoSection).toBeNull();
99
- });
100
- });