@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,507 @@
1
+ /**
2
+ * `deco schema`: reads the default export of `.deco/index.ts` (the block map)
3
+ * and writes `.deco/schema.gen.json` in the site editor's format,
4
+ * `deco-meta@1` (spec: schema; studio-compatibility › What the site editor
5
+ * reads from the schema).
6
+ *
7
+ * The file has the shape of today's `meta.gen.json`, so the site editor reads
8
+ * it unchanged: `manifest.blocks` groups every block type by kind,
9
+ * `schema.definitions` holds one JSON Schema per type keyed by the padded
10
+ * base64 of its name, and `schema.root` holds the per-group unions. It adds
11
+ * `format` and the legacy alias table.
12
+ */
13
+ import fs from "node:fs";
14
+ import path from "node:path";
15
+ import { SCHEMA_FORMAT } from "../../../protocol/types";
16
+ import { BUILT_IN_BLOCKS, LEGACY_ALIASES } from "../builtins";
17
+ import { CliError, type DecoPaths, packageVersion } from "../root";
18
+ import {
19
+ BUILT_IN_GROUPS,
20
+ builtInDefinition,
21
+ flatDefinition,
22
+ legacyMultivariateValue,
23
+ type ManifestGroup,
24
+ } from "./builtinSchemas";
25
+ import { createTsProject, type TsNode as Node, type TsType as Type } from "./tsProgram";
26
+ import {
27
+ awaitedOf,
28
+ getJsDocTags,
29
+ isDescriptorType,
30
+ isJsxType,
31
+ nonNullable,
32
+ RESOLVABLE_KEY,
33
+ type SchemaContext,
34
+ SECTION_REF_KEY,
35
+ stableFileId,
36
+ toBase64,
37
+ typeToJsonSchema,
38
+ } from "./typeToSchema";
39
+
40
+ const MANIFEST_GROUPS: ManifestGroup[] = [
41
+ "sections",
42
+ "loaders",
43
+ "matchers",
44
+ "pages",
45
+ "redirects",
46
+ "content",
47
+ ];
48
+
49
+ type ManifestEntry = { $ref: string; namespace: string };
50
+
51
+ export interface DecoMeta {
52
+ major: 1;
53
+ version: string;
54
+ namespace: string;
55
+ site: string;
56
+ manifest: { blocks: Record<string, Record<string, ManifestEntry>> };
57
+ schema: {
58
+ definitions: Record<string, any>;
59
+ root: Record<string, { anyOf: any[] }>;
60
+ };
61
+ /** The format name; the content protocol's `describe` reports the same. */
62
+ format: typeof SCHEMA_FORMAT;
63
+ /**
64
+ * Set so v7's runtime `composeMeta()` treats the file as already composed
65
+ * and serves it unchanged.
66
+ */
67
+ framework: string;
68
+ /** The alias table: legacy type name → the block type it names. */
69
+ aliases: Record<string, string>;
70
+ }
71
+
72
+ export interface SchemaDiagnostic {
73
+ severity: "error" | "warning";
74
+ message: string;
75
+ }
76
+
77
+ export interface SchemaResult {
78
+ meta: DecoMeta;
79
+ diagnostics: SchemaDiagnostic[];
80
+ /** The block map file that was read. */
81
+ blockMap: string;
82
+ /**
83
+ * The source files the schema was read from outside the root and outside
84
+ * `node_modules`: monorepo packages the block map imports. `--watch`
85
+ * watches them along with the root.
86
+ */
87
+ externalSources: string[];
88
+ }
89
+
90
+ interface BlockInfo {
91
+ key: string;
92
+ group: ManifestGroup;
93
+ propsType: Type | undefined;
94
+ /** The awaited return type. */
95
+ returnType: Type;
96
+ /** The `@Props` definition key, shared by every key bound to one function. */
97
+ propsKey: string;
98
+ docs: Record<string, string>;
99
+ }
100
+
101
+ const BUILT_IN_TYPES_SOURCE = `
102
+ export interface Seo { title: string; description: string }
103
+ export interface Route { name: string; path: string }
104
+ `;
105
+
106
+ /** The package version, written into the schema's `version`. */
107
+
108
+ function siteName(root: string): string {
109
+ try {
110
+ const name = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")).name;
111
+ if (typeof name === "string" && name) return name;
112
+ } catch {
113
+ // no package.json: use the folder name
114
+ }
115
+ return path.basename(root);
116
+ }
117
+
118
+ /** JSDoc on a block function: its declaration, or the `const` an arrow is assigned to. */
119
+ function functionDocs(declaration: Node | undefined): Record<string, string> {
120
+ const tags: Record<string, string> = {};
121
+ let node: Node | undefined = declaration;
122
+ for (let depth = 0; node && depth < 3; depth++, node = node.getParent()) {
123
+ for (const doc of node.getJsDocs()) {
124
+ const desc = doc.getDescription().trim();
125
+ if (desc && !tags.description) tags.description = desc;
126
+ for (const tag of doc.getTags()) {
127
+ tags[tag.getTagName()] ??= tag.getCommentText()?.trim() || "true";
128
+ }
129
+ }
130
+ }
131
+ return tags;
132
+ }
133
+
134
+ /** The block-level JSDoc the site editor shows on gallery cards. */
135
+ function blockExtras(docs: Record<string, string>): Record<string, string> {
136
+ const extras: Record<string, string> = {};
137
+ for (const tag of ["description", "icon", "image"] as const) {
138
+ if (docs[tag]) extras[tag] = docs[tag];
139
+ }
140
+ return extras;
141
+ }
142
+
143
+ function isBooleanType(type: Type): boolean {
144
+ if (type.isBoolean() || type.isBooleanLiteral()) return true;
145
+ return type.isUnion() && type.getUnionTypes().every((t) => t.isBooleanLiteral());
146
+ }
147
+
148
+ function sameType(a: Type, b: Type): boolean {
149
+ return a === b || a.compilerType === b.compilerType || a.getText() === b.getText();
150
+ }
151
+
152
+ function isInside(dir: string, file: string): boolean {
153
+ const rel = path.relative(dir, file);
154
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
155
+ }
156
+
157
+ function findBlockMap(paths: DecoPaths): string {
158
+ const file = paths.blockMapCandidates.find((candidate) => fs.existsSync(candidate));
159
+ if (!file) {
160
+ throw new CliError(
161
+ `no .deco/index.ts (or .deco/index.tsx) in ${paths.root}; it holds your block map`,
162
+ );
163
+ }
164
+ return file;
165
+ }
166
+
167
+ /** Generate the schema for a root. Throws `CliError` when the block map can't be read. */
168
+ export async function generateSchema(paths: DecoPaths): Promise<SchemaResult> {
169
+ const blockMap = findBlockMap(paths);
170
+ const root = paths.root;
171
+ const builtInTypesFile = path.join(paths.deco, "__deco_builtin_types__.ts");
172
+ const project = await createTsProject(root, [blockMap], {
173
+ [builtInTypesFile]: BUILT_IN_TYPES_SOURCE,
174
+ });
175
+ const builtInTypes = project.sourceFile(builtInTypesFile);
176
+ const seoType = builtInTypes.getInterfaceType("Seo");
177
+ const routeType = builtInTypes.getInterfaceType("Route");
178
+ const source = project.sourceFile(blockMap);
179
+ const diagnostics: SchemaDiagnostic[] = [];
180
+ const relMap = path.relative(root, blockMap).split(path.sep).join("/");
181
+
182
+ const defaultExport = source.getDefaultExportSymbol();
183
+ if (!defaultExport) {
184
+ throw new CliError(`${relMap}: no default export; export your block map as the default`);
185
+ }
186
+ const mapType = defaultExport.getTypeAtLocation(source);
187
+
188
+ // -------------------------------------------------------------------------
189
+ // 1. Read every key: its props, its awaited return type and its group.
190
+ // -------------------------------------------------------------------------
191
+ const infos: BlockInfo[] = [];
192
+ for (const prop of mapType.getProperties()) {
193
+ const key = prop.getName();
194
+ const valueType = prop.getTypeAtLocation(source);
195
+ const [signature] = valueType.getCallSignatures();
196
+ if (!signature) {
197
+ diagnostics.push({ severity: "error", message: `${relMap}: "${key}" isn't a function` });
198
+ continue;
199
+ }
200
+ const [param] = signature.getParameters();
201
+ const propsType = param ? param.getTypeAtLocation(source) : undefined;
202
+ const returnType = awaitedOf(signature.getReturnType()) ?? signature.getReturnType();
203
+ const declaration = signature.getDeclaration();
204
+
205
+ if (propsType?.isAny()) {
206
+ diagnostics.push({
207
+ severity: "warning",
208
+ message: `"${key}": its props are typed any, so its form is empty`,
209
+ });
210
+ }
211
+ const usableReturn = !returnType.isAny() && !returnType.isUnknown();
212
+ if (!usableReturn) {
213
+ diagnostics.push({
214
+ severity: "warning",
215
+ message: `"${key}": returns any, so it isn't offered for any field`,
216
+ });
217
+ }
218
+
219
+ const ret = nonNullable(returnType);
220
+ let group: ManifestGroup;
221
+ if (key === "page") group = "pages";
222
+ else if (key === "redirect") group = "redirects";
223
+ else if (usableReturn && (isJsxType(ret) || isDescriptorType(ret))) group = "sections";
224
+ else if (usableReturn && isBooleanType(ret)) group = "matchers";
225
+ else if (propsType && usableReturn && sameType(returnType, propsType)) {
226
+ group = propsType.isAssignableTo(routeType) ? "pages" : "content";
227
+ } else group = "loaders";
228
+
229
+ // Spec: routing. `path` makes an entry routable, so it must be intentional.
230
+ if (
231
+ propsType?.getProperty("path") &&
232
+ key !== "redirect" &&
233
+ !propsType.isAssignableTo(routeType)
234
+ ) {
235
+ diagnostics.push({
236
+ severity: "error",
237
+ message: `"${key}": has a "path" field but its type doesn't extend Route (name: string; path: string)`,
238
+ });
239
+ }
240
+
241
+ // Keys bound to one function (aliases) share its props definition. A
242
+ // function that is the default export of its own file is keyed by that
243
+ // file, as the v7 generator did.
244
+ const declFile = declaration?.getSourceFile();
245
+ let propsKey = `${toBase64(key)}@Props`;
246
+ if (declFile && declFile !== source) {
247
+ const fileDefault = declFile.getDefaultExportSymbol();
248
+ const target = fileDefault?.isAlias() ? fileDefault.getAliasedSymbol() : fileDefault;
249
+ const declNodes = target?.getDeclarations() ?? [];
250
+ const isDefault = declaration
251
+ ? declNodes.some((n) => n === declaration || n.contains(declaration))
252
+ : false;
253
+ if (isDefault) propsKey = `${toBase64(stableFileId(declFile.getFilePath(), root))}@Props`;
254
+ }
255
+
256
+ infos.push({
257
+ key,
258
+ group,
259
+ propsType,
260
+ returnType,
261
+ propsKey,
262
+ docs: { ...functionDocs(declaration), ...getJsDocTags(prop) },
263
+ });
264
+ }
265
+
266
+ // -------------------------------------------------------------------------
267
+ // 2. Fields → blocks: which functions' return types fit an object field.
268
+ // -------------------------------------------------------------------------
269
+ const STRUCTURAL = new Set<string>(["lazy", "multivariate", "secret", "always", "never", "date"]);
270
+ const candidates = infos.filter(
271
+ (info) =>
272
+ info.group !== "sections" &&
273
+ info.group !== "matchers" &&
274
+ !STRUCTURAL.has(info.key) &&
275
+ !info.returnType.isAny() &&
276
+ !info.returnType.isUnknown() &&
277
+ !nonNullable(info.returnType).isNever(),
278
+ );
279
+ const fitCache = new Map<unknown, string[]>();
280
+ const definitions: Record<string, any> = {};
281
+
282
+ const ctx: SchemaContext = {
283
+ root,
284
+ fitting(type) {
285
+ const target = nonNullable(type);
286
+ if (target.isAny() || target.isUnknown()) return [];
287
+ const cached = fitCache.get(target.compilerType);
288
+ if (cached) return cached;
289
+ const keys = candidates
290
+ .filter((c) => returnFits(c.returnType, target))
291
+ .map((c) => toBase64(c.key));
292
+ fitCache.set(target.compilerType, keys);
293
+ return keys;
294
+ },
295
+ namedDefinition(type) {
296
+ const t = nonNullable(type);
297
+ if (t.isArray() || t.getAliasTypeArguments().length > 0 || t.getTypeArguments().length > 0) {
298
+ return null;
299
+ }
300
+ const symbol = t.getAliasSymbol() ?? t.getSymbol();
301
+ const name = symbol?.getName();
302
+ const file = symbol?.getDeclarations()[0]?.getSourceFile().getFilePath();
303
+ if (!name || !file || name.startsWith("__") || !(t.isObject() || t.isInterface()))
304
+ return null;
305
+ const key = `${toBase64(stableFileId(file, root))}@${name}`;
306
+ if (!(key in definitions)) {
307
+ definitions[key] = { type: "object" }; // placeholder for recursive types
308
+ definitions[key] = typeToJsonSchema(t, new Set(), { ...ctx, shareNamed: { rootType: t } });
309
+ }
310
+ return { $ref: `#/definitions/${key}` };
311
+ },
312
+ };
313
+
314
+ // -------------------------------------------------------------------------
315
+ // 3. Definitions, manifest and root unions.
316
+ // -------------------------------------------------------------------------
317
+ const resolvable = {
318
+ title: "Select from saved",
319
+ type: "object",
320
+ required: ["__resolveType"],
321
+ additionalProperties: true,
322
+ properties: { __resolveType: { type: "string" } },
323
+ };
324
+ definitions[RESOLVABLE_KEY] = resolvable;
325
+ definitions[toBase64(RESOLVABLE_KEY)] = resolvable;
326
+
327
+ const manifest: Record<string, Record<string, ManifestEntry>> = {};
328
+ const unions: Record<string, { anyOf: any[] }> = {};
329
+ for (const group of MANIFEST_GROUPS) {
330
+ manifest[group] = {};
331
+ unions[group] = { anyOf: [{ $ref: `#/definitions/${RESOLVABLE_KEY}` }] };
332
+ }
333
+
334
+ const declared = new Set(infos.map((i) => i.key));
335
+ for (const info of infos) {
336
+ const defKey = toBase64(info.key);
337
+ const props =
338
+ info.propsType && !info.propsType.isAny()
339
+ ? typeToJsonSchema(info.propsType, new Set(), ctx)
340
+ : { type: "object", properties: {} };
341
+ if (props.type !== "object") {
342
+ diagnostics.push({
343
+ severity: "warning",
344
+ message: `"${info.key}": its first parameter isn't an object of props, so its form is empty`,
345
+ });
346
+ props.type = "object";
347
+ props.properties = {};
348
+ delete props.anyOf;
349
+ delete props.items;
350
+ delete props.enum;
351
+ delete props.nullable;
352
+ }
353
+ const extras = blockExtras(info.docs);
354
+ if (info.group === "sections") {
355
+ definitions[info.propsKey] ??= props;
356
+ definitions[defKey] = {
357
+ title: info.docs.title && !info.docs.title.includes("/") ? info.docs.title : info.key,
358
+ ...extras,
359
+ type: "object",
360
+ allOf: [{ $ref: `#/definitions/${info.propsKey}` }],
361
+ required: ["__resolveType"],
362
+ properties: { __resolveType: { type: "string", enum: [info.key], default: info.key } },
363
+ };
364
+ unions.sections.anyOf.push({
365
+ $ref: `#/definitions/${defKey}`,
366
+ inputSchema: `#/definitions/${info.propsKey}`,
367
+ });
368
+ } else {
369
+ const title = info.docs.title && !info.docs.title.includes("/") ? info.docs.title : undefined;
370
+ definitions[defKey] = flatDefinition(info.key, props, extras);
371
+ if (title) definitions[defKey].title = title;
372
+ unions[info.group].anyOf.push({ $ref: `#/definitions/${defKey}` });
373
+ }
374
+ manifest[info.group][info.key] = {
375
+ $ref: `#/definitions/${defKey}`,
376
+ namespace: namespaceOf(info.key),
377
+ };
378
+ }
379
+
380
+ const seoRefs = ctx.fitting(seoType).map((key) => ({ $ref: `#/definitions/${key}` }));
381
+ for (const name of BUILT_IN_BLOCKS) {
382
+ if (declared.has(name)) continue;
383
+ const group = BUILT_IN_GROUPS[name];
384
+ const defKey = toBase64(name);
385
+ definitions[defKey] = builtInDefinition(name, { seoRefs });
386
+ manifest[group][name] = { $ref: `#/definitions/${defKey}`, namespace: "deco" };
387
+ unions[group].anyOf.push({ $ref: `#/definitions/${defKey}` });
388
+ }
389
+
390
+ // The alias table: each legacy name gets a definition (the site editor
391
+ // builds refs with btoa(name)) and a manifest entry (it tells a block type
392
+ // from a saved block by manifest lookup), but no place in the root unions,
393
+ // so pickers don't list a type twice.
394
+ const aliases: Record<string, string> = {};
395
+ for (const [alias, target] of Object.entries(LEGACY_ALIASES)) {
396
+ if (declared.has(alias)) continue; // the block map's own key wins
397
+ const targetDef = definitions[toBase64(target)];
398
+ if (!targetDef) continue;
399
+ const group = groupOf(target, infos);
400
+ const aliasDef = structuredClone(targetDef);
401
+ aliasDef.title = alias;
402
+ aliasDef.properties = {
403
+ ...aliasDef.properties,
404
+ __resolveType: { type: "string", enum: [alias], default: alias },
405
+ };
406
+ if (target === "multivariate" && aliasDef.properties.variants?.items?.properties) {
407
+ aliasDef.properties.variants.items.properties.value = legacyMultivariateValue(alias);
408
+ }
409
+ if (alias === LEGACY_REDIRECT && !declared.has("redirect")) {
410
+ // The site editor's legacy redirect screen saves the nested shape.
411
+ aliasDef.required = ["__resolveType", "redirect"];
412
+ aliasDef.properties = {
413
+ __resolveType: aliasDef.properties.__resolveType,
414
+ redirect: legacyRedirectSchema(),
415
+ };
416
+ }
417
+ definitions[toBase64(alias)] = aliasDef;
418
+ manifest[group][alias] = { $ref: `#/definitions/${toBase64(alias)}`, namespace: "website" };
419
+ aliases[alias] = target;
420
+ }
421
+
422
+ definitions[SECTION_REF_KEY] = { title: "Section", anyOf: [...unions.sections.anyOf] };
423
+
424
+ const meta: DecoMeta = {
425
+ major: 1,
426
+ version: packageVersion(),
427
+ namespace: "site",
428
+ site: siteName(paths.root),
429
+ manifest: { blocks: manifest },
430
+ schema: { definitions, root: unions },
431
+ format: SCHEMA_FORMAT,
432
+ framework: "deco-cli",
433
+ aliases,
434
+ };
435
+ const externalSources = project
436
+ .fileNames()
437
+ .filter((f) => !isInside(root, f) && !f.split(/[\\/]/).includes("node_modules"));
438
+ return { meta, diagnostics, blockMap, externalSources };
439
+ }
440
+
441
+ /**
442
+ * An object type whose properties are all optional: nearly any object is
443
+ * assignable to it, so assignability alone would offer unrelated functions.
444
+ */
445
+ function isWeakType(type: Type): boolean {
446
+ if (!(type.isObject() || type.isInterface()) || type.isArray()) return false;
447
+ if (
448
+ type.getStringIndexType() ||
449
+ type.getNumberIndexType() ||
450
+ type.getCallSignatures().length > 0
451
+ ) {
452
+ return false;
453
+ }
454
+ const props = type.getProperties();
455
+ return props.length > 0 && props.every((p) => p.isOptional());
456
+ }
457
+
458
+ function sameNamedType(a: Type, b: Type): boolean {
459
+ const sa = (a.getAliasSymbol() ?? a.getSymbol())?.compilerSymbol;
460
+ const sb = (b.getAliasSymbol() ?? b.getSymbol())?.compilerSymbol;
461
+ return sa !== undefined && sa === sb;
462
+ }
463
+
464
+ /**
465
+ * Does a function returning `returnType` fit a field of type `field`? The
466
+ * TypeScript rule (assignability of the awaited, non-null types), except for
467
+ * weak target types, which need the same named type.
468
+ */
469
+ function returnFits(returnType: Type, field: Type): boolean {
470
+ const source = nonNullable(returnType);
471
+ const target = nonNullable(field);
472
+ if (!source.isAssignableTo(target)) return false;
473
+ const element = (t: Type) => (t.isArray() ? (t.getArrayElementType() ?? t) : t);
474
+ const targetElement = element(target);
475
+ return isWeakType(targetElement) ? sameNamedType(element(source), targetElement) : true;
476
+ }
477
+
478
+ /**
479
+ * The site editor groups blocks by namespace. A path-like key keeps the one
480
+ * v7 gave it (`shopify/loaders/ProductList.ts` is "shopify"); short keys are
481
+ * the site's.
482
+ */
483
+ function namespaceOf(key: string): string {
484
+ const slash = key.indexOf("/");
485
+ return slash > 0 ? key.slice(0, slash) : "site";
486
+ }
487
+
488
+ const LEGACY_REDIRECT = "website/loaders/redirect.ts";
489
+
490
+ /** `{ redirect: { from, to, type } }`, as v7's redirect screen saves it. */
491
+ function legacyRedirectSchema() {
492
+ return {
493
+ type: "object",
494
+ title: "Redirect",
495
+ required: ["from", "to"],
496
+ properties: {
497
+ from: { type: "string", title: "From" },
498
+ to: { type: "string", title: "To" },
499
+ type: { type: "string", enum: ["permanent", "temporary"], title: "Type" },
500
+ discardQueryParameters: { type: "boolean", title: "Discard query parameters" },
501
+ },
502
+ };
503
+ }
504
+
505
+ function groupOf(name: string, infos: BlockInfo[]): ManifestGroup {
506
+ return infos.find((i) => i.key === name)?.group ?? BUILT_IN_GROUPS[name];
507
+ }
@@ -0,0 +1,63 @@
1
+ import path from "node:path";
2
+ import { writeIfChanged } from "../content";
3
+ import { consoleReporter, type Reporter } from "../log";
4
+ import { CliError, type DecoPaths, decoPaths, findDecoRoot } from "../root";
5
+ import { generateSchema, type SchemaResult } from "./generate";
6
+
7
+ export interface SchemaOptions {
8
+ root?: string;
9
+ cwd?: string;
10
+ reporter?: Reporter;
11
+ }
12
+
13
+ export interface WriteSchemaResult extends SchemaResult {
14
+ written: boolean;
15
+ changed: boolean;
16
+ }
17
+
18
+ /**
19
+ * Generate and write `.deco/schema.gen.json`. A schema with errors is not
20
+ * written, so the committed file never holds a half-right form.
21
+ */
22
+ export async function writeSchema(paths: DecoPaths): Promise<WriteSchemaResult> {
23
+ const result = await generateSchema(paths);
24
+ if (result.diagnostics.some((d) => d.severity === "error")) {
25
+ return { ...result, written: false, changed: false };
26
+ }
27
+ const changed = writeIfChanged(paths.schema, `${JSON.stringify(result.meta, null, 2)}\n`);
28
+ return { ...result, written: true, changed };
29
+ }
30
+
31
+ export function reportSchema(result: WriteSchemaResult, reporter: Reporter): number {
32
+ for (const d of result.diagnostics) {
33
+ if (d.severity === "error") reporter.error(d.message);
34
+ else reporter.warn(`warning: ${d.message}`);
35
+ }
36
+ if (!result.written) {
37
+ reporter.error(".deco/schema.gen.json not written: fix the errors above");
38
+ return 1;
39
+ }
40
+ const groups = result.meta.manifest.blocks;
41
+ const count = (g: string) => Object.keys(groups[g] ?? {}).length;
42
+ reporter.info(
43
+ `${result.changed ? "wrote" : "unchanged"} .deco/schema.gen.json from ${path.basename(result.blockMap)} ` +
44
+ `(${count("sections")} sections, ${count("loaders")} loaders, ${count("matchers")} matchers, ` +
45
+ `${count("pages")} pages, ${count("content")} content types)`,
46
+ );
47
+ return 0;
48
+ }
49
+
50
+ /** `deco schema`, once. Returns the exit code. */
51
+ export async function schema(options: SchemaOptions = {}): Promise<number> {
52
+ const reporter = options.reporter ?? consoleReporter;
53
+ const paths = decoPaths(findDecoRoot(options));
54
+ try {
55
+ return reportSchema(await writeSchema(paths), reporter);
56
+ } catch (error) {
57
+ if (error instanceof CliError) {
58
+ reporter.error(error.message);
59
+ return 1;
60
+ }
61
+ throw error;
62
+ }
63
+ }