@decocms/blocks 8.0.0 → 8.1.0-next.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.
Files changed (220) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -82
  3. package/src/index.ts +35 -8
  4. package/src/protocol/assets.ts +124 -0
  5. package/src/protocol/canonical.ts +7 -0
  6. package/src/protocol/ciphertext.ts +6 -0
  7. package/src/protocol/client.ts +170 -0
  8. package/src/protocol/conformance/cases/assets.ts +81 -0
  9. package/src/protocol/conformance/cases/guards.ts +314 -0
  10. package/src/protocol/conformance/cases/reads.ts +168 -0
  11. package/src/protocol/conformance/cases/types.ts +9 -0
  12. package/src/protocol/conformance/cases/wire.ts +138 -0
  13. package/src/protocol/conformance/cases/writes.ts +345 -0
  14. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  15. package/src/protocol/conformance/context.ts +222 -0
  16. package/src/protocol/conformance/index.ts +140 -0
  17. package/src/protocol/errors.ts +142 -0
  18. package/src/protocol/index.ts +39 -0
  19. package/src/protocol/keys.ts +279 -0
  20. package/src/protocol/params.ts +67 -0
  21. package/src/protocol/secrets.ts +231 -0
  22. package/src/protocol/server/assets.ts +119 -0
  23. package/src/protocol/server/auth.ts +49 -0
  24. package/src/protocol/server/bodyCache.ts +84 -0
  25. package/src/protocol/server/content.ts +175 -0
  26. package/src/protocol/server/core.ts +112 -0
  27. package/src/protocol/server/handler.ts +102 -0
  28. package/src/protocol/server/http.ts +139 -0
  29. package/src/protocol/server/index.ts +11 -0
  30. package/src/protocol/server/methods/apply.ts +341 -0
  31. package/src/protocol/server/methods/read.ts +156 -0
  32. package/src/protocol/server/rpc.ts +136 -0
  33. package/src/protocol/storage/fs/hash.ts +21 -0
  34. package/src/protocol/storage/fs/index.ts +338 -0
  35. package/src/protocol/storage/fs/lock.ts +68 -0
  36. package/src/protocol/storage/fs/transaction.ts +183 -0
  37. package/src/protocol/storage/fs/unsupported.ts +15 -0
  38. package/src/protocol/storage/memory.ts +238 -0
  39. package/src/protocol/storage.ts +182 -0
  40. package/src/protocol/types.ts +172 -0
  41. package/src/v8/analytics.ts +50 -0
  42. package/src/v8/background.ts +107 -0
  43. package/src/v8/builtins/data.ts +23 -0
  44. package/src/v8/builtins/index.ts +26 -0
  45. package/src/v8/builtins/lazy.ts +23 -0
  46. package/src/v8/builtins/legacy.ts +65 -0
  47. package/src/v8/builtins/matchers.ts +31 -0
  48. package/src/v8/builtins/multivariate.ts +25 -0
  49. package/src/v8/builtins/secret.ts +82 -0
  50. package/src/v8/canonical.ts +117 -0
  51. package/src/v8/ciphertext.ts +158 -0
  52. package/src/v8/cli/builtins.ts +20 -0
  53. package/src/v8/cli/check/index.ts +774 -0
  54. package/src/v8/cli/check/messages.ts +168 -0
  55. package/src/v8/cli/content.ts +287 -0
  56. package/src/v8/cli/index.ts +17 -0
  57. package/src/v8/cli/log.ts +18 -0
  58. package/src/v8/cli/main.ts +12 -0
  59. package/src/v8/cli/root.ts +66 -0
  60. package/src/v8/cli/run.ts +236 -0
  61. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  62. package/src/v8/cli/schema/generate.ts +507 -0
  63. package/src/v8/cli/schema/index.ts +63 -0
  64. package/src/v8/cli/schema/tsProgram.ts +497 -0
  65. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  66. package/src/v8/cli/serve/server.ts +303 -0
  67. package/src/v8/cli/watch.ts +86 -0
  68. package/src/v8/client.ts +147 -0
  69. package/src/v8/cms.ts +237 -0
  70. package/src/v8/content.ts +195 -0
  71. package/src/v8/draft.ts +136 -0
  72. package/src/v8/errors.ts +59 -0
  73. package/src/v8/fetch.ts +133 -0
  74. package/src/v8/identity.ts +65 -0
  75. package/src/v8/index.ts +39 -0
  76. package/src/v8/json.ts +74 -0
  77. package/src/v8/matchRoute.ts +204 -0
  78. package/src/v8/remoteLoader.ts +282 -0
  79. package/src/v8/resolver.ts +278 -0
  80. package/src/v8/secrets.ts +17 -0
  81. package/src/v8/telemetry.ts +533 -0
  82. package/src/v8/types.ts +240 -0
  83. package/src/cms/applySectionConventions.ts +0 -124
  84. package/src/cms/blockSource.test.ts +0 -76
  85. package/src/cms/blockSource.ts +0 -191
  86. package/src/cms/client.browserBundle.test.ts +0 -44
  87. package/src/cms/client.ts +0 -80
  88. package/src/cms/draftSource.test.ts +0 -343
  89. package/src/cms/draftSource.ts +0 -362
  90. package/src/cms/index.ts +0 -151
  91. package/src/cms/layoutCacheRace.test.ts +0 -181
  92. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  93. package/src/cms/loadDecofileDirectory.ts +0 -89
  94. package/src/cms/loader.test.ts +0 -200
  95. package/src/cms/loader.ts +0 -304
  96. package/src/cms/registry.test.ts +0 -110
  97. package/src/cms/registry.ts +0 -242
  98. package/src/cms/resolve.test.ts +0 -980
  99. package/src/cms/resolve.ts +0 -2282
  100. package/src/cms/schema.test.ts +0 -356
  101. package/src/cms/schema.ts +0 -1215
  102. package/src/cms/sectionLoaderContext.test.ts +0 -111
  103. package/src/cms/sectionLoaderContext.ts +0 -113
  104. package/src/cms/sectionLoaders.test.ts +0 -533
  105. package/src/cms/sectionLoaders.ts +0 -636
  106. package/src/cms/sectionMixins.test.ts +0 -167
  107. package/src/cms/sectionMixins.ts +0 -153
  108. package/src/cms/stickyFlags.test.ts +0 -117
  109. package/src/flags/audience.ts +0 -56
  110. package/src/flags/everyone.ts +0 -29
  111. package/src/flags/flag.ts +0 -15
  112. package/src/flags/flags.test.ts +0 -148
  113. package/src/flags/multivariate/image.ts +0 -11
  114. package/src/flags/multivariate/message.ts +0 -11
  115. package/src/flags/multivariate/page.ts +0 -16
  116. package/src/flags/multivariate/section.ts +0 -16
  117. package/src/flags/multivariate.ts +0 -1
  118. package/src/flags/types.ts +0 -59
  119. package/src/flags/utils/multivariate.ts +0 -20
  120. package/src/hooks/Image.test.ts +0 -100
  121. package/src/hooks/Image.tsx +0 -250
  122. package/src/hooks/JsonLd.tsx +0 -353
  123. package/src/hooks/LazySection.tsx +0 -121
  124. package/src/hooks/LiveControls.tsx +0 -122
  125. package/src/hooks/Picture.tsx +0 -127
  126. package/src/hooks/RenderSection.test.tsx +0 -81
  127. package/src/hooks/RenderSection.tsx +0 -91
  128. package/src/hooks/SectionErrorFallback.tsx +0 -97
  129. package/src/hooks/index.ts +0 -30
  130. package/src/matchers/builtins.test.ts +0 -318
  131. package/src/matchers/builtins.ts +0 -459
  132. package/src/matchers/countryNames.ts +0 -104
  133. package/src/matchers/override.test.ts +0 -205
  134. package/src/matchers/override.ts +0 -136
  135. package/src/matchers/posthog.ts +0 -154
  136. package/src/middleware/decoState.ts +0 -55
  137. package/src/middleware/healthMetrics.ts +0 -133
  138. package/src/middleware/hydrationContext.test.ts +0 -61
  139. package/src/middleware/hydrationContext.ts +0 -79
  140. package/src/middleware/index.ts +0 -88
  141. package/src/middleware/liveness.ts +0 -21
  142. package/src/middleware/observability.test.ts +0 -242
  143. package/src/middleware/observability.ts +0 -643
  144. package/src/middleware/validateSection.test.ts +0 -147
  145. package/src/middleware/validateSection.ts +0 -100
  146. package/src/sdk/abTesting.test.ts +0 -326
  147. package/src/sdk/abTesting.ts +0 -499
  148. package/src/sdk/analytics.ts +0 -77
  149. package/src/sdk/cacheHeaders.test.ts +0 -115
  150. package/src/sdk/cacheHeaders.ts +0 -433
  151. package/src/sdk/cachedLoader.test.ts +0 -122
  152. package/src/sdk/cachedLoader.ts +0 -503
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/clx.ts +0 -5
  155. package/src/sdk/cn.test.ts +0 -34
  156. package/src/sdk/cn.ts +0 -28
  157. package/src/sdk/composite.test.ts +0 -121
  158. package/src/sdk/composite.ts +0 -114
  159. package/src/sdk/cookie.test.ts +0 -108
  160. package/src/sdk/cookie.ts +0 -129
  161. package/src/sdk/crypto.ts +0 -185
  162. package/src/sdk/csp.ts +0 -59
  163. package/src/sdk/detectDevice.ts +0 -45
  164. package/src/sdk/djb2.ts +0 -20
  165. package/src/sdk/encoding.test.ts +0 -71
  166. package/src/sdk/encoding.ts +0 -47
  167. package/src/sdk/env.test.ts +0 -33
  168. package/src/sdk/env.ts +0 -54
  169. package/src/sdk/flags.test.ts +0 -91
  170. package/src/sdk/flags.ts +0 -108
  171. package/src/sdk/http.test.ts +0 -71
  172. package/src/sdk/http.ts +0 -124
  173. package/src/sdk/index.ts +0 -90
  174. package/src/sdk/inflightTimeout.test.ts +0 -35
  175. package/src/sdk/inflightTimeout.ts +0 -53
  176. package/src/sdk/instrumentedFetch.test.ts +0 -559
  177. package/src/sdk/instrumentedFetch.ts +0 -339
  178. package/src/sdk/invoke.test.ts +0 -115
  179. package/src/sdk/invoke.ts +0 -298
  180. package/src/sdk/logger.test.ts +0 -432
  181. package/src/sdk/logger.ts +0 -304
  182. package/src/sdk/mergeCacheControl.ts +0 -150
  183. package/src/sdk/normalizeUrls.ts +0 -91
  184. package/src/sdk/observability.ts +0 -109
  185. package/src/sdk/otel.test.ts +0 -526
  186. package/src/sdk/otel.ts +0 -1012
  187. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  188. package/src/sdk/otelAdapters.test.ts +0 -89
  189. package/src/sdk/otelAdapters.ts +0 -144
  190. package/src/sdk/otelHttpLog.test.ts +0 -457
  191. package/src/sdk/otelHttpLog.ts +0 -419
  192. package/src/sdk/otelHttpMeter.test.ts +0 -292
  193. package/src/sdk/otelHttpMeter.ts +0 -506
  194. package/src/sdk/otelHttpTracer.test.ts +0 -474
  195. package/src/sdk/otelHttpTracer.ts +0 -543
  196. package/src/sdk/redirects.ts +0 -228
  197. package/src/sdk/requestContext.ts +0 -281
  198. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  199. package/src/sdk/requestContextStorage.browser.ts +0 -43
  200. package/src/sdk/requestContextStorage.ts +0 -35
  201. package/src/sdk/retry.ts +0 -45
  202. package/src/sdk/serverTimings.ts +0 -68
  203. package/src/sdk/signal.ts +0 -42
  204. package/src/sdk/sitemap.ts +0 -160
  205. package/src/sdk/urlRedaction.test.ts +0 -73
  206. package/src/sdk/urlRedaction.ts +0 -82
  207. package/src/sdk/urlUtils.ts +0 -134
  208. package/src/sdk/useDevice.test.ts +0 -130
  209. package/src/sdk/useDevice.ts +0 -89
  210. package/src/sdk/useDeviceContext.tsx +0 -108
  211. package/src/sdk/useId.ts +0 -7
  212. package/src/sdk/useScript.test.ts +0 -128
  213. package/src/sdk/useScript.ts +0 -210
  214. package/src/sdk/useSuggestions.test.ts +0 -230
  215. package/src/sdk/useSuggestions.ts +0 -188
  216. package/src/sdk/wrapCaughtErrors.ts +0 -107
  217. package/src/setup.ts +0 -120
  218. package/src/types/index.ts +0 -53
  219. package/src/types/widgets.ts +0 -14
  220. package/tsconfig.json +0 -7
