@decocms/blocks 7.72.0 → 8.1.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -3
  3. package/src/cms/schema.ts +1 -1
  4. package/src/hooks/LiveControls.tsx +2 -0
  5. package/src/hooks/useLoadMore.ts +2 -0
  6. package/src/index.ts +37 -0
  7. package/src/protocol/assets.ts +124 -0
  8. package/src/protocol/canonical.ts +7 -0
  9. package/src/protocol/ciphertext.ts +6 -0
  10. package/src/protocol/client.ts +170 -0
  11. package/src/protocol/conformance/cases/assets.ts +81 -0
  12. package/src/protocol/conformance/cases/guards.ts +314 -0
  13. package/src/protocol/conformance/cases/reads.ts +168 -0
  14. package/src/protocol/conformance/cases/types.ts +9 -0
  15. package/src/protocol/conformance/cases/wire.ts +138 -0
  16. package/src/protocol/conformance/cases/writes.ts +345 -0
  17. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  18. package/src/protocol/conformance/context.ts +222 -0
  19. package/src/protocol/conformance/index.ts +140 -0
  20. package/src/protocol/errors.ts +142 -0
  21. package/src/protocol/index.ts +39 -0
  22. package/src/protocol/keys.ts +279 -0
  23. package/src/protocol/params.ts +67 -0
  24. package/src/protocol/secrets.ts +231 -0
  25. package/src/protocol/server/assets.ts +119 -0
  26. package/src/protocol/server/auth.ts +49 -0
  27. package/src/protocol/server/bodyCache.ts +84 -0
  28. package/src/protocol/server/content.ts +175 -0
  29. package/src/protocol/server/core.ts +112 -0
  30. package/src/protocol/server/handler.ts +102 -0
  31. package/src/protocol/server/http.ts +139 -0
  32. package/src/protocol/server/index.ts +11 -0
  33. package/src/protocol/server/methods/apply.ts +341 -0
  34. package/src/protocol/server/methods/read.ts +156 -0
  35. package/src/protocol/server/rpc.ts +136 -0
  36. package/src/protocol/storage/fs/hash.ts +21 -0
  37. package/src/protocol/storage/fs/index.ts +338 -0
  38. package/src/protocol/storage/fs/lock.ts +68 -0
  39. package/src/protocol/storage/fs/transaction.ts +183 -0
  40. package/src/protocol/storage/fs/unsupported.ts +15 -0
  41. package/src/protocol/storage/memory.ts +238 -0
  42. package/src/protocol/storage.ts +182 -0
  43. package/src/protocol/types.ts +172 -0
  44. package/src/v8/analytics.ts +50 -0
  45. package/src/v8/background.ts +107 -0
  46. package/src/v8/builtins/data.ts +23 -0
  47. package/src/v8/builtins/index.ts +26 -0
  48. package/src/v8/builtins/lazy.ts +23 -0
  49. package/src/v8/builtins/legacy.ts +65 -0
  50. package/src/v8/builtins/matchers.ts +31 -0
  51. package/src/v8/builtins/multivariate.ts +25 -0
  52. package/src/v8/builtins/secret.ts +82 -0
  53. package/src/v8/canonical.ts +117 -0
  54. package/src/v8/ciphertext.ts +158 -0
  55. package/src/v8/cli/builtins.ts +20 -0
  56. package/src/v8/cli/check/index.ts +774 -0
  57. package/src/v8/cli/check/messages.ts +168 -0
  58. package/src/v8/cli/content.ts +287 -0
  59. package/src/v8/cli/index.ts +17 -0
  60. package/src/v8/cli/log.ts +18 -0
  61. package/src/v8/cli/main.ts +12 -0
  62. package/src/v8/cli/root.ts +66 -0
  63. package/src/v8/cli/run.ts +236 -0
  64. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  65. package/src/v8/cli/schema/generate.ts +507 -0
  66. package/src/v8/cli/schema/index.ts +63 -0
  67. package/src/v8/cli/schema/tsProgram.ts +497 -0
  68. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  69. package/src/v8/cli/serve/server.ts +303 -0
  70. package/src/v8/cli/watch.ts +86 -0
  71. package/src/v8/client.ts +147 -0
  72. package/src/v8/cms.ts +237 -0
  73. package/src/v8/content.ts +195 -0
  74. package/src/v8/draft.ts +136 -0
  75. package/src/v8/errors.ts +59 -0
  76. package/src/v8/fetch.ts +152 -0
  77. package/src/v8/identity.ts +65 -0
  78. package/src/v8/index.ts +39 -0
  79. package/src/v8/json.ts +74 -0
  80. package/src/v8/matchRoute.ts +204 -0
  81. package/src/v8/remoteLoader.ts +282 -0
  82. package/src/v8/resolver.ts +278 -0
  83. package/src/v8/secrets.ts +17 -0
  84. package/src/v8/telemetry.ts +533 -0
  85. package/src/v8/types.ts +240 -0
  86. package/src/cms/blockSource.test.ts +0 -76
  87. package/src/cms/client.browserBundle.test.ts +0 -44
  88. package/src/cms/deferredTrigger.test.ts +0 -32
  89. package/src/cms/draftSource.test.ts +0 -519
  90. package/src/cms/layoutCacheRace.test.ts +0 -181
  91. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  92. package/src/cms/loader.test.ts +0 -557
  93. package/src/cms/registry.test.ts +0 -110
  94. package/src/cms/renderJson.test.ts +0 -167
  95. package/src/cms/resolve.test.ts +0 -1492
  96. package/src/cms/schema.test.ts +0 -356
  97. package/src/cms/sectionLoaderContext.test.ts +0 -111
  98. package/src/cms/sectionLoaders.test.ts +0 -625
  99. package/src/cms/sectionMixins.test.ts +0 -167
  100. package/src/cms/stickyFlags.test.ts +0 -117
  101. package/src/flags/flags.test.ts +0 -148
  102. package/src/hooks/Image.test.ts +0 -239
  103. package/src/hooks/RenderSection.test.tsx +0 -81
  104. package/src/hooks/Stats.test.ts +0 -112
  105. package/src/hooks/useLoadMore.test.ts +0 -205
  106. package/src/matchers/builtins.test.ts +0 -318
  107. package/src/matchers/override.test.ts +0 -205
  108. package/src/middleware/hydrationContext.test.ts +0 -61
  109. package/src/middleware/observability.test.ts +0 -335
  110. package/src/middleware/validateSection.test.ts +0 -147
  111. package/src/preview/DraftPreviewBadge.render.test.tsx +0 -67
  112. package/src/preview/DraftPreviewBadge.test.ts +0 -55
  113. package/src/sdk/abTesting.test.ts +0 -381
  114. package/src/sdk/cacheHeaders.test.ts +0 -258
  115. package/src/sdk/cacheStorage.test.ts +0 -242
  116. package/src/sdk/cachedLoader.test.ts +0 -122
  117. package/src/sdk/cachedLoaderMaxBytes.test.ts +0 -23
  118. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  119. package/src/sdk/cachedLoaderSizeMetric.test.ts +0 -93
  120. package/src/sdk/cn.test.ts +0 -34
  121. package/src/sdk/composite.test.ts +0 -121
  122. package/src/sdk/cookie.test.ts +0 -108
  123. package/src/sdk/crypto.test.ts +0 -65
  124. package/src/sdk/deepOmit.test.ts +0 -45
  125. package/src/sdk/encoding.test.ts +0 -71
  126. package/src/sdk/env.test.ts +0 -33
  127. package/src/sdk/experiments.test.ts +0 -328
  128. package/src/sdk/fetchCache.test.ts +0 -164
  129. package/src/sdk/flags.test.ts +0 -91
  130. package/src/sdk/http.test.ts +0 -71
  131. package/src/sdk/inflightTimeout.test.ts +0 -35
  132. package/src/sdk/instrumentedFetch.test.ts +0 -559
  133. package/src/sdk/invoke.test.ts +0 -115
  134. package/src/sdk/logger.test.ts +0 -432
  135. package/src/sdk/otel.test.ts +0 -691
  136. package/src/sdk/otelAdapters.test.ts +0 -89
  137. package/src/sdk/otelHttpLog.test.ts +0 -457
  138. package/src/sdk/otelHttpMeter.test.ts +0 -395
  139. package/src/sdk/otelHttpTracer.test.ts +0 -474
  140. package/src/sdk/replaceStream.test.ts +0 -117
  141. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  142. package/src/sdk/splitExactRedirects.test.ts +0 -154
  143. package/src/sdk/urlRedaction.test.ts +0 -73
  144. package/src/sdk/urlUtils.test.ts +0 -34
  145. package/src/sdk/useDevice.test.ts +0 -130
  146. package/src/sdk/useScript.test.ts +0 -128
  147. package/src/sdk/useSuggestions.test.ts +0 -230
  148. package/tsconfig.json +0 -7
