@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
@@ -0,0 +1,240 @@
1
+ /**
2
+ * Public types of the next-major (v8) core SDK. See the API reference
3
+ * (`/next/api-reference#types`) — every type here is documented there.
4
+ */
5
+ import type { ReactNode } from "react";
6
+
7
+ // ---------------------------------------------------------------------------
8
+ // Blocks and content
9
+ // ---------------------------------------------------------------------------
10
+
11
+ /**
12
+ * A block as stored: the JSON in `.deco/blocks`, and what `client.list` and
13
+ * `{ run: false }` return. Props never use it: a field's type is the value the
14
+ * function receives.
15
+ */
16
+ export type Block = { __resolveType: string; [input: string]: unknown };
17
+
18
+ /** A function a block can call. */
19
+ export type BlockFunction = (inputs: any) => unknown | Promise<unknown>;
20
+
21
+ /** A block map: what `.deco/index.ts` exports and the CLI reads. */
22
+ export type Blocks = Record<string, BlockFunction>;
23
+
24
+ /** One fixed copy of the content: what the content module exports and `load()` returns. */
25
+ export type Snapshot = {
26
+ revision: string;
27
+ /** The content map: entry name → saved JSON. */
28
+ blocks: Record<string, unknown>;
29
+ /** The alias table `deco content` writes: old type name → your type. */
30
+ aliases?: Record<string, string>;
31
+ };
32
+
33
+ /**
34
+ * The content module `deco content` writes: a snapshot plus `root`, the
35
+ * `.deco` folder it was generated from, which `createCMS` keys its instance
36
+ * on (see /next/api-reference#one-instance-per-process). Not exported.
37
+ */
38
+ export type ContentModule = Snapshot & { root?: string };
39
+
40
+ /** A source of content. `load()` is the release; `load(pointer)` is a draft. */
41
+ export interface Loader {
42
+ load(pointer?: string | null): Promise<Snapshot>;
43
+ update?(): Promise<{ updated: boolean }>;
44
+ }
45
+
46
+ /** The parts of a draft pointer, `<host[:port]><path[?query]>@<version>`. */
47
+ export interface DraftPointer {
48
+ /** `host[:port]` of the content source that holds the draft. */
49
+ host: string;
50
+ /** Starts with `/`; opaque to the app. */
51
+ path: string;
52
+ /** Opaque and immutable: the branch head or ETag. */
53
+ version: string;
54
+ }
55
+
56
+ // ---------------------------------------------------------------------------
57
+ // Built-in types
58
+ // ---------------------------------------------------------------------------
59
+
60
+ /** An entry that lives at a URL. Extend it to make a type routable. */
61
+ export interface Route {
62
+ /** @title Name */
63
+ name: string;
64
+ /** @title Path */
65
+ path: string;
66
+ }
67
+
68
+ export interface Seo {
69
+ title: string;
70
+ description: string;
71
+ }
72
+
73
+ /** The built-in `page` block, resolved: without `seo`, the site's defaults apply. */
74
+ export interface Page extends Route {
75
+ seo?: Seo;
76
+ sections: ReactNode[];
77
+ }
78
+
79
+ /** The built-in `redirect` block. */
80
+ export interface Redirect {
81
+ /** Literal path or template (`:name` segments, an optional trailing `/*`). */
82
+ from: string;
83
+ to: string;
84
+ /** `true` for a 301, `false` for a 302. */
85
+ permanent: boolean;
86
+ /** Wins over `permanent`. */
87
+ status?: RedirectStatus;
88
+ /** Drop the request's query string instead of carrying it over. */
89
+ discardQueryParameters?: boolean;
90
+ }
91
+
92
+ export type RedirectStatus = 301 | 302 | 307 | 308;
93
+
94
+ /**
95
+ * The nested redirect shape v7 content stores (`website/loaders/redirect.ts`).
96
+ * `matchRoute` accepts it next to {@link Redirect}: `permanent` is a 301 and
97
+ * anything else a 307, the status the site editor has always written for it.
98
+ */
99
+ export interface LegacyRedirect {
100
+ redirect: {
101
+ from: string;
102
+ to: string;
103
+ type?: "permanent" | "temporary";
104
+ discardQueryParameters?: boolean;
105
+ };
106
+ }
107
+
108
+ /** A field the site editor saves encrypted, as a `secret` block. */
109
+ export type Secret = string & { readonly __secret: true };
110
+
111
+ /** A prop the built-in `lazy` block fills; resolves its value when called, at most once. */
112
+ export type Lazy<T> = () => Promise<T>;
113
+
114
+ /** One entry of `variants`: a rule and the variant it shows. */
115
+ export interface Variant<T> {
116
+ rule: boolean;
117
+ value: Lazy<T>;
118
+ }
119
+
120
+ /** The `Telemetry` saved block's type (built-in `telemetry`). */
121
+ export interface Telemetry {
122
+ /** Default `true`; `false` switches telemetry off. */
123
+ enabled?: boolean;
124
+ /** Default `true`. */
125
+ metrics?: boolean;
126
+ /** Default 0.05, capped by `telemetry.limits`. */
127
+ errorSampleRate?: number;
128
+ /** Default 0, capped by `telemetry.limits`. */
129
+ traceSampleRate?: number;
130
+ }
131
+
132
+ /** The built-in `analytics` block's props. Separate from telemetry. */
133
+ export interface Analytics {
134
+ /** An endpoint that accepts the One Dollar Stats format; default: the hosted Deco CMS collector. */
135
+ collector?: string;
136
+ /** Default `true`; `false` makes `AnalyticsScript` render nothing. */
137
+ enabled?: boolean;
138
+ }
139
+
140
+ // ---------------------------------------------------------------------------
141
+ // Results and errors
142
+ // ---------------------------------------------------------------------------
143
+
144
+ export type CMSErrorCode =
145
+ | "NOT_FOUND"
146
+ | "UNKNOWN_BLOCK"
147
+ | "CYCLE"
148
+ | "BLOCK_FAILED"
149
+ | "LOADER_FAILED";
150
+
151
+ export interface CMSError {
152
+ code: CMSErrorCode;
153
+ message: string;
154
+ /** Where in the tree it happened, such as `["sections", 2, "product"]`. */
155
+ path: (string | number)[];
156
+ /** The original error, for `BLOCK_FAILED` and `LOADER_FAILED`. */
157
+ cause?: unknown;
158
+ }
159
+
160
+ export type Result<T> = [T, null] | [null, CMSError];
161
+
162
+ // ---------------------------------------------------------------------------
163
+ // Routing
164
+ // ---------------------------------------------------------------------------
165
+
166
+ export type Match<T> =
167
+ | { kind: "match"; entry: T; params: Record<string, string> }
168
+ | { kind: "redirect"; location: string; status: RedirectStatus }
169
+ | { kind: "not-found" };
170
+
171
+ // ---------------------------------------------------------------------------
172
+ // The CMS and its clients
173
+ // ---------------------------------------------------------------------------
174
+
175
+ export type TelemetryConfig = (
176
+ | { site: string; token: string }
177
+ | { endpoint: string; headers?: Record<string, string> }
178
+ ) & {
179
+ limits?: { errorSampleRate?: number; traceSampleRate?: number };
180
+ };
181
+
182
+ export interface CMSConfig {
183
+ /** Your block functions; the CMS uses `{ ...builtIns, ...blocks }`. */
184
+ blocks: Blocks;
185
+ /** The content module (`.deco/blocks.gen.ts`), or any {@link Loader}. */
186
+ content: ContentModule | Loader;
187
+ /** ms between `update()` checks of a content source that has one; minimum 60 000. */
188
+ interval?: number;
189
+ /** Where telemetry goes; see /next/telemetry. */
190
+ telemetry?: false | TelemetryConfig;
191
+ /** The private key that decrypts `secret` blocks. */
192
+ secrets?: { key?: string };
193
+ /** Your site's ID, for hosted releases and drafts. */
194
+ site?: string;
195
+ /** Your site token (secret), for hosted releases and drafts. */
196
+ token?: string;
197
+ }
198
+
199
+ export interface ResolveOptions {
200
+ /** `false` reads without running: saved blocks expand, no function runs. */
201
+ run?: boolean;
202
+ }
203
+
204
+ export interface ListOptions<T> {
205
+ where?: (entry: T) => boolean;
206
+ sort?: (a: T, b: T) => number;
207
+ limit?: number;
208
+ run?: boolean;
209
+ }
210
+
211
+ /**
212
+ * Reads one revision for one request.
213
+ *
214
+ * Results are read-only. A client runs each block function once per distinct
215
+ * input, so the same block at two places in a request hands both places the
216
+ * same object; mutating it in place changes the other occurrence too. Copy a
217
+ * result before changing it. (The memo belongs to one client, so nothing is
218
+ * shared across requests.)
219
+ */
220
+ export interface Client {
221
+ resolve<T = unknown>(target: unknown, options?: ResolveOptions): Promise<Result<T>>;
222
+ list<T = Block>(type: string, options?: ListOptions<T>): Promise<Result<T[]>>;
223
+ /**
224
+ * The revision this client reads (loads it on first use). Unlike `resolve`
225
+ * and `list`, it rejects with the `LOADER_FAILED` error when the content
226
+ * can't load, since there is no revision to report.
227
+ */
228
+ revision(): Promise<string>;
229
+ }
230
+
231
+ export interface CMS {
232
+ /** A client reading the current release. */
233
+ forRelease(): Client;
234
+ /** A client reading the draft a pointer names. */
235
+ forDraft(pointer: string): Client;
236
+ /** A client pinned to a revision this CMS has served; an unknown revision behaves like the release. */
237
+ forRevision(revision: string): Client;
238
+ /** Ask the content source for newer content now; never throws. */
239
+ update(): Promise<{ updated: boolean }>;
240
+ }
@@ -1,124 +0,0 @@
1
- /**
2
- * Applies convention-based section metadata generated by generate-sections.ts.
3
- *
4
- * Reads the generated sectionMeta/syncComponents/loadingFallbacks and calls
5
- * the appropriate registration functions — replacing manual calls to
6
- * registerSectionsSync, setAsyncRenderingConfig, registerCacheableSections,
7
- * registerLayoutSections, registerSeoSections, and registerSection.
8
- */
9
- import { registerSection, registerSectionsSync } from "./registry";
10
- import {
11
- type AsyncRenderingConfig,
12
- getAsyncRenderingConfig,
13
- registerEagerSections,
14
- registerNeverDeferSections,
15
- registerSeoSections,
16
- setAsyncRenderingConfig,
17
- } from "./resolve";
18
- import {
19
- type CacheableSectionInput,
20
- registerCacheableSections,
21
- registerLayoutSections,
22
- } from "./sectionLoaders";
23
-
24
- export interface SectionMetaEntry {
25
- eager?: boolean;
26
- neverDefer?: boolean;
27
- cache?: string;
28
- layout?: boolean;
29
- sync?: boolean;
30
- clientOnly?: boolean;
31
- seo?: boolean;
32
- hasLoadingFallback?: boolean;
33
- }
34
-
35
- export interface ApplySectionConventionsInput {
36
- /** Section metadata map from sections.gen.ts */
37
- meta: Record<string, SectionMetaEntry>;
38
- /** Sync-imported section modules from sections.gen.ts */
39
- syncComponents?: Record<string, any>;
40
- /** LoadingFallback components from sections.gen.ts */
41
- loadingFallbacks?: Record<string, React.ComponentType<any>>;
42
- /** Lazy section loaders from import.meta.glob (used for clientOnly/loadingFallback registration) */
43
- sectionGlob?: Record<string, () => Promise<any>>;
44
- }
45
-
46
- export function applySectionConventions(input: ApplySectionConventionsInput): void {
47
- const { meta, syncComponents, loadingFallbacks, sectionGlob } = input;
48
-
49
- const eagerSections: string[] = [];
50
- const neverDeferSections: string[] = [];
51
- const layoutSections: string[] = [];
52
- const seoSections: string[] = [];
53
- const cacheableSections: Record<string, CacheableSectionInput> = {};
54
-
55
- for (const [key, entry] of Object.entries(meta)) {
56
- if (entry.eager) eagerSections.push(key);
57
- if (entry.neverDefer) neverDeferSections.push(key);
58
- if (entry.layout) layoutSections.push(key);
59
- if (entry.seo) seoSections.push(key);
60
- if (entry.cache) cacheableSections[key] = entry.cache as CacheableSectionInput;
61
-
62
- if (entry.clientOnly && sectionGlob) {
63
- const globKey = sectionGlobKey(key, sectionGlob);
64
- if (globKey) {
65
- registerSection(key, sectionGlob[globKey] as any, { clientOnly: true });
66
- }
67
- }
68
-
69
- if (entry.hasLoadingFallback && loadingFallbacks?.[key] && sectionGlob) {
70
- const globKey = sectionGlobKey(key, sectionGlob);
71
- if (globKey) {
72
- registerSection(key, sectionGlob[globKey] as any, {
73
- loadingFallback: loadingFallbacks[key],
74
- });
75
- }
76
- }
77
- }
78
-
79
- if (syncComponents && Object.keys(syncComponents).length > 0) {
80
- registerSectionsSync(syncComponents);
81
- }
82
-
83
- if (eagerSections.length > 0) {
84
- registerEagerSections(eagerSections);
85
- }
86
-
87
- if (neverDeferSections.length > 0) {
88
- registerNeverDeferSections(neverDeferSections);
89
- }
90
-
91
- // Always initialize asyncConfig so CMS Lazy deferral (`respectCmsLazy`) is
92
- // active — this is what makes the admin ⚡ toggle the source of truth. Without
93
- // it, asyncConfig stays null, `useAsync` is false in resolveDecoPage, and
94
- // even editor-marked ⚡ sections render eagerly. (The default foldThreshold is
95
- // Infinity, so position-based deferral stays off unless a site opts in.)
96
- const existing: Partial<AsyncRenderingConfig> = getAsyncRenderingConfig() ?? {};
97
- setAsyncRenderingConfig({
98
- ...existing,
99
- alwaysEager: [...(existing.alwaysEager ?? []), ...eagerSections],
100
- });
101
-
102
- if (layoutSections.length > 0) {
103
- registerLayoutSections(layoutSections);
104
- }
105
-
106
- if (seoSections.length > 0) {
107
- registerSeoSections(seoSections);
108
- }
109
-
110
- if (Object.keys(cacheableSections).length > 0) {
111
- registerCacheableSections(cacheableSections);
112
- }
113
- }
114
-
115
- function sectionGlobKey(
116
- sectionKey: string,
117
- glob: Record<string, () => Promise<any>>,
118
- ): string | null {
119
- const relative = sectionKey.replace("site/sections/", "./sections/");
120
- if (glob[relative]) return relative;
121
- const withDot = sectionKey.replace("site/", "./");
122
- if (glob[withDot]) return withDot;
123
- return null;
124
- }
@@ -1,76 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { djb2Hex } from "../sdk/djb2";
3
- import {
4
- BundledBlockSource,
5
- computeRevision,
6
- DEPLOYMENTS_KEY,
7
- type KVNamespace,
8
- LIVE_KEY,
9
- revisionKey,
10
- snapshotKey,
11
- } from "./blockSource";
12
-
13
- describe("computeRevision", () => {
14
- it("matches loader.ts computeRevision (djb2Hex of JSON.stringify)", () => {
15
- const blocks = { Site: { name: "x" }, "pages-home": { path: "/" } };
16
- expect(computeRevision(blocks)).toBe(djb2Hex(JSON.stringify(blocks)));
17
- });
18
-
19
- it("is stable for the same input and differs on change", () => {
20
- const a = { a: 1 };
21
- const b = { a: 2 };
22
- expect(computeRevision(a)).toBe(computeRevision(a));
23
- expect(computeRevision(a)).not.toBe(computeRevision(b));
24
- });
25
-
26
- it("hashes an empty decofile without throwing", () => {
27
- expect(typeof computeRevision({})).toBe("string");
28
- });
29
- });
30
-
31
- describe("BundledBlockSource", () => {
32
- it("loadSnapshot resolves null (bundled is applied at startup, not here)", async () => {
33
- const src = new BundledBlockSource();
34
- await expect(src.loadSnapshot()).resolves.toBeNull();
35
- });
36
-
37
- it("getRevision resolves null", async () => {
38
- const src = new BundledBlockSource();
39
- await expect(src.getRevision()).resolves.toBeNull();
40
- });
41
- });
42
-
43
- describe("KV key layout (per deployment)", () => {
44
- it("keys the snapshot and revision by deployment id", () => {
45
- expect(snapshotKey("abc123")).toBe("decofile:abc123");
46
- expect(revisionKey("abc123")).toBe("index:revision:abc123");
47
- });
48
-
49
- it("exposes stable pointer/bookkeeping keys", () => {
50
- expect(LIVE_KEY).toBe("index:live");
51
- expect(DEPLOYMENTS_KEY).toBe("index:deployments");
52
- });
53
- });
54
-
55
- describe("KVNamespace structural type", () => {
56
- it("a plain Map-backed stub satisfies the interface", async () => {
57
- const store = new Map<string, string>();
58
- const kv: KVNamespace = {
59
- get: (k) => Promise.resolve(store.get(k) ?? null),
60
- put: (k, v) => {
61
- store.set(k, v);
62
- return Promise.resolve();
63
- },
64
- delete: (k) => {
65
- store.delete(k);
66
- return Promise.resolve();
67
- },
68
- };
69
-
70
- const key = revisionKey("abc123");
71
- await kv.put(key, "abc");
72
- await expect(kv.get(key)).resolves.toBe("abc");
73
- await kv.delete(key);
74
- await expect(kv.get(key)).resolves.toBeNull();
75
- });
76
- });
@@ -1,191 +0,0 @@
1
- /**
2
- * BlockSource — the runtime source of truth for the CMS decofile.
3
- *
4
- * A `BlockSource` asynchronously yields the *whole* decofile snapshot (the
5
- * `Record<string, unknown>` blocks map) plus its revision hash. This is the
6
- * "fast deploy" seam: the framework can hydrate the in-memory block map from a
7
- * remote source (Cloudflare KV) on cold start and swap it on revision change,
8
- * WITHOUT making the synchronous resolution hot path (`loadBlocks()` in
9
- * `loader.ts`) async.
10
- *
11
- * Design note (whole-snapshot vs per-block): the resolver calls `loadBlocks()`
12
- * synchronously in dozens of places (matchers, deferral checks, page lookup,
13
- * SEO). Rather than threading `async` through all of that, a `BlockSource`
14
- * loads the entire decofile once and the framework calls `setBlocks()` to swap
15
- * the in-memory map. Per-request reads stay in-memory (zero added latency); KV
16
- * is touched only on cold start and during the opportunistic revision poll.
17
- *
18
- * Mirrors the `DecofileProvider` pattern from the original deco-cx/deco Fresh
19
- * runtime (`engine/decofile/provider.ts`), trimmed to what the snapshot-swap
20
- * model needs.
21
- */
22
-
23
- import { djb2Hex } from "../sdk/djb2";
24
-
25
- /** A fully-loaded decofile snapshot: the blocks map and its revision hash. */
26
- export interface BlockSnapshot {
27
- /** The decofile — a flat map of block name → block JSON. */
28
- blocks: Record<string, unknown>;
29
- /** DJB2 hex revision computed over the blocks (see `computeRevision`). */
30
- revision: string;
31
- }
32
-
33
- /**
34
- * Source of the runtime decofile snapshot.
35
- *
36
- * Implementations:
37
- * - `BundledBlockSource` — the build-time `blocks.gen` snapshot (fallback /
38
- * local dev). A no-op here because `setup.ts` already loads it via
39
- * `setBlocks()` at module init.
40
- * - `KVBlockSource` — reads `decofile:<id>` + `index:revision:<id>` (keyed by
41
- * deployment id) from a Cloudflare KV namespace.
42
- */
43
- export interface BlockSource {
44
- /**
45
- * Load the full decofile snapshot. Returns `null` when this source has no
46
- * snapshot to offer (e.g. KV key missing, or the bundled source which is
47
- * already applied at startup) — the caller then keeps whatever blocks are
48
- * currently in memory.
49
- */
50
- loadSnapshot(): Promise<BlockSnapshot | null>;
51
-
52
- /**
53
- * Cheap revision probe used for change detection during polling. Returns the
54
- * current revision without transferring the full snapshot, or `null` when
55
- * unavailable.
56
- */
57
- getRevision(): Promise<string | null>;
58
- }
59
-
60
- /**
61
- * Compute the revision hash for a blocks map.
62
- *
63
- * MUST match `computeRevision` in `loader.ts` (DJB2 over the JSON string) so
64
- * that a snapshot written to KV and the revision stored alongside it agree
65
- * with the revision an isolate computes after `setBlocks()` — otherwise the
66
- * poller would see a permanent mismatch and reload on every tick.
67
- */
68
- export function computeRevision(blocks: Record<string, unknown>): string {
69
- return djb2Hex(JSON.stringify(blocks));
70
- }
71
-
72
- /**
73
- * Bundled (build-time) snapshot source.
74
- *
75
- * Intentionally a no-op `loadSnapshot()`: the bundled `blocks.gen` is applied
76
- * by `createSiteSetup()` → `setBlocks()` at module load, before any request.
77
- * This exists so callers can treat "bundled" uniformly through the
78
- * `BlockSource` interface and so the composition layer (KV primary + bundled
79
- * fallback) has a concrete fallback object.
80
- */
81
- export class BundledBlockSource implements BlockSource {
82
- loadSnapshot(): Promise<BlockSnapshot | null> {
83
- return Promise.resolve(null);
84
- }
85
-
86
- getRevision(): Promise<string | null> {
87
- return Promise.resolve(null);
88
- }
89
- }
90
-
91
- // ---------------------------------------------------------------------------
92
- // Minimal Cloudflare KV type
93
- // ---------------------------------------------------------------------------
94
-
95
- /**
96
- * Minimal structural type for a Cloudflare KV namespace binding.
97
- *
98
- * Declared locally (matching the pattern in `workerEntry.ts`, which defines
99
- * its own `WorkerExecutionContext`) so `@decocms/start` does not depend on
100
- * `@cloudflare/workers-types`. Only the methods the framework actually uses
101
- * are modeled.
102
- */
103
- export interface KVNamespace {
104
- get(key: string, options?: { type?: "text" }): Promise<string | null>;
105
- put(
106
- key: string,
107
- value: string,
108
- options?: { expirationTtl?: number; metadata?: Record<string, unknown> },
109
- ): Promise<void>;
110
- delete(key: string): Promise<void>;
111
- }
112
-
113
- // ---------------------------------------------------------------------------
114
- // KV key layout — keyed by DEPLOYMENT ID so every code deployment reads its own
115
- // content snapshot (deploy isolation, cheap rollback, build-time content sync).
116
- //
117
- // The deployment id is the git commit sha (see `getDeploymentId` below).
118
- // Shared by the runtime reader (`kvBlockSource.ts`), the write-through path
119
- // (`admin/decofile.ts`), and the CI sync/migrate scripts, so the contract can't
120
- // drift between read and write sides.
121
- //
122
- // decofile:<id> full decofile JSON for deployment <id>
123
- // index:revision:<id> DJB2 hex revision of that snapshot (polled)
124
- // index:live pointer to the currently-live <id> (set post-deploy)
125
- // index:deployments JSON [{id, ts}] (newest last) — GC bookkeeping
126
- // ---------------------------------------------------------------------------
127
-
128
- /** KV key holding the full decofile JSON for deployment `id`. */
129
- export function snapshotKey(id: string): string {
130
- return `decofile:${id}`;
131
- }
132
-
133
- /** KV key holding the DJB2 hex revision of deployment `id`'s snapshot. */
134
- export function revisionKey(id: string): string {
135
- return `index:revision:${id}`;
136
- }
137
-
138
- /** Pointer key naming the currently-live deployment id. Written by a code
139
- * deploy AFTER the new version has activated (so a rolling deploy never points
140
- * live at a version that isn't serving yet). */
141
- export const LIVE_KEY = "index:live";
142
-
143
- /** Bookkeeping key: JSON array of `{ id, ts }` (newest last) tracking known
144
- * deployment snapshots so the sync script can GC all but the last N. */
145
- export const DEPLOYMENTS_KEY = "index:deployments";
146
-
147
- // ---------------------------------------------------------------------------
148
- // Deployment id resolution
149
- //
150
- // Which snapshot key does THIS running worker read/write? The deployment id.
151
- // Kept here (framework-agnostic) alongside the key builders it feeds, so the
152
- // runtime read path (`@decocms/tanstack` kvHydration) and the write-through
153
- // path (`@decocms/blocks-admin` decofile) resolve it identically — no drift.
154
- // ---------------------------------------------------------------------------
155
-
156
- /** Deploy-time var naming this version's content snapshot key. Set by the
157
- * deploy command (`wrangler deploy --var DECO_DEPLOYMENT_ID:<sha>`). */
158
- export const DEPLOYMENT_ID_ENV = "DECO_DEPLOYMENT_ID";
159
-
160
- /** Fallback var (cache-key version) — the same commit sha, already threaded by
161
- * some sites via `--var BUILD_HASH:<sha>`. */
162
- export const BUILD_HASH_ENV = "BUILD_HASH";
163
-
164
- // Build-time constant injected by the tanstack `decoVitePlugin()` (git
165
- // rev-parse / WORKERS_CI_COMMIT_SHA) as the last-resort deployment id. Declared
166
- // here with a `typeof` guard so it's inert where the define isn't applied
167
- // (e.g. the Next.js build, or this package's own tsc output).
168
- declare const __DECO_BUILD_HASH__: string | undefined;
169
-
170
- /**
171
- * Resolve this worker's deployment id — the key its content is stored under
172
- * (`decofile:<id>`). Priority:
173
- * 1. `env.DECO_DEPLOYMENT_ID` — set by the deploy command (authoritative).
174
- * 2. `env.BUILD_HASH` — the cache-key version var; the same commit sha.
175
- * 3. `__DECO_BUILD_HASH__` — build-time constant (the commit the bundle, and
176
- * thus the build-time content sync, was produced from).
177
- * Returns `null` when none resolves — the caller then serves the bundled
178
- * snapshot (never another deployment's content).
179
- */
180
- export function getDeploymentId(env: Record<string, unknown>): string | null {
181
- const fromDeploymentVar = env[DEPLOYMENT_ID_ENV];
182
- if (typeof fromDeploymentVar === "string" && fromDeploymentVar) {
183
- return fromDeploymentVar;
184
- }
185
- const fromBuildHash = env[BUILD_HASH_ENV];
186
- if (typeof fromBuildHash === "string" && fromBuildHash) return fromBuildHash;
187
- if (typeof __DECO_BUILD_HASH__ !== "undefined" && __DECO_BUILD_HASH__) {
188
- return __DECO_BUILD_HASH__;
189
- }
190
- return null;
191
- }
@@ -1,44 +0,0 @@
1
- import { execFileSync } from "node:child_process";
2
- import { dirname, join } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
- import { describe, expect, it } from "vitest";
5
-
6
- const here = dirname(fileURLToPath(import.meta.url));
7
- // esbuild's JS API relies on `new TextEncoder().encode("") instanceof
8
- // Uint8Array` internally, which fails across Vitest's module-isolation VM
9
- // boundary (a realm mismatch, not a real environment problem — `bun -e`
10
- // confirms the invariant holds outside Vitest). Shelling out to the esbuild
11
- // CLI binary sidesteps this: it's a separate OS process, no shared JS realm.
12
- const esbuildBin = join(here, "../../../../node_modules/.bin/esbuild");
13
-
14
- function bundleForBrowser(entry: string) {
15
- return execFileSync(
16
- esbuildBin,
17
- [entry, "--bundle", "--platform=browser", "--format=esm", "--external:react"],
18
- { encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] },
19
- );
20
- }
21
-
22
- /**
23
- * Regression test for the bug that motivated splitting `client.ts` out of
24
- * `index.ts`: importing ANYTHING from the full `cms` barrel forces a
25
- * bundler to evaluate `loader.ts` and `middleware/observability.ts`, which
26
- * import `node:async_hooks` at the module level. Turbopack rejects that
27
- * outright when bundling for a browser target; this test catches the same
28
- * class of failure in CI, deterministically, without needing a real Next.js
29
- * app to reproduce it.
30
- */
31
- describe("cms/client browser bundle", () => {
32
- it("bundles for a browser target with no Node built-ins", () => {
33
- const output = bundleForBrowser(join(here, "client.ts"));
34
- expect(output).not.toMatch(/node:async_hooks|node:fs|node:path/);
35
- });
36
-
37
- it("sanity check: the full cms barrel does NOT bundle for a browser target", () => {
38
- // Confirms the test above is actually discriminating — if this ever
39
- // stops throwing, either the barrel no longer has the leak (great,
40
- // update this test) or esbuild's Node-builtin detection changed
41
- // (investigate before trusting the test above).
42
- expect(() => bundleForBrowser(join(here, "index.ts"))).toThrow();
43
- });
44
- });