package/src/cms/loader.ts DELETED
@@ -1,304 +0,0 @@
1
- import * as asyncHooks from "node:async_hooks";
2
- import { djb2Hex } from "../sdk/djb2";
3
- import { getRequestDraftOverride } from "./draftSource";
4
-
5
- export type Resolvable = {
6
- __resolveType?: string;
7
- [key: string]: unknown;
8
- };
9
-
10
- export type DecoPage = {
11
- name: string;
12
- path?: string;
13
- sections: Resolvable[] | Resolvable;
14
- seo?: Record<string, unknown>;
15
- };
16
-
17
- // globalThis-backed storage: TanStack Start server function split modules
18
- // may get isolated module instances. globalThis ensures shared state.
19
- const G = globalThis as any;
20
- if (!G.__deco) G.__deco = {};
21
-
22
- let blockData: Record<string, unknown> = G.__deco.blockData ?? {};
23
- let revision: string | null = G.__deco.revision ?? null;
24
-
25
- interface ALSLike<T> {
26
- getStore(): T | undefined;
27
- run<R>(store: T, fn: () => R): R;
28
- }
29
-
30
- // AsyncLocalStorage might not be available in client builds (Vite replaces
31
- // node:async_hooks with an empty shim). The namespace import avoids Rollup's
32
- // named-export validation, and the runtime check prevents construction errors.
33
- const ALS = (asyncHooks as any).AsyncLocalStorage;
34
- const blocksOverrideStorage: ALSLike<Record<string, unknown>> = ALS
35
- ? new ALS()
36
- : { getStore: () => undefined, run: (_s: any, fn: any) => fn() };
37
-
38
- // ---------------------------------------------------------------------------
39
- // Change listeners
40
- // ---------------------------------------------------------------------------
41
-
42
- type ChangeListener = (blocks: Record<string, unknown>, revision: string) => void;
43
- const changeListeners: ChangeListener[] = [];
44
-
45
- /** Register a callback invoked whenever setBlocks() changes the decofile. */
46
- export function onChange(listener: ChangeListener) {
47
- changeListeners.push(listener);
48
- return () => {
49
- const idx = changeListeners.indexOf(listener);
50
- if (idx >= 0) changeListeners.splice(idx, 1);
51
- };
52
- }
53
-
54
- // ---------------------------------------------------------------------------
55
- // Revision hashing
56
- // ---------------------------------------------------------------------------
57
-
58
- function computeRevision(blocks: Record<string, unknown>): string {
59
- return djb2Hex(JSON.stringify(blocks));
60
- }
61
-
62
- // ---------------------------------------------------------------------------
63
- // Block management
64
- // ---------------------------------------------------------------------------
65
-
66
- /**
67
- * Set the blocks data. Called at startup with generated blocks,
68
- * and by the admin on hot-reload.
69
- * Notifies all onChange listeners and updates the revision.
70
- */
71
- export function setBlocks(blocks: Record<string, unknown>) {
72
- blockData = blocks;
73
- revision = computeRevision(blocks);
74
-
75
- // Persist to globalThis so other module instances see them
76
- G.__deco.blockData = blockData;
77
- G.__deco.revision = revision;
78
-
79
- for (const listener of [...changeListeners]) {
80
- try {
81
- listener(blocks, revision);
82
- } catch (e) {
83
- console.error("[CMS] onChange listener error:", e);
84
- }
85
- }
86
- }
87
-
88
- /**
89
- * Load the current blocks. If running inside a `withBlocksOverride` scope
90
- * (admin preview) or a request carrying a draft-preview override, that
91
- * override is merged on top of the base blocks.
92
- */
93
- export function loadBlocks(): Record<string, unknown> {
94
- // Re-sync from globalThis in case setBlocks was called in another module instance
95
- if (G.__deco.blockData && G.__deco.blockData !== blockData) {
96
- blockData = G.__deco.blockData;
97
- revision = G.__deco.revision ?? null;
98
- }
99
-
100
- // `withBlocksOverride` (an explicit admin render of a specific payload) wins
101
- // over an ambient draft: the caller named the exact blocks to render, so a
102
- // draft pointer on the same request must not silently replace them.
103
- const override = blocksOverrideStorage.getStore() ?? getRequestDraftOverride();
104
- if (override) {
105
- const merged = { ...blockData };
106
- for (const [key, value] of Object.entries(override)) {
107
- if (value === null || value === undefined) {
108
- delete merged[key];
109
- } else {
110
- merged[key] = value;
111
- }
112
- }
113
- return merged;
114
- }
115
- return blockData;
116
- }
117
-
118
- /** Get the current decofile revision hash. Changes on each setBlocks(). */
119
- export function getRevision(): string | null {
120
- return revision;
121
- }
122
-
123
- /**
124
- * Run a function with a temporary blocks overlay.
125
- *
126
- * Used by admin preview: the admin sends a partial decofile (only the
127
- * blocks that changed), and `loadBlocks()` returns the merged result
128
- * for the duration of the render. Other concurrent requests are not
129
- * affected (AsyncLocalStorage is per-request scoped).
130
- */
131
- export function withBlocksOverride<T>(override: Record<string, unknown>, fn: () => T): T {
132
- return blocksOverrideStorage.run(override, fn);
133
- }
134
-
135
- // Higher key wins. Compared lexicographically:
136
- // [hasNoWildcard, literalSegments, paramSegments]
137
- //
138
- // `hasNoWildcard` is the top key so a literal-only path always beats any
139
- // pattern that contains `*` or `{group}?` — including the empty-parts case
140
- // `/` (literals=0) vs the catch-all `/{prefix/}?*` (literals=0, params=1).
141
- // Without this, the URLPattern fix (#213/#214) inadvertently lets a
142
- // `/{group/}?*` catch-all out-rank an exact `/` home page because the
143
- // `{group` segment counted as a param. See deco-sites/granadobr-tanstack
144
- // where `/` was being routed to the granado PDP/PLP block's NotFound
145
- // fallback.
146
- //
147
- // Order produced:
148
- // /foo/bar (no wildcard, literals=2) > /foo/:x (no wildcard, lit=1, param=1)
149
- // /foo (no wildcard) > /{granado/}?* (has wildcard) > /*
150
- function pathSpecificityKey(path: string): [number, number, number] {
151
- const parts = path.split("/").filter(Boolean);
152
- let literals = 0;
153
- let params = 0;
154
- let hasWildcard = false;
155
- for (const part of parts) {
156
- // A wildcard is any `*`, optional group `{...}?`, or any segment
157
- // bearing `?` — these all make the pattern match strictly more URLs
158
- // than a plain literal/`:param`/`:slug([\w-]+)` segment, so they
159
- // are demoted to "least specific" together regardless of count.
160
- if (part.includes("*") || /[{}?]/.test(part)) {
161
- hasWildcard = true;
162
- } else if (part.startsWith(":") || part.startsWith("$")) {
163
- params++;
164
- } else {
165
- literals++;
166
- }
167
- }
168
- return [hasWildcard ? 0 : 1, literals, params];
169
- }
170
-
171
- export function getAllPages(): Array<{ key: string; page: DecoPage }> {
172
- const blocks = loadBlocks();
173
- const pages: Array<{ key: string; page: DecoPage; key2: [number, number, number] }> = [];
174
-
175
- for (const [key, block] of Object.entries(blocks)) {
176
- if (!key.startsWith("pages-")) continue;
177
- const page = block as DecoPage;
178
- if (!page.sections) continue;
179
- if (!page.path) continue;
180
-
181
- pages.push({ key, page, key2: pathSpecificityKey(page.path) });
182
- }
183
-
184
- return pages
185
- .sort((a, b) => {
186
- for (let i = 0; i < a.key2.length; i++) {
187
- if (a.key2[i] !== b.key2[i]) return b.key2[i] - a.key2[i];
188
- }
189
- return 0;
190
- })
191
- .map(({ key, page }) => ({ key, page }));
192
- }
193
-
194
- // Module-scoped (NOT `declare global`) ambient declaration for the
195
- // `URLPattern` Web API. It's natively available at runtime in browsers,
196
- // Cloudflare Workers, Deno, and Node 24+, but its type declarations aren't
197
- // consistently present: TypeScript's bundled lib.dom.d.ts doesn't ship it
198
- // yet, and @types/node only started shipping a global augmentation for it
199
- // in newer major versions (via `node/web-globals/url.d.ts`).
200
- //
201
- // A `declare global` shim here would merge with @types/node's own global
202
- // `URLPattern`/`URLPatternResult` augmentation whenever a new-enough
203
- // @types/node wins the workspace's package hoist — and merging two
204
- // independently-authored global interfaces under the same name throws
205
- // TS2430 ("incorrectly extends") the moment their shapes don't line up
206
- // structurally. Declaring `URLPattern` and its result shape as file-local
207
- // bindings instead (no `declare global`) means this file typechecks the
208
- // same regardless of whether @types/node has its own `URLPattern` global or
209
- // not — there's nothing for a local declaration to collide with.
210
- type MatchPatternResult = {
211
- pathname: { groups: Record<string, string | undefined> };
212
- };
213
- declare const URLPattern: {
214
- new (init: {
215
- pathname: string;
216
- }): {
217
- exec(input: { pathname: string }): MatchPatternResult | null;
218
- };
219
- };
220
-
221
- /**
222
- * Match a CMS page path pattern against a URL path.
223
- *
224
- * Mirrors the original deco-cx/deco Fresh framework
225
- * (`runtime/features/render.tsx`) by delegating to the platform's native
226
- * `URLPattern`. Supports the full URLPattern syntax that the admin emits:
227
- * `:slug`, `:slug([\w-]+)`, optional groups `{...}?`, and trailing `*`
228
- * splats. Splats are exposed as the standard numbered groups (`"0"`, `"1"`,
229
- * …), matching the Fresh shape.
230
- *
231
- * Malformed patterns return `null` instead of throwing — bad CMS data must
232
- * never take down the worker.
233
- *
234
- * A MISSING `URLPattern` API, however, throws loudly and immediately: the
235
- * try/catch below exists to absorb bad *patterns*, and letting it also
236
- * swallow a `ReferenceError` from an old runtime turns "wrong Node version"
237
- * into "every CMS page silently 404s" — the worst possible failure mode.
238
- * `URLPattern` is native in browsers, workerd, Deno, and Node >= 24 (this
239
- * package's `engines` floor). Node 22 and older lack it.
240
- */
241
- export function matchPath(pattern: string, urlPath: string): Record<string, string> | null {
242
- if (typeof URLPattern === "undefined") {
243
- throw new Error(
244
- "@decocms/blocks: this runtime has no URLPattern Web API, so CMS page " +
245
- "paths cannot be matched. URLPattern is native in browsers, " +
246
- "Cloudflare workerd, Deno, and Node.js >= 24 — you are most likely " +
247
- "running Node <= 22. Upgrade the runtime to Node 24+ (see this " +
248
- 'package\'s "engines" field).',
249
- );
250
- }
251
- let result: MatchPatternResult | null;
252
- try {
253
- result = new URLPattern({ pathname: pattern }).exec({ pathname: urlPath });
254
- } catch {
255
- return null;
256
- }
257
- if (!result) return null;
258
-
259
- const groups = result.pathname.groups as Record<string, string | undefined>;
260
- const out: Record<string, string> = {};
261
- for (const [k, v] of Object.entries(groups)) {
262
- if (v !== undefined) out[k] = v;
263
- }
264
- return out;
265
- }
266
-
267
- /**
268
- * Extract the site-wide SEO config from the "Site" app block.
269
- *
270
- * In the original deco-cx/deco framework this is `ctx.seo` — the app-level
271
- * SEO configuration that provides fallback title, description, and templates
272
- * when page-level seo blocks don't supply them.
273
- */
274
- export function getSiteSeo(): {
275
- title?: string;
276
- description?: string;
277
- titleTemplate?: string;
278
- descriptionTemplate?: string;
279
- image?: string;
280
- favicon?: string;
281
- themeColor?: string;
282
- noIndexing?: boolean;
283
- } {
284
- const blocks = loadBlocks();
285
- const site = blocks["Site"] as Record<string, unknown> | undefined;
286
- if (!site) return {};
287
- const seo = site.seo as Record<string, unknown> | undefined;
288
- if (!seo) return {};
289
- return seo as ReturnType<typeof getSiteSeo>;
290
- }
291
-
292
- export function findPageByPath(
293
- targetPath: string,
294
- ): { page: DecoPage; params: Record<string, string>; blockKey: string } | null {
295
- const allPages = getAllPages();
296
-
297
- for (const { key, page } of allPages) {
298
- if (!page.path) continue;
299
- const params = matchPath(page.path, targetPath);
300
- if (params !== null) return { page, params, blockKey: key };
301
- }
302
-
303
- return null;
304
- }
@@ -1,110 +0,0 @@
1
- import { beforeEach, describe, expect, it } from "vitest";
2
- import {
3
- getResolvedComponent,
4
- getSection,
5
- getSectionOptions,
6
- getSyncComponent,
7
- registerSection,
8
- registerSectionsSync,
9
- } from "./registry";
10
-
11
- // Reset globalThis.__deco between tests to avoid cross-test pollution
12
- beforeEach(() => {
13
- const G = globalThis as any;
14
- G.__deco.sectionRegistry = {};
15
- G.__deco.sectionOptions = {};
16
- G.__deco.resolvedComponents = {};
17
- G.__deco.syncComponents = {};
18
- });
19
-
20
- describe("registerSection + getSection", () => {
21
- it("registers and retrieves a section loader", () => {
22
- const loader = async () => ({ default: () => null });
23
- registerSection("site/sections/Hero.tsx", loader);
24
-
25
- const retrieved = getSection("site/sections/Hero.tsx");
26
- expect(retrieved).toBe(loader);
27
- });
28
-
29
- it("returns undefined for unregistered section", () => {
30
- expect(getSection("nonexistent")).toBeUndefined();
31
- });
32
- });
33
-
34
- describe("registerSection with options", () => {
35
- it("stores loadingFallback in section options", () => {
36
- const fallback = () => null;
37
- registerSection("site/sections/Shelf.tsx", async () => ({ default: () => null }), {
38
- loadingFallback: fallback,
39
- });
40
-
41
- const opts = getSectionOptions("site/sections/Shelf.tsx");
42
- expect(opts?.loadingFallback).toBe(fallback);
43
- });
44
-
45
- it("stores clientOnly flag in section options", () => {
46
- registerSection("site/sections/Analytics.tsx", async () => ({ default: () => null }), {
47
- clientOnly: true,
48
- });
49
-
50
- const opts = getSectionOptions("site/sections/Analytics.tsx");
51
- expect(opts?.clientOnly).toBe(true);
52
- });
53
-
54
- it("clientOnly defaults to undefined when not set", () => {
55
- registerSection("site/sections/Normal.tsx", async () => ({ default: () => null }), {
56
- loadingFallback: () => null,
57
- });
58
-
59
- const opts = getSectionOptions("site/sections/Normal.tsx");
60
- expect(opts?.clientOnly).toBeUndefined();
61
- });
62
-
63
- it("clientOnly false is preserved", () => {
64
- registerSection("site/sections/Explicit.tsx", async () => ({ default: () => null }), {
65
- clientOnly: false,
66
- });
67
-
68
- const opts = getSectionOptions("site/sections/Explicit.tsx");
69
- expect(opts?.clientOnly).toBe(false);
70
- });
71
-
72
- it("returns undefined options for section without options", () => {
73
- registerSection("site/sections/Plain.tsx", async () => ({ default: () => null }));
74
- expect(getSectionOptions("site/sections/Plain.tsx")).toBeUndefined();
75
- });
76
- });
77
-
78
- describe("registerSectionsSync", () => {
79
- it("registers component as sync and resolved", () => {
80
- const MyComponent = () => null;
81
- registerSectionsSync({ "site/sections/Header.tsx": MyComponent });
82
-
83
- expect(getSyncComponent("site/sections/Header.tsx")).toBe(MyComponent);
84
- expect(getResolvedComponent("site/sections/Header.tsx")).toBe(MyComponent);
85
- });
86
-
87
- it("accepts module objects with LoadingFallback", () => {
88
- const MyComponent = () => null;
89
- const MyFallback = () => null;
90
-
91
- registerSectionsSync({
92
- "site/sections/Footer.tsx": {
93
- default: MyComponent,
94
- LoadingFallback: MyFallback,
95
- },
96
- });
97
-
98
- expect(getSyncComponent("site/sections/Footer.tsx")).toBe(MyComponent);
99
- const opts = getSectionOptions("site/sections/Footer.tsx");
100
- expect(opts?.loadingFallback).toBe(MyFallback);
101
- });
102
-
103
- it("skips entries without callable default export", () => {
104
- registerSectionsSync({
105
- "site/sections/Bad.tsx": { default: "not a function" } as any,
106
- });
107
-
108
- expect(getSyncComponent("site/sections/Bad.tsx")).toBeUndefined();
109
- });
110
- });
@@ -1,242 +0,0 @@
1
- import type { ComponentType } from "react";
2
-
3
- export type OnBeforeResolveProps = (props: Record<string, unknown>) => Record<string, unknown>;
4
-
5
- export type SectionModule = {
6
- default: ComponentType<any>;
7
- loader?: (props: any) => Promise<any> | any;
8
- onBeforeResolveProps?: OnBeforeResolveProps;
9
- LoadingFallback?: ComponentType<any>;
10
- ErrorFallback?: ComponentType<{ error: Error }>;
11
- };
12
-
13
- type RegistryEntry = () => Promise<SectionModule>;
14
-
15
- export interface SectionOptions {
16
- /** Custom loading fallback component for this section. */
17
- loadingFallback?: ComponentType<any>;
18
- /** Custom error fallback component for this section. */
19
- errorFallback?: ComponentType<{ error: Error }>;
20
- /**
21
- * When true, the section is wrapped in `<ClientOnly>` from TanStack Router.
22
- * It renders only on the client — no SSR, no hydration mismatch.
23
- * Use for analytics scripts, GTM, third-party widgets, and other
24
- * browser-dependent components.
25
- */
26
- clientOnly?: boolean;
27
- }
28
-
29
- // globalThis-backed: server function split modules need access to the registry
30
- const G = globalThis as any;
31
- if (!G.__deco) G.__deco = {};
32
- if (!G.__deco.sectionRegistry) G.__deco.sectionRegistry = {};
33
- if (!G.__deco.sectionOptions) G.__deco.sectionOptions = {};
34
- if (!G.__deco.resolvedComponents) G.__deco.resolvedComponents = {};
35
- if (!G.__deco.syncComponents) G.__deco.syncComponents = {};
36
- if (!G.__deco.onBeforeResolvePropsRegistry) G.__deco.onBeforeResolvePropsRegistry = {};
37
-
38
- const registry: Record<string, RegistryEntry> = G.__deco.sectionRegistry;
39
- const sectionOptions: Record<string, SectionOptions> = G.__deco.sectionOptions;
40
-
41
- // Cache of already-resolved component references.
42
- // When a module is loaded (server-side or after first client import),
43
- // the default export is stored here so subsequent renders can use
44
- // the component directly WITHOUT React.lazy/Suspense — preventing
45
- // hydration flash on SSR'd content.
46
- const resolvedComponents: Record<string, ComponentType<any>> = G.__deco.resolvedComponents;
47
-
48
- // Static sync registry — components that were statically imported and
49
- // are guaranteed available on BOTH server and client without any async import.
50
- // These never need React.lazy/Suspense and render identically on SSR and hydration.
51
- const syncComponents: Record<string, ComponentType<any>> = G.__deco.syncComponents;
52
-
53
- // onBeforeResolveProps registry — functions that transform raw CMS props
54
- // BEFORE resolvables are resolved. Allows sections to extract data from
55
- // raw resolvable structures (e.g., collection IDs from loader refs) that
56
- // would be lost after resolution.
57
- const onBeforeResolvePropsRegistry: Record<string, OnBeforeResolveProps> =
58
- G.__deco.onBeforeResolvePropsRegistry;
59
-
60
- export function registerSection(key: string, loader: RegistryEntry, options?: SectionOptions) {
61
- registry[key] = loader;
62
- if (options) sectionOptions[key] = options;
63
- }
64
-
65
- export function registerSections(
66
- sections: Record<string, RegistryEntry>,
67
- defaultOptions?: SectionOptions,
68
- ) {
69
- for (const [key, loader] of Object.entries(sections)) {
70
- registry[key] = loader;
71
- if (defaultOptions) sectionOptions[key] = { ...defaultOptions };
72
- }
73
- }
74
-
75
- export function getSection(resolveType: string): RegistryEntry | undefined {
76
- return registry[resolveType];
77
- }
78
-
79
- export function getSectionOptions(resolveType: string): SectionOptions | undefined {
80
- return sectionOptions[resolveType];
81
- }
82
-
83
- /**
84
- * Load a section module eagerly to extract LoadingFallback/ErrorFallback.
85
- * Used by DeferredSectionWrapper to show custom skeletons before the section
86
- * scrolls into view and its full props are fetched.
87
- */
88
- export async function preloadSectionModule(
89
- resolveType: string,
90
- ): Promise<SectionOptions | undefined> {
91
- const existing = sectionOptions[resolveType];
92
- if (existing?.loadingFallback) return existing;
93
-
94
- const loader = registry[resolveType];
95
- if (!loader) return undefined;
96
-
97
- try {
98
- const mod = await loader();
99
- const opts: SectionOptions = { ...existing };
100
- if (mod.LoadingFallback) opts.loadingFallback = mod.LoadingFallback;
101
- if (mod.ErrorFallback) opts.errorFallback = mod.ErrorFallback;
102
- sectionOptions[resolveType] = opts;
103
- return opts;
104
- } catch (e) {
105
- console.warn(`[Registry] Failed to preload section module "${resolveType}":`, e);
106
- return existing;
107
- }
108
- }
109
-
110
- /**
111
- * Get a previously resolved component. Returns undefined if the module
112
- * hasn't been imported yet. Use this to render WITHOUT React.lazy/Suspense
113
- * for sections whose JS is already loaded — avoids hydration flash.
114
- */
115
- export function getResolvedComponent(key: string): ComponentType<any> | undefined {
116
- return resolvedComponents[key];
117
- }
118
-
119
- /**
120
- * Store a resolved component reference. Called after a successful import()
121
- * so future renders can skip React.lazy entirely.
122
- */
123
- export function setResolvedComponent(key: string, component: ComponentType<any>): void {
124
- resolvedComponents[key] = component;
125
- }
126
-
127
- /**
128
- * Pre-import section modules and cache their default exports.
129
- * Called server-side after resolving eager sections so that
130
- * the SSR render tree uses direct component refs instead of React.lazy.
131
- */
132
- export async function preloadSectionComponents(keys: string[]): Promise<void> {
133
- await Promise.all(
134
- keys.map(async (key) => {
135
- if (resolvedComponents[key]) return;
136
- const loader = registry[key];
137
- if (!loader) return;
138
- try {
139
- const mod = await loader();
140
- if (mod?.default) {
141
- resolvedComponents[key] = mod.default;
142
- }
143
- if (mod?.onBeforeResolveProps && !onBeforeResolvePropsRegistry[key]) {
144
- onBeforeResolvePropsRegistry[key] = mod.onBeforeResolveProps;
145
- }
146
- const opts: SectionOptions = { ...sectionOptions[key] };
147
- if (mod.LoadingFallback) opts.loadingFallback = mod.LoadingFallback;
148
- if (mod.ErrorFallback) opts.errorFallback = mod.ErrorFallback;
149
- sectionOptions[key] = opts;
150
- } catch (e) {
151
- console.warn(`[Registry] Failed to preload component "${key}":`, e);
152
- }
153
- }),
154
- );
155
- }
156
-
157
- /**
158
- * A sync section entry: either a plain component reference or a full module
159
- * object with optional LoadingFallback and ErrorFallback.
160
- * Providing the full module allows DeferredSectionWrapper to show the correct
161
- * skeleton immediately (optionsReady=true on first render) without waiting for
162
- * the async preloadSectionModule() call.
163
- */
164
- export type SyncSectionEntry =
165
- | ComponentType<any>
166
- | {
167
- default: ComponentType<any>;
168
- LoadingFallback?: ComponentType<any>;
169
- ErrorFallback?: ComponentType<{ error: Error }>;
170
- };
171
-
172
- /**
173
- * Register sections with their already-imported component references.
174
- * These are available synchronously on both server and client — no dynamic
175
- * import, no React.lazy, no Suspense. Use for critical above-the-fold
176
- * sections that must never flash during hydration.
177
- *
178
- * Accepts either a plain component or a full module object (with optional
179
- * LoadingFallback / ErrorFallback). Providing the module object populates
180
- * sectionOptions immediately, so DeferredSectionWrapper can show the correct
181
- * skeleton without an extra async preloadSectionModule() round-trip.
182
- */
183
- export function registerSectionsSync(sections: Record<string, SyncSectionEntry>): void {
184
- for (const [key, entry] of Object.entries(sections)) {
185
- const raw = typeof entry === "function" ? entry : (entry as any).default;
186
- // Accept functions and React wrapper objects (React.memo, forwardRef, lazy)
187
- const REACT_WRAPPERS = [
188
- Symbol.for("react.memo"),
189
- Symbol.for("react.forward_ref"),
190
- Symbol.for("react.lazy"),
191
- ];
192
- const component =
193
- typeof raw === "function" ||
194
- (raw != null && typeof raw === "object" && REACT_WRAPPERS.includes((raw as any).$$typeof))
195
- ? raw
196
- : undefined;
197
- if (!component) {
198
- console.warn(`[registerSectionsSync] "${key}" has no callable default export — skipping`);
199
- continue;
200
- }
201
- syncComponents[key] = component;
202
- resolvedComponents[key] = component;
203
-
204
- if (typeof entry !== "function") {
205
- const opts: SectionOptions = { ...sectionOptions[key] };
206
- if (entry.LoadingFallback) opts.loadingFallback = entry.LoadingFallback;
207
- if (entry.ErrorFallback) opts.errorFallback = entry.ErrorFallback;
208
- sectionOptions[key] = opts;
209
- }
210
- }
211
- }
212
-
213
- /**
214
- * Get a synchronously-registered component. Returns undefined if the
215
- * section was only registered with a lazy loader (registerSections).
216
- */
217
- export function getSyncComponent(key: string): ComponentType<any> | undefined {
218
- return syncComponents[key];
219
- }
220
-
221
- /**
222
- * Register an onBeforeResolveProps function for a section.
223
- * Called with raw CMS props (containing unresolved `__resolveType` references)
224
- * BEFORE the resolution engine resolves them. Use to extract metadata from
225
- * resolvable structures that would be lost after resolution.
226
- */
227
- export function registerOnBeforeResolveProps(sectionKey: string, fn: OnBeforeResolveProps): void {
228
- onBeforeResolvePropsRegistry[sectionKey] = fn;
229
- }
230
-
231
- /** Get the registered onBeforeResolveProps for a section, if any. */
232
- export function getOnBeforeResolveProps(sectionKey: string): OnBeforeResolveProps | undefined {
233
- return onBeforeResolvePropsRegistry[sectionKey];
234
- }
235
-
236
- export function listRegisteredSections(): string[] {
237
- return Object.keys(registry);
238
- }
239
-
240
- export function getSectionRegistry(): Record<string, RegistryEntry> {
241
- return registry;
242
- }