@@ -0,0 +1,689 @@
1
+ /**
2
+ * TypeScript types to JSON Schema, in the site editor's dialect (the
3
+ * `deco-meta@1` format, which is today's `meta.gen.json`).
4
+ *
5
+ * Ported from the v7 generator (`@decocms/blocks-cli`'s
6
+ * `scripts/generate-schema.ts`: `typeToJsonSchema`, the JSDoc tag table and
7
+ * the widget aliases), so a type produces the same field it always has. What
8
+ * changed for the next major (spec: schema › From types to forms):
9
+ *
10
+ * - `ReactNode` / `ReactNode[]` are a choice of components (the section
11
+ * picker) instead of a hidden field.
12
+ * - An object field takes a plain value or any block whose function's awaited
13
+ * return type fits it, decided by TypeScript assignability, not by type
14
+ * name (spec: schema › Interchangeable blocks).
15
+ * - `Lazy<T>` is a `lazy` block whose `value` has the form of `T`.
16
+ * - `Secret` holds a `secret` block, never a plain string.
17
+ * - `@options` with a literal list becomes an `enum`; a function-backed list
18
+ * falls back to a text field, since the site editor never runs site code.
19
+ *
20
+ * The compiler is only imported as types here; `generate.ts` loads the
21
+ * app's `typescript` when `deco schema` runs.
22
+ */
23
+
24
+ import fs from "node:fs";
25
+ import path from "node:path";
26
+ import type { TsSymbol as MorphSymbol, TsType as Type } from "./tsProgram";
27
+
28
+ export const RESOLVABLE_KEY = "Resolvable";
29
+ export const SECTION_REF_KEY = "__SECTION_REF__";
30
+
31
+ /** Standard padded base64, matching the browser's `btoa()`. */
32
+ export function toBase64(value: string): string {
33
+ return Buffer.from(value, "utf8").toString("base64");
34
+ }
35
+
36
+ export const resolvableRef = () => ({ $ref: `#/definitions/${RESOLVABLE_KEY}` });
37
+ export const sectionRef = () => ({ $ref: `#/definitions/${SECTION_REF_KEY}` });
38
+
39
+ /** What a field position needs from the generator to link blocks into it. */
40
+ export interface SchemaContext {
41
+ root: string;
42
+ /**
43
+ * The definition keys of the blocks whose function's awaited return type
44
+ * fits an object field of this type, in block map order. Empty when none do.
45
+ */
46
+ fitting(type: Type): string[];
47
+ /** A `$ref` to a shared definition of a named object type (the inline branch). */
48
+ namedDefinition(type: Type): { $ref: string } | null;
49
+ /**
50
+ * Set while generating a shared definition: nested named object types are
51
+ * refs to their own shared definitions too, so a type graph like
52
+ * `Product → ProductGroup → Product[]` is written once, not expanded at
53
+ * every level. `rootType` is the definition being expanded.
54
+ */
55
+ shareNamed?: { rootType: Type };
56
+ }
57
+
58
+ // ---------------------------------------------------------------------------
59
+ // JSDoc tags (spec: schema › Widgets)
60
+ // ---------------------------------------------------------------------------
61
+
62
+ const NUMERIC_TAGS = new Set([
63
+ "maximum",
64
+ "minimum",
65
+ "exclusiveMaximum",
66
+ "exclusiveMinimum",
67
+ "multipleOf",
68
+ "maxLength",
69
+ "minLength",
70
+ "maxItems",
71
+ "minItems",
72
+ "maxProperties",
73
+ "minProperties",
74
+ ]);
75
+ const BOOLEAN_TAGS = new Set(["readOnly", "writeOnly", "deprecated", "uniqueItems"]);
76
+
77
+ export function getJsDocTags(symbol: MorphSymbol): Record<string, string> {
78
+ const tags: Record<string, string> = {};
79
+ for (const decl of symbol.getDeclarations()) {
80
+ for (const doc of decl.getJsDocs()) {
81
+ const desc = doc.getDescription().trim();
82
+ if (desc) tags.description = desc;
83
+ for (const tag of doc.getTags()) {
84
+ tags[tag.getTagName()] = tag.getCommentText()?.trim() || "true";
85
+ }
86
+ }
87
+ }
88
+ return tags;
89
+ }
90
+
91
+ /**
92
+ * Parse an `@options` value. A JSON list of strings, numbers, or
93
+ * `{ value, label }` objects is a static list; anything else (a loader path,
94
+ * a function name) is dynamic and can't be written into the schema.
95
+ */
96
+ function parseOptions(raw: string): { values: (string | number)[]; labels?: string[] } | null {
97
+ let parsed: unknown;
98
+ try {
99
+ parsed = JSON.parse(raw);
100
+ } catch {
101
+ return null;
102
+ }
103
+ if (!Array.isArray(parsed) || parsed.length === 0) return null;
104
+ const values: (string | number)[] = [];
105
+ const labels: string[] = [];
106
+ let labelled = false;
107
+ for (const item of parsed) {
108
+ if (typeof item === "string" || typeof item === "number") {
109
+ values.push(item);
110
+ labels.push(String(item));
111
+ } else if (
112
+ item &&
113
+ typeof item === "object" &&
114
+ (typeof item.value === "string" || typeof item.value === "number")
115
+ ) {
116
+ values.push(item.value);
117
+ labels.push(typeof item.label === "string" ? item.label : String(item.value));
118
+ labelled ||= typeof item.label === "string";
119
+ } else {
120
+ return null;
121
+ }
122
+ }
123
+ return labelled ? { values, labels } : { values };
124
+ }
125
+
126
+ function applyJsDocToSchema(schema: any, tags: Record<string, string>): void {
127
+ for (const [tag, value] of Object.entries(tags)) {
128
+ if (tag === "ignore") continue;
129
+ if (tag === "hide") {
130
+ schema.hide = "true";
131
+ continue;
132
+ }
133
+ if (tag === "default") {
134
+ if (value === "true") schema.default = true;
135
+ else if (value === "false") schema.default = false;
136
+ else if (value === "null") schema.default = null;
137
+ else if (!Number.isNaN(Number(value)) && value.trim() !== "") schema.default = Number(value);
138
+ else {
139
+ try {
140
+ schema.default = JSON.parse(value);
141
+ } catch {
142
+ schema.default = value;
143
+ }
144
+ }
145
+ continue;
146
+ }
147
+ if (tag === "examples") {
148
+ const lines = value
149
+ .split("\n")
150
+ .map((l) => l.trim())
151
+ .filter(Boolean);
152
+ if (lines.length > 1) schema.examples = lines;
153
+ else {
154
+ try {
155
+ schema.examples = JSON.parse(value);
156
+ } catch {
157
+ schema.examples = [value];
158
+ }
159
+ }
160
+ continue;
161
+ }
162
+ if (tag === "options") {
163
+ const options = parseOptions(value);
164
+ // Static lists become an enum the site editor shows as a select without
165
+ // asking the site. A dynamic list falls back to a plain text field.
166
+ if (options) {
167
+ schema.enum = options.values;
168
+ if (options.labels) schema.enumNames = options.labels;
169
+ }
170
+ continue;
171
+ }
172
+ if (NUMERIC_TAGS.has(tag)) {
173
+ schema[tag] = Number(value);
174
+ continue;
175
+ }
176
+ if (BOOLEAN_TAGS.has(tag)) {
177
+ schema[tag] = value === "true";
178
+ continue;
179
+ }
180
+ // Everything else passes through as-is, matching the v7 generator: title,
181
+ // description, format, widget, icon, titleBy, mode, label, pattern, …
182
+ schema[tag] = value;
183
+ }
184
+ }
185
+
186
+ // ---------------------------------------------------------------------------
187
+ // Widget aliases (kept from v7: `image: ImageWidget` is an image picker)
188
+ // ---------------------------------------------------------------------------
189
+
190
+ const WIDGET_TYPE_FORMATS: Record<string, string> = {
191
+ ImageWidget: "image-uri",
192
+ VideoWidget: "video-uri",
193
+ HTMLWidget: "html",
194
+ RichText: "rich-text",
195
+ Color: "color",
196
+ TextArea: "textarea",
197
+ Code: "code",
198
+ DateTimeWidget: "date-time",
199
+ };
200
+
201
+ /** Apply the format of a widget alias named in `typeHint` to the right inner schema. */
202
+ function applyWidgetFormat(schema: any, typeHint: string): void {
203
+ const format = Object.entries(WIDGET_TYPE_FORMATS).find(
204
+ ([alias]) => typeHint === alias || new RegExp(`\\b${alias}\\b`).test(typeHint),
205
+ )?.[1];
206
+ if (!format) return;
207
+ if (schema.type === "string") {
208
+ schema.format ??= format;
209
+ } else if (schema.type === "array" && schema.items?.type === "string") {
210
+ schema.items.format ??= format;
211
+ } else if (Array.isArray(schema.anyOf)) {
212
+ for (const variant of schema.anyOf) {
213
+ if (variant.type === "string") variant.format ??= format;
214
+ }
215
+ } else if (!schema.type && !schema.$ref && !schema.anyOf) {
216
+ // A widget alias the checker couldn't resolve (remote import) came through as
217
+ // `any`; every widget alias is a string, so recover the intended widget.
218
+ schema.type = "string";
219
+ schema.format = format;
220
+ }
221
+ }
222
+
223
+ // ---------------------------------------------------------------------------
224
+ // Recognizing the framework's own types
225
+ // ---------------------------------------------------------------------------
226
+
227
+ const JSX_SYMBOLS = new Set([
228
+ "ReactNode",
229
+ "ReactElement",
230
+ "ReactPortal",
231
+ "VNode",
232
+ "ComponentChildren",
233
+ ]);
234
+
235
+ function typeNames(type: Type): string[] {
236
+ const names: string[] = [];
237
+ const alias = type.getAliasSymbol()?.getName();
238
+ if (alias) names.push(alias);
239
+ const sym = type.getSymbol()?.getName();
240
+ if (sym) names.push(sym);
241
+ return names;
242
+ }
243
+
244
+ /** `ReactNode`, `ReactElement`, `JSX.Element` and friends. */
245
+ /** A render descriptor (spec: rendering): `{ component: string; props: … }`. */
246
+ export function isDescriptorType(type: Type): boolean {
247
+ const check = (t: Type) => {
248
+ const component = t.getProperty("component");
249
+ return component !== undefined && t.getProperty("props") !== undefined;
250
+ };
251
+ if (type.isUnion()) return type.getUnionTypes().every((t) => check(t));
252
+ return type.isObject() && check(type);
253
+ }
254
+
255
+ /**
256
+ * What a section renders to: JSX, or a render descriptor in data mode. A field
257
+ * of either type is a section picker.
258
+ */
259
+ function isSectionType(type: Type): boolean {
260
+ return isJsxType(type) || isDescriptorType(type);
261
+ }
262
+
263
+ export function isJsxType(type: Type): boolean {
264
+ if (typeNames(type).some((n) => JSX_SYMBOLS.has(n))) return true;
265
+ const text = type.getText();
266
+ if (/(^|\.)Element$/.test(text) && /\bJSX\b/.test(text)) return true;
267
+ // A flattened `ReactNode` (it lost its alias): a union with an element member.
268
+ return (
269
+ type.isUnion() &&
270
+ type
271
+ .getUnionTypes()
272
+ .some((member) => typeNames(member).some((n) => n === "ReactElement" || n === "ReactPortal"))
273
+ );
274
+ }
275
+
276
+ /**
277
+ * `Lazy<T>`: the `T`, or null for any other type. Only the `Lazy` alias
278
+ * counts, so a method like `onLoad: () => Promise<void>` stays a method
279
+ * (skipped) instead of becoming a lazy field. `typeHint`, the annotation as
280
+ * written, covers a checker that printed the alias away; the type must still
281
+ * have `Lazy`'s shape, a call with no parameters returning a promise of data.
282
+ */
283
+ function lazyInner(type: Type, typeHint = ""): Type | null {
284
+ const alias = type.getAliasSymbol();
285
+ if (alias?.getName() === "Lazy") {
286
+ const [arg] = type.getAliasTypeArguments();
287
+ if (arg) return arg;
288
+ }
289
+ if (!/^(\w+\.)?Lazy\s*</.test(typeHint.trim())) return null;
290
+ const signatures = type.getCallSignatures();
291
+ if (signatures.length !== 1 || type.getProperties().length > 0) return null;
292
+ const [signature] = signatures;
293
+ if (signature.getParameters().length > 0) return null;
294
+ const inner = awaitedOf(signature.getReturnType(), true);
295
+ if (!inner || inner.isVoid() || inner.isUndefined() || inner.isNever()) return null;
296
+ return inner;
297
+ }
298
+
299
+ /** `Secret`, from `@decocms/blocks` (`string & { readonly __secret: true }`). */
300
+ function isSecretType(type: Type, typeHint = ""): boolean {
301
+ if (type.getAliasSymbol()?.getName() === "Secret") return true;
302
+ if (/^(\w+\.)?Secret$/.test(typeHint.trim())) return true;
303
+ return (
304
+ type.isIntersection() &&
305
+ type.getIntersectionTypes().some((t) => t.getProperty("__secret") !== undefined)
306
+ );
307
+ }
308
+
309
+ /**
310
+ * The awaited type: `Promise<T>` is `T`. With `strict`, anything that isn't a
311
+ * promise returns null (used to recognize `() => Promise<T>`).
312
+ */
313
+ export function awaitedOf(type: Type, strict = false): Type | null {
314
+ if (type.getSymbol()?.getName() === "Promise" || type.getAliasSymbol()?.getName() === "Promise") {
315
+ const [arg] = type.getTypeArguments();
316
+ return arg ?? null;
317
+ }
318
+ return strict ? null : type;
319
+ }
320
+
321
+ export function nonNullable(type: Type): Type {
322
+ if (!type.isUnion()) return type;
323
+ const parts = type.getUnionTypes().filter((t) => !t.isNull() && !t.isUndefined());
324
+ return parts.length === 1 ? parts[0] : type.getNonNullableType();
325
+ }
326
+
327
+ /** Types a block can fill: objects, arrays and intersections of objects, not primitives. */
328
+ function isObjectLike(type: Type): boolean {
329
+ const t = nonNullable(type);
330
+ if (t.isAny() || t.isUnknown() || t.isNever()) return false;
331
+ if (t.isString() || t.isNumber() || t.isBoolean() || t.isLiteral() || t.isBooleanLiteral()) {
332
+ return false;
333
+ }
334
+ if (t.isUnion()) {
335
+ // A union of objects (`A | B`) can be filled; a union with a primitive can't.
336
+ return t.getUnionTypes().every((u) => isObjectLike(u) || u.isNull() || u.isUndefined());
337
+ }
338
+ if (t.isIntersection()) {
339
+ return !t.getIntersectionTypes().some((p) => p.isString() || p.isNumber() || p.isBoolean());
340
+ }
341
+ return t.isArray() || t.isObject() || t.isInterface();
342
+ }
343
+
344
+ // ---------------------------------------------------------------------------
345
+ // The converter
346
+ // ---------------------------------------------------------------------------
347
+
348
+ const REACT_INTERNAL_PROPS = new Set([
349
+ "ref",
350
+ "then",
351
+ "catch",
352
+ "finally",
353
+ "$$typeof",
354
+ "_owner",
355
+ "_store",
356
+ ]);
357
+
358
+ // Platform types never configured in a form; collapsed to a hidden object.
359
+ const RUNTIME_INJECTED_TYPES = new Set([
360
+ "URL",
361
+ "URLSearchParams",
362
+ "Request",
363
+ "Response",
364
+ "Headers",
365
+ "AbortSignal",
366
+ "ReadableStream",
367
+ "WritableStream",
368
+ "Blob",
369
+ "File",
370
+ "FormData",
371
+ ]);
372
+
373
+ const titleCase = (name: string) => name.charAt(0).toUpperCase() + name.slice(1);
374
+
375
+ /** `Secret | undefined` → `Secret`: the annotation without its nullish members. */
376
+ function stripNullish(typeHint: string): string {
377
+ return typeHint.replace(/\s*\|\s*(null|undefined)\b/g, "").trim();
378
+ }
379
+
380
+ function isNullableHint(optional: boolean, typeHint: string): boolean {
381
+ return optional || /\bnull\b|\bundefined\b/.test(typeHint);
382
+ }
383
+
384
+ /** The schema of a `lazy` block whose value has the form `value`. */
385
+ export function lazySchema(value: any): any {
386
+ return {
387
+ type: "object",
388
+ required: ["__resolveType", "value"],
389
+ properties: {
390
+ __resolveType: { type: "string", enum: ["lazy"], default: "lazy" },
391
+ value,
392
+ },
393
+ };
394
+ }
395
+
396
+ /** The schema of a `secret` block: a write-only field saved encrypted. */
397
+ function secretSchema(): any {
398
+ return {
399
+ type: "object",
400
+ format: "secret",
401
+ writeOnly: true,
402
+ required: ["__resolveType", "ciphertext"],
403
+ properties: {
404
+ __resolveType: { type: "string", enum: ["secret"], default: "secret" },
405
+ ciphertext: { type: "string" },
406
+ },
407
+ };
408
+ }
409
+
410
+ /**
411
+ * The schema of one field: everything a type means at a property position,
412
+ * before the property's own JSDoc and title are applied.
413
+ */
414
+ function fieldSchema(
415
+ propType: Type,
416
+ typeHint: string,
417
+ ctx?: SchemaContext,
418
+ visited: Set<string> = new Set(),
419
+ ): any {
420
+ const lazy = lazyInner(nonNullable(propType), stripNullish(typeHint));
421
+ if (lazy) return lazySchema(fieldSchema(lazy, lazy.getText(), ctx, visited));
422
+
423
+ if (isSecretType(nonNullable(propType), stripNullish(typeHint))) return secretSchema();
424
+
425
+ if (ctx && isObjectLike(propType) && !isSectionType(nonNullable(propType))) {
426
+ const fits = ctx.fitting(propType);
427
+ if (fits.length > 0) {
428
+ const inner = nonNullable(propType);
429
+ const inline = inlineSchema(inner, ctx, visited);
430
+ return {
431
+ anyOf: [resolvableRef(), inline, ...fits.map((key) => ({ $ref: `#/definitions/${key}` }))],
432
+ };
433
+ }
434
+ }
435
+
436
+ const schema = typeToJsonSchema(propType, new Set(visited), ctx);
437
+ applyWidgetFormat(schema, typeHint);
438
+ return schema;
439
+ }
440
+
441
+ /** The "plain value" branch of a field that blocks can fill. */
442
+ function inlineSchema(type: Type, ctx: SchemaContext, visited: Set<string>): any {
443
+ if (type.isArray()) {
444
+ const element = type.getArrayElementType();
445
+ const items = element
446
+ ? (ctx.namedDefinition(element) ?? typeToJsonSchema(element, new Set(visited), ctx))
447
+ : {};
448
+ return { type: "array", items, title: "Inline data" };
449
+ }
450
+ const named = ctx.namedDefinition(type);
451
+ return named
452
+ ? { ...named, title: "Inline data" }
453
+ : { ...typeToJsonSchema(type, new Set(visited), ctx), title: "Inline data" };
454
+ }
455
+
456
+ /**
457
+ * Whether a prop annotated `Section` / `Section[]` is v7's opaque Section type
458
+ * (`type Section = any`), a "pick any section" field, rather than a site type
459
+ * that happens to be called `Section`.
460
+ */
461
+ function isOpaqueSectionType(propType: Type): boolean {
462
+ let type = nonNullable(propType);
463
+ if (type.isArray()) type = type.getArrayElementType() ?? type;
464
+ return type.isAny() || type.isUnknown();
465
+ }
466
+
467
+ export function typeToJsonSchema(
468
+ type: Type,
469
+ visited = new Set<string>(),
470
+ ctx?: SchemaContext,
471
+ ): any {
472
+ const typeText = type.getText();
473
+ if (visited.has(typeText)) return { type: "object" };
474
+ visited.add(typeText);
475
+
476
+ try {
477
+ if (type.isAny() || type.isUnknown()) return {};
478
+
479
+ // Structural blocks wherever the type appears, not only as a whole field:
480
+ // `Secret[]` is a list of secret blocks, `Lazy<T>[]` a list of lazy ones.
481
+ if (isSecretType(type)) return secretSchema();
482
+ const lazy = lazyInner(type);
483
+ if (lazy) return lazySchema(fieldSchema(lazy, lazy.getText(), ctx, visited));
484
+
485
+ if (type.isArray()) {
486
+ const el = type.getArrayElementType();
487
+ return el
488
+ ? { type: "array", items: typeToJsonSchema(el, new Set(visited), ctx) }
489
+ : { type: "array" };
490
+ }
491
+
492
+ if (isSectionType(type)) return sectionRef();
493
+
494
+ if (type.isString() || type.isStringLiteral()) {
495
+ return type.isStringLiteral()
496
+ ? { type: "string", const: type.getLiteralValue() }
497
+ : { type: "string" };
498
+ }
499
+ if (type.isNumber() || type.isNumberLiteral()) return { type: "number" };
500
+ if (type.isBoolean() || type.isBooleanLiteral()) return { type: "boolean" };
501
+ if (type.isNull() || type.isUndefined()) return { type: "null" };
502
+
503
+ if (type.isUnion()) {
504
+ const parts = type.getUnionTypes();
505
+ const nonNull = parts.filter((t) => !t.isNull() && !t.isUndefined());
506
+ const isNullable = nonNull.length < parts.length;
507
+
508
+ if (nonNull.length === 1) {
509
+ const inner = typeToJsonSchema(nonNull[0], new Set(visited), ctx);
510
+ return isNullable ? { ...inner, nullable: true } : inner;
511
+ }
512
+ if (nonNull.every((t) => t.isBooleanLiteral())) {
513
+ return isNullable ? { type: "boolean", nullable: true } : { type: "boolean" };
514
+ }
515
+ // String-literal unions and string enums: a select, written into the schema.
516
+ if (nonNull.every((t) => t.isStringLiteral())) {
517
+ const result: any = { type: "string", enum: nonNull.map((t) => t.getLiteralValue()) };
518
+ if (isNullable) result.nullable = true;
519
+ return result;
520
+ }
521
+ if (nonNull.every((t) => t.isNumberLiteral())) {
522
+ const result: any = { type: "number", enum: nonNull.map((t) => t.getLiteralValue()) };
523
+ if (isNullable) result.nullable = true;
524
+ return result;
525
+ }
526
+
527
+ const anyOf = nonNull.map((t) => {
528
+ const schema = typeToJsonSchema(t, new Set(visited), ctx);
529
+ if (!schema.title && schema.type === "object") {
530
+ const symName = (t.getAliasSymbol() ?? t.getSymbol())?.getName();
531
+ if (symName && symName !== "__type" && symName !== "default" && symName !== "__object") {
532
+ schema.title = symName;
533
+ }
534
+ if (!schema.title && schema.properties) {
535
+ for (const v of Object.values(schema.properties) as any[]) {
536
+ if (v?.const !== undefined) {
537
+ schema.title = String(v.const);
538
+ break;
539
+ }
540
+ }
541
+ }
542
+ }
543
+ return schema;
544
+ });
545
+ const result: any = { anyOf };
546
+ if (isNullable) result.nullable = true;
547
+ return result;
548
+ }
549
+
550
+ if (type.isIntersection()) {
551
+ const parts = type.getIntersectionTypes();
552
+ const primitive = parts.find((t) => t.isString() || t.isNumber() || t.isBoolean());
553
+ if (primitive) return typeToJsonSchema(primitive, new Set(visited), ctx);
554
+
555
+ const merged: any = { type: "object", properties: {} };
556
+ const required = new Set<string>();
557
+ for (const part of parts) {
558
+ const sub = typeToJsonSchema(part, new Set(visited), ctx);
559
+ if (sub?.type !== "object" || !sub.properties) continue;
560
+ Object.assign(merged.properties, sub.properties);
561
+ for (const r of sub.required ?? []) required.add(r);
562
+ for (const [k, v] of Object.entries(sub)) {
563
+ if (k === "type" || k === "properties" || k === "required") continue;
564
+ if (!(k in merged)) merged[k] = v;
565
+ }
566
+ }
567
+ if (required.size > 0) merged.required = [...required];
568
+ return merged;
569
+ }
570
+
571
+ if (type.isObject() || type.isInterface()) {
572
+ if (ctx?.shareNamed && type.compilerType !== ctx.shareNamed.rootType.compilerType) {
573
+ const shared = ctx.namedDefinition(type);
574
+ if (shared) return shared;
575
+ }
576
+ const symName = type.getSymbol()?.getName();
577
+ if (symName && RUNTIME_INJECTED_TYPES.has(symName)) {
578
+ const declFile = type.getSymbol()?.getDeclarations()?.[0]?.getSourceFile().getFilePath();
579
+ if (declFile?.includes("typescript/lib/") || declFile?.includes("@types/")) {
580
+ return { type: "object", hide: "true" };
581
+ }
582
+ }
583
+
584
+ const stringIdx = type.getStringIndexType();
585
+ const numberIdx = type.getNumberIndexType();
586
+ if ((stringIdx || numberIdx) && type.getProperties().length === 0) {
587
+ return {
588
+ type: "object",
589
+ additionalProperties: typeToJsonSchema((stringIdx || numberIdx)!, new Set(visited), ctx),
590
+ };
591
+ }
592
+
593
+ const properties: Record<string, any> = {};
594
+ const required: string[] = [];
595
+
596
+ for (const prop of type.getProperties()) {
597
+ const name = prop.getName();
598
+ if (name.startsWith("_") || name.startsWith("$") || name === "@type") continue;
599
+ if (REACT_INTERNAL_PROPS.has(name)) continue;
600
+
601
+ const decl = prop.getValueDeclaration() ?? prop.getDeclarations()[0];
602
+ if (!decl) continue;
603
+ const propType = prop.getTypeAtLocation(decl);
604
+ const tags = getJsDocTags(prop);
605
+ if (tags.ignore) continue;
606
+
607
+ // The annotation as written (`ImageWidget`, `Section[]`, `Secret`),
608
+ // before the checker resolves aliases away.
609
+ const typeNode = decl.getTypeNode();
610
+ const typeHint: string = typeNode ? typeNode.getText() : propType.getText();
611
+ const optional = prop.isOptional();
612
+
613
+ // Methods aren't data, but `Lazy<T>` (a function prop) is a field.
614
+ const callable = nonNullable(propType);
615
+ const isFunction =
616
+ callable.getCallSignatures().length > 0 && callable.getProperties().length === 0;
617
+ if (isFunction && !lazyInner(nonNullable(propType), stripNullish(typeHint))) continue;
618
+
619
+ // v7's opaque `Section` type: a section picker.
620
+ const baseHint = typeHint.replace(/\s*\|\s*(null|undefined)/g, "").trim();
621
+ if ((baseHint === "Section" || baseHint === "Section[]") && isOpaqueSectionType(propType)) {
622
+ const schema: any = baseHint.endsWith("[]")
623
+ ? { type: "array", items: sectionRef(), title: titleCase(name) }
624
+ : { ...sectionRef(), title: titleCase(name) };
625
+ if (isNullableHint(optional, typeHint)) schema.nullable = true;
626
+ applyJsDocToSchema(schema, tags);
627
+ properties[name] = schema;
628
+ if (!optional) required.push(name);
629
+ continue;
630
+ }
631
+
632
+ const schema = fieldSchema(propType, typeHint, ctx, visited);
633
+ if (schema.anyOf && schema.anyOf[0]?.$ref === resolvableRef().$ref) {
634
+ // A block-ref field: nullability lives on the wrapper.
635
+ if (isNullableHint(optional, typeHint)) schema.nullable = true;
636
+ }
637
+ if (schema.$ref === sectionRef().$ref && isNullableHint(optional, typeHint)) {
638
+ schema.nullable = true;
639
+ }
640
+ applyJsDocToSchema(schema, tags);
641
+ schema.title ??= titleCase(name);
642
+ properties[name] = schema;
643
+ // A hidden prop can't be filled in by an editor; requiring it would
644
+ // deadlock the form.
645
+ if (!optional && schema.hide !== "true") required.push(name);
646
+ }
647
+
648
+ const result: any = { type: "object", properties };
649
+ if (required.length > 0) result.required = required;
650
+ const ifaceSym = type.getAliasSymbol() ?? type.getSymbol();
651
+ if (ifaceSym) applyJsDocToSchema(result, getJsDocTags(ifaceSym));
652
+ return result;
653
+ }
654
+
655
+ return { type: "string" };
656
+ } finally {
657
+ visited.delete(typeText);
658
+ }
659
+ }
660
+
661
+ /**
662
+ * A machine-independent id for a source file: relative to the app root, or
663
+ * `<package name>/<path in package>` for a file in a dependency (including a
664
+ * workspace package the checker reached through a symlink).
665
+ */
666
+ export function stableFileId(filePath: string, root: string): string {
667
+ const file = filePath.replace(/^file:\/+/, "/");
668
+ const nm = file.lastIndexOf("/node_modules/");
669
+ if (nm >= 0) return file.slice(nm + "/node_modules/".length);
670
+ const rel = path.relative(root, file).split(path.sep).join("/");
671
+ if (!rel.startsWith("..")) return rel;
672
+ let dir = path.dirname(file);
673
+ for (;;) {
674
+ const manifest = path.join(dir, "package.json");
675
+ if (fs.existsSync(manifest)) {
676
+ try {
677
+ const name = JSON.parse(fs.readFileSync(manifest, "utf8")).name;
678
+ if (typeof name === "string") {
679
+ return `${name}/${path.relative(dir, file).split(path.sep).join("/")}`;
680
+ }
681
+ } catch {
682
+ // unreadable manifest: keep walking
683
+ }
684
+ }
685
+ const parent = path.dirname(dir);
686
+ if (parent === dir) return path.basename(file);
687
+ dir = parent;
688
+ }
689
+ }