@writedocs/generator 0.10.13 → 0.10.15

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.
@@ -1,1768 +1,1882 @@
1
- // O schema do writedocs.json, e nada alem disso.
2
- //
3
- // Este arquivo era as primeiras 875 linhas do config.ts (que continua
4
- // reexportando tudo daqui, entao nada que importa de './config.js' mudou). A
5
- // separacao existe por um motivo concreto: o config.ts importa node:fs,
6
- // node:path e gray-matter no topo pras funcoes que leem o disco, e o
7
- // package.json passou a exportar './config-schema' pra que a plataforma
8
- // (writedocs-application) possa importar o schema DE VERDADE - o mesmo que o
9
- // build usa - em vez de manter uma copia que diverge em algumas semanas. Um
10
- // Worker da Cloudflare nao consegue importar um modulo que traz node:fs junto.
11
- //
12
- // Por isso a unica dependencia aqui e o zod. Nada neste arquivo pode passar a
13
- // tocar o sistema de arquivos: se precisar de fs/path, o lugar e o config.ts.
14
- //
15
- // ESTE arquivo e a fonte de verdade, mas NAO e o que o pacote publica: o script
16
- // `prepare` (package.json) transpila ele pra ./config-schema.js, e e o `.js` que
17
- // o `exports` e o bin/writedocs.js apontam. Sem isso o `writedocs validate`
18
- // quebra pra quem instala o pacote - o Node recusa type stripping sob
19
- // node_modules. Editou aqui, rode `npm run build:schema` (ou qualquer
20
- // `npm install`) antes de testar o caminho da CLI ou da plataforma.
21
- //
22
- // (`zod` e nao `astro/zod`: as duas especificacoes resolvem pra mesma instalacao
23
- // - node_modules/zod 4.4.3, que e o que astro@7.2.2 tambem pede via `^4.3.6` -
24
- // entao a troca nao muda comportamento nenhum, so tira o astro do caminho de
25
- // quem importa isto de fora do gerador.)
26
- import { z } from 'zod';
27
- // WD-063: `parseTree` + `findNodeAtLocation` traduzem o caminho de um erro
28
- // (`navigation.products.0.product`) para o offset dele no TEXTO, que e o que
29
- // vira linha. E o parser de JSON do VS Code: zero dependencias, nada de `node:`,
30
- // entao continua bundlavel pro Worker da plataforma. Escrever o scanner a mao
31
- // foi tentado e deu errado (perdia todo caminho aninhado, que e justamente o que
32
- // importa aqui) - nao repita.
33
- import { findNodeAtLocation, parseTree } from 'jsonc-parser';
34
-
35
- // ---------------------------------------------------------------------
36
- // Pages & groups - the leaf content any container ultimately bottoms out
37
- // at. A group can nest other groups arbitrarily deep, and can optionally
38
- // link its own label to a page (`page`) independent of expanding or
39
- // collapsing its children - see NavTree.astro for how that renders.
40
- // ---------------------------------------------------------------------
41
-
42
- const navPageSchema = z.string();
43
-
44
- // A group ordinarily lists its own children by hand (`pages`), but can
45
- // instead auto-generate them from an OpenAPI spec via `openapi: { src,
46
- // path }` - resolved by loadDocsConfig() (via expandOpenApiInNavigation()
47
- // below, reading the manifest generate-api-pages.js writes for this exact
48
- // group) into a real `{ group, pages }` node - one sub-group per tag -
49
- // before anything else in this file ever sees it, so
50
- // resolveSections()/flattenNav()/buildNavTree()/etc. only ever need to
51
- // understand the ordinary pages-array shape. `.strict()` on both variants
52
- // is load-bearing (see withChildren()'s own comment on this pattern
53
- // below): without it, a group written with both `pages` and `openapi` at
54
- // once would silently have one dropped instead of rejected.
55
- const navGroupPagesSchema: z.ZodType<{ group: string; page?: string; pages: NavItem[] }> = z.lazy(() =>
56
- z
57
- .object({
58
- group: z.string(),
59
- page: z.string().optional(),
60
- pages: z.array(navItemSchema),
61
- })
62
- .strict()
63
- );
64
-
65
- const navGroupOpenApiSchema = z.object({
66
- group: z.string(),
67
- openapi: z
68
- .object({
69
- // Path to an OpenAPI 3.x spec, relative to the content directory
70
- // (alongside writedocs.json) - same convention the old top-level
71
- // `openapi` field used. See generate-api-pages.js (the pre-Astro
72
- // build/dev step that actually parses this and writes the
73
- // manifest/operation JSON this group's pages are expanded from).
74
- src: z.string(),
75
- // Base URL path every page generated from this spec is namespaced
76
- // under, e.g. "/api" -> pages served at /api/<tag>/<operation>/.
77
- // Also doubles as this spec's own unique key under
78
- // writedocsTempDir()'s openapi/<path>/ directory (manifest.json + operations/*.json),
79
- // so two openapi groups in the same writedocs.json must use different
80
- // `path` values - generate-api-pages.js throws a clear error if
81
- // they collide.
82
- path: z.string(),
83
- })
84
- .strict(),
85
- }).strict();
86
-
87
- export type GroupNavItem =
88
- | { group: string; page?: string; pages: NavItem[] }
89
- | { group: string; openapi: { src: string; path: string } };
90
-
91
- const navGroupSchema: z.ZodType<GroupNavItem> = z.union([navGroupPagesSchema, navGroupOpenApiSchema]);
92
-
93
- // A bare external link sitting directly in a `pages` array, alongside
94
- // page slugs and groups - e.g. a "Support" link to an external help
95
- // desk shown right in the sidebar, rather than only reachable via
96
- // navigation.global.dropdowns. Discriminated from navGroupSchema by
97
- // its required `label`/`href` keys (vs `group`/`pages`/`openapi`), so a
98
- // plain (non-strict at the union level) schema is enough for Zod to pick
99
- // the right branch; `.strict()` here still catches a typo'd extra key.
100
- const navLinkSchema = z.object({ label: z.string(), href: z.string() }).strict();
101
-
102
- const navItemSchema: z.ZodType<NavItem> = z.lazy(() =>
103
- z.union([navPageSchema, navGroupSchema, navLinkSchema])
104
- );
105
-
106
- export type NavItem = string | GroupNavItem | { label: string; href: string };
107
-
108
- // ---------------------------------------------------------------------
109
- // Containers: tabs, versions, languages, dropdowns, products.
110
- //
111
- // This schema is modeled directly on Mintlify's writedocs.json
112
- // (https://mintlify.com/writedocs.json / mintlify.com/docs/organize/navigation):
113
- // all five container kinds are structurally identical except for their
114
- // own identifying field. Each owns *exactly one* of {pages, tabs,
115
- // versions, languages, dropdowns, products} as its content, or is a bare
116
- // external `href` link with no content of its own. That symmetry is what
117
- // lets any of them nest inside any other - a tab can contain versions, a
118
- // version can contain languages, a language can contain tabs, and so on,
119
- // bottoming out at a `pages` array. `withChildren()` is the single place
120
- // that shape is defined, instead of hand-writing the union five times.
121
- // ---------------------------------------------------------------------
122
-
123
- export type NavChildren =
124
- | { pages: NavItem[] }
125
- | { tabs: TabItem[] }
126
- | { versions: VersionItem[] }
127
- | { languages: LanguageItem[] }
128
- | { dropdowns: DropdownItem[] }
129
- | { products: ProductItem[] }
130
- | { href: string };
131
-
132
- /** Any navigation item can be hidden: reachable only by its address - no
133
- * switcher, tab or menu lists it, and its pages search only among
134
- * themselves (plus the public ones, with `searchPublic`). See
135
- * lib/hidden-sections.js.
136
- * And any can have a `page` of its own: where choosing the item leads, in
137
- * place of its first page - an overview of what's in it. In a sidebar too,
138
- * it opens there; otherwise it opens inside the item (resolveLandings() in
139
- * lib/config.ts). */
140
- export type Hideable = { hidden?: boolean; searchPublic?: boolean; page?: string };
141
-
142
- export type TabItem = { tab: string; icon?: string } & Hideable & NavChildren;
143
- export type VersionItem = { version: string; label?: string; tag?: string; default?: boolean } & Hideable & NavChildren;
144
- export type LanguageItem = { language: string; label?: string } & Hideable & NavChildren;
145
- export type DropdownItem = { dropdown: string; icon?: string } & Hideable & NavChildren;
146
- export type ProductItem = { product: string; icon?: string; description?: string } & Hideable & NavChildren;
147
-
148
- // `.strict()` on every variant is load-bearing, not decoration: Zod
149
- // objects silently strip unrecognized keys by default, so without it a
150
- // node written with two children fields at once (e.g. both `pages` and
151
- // `versions`) would just have the second one dropped instead of
152
- // rejected - defeating the entire "exactly one child kind per level"
153
- // rule this schema exists to enforce (mirroring Mintlify's own "a tab
154
- // cannot contain both anchors and groups at the same level").
155
- function withChildren<Base extends z.ZodRawShape>(ownFields: Base) {
156
- const base = { ...ownFields, hidden: z.boolean().optional(), searchPublic: z.boolean().optional(), page: z.string().optional() };
157
- return z.union([
158
- z.object({ ...base, pages: z.array(navItemSchema) }).strict(),
159
- z.object({ ...base, tabs: z.array(tabSchema).min(1) }).strict(),
160
- z.object({ ...base, versions: z.array(versionSchema).min(1) }).strict(),
161
- z.object({ ...base, languages: z.array(languageSchema).min(1) }).strict(),
162
- z.object({ ...base, dropdowns: z.array(dropdownSchema).min(1) }).strict(),
163
- z.object({ ...base, products: z.array(productSchema).min(1) }).strict(),
164
- z.object({ ...base, href: z.string() }).strict(),
165
- ]);
166
- }
167
-
168
- // Each of these five is defined via z.lazy() because withChildren()
169
- // references all five by name (mutual recursion) - safe because none of
170
- // them are actually *called* until a real writedocs.json is parsed, by which
171
- // point every const below has been assigned. The same pattern already
172
- // used for navItemSchema/navGroupSchema above.
173
- const tabSchema: z.ZodType<TabItem> = z.lazy(() =>
174
- withChildren({ tab: z.string(), icon: z.string().optional() })
175
- );
176
-
177
- const versionSchema: z.ZodType<VersionItem> = z.lazy(() =>
178
- withChildren({
179
- version: z.string(),
180
- label: z.string().optional(),
181
- tag: z.string().optional(),
182
- default: z.boolean().optional(),
183
- })
184
- );
185
-
186
- const languageSchema: z.ZodType<LanguageItem> = z.lazy(() =>
187
- withChildren({ language: z.string(), label: z.string().optional() })
188
- );
189
-
190
- const dropdownSchema: z.ZodType<DropdownItem> = z.lazy(() =>
191
- withChildren({ dropdown: z.string(), icon: z.string().optional() })
192
- );
193
-
194
- const productSchema: z.ZodType<ProductItem> = z.lazy(() =>
195
- withChildren({ product: z.string(), icon: z.string().optional(), description: z.string().optional() })
196
- );
197
-
198
- // ---------------------------------------------------------------------
199
- // Root navigation: a flat array (shorthand for one implicit section - the
200
- // common case) or an object choosing exactly one primary organizational
201
- // pattern, per Mintlify's convention ("choose one primary organizational
202
- // pattern at the root level of your navigation").
203
- //
204
- // `global.dropdowns` is the one exception to "exactly one pattern": it's
205
- // not a primary pattern, it's a persistent set of topbar dropdown
206
- // triggers that render on every page regardless of which tab/version/
207
- // language/product is active - equivalent to Mintlify's
208
- // `navigation.global.anchors`. This replaces the earlier `{tabs,
209
- // dropdowns}` shape (both present at once), which doesn't generalize
210
- // once versions/languages/products are also root-level choices.
211
- // ---------------------------------------------------------------------
212
-
213
- export type NavigationConfig =
214
- | NavItem[]
215
- | { global?: { dropdowns: DropdownItem[] }; tabs: TabItem[] }
216
- | { global?: { dropdowns: DropdownItem[] }; versions: VersionItem[] }
217
- | { global?: { dropdowns: DropdownItem[] }; languages: LanguageItem[] }
218
- | { global?: { dropdowns: DropdownItem[] }; dropdowns: DropdownItem[] }
219
- | { global?: { dropdowns: DropdownItem[] }; products: ProductItem[] };
220
-
221
- /** Levels of tabs a page can sit under - one row of the top bar each. */
222
- export const MAX_TAB_LEVELS = 2;
223
- /** Levels of dropdowns in a tab's menu - the menu, and a flyout beside an
224
- * entry for the dropdowns inside it (lib/selector-placement.js). */
225
- export const MAX_TAB_MENU_LEVELS = 2;
226
-
227
- const globalSchema = z.object({ dropdowns: z.array(dropdownSchema).min(1) });
228
-
229
- const navigationSchema = z.union([
230
- z.array(navItemSchema),
231
- z.object({ global: globalSchema.optional(), tabs: z.array(tabSchema).min(1) }).strict(),
232
- z.object({ global: globalSchema.optional(), versions: z.array(versionSchema).min(1) }).strict(),
233
- z.object({ global: globalSchema.optional(), languages: z.array(languageSchema).min(1) }).strict(),
234
- z.object({ global: globalSchema.optional(), dropdowns: z.array(dropdownSchema).min(1) }).strict(),
235
- z.object({ global: globalSchema.optional(), products: z.array(productSchema).min(1) }).strict(),
236
- ]).superRefine((navigation, ctx) => {
237
- // Every page under a language is in that language - a second `languages`
238
- // inside it would make a page two languages at once. And tabs take a row
239
- // of the top bar per level: two levels at most (TopBar.astro).
240
- const CONTAINERS = ['tabs', 'versions', 'languages', 'dropdowns', 'products'] as const;
241
- // `menu`: the dropdown levels in a tab's menu down to `node` - 0 outside
242
- // one, 1 for a dropdown right inside a tab, 2 for a dropdown inside that.
243
- const walk = (node: unknown, path: (string | number)[], language: string | null, tabs: string[], menu = 0) => {
244
- if (!node || typeof node !== 'object' || Array.isArray(node)) return;
245
- const own = node as Record<string, unknown>;
246
- for (const key of CONTAINERS) {
247
- const items = own[key];
248
- if (!Array.isArray(items)) continue;
249
- if (key === 'languages' && language !== null) {
250
- ctx.addIssue({
251
- code: 'custom',
252
- path: [...path, key],
253
- message: `The language "${language}" contains another "languages" list. A page can only be in one language - put the languages at one level, and the rest (tabs, versions, ...) inside each of them.`,
254
- });
255
- continue;
256
- }
257
- if (key === 'tabs' && tabs.length >= MAX_TAB_LEVELS) {
258
- ctx.addIssue({
259
- code: 'custom',
260
- path: [...path, key],
261
- message: `Tabs go at most ${MAX_TAB_LEVELS} levels deep, and these are a third level (inside "${tabs.join('" > "')}"). Each level of tabs is a row in the top bar - use a dropdown or groups for this level instead.`,
262
- });
263
- continue;
264
- }
265
- // Dropdowns right inside a tab are its menu; dropdowns inside one of
266
- // those, a flyout beside its entry. Any other level of dropdowns starts
267
- // its own count.
268
- const menuLevel = key !== 'dropdowns' ? 0 : 'tab' in own ? 1 : 'dropdown' in own && menu > 0 ? menu + 1 : 0;
269
- if (menuLevel > MAX_TAB_MENU_LEVELS) {
270
- ctx.addIssue({
271
- code: 'custom',
272
- path: [...path, key],
273
- message: `A tab's menu goes ${MAX_TAB_MENU_LEVELS} levels deep at most - its dropdowns, and the dropdowns inside each of them - and these are a third level (inside "${String(own.dropdown)}"). Use products or groups for this level instead.`,
274
- });
275
- continue;
276
- }
277
- items.forEach((item, i) => {
278
- const own = item as { hidden?: unknown; searchPublic?: unknown; page?: unknown; href?: unknown };
279
- if (own?.page !== undefined && own.href !== undefined) {
280
- ctx.addIssue({
281
- code: 'custom',
282
- path: [...path, key, i, 'page'],
283
- message: 'An item with `href` is a link, so it has no page of its own - remove `page`, or `href`.',
284
- });
285
- }
286
- if (own?.searchPublic === true && own.hidden !== true) {
287
- ctx.addIssue({
288
- code: 'custom',
289
- path: [...path, key, i, 'searchPublic'],
290
- message: '`searchPublic` only applies to a hidden item - add "hidden": true, or remove `searchPublic`.',
291
- });
292
- }
293
- const inner = key === 'languages' ? String((item as { language?: unknown })?.language ?? '') : language;
294
- const tab = (item as { tab?: unknown })?.tab;
295
- walk(item, [...path, key, i], inner, key === 'tabs' ? [...tabs, String(tab ?? '')] : tabs, menuLevel);
296
- });
297
- }
298
- };
299
- walk(navigation, [], null, []);
300
- }) as z.ZodType<NavigationConfig>;
301
-
302
- const DEFAULT_PRIMARY = '#6366f1';
303
-
304
- // A logo is either one path used for both color modes, or a
305
- // { light, dark, label } object - each image shown only while that mode
306
- // is active (see BaseLayout.astro's .wd-logo-light/.wd-logo-dark CSS).
307
- // The topbar shows *only* the image by default - no site name text next
308
- // to it, since a real logo asset usually already is a wordmark. `label`
309
- // is the opt-in way to add text back next to the image (e.g. a product
310
- // name alongside a symbol-only mark); it only exists on the object form,
311
- // since a single shared image path is just as easy to bake the label
312
- // into directly.
313
- //
314
- // `light`/`dark` are themselves optional (unlike the string form, which
315
- // is inherently "both"): a site with no logo *images* at all can still
316
- // set `styles.logo: { label: "..." }` to override the topbar's fallback
317
- // text without providing any image - see BaseLayout.astro's
318
- // hasLogoImage/logoLabel/brandLabel derivation, where an object with
319
- // only `label` set already resolves correctly (brandLabel = logoLabel,
320
- // same as if an image were also present) without needing any change
321
- // there; only this schema needed loosening; light/dark were previously
322
- // both required whenever the object form was used at all.
323
- //
324
- // Standalone const (rather than inlined into stylesSchema.logo below) so
325
- // footer.logo further down can share the exact same union instead of an
326
- // independently-written copy - see footerSchema's own comment on why a
327
- // footer logo needs this at all.
328
- const logoSchema = z.union([
329
- z.string(),
330
- z.object({ light: z.string().optional(), dark: z.string().optional(), label: z.string().optional() }).strict(),
331
- ]);
332
-
333
- // Same {light, dark}-with-fallback shape applies to `colors.dark`: any
334
- // of primary/text left unset there falls back to the light-mode value
335
- // already given above, so a site only has to specify what actually
336
- // differs in dark mode. There used to be a `background`/`dark.background`
337
- // pair here too, doing effectively the same job as `background.colors`
338
- // further down (see that field's own comment) - two writedocs.json fields
339
- // both named "background" that visually looked interchangeable but
340
- // weren't quite (one drove --wd-background site-wide, the other only
341
- // the <body> canvas), which was confusing to author against and easy to
342
- // half-configure by setting only one. Removed in favor of `background`
343
- // alone being the single place to set any background color - see that
344
- // field's comment for what it now covers.
345
- // One side of `styles.navbar` (light or dark) - either a bare background
346
- // color (the original shape) or `{ background, accent? }` once a site
347
- // wants its own accent color (the active tab's underline)
348
- // inside the navbar specifically, independent of the sitewide
349
- // `styles.colors.primary`. Deliberately does NOT carry a text/icon color
350
- // field at all - see `navbar`'s own comment below (stylesSchema) for why
351
- // that's resolved automatically instead of being configurable. Kept as a
352
- // standalone const rather than inlined so `light`/`dark` share the exact
353
- // same union rather than two independently-written (and possibly
354
- // drifting) copies of it.
355
- const navbarColorValueSchema = z.union([
356
- z.string(),
357
- z
358
- .object({
359
- background: z.string(),
360
- accent: z.string().optional(),
361
- })
362
- .strict(),
363
- ]);
364
-
365
- // One font declaration - almost exactly Mintlify's own `fonts` shape (see
366
- // docs/dev/docs/site-config.mdx's own "Fonts" section for the research this
367
- // was based on): a bare Google Fonts family name (`family` alone - Google
368
- // Fonts loads it automatically, see googleFontsHref() below), or a local/
369
- // externally-hosted font file (`source` + `format` together; `source` is
370
- // either a project-relative path like the other five asset-fallback fields
371
- // this schema already has - see collectConfiguredAssetPaths() - or a full
372
- // https:// URL to an externally-hosted font). `weight` does two things at
373
- // once, both driven by BaseLayout.astro: it narrows which file actually
374
- // loads (folded into the Google Fonts URL's `:wght@` axis, or the
375
- // generated `@font-face` rule's own `font-weight` descriptor for a
376
- // `source` font - see googleFontsHref()/fontFaceRule() below), *and* it's
377
- // applied as a real CSS `font-weight` on h1-h6 (for `heading`) or `body`
378
- // (for `body`) - see BaseLayout's own `wdFontWeightHeading`/
379
- // `wdFontWeightBody`. Both halves matter: loading only the 400-weight file
380
- // while leaving h1-h6 at the browser's UA-default `font-weight: bold`
381
- // faux-bolds that file back to looking bold anyway, with no visible
382
- // change from configuring a lighter weight at all - the bug this second
383
- // half fixes (caught from real user-reported behavior, not anticipated
384
- // up front). Left unset anywhere in `styles.fonts` renders no font-weight
385
- // rule at all, keeping today's plain browser-default bold headings/normal
386
- // body text unchanged for a site that hasn't touched this field.
387
- const fontVariantSchema = z
388
- .object({
389
- family: z.string(),
390
- weight: z.number().optional(),
391
- source: z.string().optional(),
392
- format: z.enum(['woff', 'woff2']).optional(),
393
- })
394
- .strict();
395
-
396
- export type FontVariant = z.infer<typeof fontVariantSchema>;
397
-
398
- // The top-level shape adds `heading`/`body`: each independently optional,
399
- // each falling back to the top-level family/weight/source/format when
400
- // unset (see resolveFonts() below) - so a site can set one font for
401
- // everything (`fonts.family` alone), or split headings and body text
402
- // without needing to repeat itself for whichever side isn't changing.
403
- const fontsSchema = z
404
- .object({
405
- family: z.string(),
406
- weight: z.number().optional(),
407
- source: z.string().optional(),
408
- format: z.enum(['woff', 'woff2']).optional(),
409
- heading: fontVariantSchema.optional(),
410
- body: fontVariantSchema.optional(),
411
- })
412
- .strict();
413
-
414
- export type FontsConfig = z.infer<typeof fontsSchema>;
415
-
416
- const stylesSchema = z
417
- .object({
418
- colors: z
419
- .object({
420
- primary: z.string().default(DEFAULT_PRIMARY),
421
- text: z.string().optional(),
422
- dark: z
423
- .object({
424
- primary: z.string().optional(),
425
- text: z.string().optional(),
426
- })
427
- .optional(),
428
- })
429
- .default({ primary: DEFAULT_PRIMARY }),
430
- logo: logoSchema.optional(),
431
- favicon: z.string().optional(),
432
- // No default value here (unlike `colors.primary`'s DEFAULT_PRIMARY) -
433
- // resolveFonts() below is where "Inter" actually gets applied as the
434
- // site-wide default whenever this field is left unset entirely, so
435
- // that fallback lives in one place alongside the rest of the
436
- // resolution logic rather than being duplicated as a schema default
437
- // *and* a resolver fallback.
438
- fonts: fontsSchema.optional(),
439
- // The Shiki theme *name* (not a full theme object/JSON - see
440
- // https://shiki.style/themes for the built-in list) each fenced
441
- // (```) MDX code block, and the API playground's request/response
442
- // snippets, use in light/dark mode - read out of writedocs.json by both
443
- // astro.config.mjs (Shiki's dual-theme markdown config) and
444
- // ApiReferencePanel.astro (its own separate <Code/> usages, which
445
- // don't inherit markdown.shikiConfig) via resolveCodeblockTheme()
446
- // below, the single source of truth for the 'github-light'/
447
- // 'github-dark' fallback. Left per-key optional (not defaulted in
448
- // the schema itself) so a site can override just one side (e.g.
449
- // only `dark`) and still get the ordinary default for the other.
450
- codeblocks: z
451
- .object({
452
- light: z.string().optional(),
453
- dark: z.string().optional(),
454
- // Maps a fenced (```) block's own language tag to whichever real
455
- // Shiki grammar actually highlights it, before that tag ever
456
- // reaches Shiki - see resolveCodeblockLangAlias() below for the
457
- // one built-in entry (mdx -> jsx) this ships with by default and
458
- // why. A site can add its own entries for any other language tag
459
- // that either doesn't tokenize well under its own grammar, or
460
- // that a site wants to write under a shorter/friendlier fence tag
461
- // than Shiki's own bundled id (e.g. `groovy: 'java'` for a close-
462
- // enough approximation Shiki doesn't ship a dedicated grammar for
463
- // at all) - merged with, not replacing, the built-in default, so
464
- // adding one of a site's own doesn't require re-declaring mdx.
465
- langAlias: z.record(z.string(), z.string()).optional(),
466
- })
467
- .strict()
468
- .optional(),
469
- // The topbar's own background, independent of `background` below (the
470
- // page's) - a site may want its navbar to stand out (a dark or
471
- // brand-colored bar over a light page) rather than blend into the
472
- // page, which is the default when this is left unset. Same {light,
473
- // dark} shape (and same per-key-optional, not defaulted here) as
474
- // `codeblocks` right above, rather than nested under `colors` - it's a
475
- // topbar-specific override, not a third general-purpose page color, so
476
- // it reads more like "one more themed surface" alongside codeblocks
477
- // than a sibling of primary/text. BaseLayout.astro's own
478
- // lightNavbarBg/darkNavbarBg resolution is what falls each side back
479
- // to the page background when unset.
480
- //
481
- // Each side (`light`/`dark`) is either a bare string - just the
482
- // background color, exactly the original shape, kept for backwards
483
- // compatibility - or `{ background, accent? }`, for when a site also
484
- // wants the navbar's own active-tab underline color to
485
- // differ from the sitewide `styles.colors.primary` (`accent`'s only
486
- // job - see BaseLayout.astro's lightNavbarAccent). Deliberately no
487
- // text/icon color field here at all: BaseLayout.astro always resolves
488
- // the navbar's plain text/icon color itself, picking black or white by
489
- // contrast against whatever `background` resolves to
490
- // (contrastTextColor() below) the moment this field is configured at
491
- // all (string or object) - never a value read from writedocs.json. A
492
- // manually-set text color is a legibility footgun a site author can
493
- // get wrong (or drift out of sync after later changing `background`
494
- // without remembering to update it too) in a way "compute it
495
- // correctly, every time" simply can't - there's no legitimate reason
496
- // to want *illegible* navbar text, unlike `accent`, which is a real
497
- // aesthetic choice. Real bug this fixes: a site setting `navbar.light`
498
- // to the same value as `colors.primary` (a plausible thing to reach
499
- // for - "brand-colored navbar") made every topbar label/icon/link
500
- // render in the default near-black text color against that same
501
- // saturated background, all but unreadable - and an earlier version of
502
- // this feature that let a writedocs.json-supplied color double as the text
503
- // color reintroduced the identical bug one level down, just requiring
504
- // one more (still guessable-wrong) field to trigger it.
505
- navbar: z
506
- .object({
507
- light: navbarColorValueSchema.optional(),
508
- dark: navbarColorValueSchema.optional(),
509
- })
510
- .strict()
511
- .optional(),
512
- // The single place to configure any background color: `colors` is a
513
- // solid color (falls back to '#ffffff'/'#0b1120' when unset - see
514
- // BaseLayout.astro's lightBackground/darkBackground resolution), and
515
- // `images` layers an image on top of it (or is the whole background
516
- // by itself, if `colors` is left at its default). This one pair now
517
- // drives everything background-related site-wide - --wd-background
518
- // (dropdowns/modals/kbd chips/footer/topbar-fallback/etc., see every
519
- // `var(--wd-background)` call site) *and* the <body> canvas behind the
520
- // main/toc columns - rather than the two being independently
521
- // configurable fields that happened to look alike but didn't affect
522
- // the same things (see this schema's own comment on `colors.dark`
523
- // above for why that split was removed). Both are per-mode optional,
524
- // same "only specify what differs" pattern as codeblocks/navbar above.
525
- // The topbar and footer still get their own explicit opaque
526
- // background (topbar.css/footer.css) specifically so an `images`
527
- // background doesn't show through them; see those files' own
528
- // comments. The sidebar column has no background of its own (base.css)
529
- // and lets it show through, same as the main/toc columns.
530
- background: z
531
- .object({
532
- colors: z
533
- .object({
534
- light: z.string().optional(),
535
- dark: z.string().optional(),
536
- })
537
- .strict()
538
- .optional(),
539
- images: z
540
- .object({
541
- light: z.string().optional(),
542
- dark: z.string().optional(),
543
- })
544
- .strict()
545
- .optional(),
546
- })
547
- .strict()
548
- .optional(),
549
- })
550
- .default({ colors: { primary: DEFAULT_PRIMARY } });
551
-
552
- // `href` is always required - a link with nowhere to go isn't a link.
553
- // `label`/`icon` are each individually optional, but not both at once
554
- // (enforced by the .refine() below, same shape as scriptEntrySchema's own
555
- // exactly-one-of check above) - a link needs *something* visible to render,
556
- // whichever of the two, and can have both (icon rendered to the left of the
557
- // label - see TopBar.astro/SiteFooter.astro, the two renderers of this
558
- // shape). An icon-only link (no label) is the common case for something
559
- // like a bare GitHub mark in the topbar; label-only (no icon) is every
560
- // plain text link this already supported before `icon` existed - both
561
- // still need to keep working unchanged, hence neither field being outright
562
- // required on its own.
563
- const topbarLinkSchema = z
564
- .object({
565
- label: z.string().optional(),
566
- href: z.string(),
567
- // Same string shape as every other writedocs.json `icon` field (a plain
568
- // Lucide name, or the explicit "collection:icon-name" form for
569
- // anything else - see resolveIcon()/AppIcon.astro) - not documented
570
- // again here since that convention is already established elsewhere
571
- // in this file (tabs/switchers/socials all take the identical shape).
572
- icon: z.string().optional(),
573
- })
574
- .strict()
575
- .refine((link) => Boolean(link.label) || Boolean(link.icon), {
576
- message: 'Each topbar.links/footer column link needs a "label", an "icon", or both - a link with neither has nothing to render.',
577
- });
578
-
579
- // One column of the footer (BaseLayout.astro's <footer class="wd-footer">) -
580
- // an optional heading (e.g. "Resources", "Community") plus a list of links,
581
- // reusing the exact same {label, icon, href} shape as topbar.links above (a
582
- // footer link is the same thing rendered in a different place, no reason
583
- // for a second, identical-but-differently-named schema). `title` is
584
- // optional so a single-column footer with no heading (just a bare list of
585
- // links) is valid too.
586
- const footerColumnSchema = z
587
- .object({
588
- title: z.string().optional(),
589
- links: z.array(topbarLinkSchema).default([]),
590
- })
591
- .strict();
592
-
593
- // Off by default (empty `columns`, same convention as `topbar` above - a
594
- // footer with nothing configured just doesn't render at all, see
595
- // BaseLayout.astro's `hasFooterContent` check) rather than `.optional()`
596
- // like contextMenu: unlike that field, an empty/default footer has no
597
- // build-output or routing implications to gate, it's purely visual, so
598
- // there's no reason to distinguish "unset" from "set to nothing" the way
599
- // contextMenu needs to.
600
- // Same {light, dark, label} union as `styles.logo` (via the shared
601
- // logoSchema above) - unset by default, in which case the footer just
602
- // shows the sitewide `styles.logo` (BaseLayout.astro's existing
603
- // logoLight/logoDark/logoLabel, already threaded into SiteFooter as-is).
604
- // Set here, it replaces that entirely rather than filling in only the
605
- // missing side of it - a footer.logo with only `dark` set shows *just*
606
- // the dark-mode image, not styles.logo's light image plus this dark one -
607
- // the same all-or-nothing-relative-to-styles.logo resolution BaseLayout.astro
608
- // already applies.
609
- const footerSchema = z
610
- .object({
611
- columns: z.array(footerColumnSchema).default([]),
612
- logo: logoSchema.optional(),
613
- })
614
- .strict()
615
- .default({ columns: [] });
616
-
617
- export type FooterColumn = z.infer<typeof footerColumnSchema>;
618
- export type FooterConfig = z.infer<typeof footerSchema>;
619
-
620
- // Shared by both writedocs.json's top-level `seo` (site-wide defaults) and a
621
- // page's own frontmatter `seo` (per-page overrides) - see
622
- // content.config.ts's docsSchema, which imports this exact schema rather
623
- // than redeclaring the same shape a second time. mergeSeo() below is what
624
- // actually combines the two, field by field, at render time.
625
- export const seoFieldsSchema = z
626
- .object({
627
- // Open Graph / Twitter card image - a relative path (resolved against
628
- // `domain` below into an absolute URL, since most social crawlers
629
- // require one) or an already-absolute https:// URL.
630
- ogImage: z.string().optional(),
631
- // og:type - "website" for most pages, "article" for blog-post-shaped
632
- // content, etc. Defaults to "website" if never set anywhere.
633
- ogType: z.string().optional(),
634
- twitterCard: z.enum(['summary', 'summary_large_image']).optional(),
635
- keywords: z.array(z.string()).optional(),
636
- // Renders <meta name="robots" content="noindex, nofollow" /> and
637
- // (see astro.config.mjs's sitemap `filter`) excludes the page from
638
- // sitemap.xml entirely - both driven off this one flag, since listing
639
- // a page in the sitemap while also telling crawlers not to index it
640
- // would be self-contradictory.
641
- noindex: z.boolean().optional(),
642
- })
643
- .strict();
644
-
645
- export type SeoFields = z.infer<typeof seoFieldsSchema>;
646
-
647
- /** Field-by-field merge of a page's own `seo` frontmatter over writedocs.json's
648
- * site-wide `seo` defaults - a page only overrides the specific fields it
649
- * sets, falling back to the site default for everything else, rather than
650
- * a page's (possibly partial) `seo` object replacing the site's wholesale. */
651
- export function mergeSeo(site: SeoFields, page?: SeoFields): SeoFields {
652
- if (!page) return site;
653
- return {
654
- ogImage: page.ogImage ?? site.ogImage,
655
- ogType: page.ogType ?? site.ogType,
656
- twitterCard: page.twitterCard ?? site.twitterCard,
657
- keywords: page.keywords ?? site.keywords,
658
- noindex: page.noindex ?? site.noindex,
659
- };
660
- }
661
-
662
- const MINTLIFY_MODE_ALIASES: Record<string, string> = { center: 'frame', assistant: 'default' };
663
-
664
- /** A page's own frontmatter - the `pages` and `generatedDocs` content
665
- * collections' schema (content.config.ts), and what `writedocs validate`
666
- * checks every page against. */
667
- export const pageFrontmatterSchema = z.object({
668
- title: z.string(),
669
- description: z.string().optional(),
670
- // Overrides the URL this page is served at, independent of where the
671
- // file actually lives - writedocs.json's `pages` arrays always keep
672
- // referencing the file's own path regardless. This is Astro's own
673
- // glob()-loader convention (a `slug` frontmatter field becomes
674
- // `entry.id` verbatim - see generateIdDefault in
675
- // astro/dist/content/loaders/glob.js), not writedocs-specific
676
- // behavior; declaring it here just brings it into the schema (and
677
- // its docs) rather than leaving it an undocumented Astro feature.
678
- // See fileIdForEntry() in lib/config.ts for how routes/links still
679
- // resolve a page by its file id once this diverges from `entry.id`.
680
- // Leading/trailing slashes are fine either way ("/", "/guides/x",
681
- // "guides/x" and "guides/x/" all mean the same thing) - see
682
- // normalizeEntryId() in lib/config.ts, which is what actually
683
- // strips them before this value is ever used as a route or href.
684
- slug: z.string().optional(),
685
- // Marks this page as an OpenAPI operation reference: "METHOD /path"
686
- // matching an operation in the owning group's OpenAPI spec, e.g.
687
- // "GET /pets/{petId}" - [...slug].astro renders <ApiPlayground /> for
688
- // any page with this field set, below the page's own MDX body (if
689
- // any). Sites don't write this by hand for most pages; it's either
690
- // set on a generated stub in the `generatedDocs` collection below (see
691
- // generate-api-pages.js) or hand-authored to "eject" one specific
692
- // operation into a real file (in `docs`) with custom prose - either
693
- // way, the value is always exactly the same "METHOD /path" key
694
- // generate-api-pages.js uses to look up the operation's full resolved
695
- // schema/examples at render time.
696
- openapi: z.string().optional(),
697
- // Controls how much of the site's own chrome (topbar, sidebar, table of
698
- // contents) wraps this page - see BaseLayout.astro/[...slug].astro for
699
- // what each value actually removes:
700
- // default - the normal three-column reading layout (all chrome).
701
- // wide - drops the table of contents; the article itself also
702
- // renders wider, for content that wants the extra room
703
- // (wide tables, side-by-side images).
704
- // frame - drops the sidebar and table of contents, but keeps the
705
- // topbar and the article's own normal presentation
706
- // ("frame" as in: still inside the site's outer frame).
707
- // custom - drops the sidebar and table of contents, the
708
- // auto-rendered <h1>, and prev/next nav, and skips the
709
- // article's own prose width/padding too - a blank canvas
710
- // for a hand-built landing/home page made entirely of
711
- // components - but keeps the topbar, so the page still
712
- // has site branding/nav/search/theme-toggle available.
713
- // blank - everything 'custom' drops, plus the topbar too: no site
714
- // chrome at all, just <slot />. For a page that wants to
715
- // look nothing like the rest of the site (an auth screen,
716
- // a print-style page).
717
- //
718
- // Two Mintlify values are accepted so a migrated page doesn't fail the
719
- // build (see MINTLIFY_MODE_ALIASES above): `center` is the same layout
720
- // as our `frame`, and `assistant` (a full-page Mintlify AI chat, which
721
- // writedocs doesn't have) falls back to `default`. Mintlify's own
722
- // `frame` means something else (a canvas that keeps the sidebar) - it's
723
- // left as our `frame`; see docs/dev/docs/mintlify-compat.mdx.
724
- mode: z
725
- .preprocess(
726
- (value) => (typeof value === 'string' && value in MINTLIFY_MODE_ALIASES ? MINTLIFY_MODE_ALIASES[value] : value),
727
- z.enum(['default', 'wide', 'frame', 'custom', 'blank']),
728
- )
729
- .default('default'),
730
- // Per-page meta tag overrides - same shape as writedocs.json's top-level
731
- // `seo` (see seoFieldsSchema in lib/config.ts, the single source of
732
- // truth for this shape). A page only needs to set the specific fields
733
- // it wants to override; mergeSeo() falls back to the site-wide default
734
- // for anything left unset. See BaseLayout.astro for where this and the
735
- // site-wide seo actually get merged and rendered.
736
- seo: seoFieldsSchema.optional(),
737
- // Mintlify's spelling of `seo.noindex` - a top-level `noindex: true`.
738
- // Folded into `seo` by the transform below, so everything downstream
739
- // (the robots meta tag, sitemap.xml, llms.txt) keeps reading
740
- // `seo.noindex` only.
741
- noindex: z.boolean().optional(),
742
- // Mintlify's short navigation label - used for the sidebar and the
743
- // topbar dropdown menus in place of `title` ([...slug].astro's
744
- // navTitleForSlug). The page's own <h1> and prev/next links keep `title`.
745
- sidebarTitle: z.string().optional(),
746
- // Mintlify's spellings of `seo.keywords`, `seo.ogImage`, `seo.ogType`
747
- // and `seo.twitterCard`, folded into `seo` below like `noindex`.
748
- keywords: z.array(z.string()).optional(),
749
- 'og:image': z.string().optional(),
750
- 'og:type': z.string().optional(),
751
- 'twitter:card': z.enum(['summary', 'summary_large_image']).optional(),
752
- // Mintlify's sidebar/page-chrome fields - see NavTree.astro and
753
- // [...slug].astro for where each is used:
754
- // icon - shown before the page's label in the sidebar.
755
- // tag - a short label after it (e.g. "NEW").
756
- // deprecated - a "Deprecated" label in the sidebar and next
757
- // to the page's <h1>.
758
- // hidden - left out of the sidebar, dropdowns and
759
- // prev/next, but still built and reachable by
760
- // URL. Also noindexed, as on Mintlify.
761
- // url - an external link: the page's sidebar entry
762
- // links straight to it, and the page's own URL
763
- // redirects there.
764
- // hideFooterPagination - no prev/next links on this page.
765
- // hideApiMarker - no HTTP method badge on this page's sidebar
766
- // entry.
767
- icon: z.string().optional(),
768
- tag: z.string().optional(),
769
- deprecated: z.boolean().optional(),
770
- hidden: z.boolean().optional(),
771
- url: z.string().optional(),
772
- hideFooterPagination: z.boolean().optional(),
773
- hideApiMarker: z.boolean().optional(),
774
- }).transform(
775
- ({ noindex, keywords, 'og:image': ogImage, 'og:type': ogType, 'twitter:card': twitterCard, ...data }) => {
776
- // Top-level Mintlify keys fill in `seo` only where the page's own `seo`
777
- // doesn't already set that field - an explicit `seo` value always wins.
778
- // A `hidden` page is noindexed unless it says otherwise.
779
- const fromMintlify = { noindex: noindex ?? (data.hidden ? true : undefined), keywords, ogImage, ogType, twitterCard };
780
- const seo = { ...data.seo };
781
- let changed = false;
782
- for (const [key, value] of Object.entries(fromMintlify)) {
783
- if (value === undefined || seo[key as keyof typeof seo] !== undefined) continue;
784
- (seo as Record<string, unknown>)[key] = value;
785
- changed = true;
786
- }
787
- return changed ? { ...data, seo } : data;
788
- },
789
- );
790
-
791
- // Controls for the OpenAPI API playground's "Try it" modal - separate
792
- // from a group's own `openapi: { src, path }` field (which spec to use,
793
- // and where) since this is about how a *request* it sends behaves, not
794
- // about the spec itself.
795
- const apiSchema = z
796
- .object({
797
- // Whether a Try-it request the browser blocks is retried through
798
- // writedocs' own CORS proxy (https://proxy.writechoice.io/). The
799
- // request always goes to the API directly first, so a reader's key
800
- // reaches the proxy only when the API itself refuses browser calls.
801
- // Almost no real-world API sends back Access-Control-Allow-Origin
802
- // headers permitting an arbitrary docs site's origin, so the direct
803
- // call fails for most real APIs - see the send handler and
804
- // PROXY_BASE_URL in ApiReferencePanel.astro. Defaults to enabled; a
805
- // site can set this to `false` to never involve a third party.
806
- proxy: z.boolean().default(true),
807
- })
808
- .strict()
809
- .default({ proxy: true });
810
-
811
- // The "Copy page" menu shown next to a page's title - copy the page's
812
- // Markdown, view it, or open it in an AI assistant - and the .md copy of
813
- // every page it relies on ([...slug].md.ts). On by default, with every
814
- // option, like the MCP server. writedocs.json narrows or turns it off:
815
- //
816
- // (absent) or true every option
817
- // ["copy", "claude"] only these, in the menu's own order
818
- // (copy, view, chatgpt, claude, perplexity,
819
- // mcp, cursor, vscode - the last three connect
820
- // AI tools to the site's MCP server, and are
821
- // left out when `mcp` is false)
822
- // false (or []) no menu, and no .md routes
823
- // { "openIn": [...] } the earlier form: copy and view, plus these
824
- // assistants - still accepted
825
- //
826
- // Read it through contextMenuOptions() below - never test the raw value for
827
- // truthiness: absent now means on.
828
- export const CONTEXT_MENU_OPTIONS = ['copy', 'view', 'chatgpt', 'claude', 'perplexity', 'mcp', 'cursor', 'vscode'] as const;
829
- export type ContextMenuOption = (typeof CONTEXT_MENU_OPTIONS)[number];
830
- const ASSISTANT_OPTIONS = ['chatgpt', 'claude', 'perplexity'] as const;
831
- /** The options that point at the site's MCP server - see `mcp` below. */
832
- export const MCP_MENU_OPTIONS = ['mcp', 'cursor', 'vscode'] as const;
833
-
834
- const contextMenuSchema = z.union([
835
- z.boolean(),
836
- z.array(z.enum(CONTEXT_MENU_OPTIONS)),
837
- z
838
- .object({
839
- openIn: z.array(z.enum(ASSISTANT_OPTIONS)).optional(),
840
- })
841
- .strict(),
842
- ]);
843
-
844
- export type ContextMenuConfig = z.infer<typeof contextMenuSchema>;
845
-
846
- /** The menu options a writedocs.json `contextMenu` value turns on, in menu
847
- * order - [] when the menu is off. Takes the raw value too (link-check.js
848
- * reads writedocs.json without the schema), so absent means every option.
849
- * With `mcp: false` (no MCP server), the MCP options are left out. */
850
- export function contextMenuOptions(value: unknown, { mcp = true }: { mcp?: boolean } = {}): ContextMenuOption[] {
851
- const available = CONTEXT_MENU_OPTIONS.filter((option) => mcp || !(MCP_MENU_OPTIONS as readonly string[]).includes(option));
852
- if (value === false) return [];
853
- if (value === undefined || value === null || value === true) return [...available];
854
- if (Array.isArray(value)) return available.filter((option) => value.includes(option));
855
- if (typeof value === 'object') {
856
- const openIn = (value as { openIn?: unknown }).openIn;
857
- const assistants = Array.isArray(openIn) ? openIn : [...ASSISTANT_OPTIONS];
858
- return CONTEXT_MENU_OPTIONS.filter((option) => option === 'copy' || option === 'view' || assistants.includes(option));
859
- }
860
- return [];
861
- }
862
-
863
- // One entry in writedocs.json's `redirects` array - wired almost directly into
864
- // Astro's own `redirects` config option (astro.config.mjs), which is what
865
- // actually generates the redirect pages. `permanent` is deliberately not
866
- // part of this schema: with no server/adapter (this project always builds
867
- // `output: 'static'` with none installed), Astro's own docs say a static
868
- // redirect "does not support status codes" at all - it's always a client-
869
- // side `<meta http-equiv="refresh">` page, full stop. Accepting a
870
- // `permanent` field here that silently did nothing would be worse than
871
- // not offering it.
872
- const redirectSchema = z
873
- .object({
874
- source: z.string(),
875
- destination: z.string(),
876
- })
877
- .strict();
878
-
879
- export type RedirectConfig = z.infer<typeof redirectSchema>;
880
-
881
- // A site-wide banner rendered above the topbar on every page (except
882
- // `mode: blank`, which drops all site chrome including this - see
883
- // BaseLayout.astro). Optional/undefined by default, same convention as
884
- // `contextMenu` above - a site with no banner configured gets no banner
885
- // markup at all, not an empty one.
886
- const bannerSchema = z
887
- .object({
888
- content: z.string(),
889
- // Persisted via localStorage once dismissed (see BaseLayout.astro's
890
- // initBanner()) - a static site has no server-side session to track
891
- // this against, so "dismissed" only ever means "dismissed in this
892
- // browser". A banner without `dismissible` reappears on every visit,
893
- // appropriate for something that should stay visible until the site
894
- // author removes it from writedocs.json themselves (e.g. "this version is
895
- // deprecated"), not something a reader can permanently clear.
896
- dismissible: z.boolean().default(false),
897
- type: z.enum(['info', 'warning', 'critical']).default('info'),
898
- })
899
- .strict();
900
-
901
- export type BannerConfig = z.infer<typeof bannerSchema>;
902
-
903
- // Content for the custom 404 page (src/pages/404.astro) - Astro's own
904
- // file-based convention (a static build emits this as 404.html at the
905
- // site root; most static hosts pick it up automatically for unmatched
906
- // routes). Both fields are optional with hardcoded fallbacks in 404.astro
907
- // itself, so a site doesn't have to set either to get a reasonably
908
- // branded 404 page (still rendered inside the normal BaseLayout/topbar
909
- // chrome, just with placeholder content).
910
- const notFoundSchema = z
911
- .object({
912
- title: z.string().optional(),
913
- description: z.string().optional(),
914
- })
915
- .strict()
916
- .default({});
917
-
918
- export type NotFoundConfig = z.infer<typeof notFoundSchema>;
919
-
920
- // One <script> tag to inject - exactly one of `src` (an external/local
921
- // file, rendered as `<script src="...">`) or `content` (inline JS,
922
- // rendered via `<script is:inline set:html="...">`) has to be set, not
923
- // both and not neither - enforced by the `.refine()` below rather than
924
- // leaving both optional and silently rendering an empty tag if a site
925
- // author gets this wrong.
926
- const scriptEntrySchema = z
927
- .object({
928
- src: z.string().optional(),
929
- content: z.string().optional(),
930
- })
931
- .strict()
932
- .refine((v) => (v.src ? !v.content : !!v.content), {
933
- message: 'Each scripts.head/scripts.body entry needs exactly one of "src" or "content", not both or neither.',
934
- });
935
-
936
- export type ScriptEntry = z.infer<typeof scriptEntrySchema>;
937
-
938
- // Raw third-party script injection - analytics snippets, chat widgets,
939
- // anything that needs a real <script> tag writedocs.json's own structured
940
- // fields (styles, integrations-style config, ...) don't have a dedicated
941
- // slot for yet. `head` renders right before </head>; `body` renders right
942
- // before </body> (after everything else has already loaded/hydrated -
943
- // see BaseLayout.astro), matching where a third-party script's own
944
- // install instructions usually say to put it.
945
- const scriptsSchema = z
946
- .object({
947
- head: z.array(scriptEntrySchema).default([]),
948
- body: z.array(scriptEntrySchema).default([]),
949
- })
950
- .strict()
951
- .default({ head: [], body: [] });
952
-
953
- export type ScriptsConfig = z.infer<typeof scriptsSchema>;
954
-
955
- // writedocs.json's `integrations` - a curated, high-value subset of analytics
956
- // providers, each getting its own minimal config object (just the id(s)
957
- // it actually needs) rather than requiring a site author to hand-write
958
- // the provider's own install snippet through the generic `scripts` field
959
- // above. This is deliberately its own thing, not built as sugar over
960
- // `scripts` the way the roadmap once implied it might be - most of these
961
- // providers' real snippets need `defer`/`async`/`data-*` attributes
962
- // ScriptEntry's plain `{ src?, content? }` shape has no way to express,
963
- // so BaseLayout.astro renders each provider with its own bespoke markup
964
- // instead of generating a ScriptEntry array to feed through the generic
965
- // renderer. Every snippet shape below was sourced from that provider's
966
- // own current official docs (fetched directly, not recalled from
967
- // training data) while building this feature - see
968
- // docs/dev/docs/integrations.mdx for links and dates.
969
- //
970
- // Every provider field is optional and independent - a site can turn on
971
- // any subset (including all of them at once, for a migration period) or
972
- // none. No "the" analytics field; a site picks whichever provider(s) it
973
- // actually uses.
974
-
975
- const ga4IntegrationSchema = z
976
- .object({
977
- // A GA4 "Measurement ID", always shaped like "G-XXXXXXXXXX" - not
978
- // validated against that shape here, since Google could change the
979
- // prefix/length without this schema needing to track it.
980
- measurementId: z.string(),
981
- })
982
- .strict();
983
-
984
- const googleTagManagerIntegrationSchema = z
985
- .object({
986
- // A GTM container id, shaped like "GTM-XXXXXXX".
987
- containerId: z.string(),
988
- })
989
- .strict();
990
-
991
- const plausibleIntegrationSchema = z
992
- .object({
993
- domain: z.string(),
994
- // Plausible's own hosted script URL by default - override for a
995
- // self-hosted instance, a reverse-proxy path (Plausible's own
996
- // documented way to dodge ad-blockers), or one of Plausible's
997
- // documented script *extensions* (e.g.
998
- // "https://plausible.io/js/script.hash.outbound-links.js").
999
- src: z.string().default('https://plausible.io/js/script.js'),
1000
- })
1001
- .strict();
1002
-
1003
- const fathomIntegrationSchema = z
1004
- .object({
1005
- // Fathom's own short "Site ID", not a full URL or measurement id.
1006
- siteId: z.string(),
1007
- })
1008
- .strict();
1009
-
1010
- const posthogIntegrationSchema = z
1011
- .object({
1012
- // PostHog calls this a "project API key" (starts with "phc_") in its
1013
- // own docs - `apiKey` here rather than that exact name, matching this
1014
- // schema's own plainer naming convention for the equivalent id on
1015
- // every other provider above.
1016
- apiKey: z.string(),
1017
- // PostHog is region-sharded (US/EU) with no single universal default
1018
- // - "https://us.i.posthog.com" is PostHog's own default for a new
1019
- // project, but a site on their EU cloud (or a self-hosted instance)
1020
- // must override this to the host shown in their own project
1021
- // settings, or events silently go nowhere.
1022
- apiHost: z.string().default('https://us.i.posthog.com'),
1023
- })
1024
- .strict();
1025
-
1026
- const umamiIntegrationSchema = z
1027
- .object({
1028
- websiteId: z.string(),
1029
- // Unlike Plausible/PostHog, Umami has no single hosted default that
1030
- // works for most users - it's commonly self-hosted, and even Umami
1031
- // Cloud users get a per-region script URL. Defaults to Umami Cloud's
1032
- // own documented script URL, which only happens to be correct for a
1033
- // Cloud user on that specific region; anyone self-hosting (the more
1034
- // common case for this particular provider) must override it to
1035
- // their own instance's own /script.js path.
1036
- src: z.string().default('https://cloud.umami.is/script.js'),
1037
- })
1038
- .strict();
1039
-
1040
- // AI chat over the site's own docs content, via a third-party provider
1041
- // (DocsBot, currently the only one wired up) rather than a self-hosted
1042
- // RAG pipeline - see the roadmap's own "AI chat over docs content" line
1043
- // in docs/dev/docs/roadmap.mdx, which this fulfills via integration
1044
- // rather than by building the retrieval/generation stack in-house.
1045
- // Deliberately named `askAi` here, not `docsbot` - this is the
1046
- // writedocs.json-facing, provider-neutral name for the feature (matching
1047
- // the "Ask AI" label this kind of button/widget is conventionally
1048
- // given in docs sites generally), independent of which vendor happens
1049
- // to sit behind it today. `id` matches DocsBot's own embed config
1050
- // field name exactly (`DocsBotAI.init({ id: 'teamId/botId' })`) - it's
1051
- // a single opaque "teamId/botId" string DocsBot treats as one value,
1052
- // not two separate ids, so this schema doesn't split it either.
1053
- const askAiIntegrationSchema = z
1054
- .object({
1055
- id: z.string(),
1056
- })
1057
- .strict();
1058
-
1059
- const integrationsSchema = z
1060
- .object({
1061
- ga4: ga4IntegrationSchema.optional(),
1062
- googleTagManager: googleTagManagerIntegrationSchema.optional(),
1063
- plausible: plausibleIntegrationSchema.optional(),
1064
- fathom: fathomIntegrationSchema.optional(),
1065
- posthog: posthogIntegrationSchema.optional(),
1066
- umami: umamiIntegrationSchema.optional(),
1067
- askAi: askAiIntegrationSchema.optional(),
1068
- })
1069
- .strict()
1070
- .default({});
1071
-
1072
- export type IntegrationsConfig = z.infer<typeof integrationsSchema>;
1073
-
1074
- export const docsConfigSchema = z.object({
1075
- name: z.string(),
1076
- description: z.string().optional(),
1077
- styles: stylesSchema,
1078
- navigation: navigationSchema,
1079
- // Platform name -> profile/page URL (e.g. `{ "github": "https://
1080
- // github.com/...", "twitter": "https://twitter.com/..." }`), free-form
1081
- // rather than an enum of known platforms - the key doubles as the icon
1082
- // reference BaseLayout.astro's footer resolves via resolveIcon() below
1083
- // (bare `"github"` -> `lucide:github`; use an explicit
1084
- // `"simple-icons:whatever"` key instead when the bare lucide name isn't
1085
- // right for a given platform). Rendered as a row of icon links in the
1086
- // footer - see hasFooterContent/`.wd-footer-socials` in BaseLayout.astro.
1087
- socials: z.record(z.string(), z.string()).default({}),
1088
- topbar: z
1089
- .object({ links: z.array(topbarLinkSchema).default([]) })
1090
- .default({ links: [] }),
1091
- // Columns of links below the page content - see footerSchema/
1092
- // footerColumnSchema above. Renders alongside `socials` above (as a row
1093
- // of icon links) in the same <footer> - see BaseLayout.astro.
1094
- footer: footerSchema,
1095
- api: apiSchema,
1096
- // The site's own deployed domain, e.g. "docs.example.com" or
1097
- // "https://docs.example.com" (the scheme is optional - resolveSiteUrl()
1098
- // below normalizes either form to a full https:// origin). Powers three
1099
- // things that all need an absolute origin to work: sitemap.xml
1100
- // generation (astro.config.mjs only registers @astrojs/sitemap when this
1101
- // is set - a sitemap of relative URLs isn't meaningful), the canonical
1102
- // <link> and og:url/twitter meta tags (BaseLayout.astro), and resolving
1103
- // a relative `seo.ogImage` into an absolute URL for social crawlers.
1104
- // Left optional and simply skipped (with a log message, not an error) at
1105
- // every one of those call sites when unset - most fixtures/local builds
1106
- // have no real deployed domain yet.
1107
- domain: z.string().optional(),
1108
- // Site-wide meta tag defaults - see seoFieldsSchema above. A page's own
1109
- // frontmatter `seo` (content.config.ts's docsSchema) overrides these
1110
- // field by field via mergeSeo(), rather than needing to repeat every
1111
- // field on every page.
1112
- seo: seoFieldsSchema.default({}),
1113
- // The "Copy page" menu - see contextMenuSchema above. Absent means on,
1114
- // with every option; read it through contextMenuOptions().
1115
- contextMenu: contextMenuSchema.optional(),
1116
- // The site's MCP server - an AI tool connects to `/mcp` and searches and
1117
- // reads the docs. On by default: `writedocs build` writes the page index
1118
- // (mcp-index.json) and a Cloudflare-ready `_worker.js` into dist/ (see
1119
- // src/cli/write-mcp-files.js). `false` leaves all of it out.
1120
- mcp: z.boolean().default(true),
1121
- // See redirectSchema above. Wired directly into Astro's own `redirects`
1122
- // config option in astro.config.mjs.
1123
- redirects: z.array(redirectSchema).default([]),
1124
- // Site-wide `[[key]]` substitution values, applied to page prose text
1125
- // at build time (see the remarkSubstituteVariables plugin wired into
1126
- // astro.config.mjs) - e.g. `{ "productName": "Acme" }` lets every page
1127
- // write `[[productName]]` once instead of hardcoding it everywhere.
1128
- // Double square brackets, not the more familiar `{{key}}` - MDX
1129
- // reserves single curly braces for embedded JS expressions, so
1130
- // `{{productName}}` in an .mdx file parses as a JS object-literal
1131
- // expression (`{productName}`, shorthand syntax) rather than literal
1132
- // text, and throws `ReferenceError: productName is not defined` at
1133
- // render time - see remarkSubstituteVariables' own comment in
1134
- // mdx-substitute-variables.js for the full explanation. Deliberately a
1135
- // flat string map, not typed values - this is text substitution into
1136
- // prose, not a templating language.
1137
- variables: z.record(z.string(), z.string()).default({}),
1138
- // See bannerSchema above. Absent by default (no banner rendered).
1139
- banner: bannerSchema.optional(),
1140
- // See notFoundSchema above.
1141
- notFound: notFoundSchema,
1142
- // See scriptsSchema above.
1143
- scripts: scriptsSchema,
1144
- // See integrationsSchema above.
1145
- integrations: integrationsSchema,
1146
- });
1147
-
1148
- export type DocsConfig = z.infer<typeof docsConfigSchema>;
1149
-
1150
- // ---------------------------------------------------------------------
1151
- // Ponto de entrada unico de validacao
1152
- //
1153
- // Existe pra que o gerador (`writedocs validate` e o `loadDocsConfig` que o
1154
- // build usa) e a plataforma validem pelo MESMO codigo, com as MESMAS palavras -
1155
- // o criterio de aceite do WD-066 e do WD-062. Se cada lado formatasse os erros
1156
- // por conta propria, o cliente veria a plataforma aceitar um writedocs.json que
1157
- // o build depois recusa, que e exatamente a classe de bug que a E11 existe pra
1158
- // impedir.
1159
- //
1160
- // Recebe TEXTO CRU, e faz o JSON.parse por conta propria, por tres motivos:
1161
- // 1. um JSON sintaticamente quebrado passa a ser um resultado de validacao
1162
- // como qualquer outro, em vez de uma excecao solta do runtime;
1163
- // 2. linha/coluna so existem no texto - e o WD-063 precisa reportar linha;
1164
- // 3. do lado da plataforma, importProjectConfig ja tem os bytes crus em maos
1165
- // antes de parsear, entao encaixa sem ginastica nenhuma.
1166
- //
1167
- // IMPORTANTE, e deliberado: as mensagens aqui sao as do Zod, VERBATIM. Melhorar
1168
- // a linguagem delas e o WD-063, que precisa deste comportamento como ponto de
1169
- // partida pra medir a melhora. Nada aqui reescreve, traduz ou embeleza mensagem.
1170
- // ---------------------------------------------------------------------
1171
-
1172
- /** Um problema encontrado na configuracao. `path` e o caminho do campo em
1173
- * notacao de ponto (`navigation.tabs.0.label`), ou `(root)` quando o problema e
1174
- * do documento inteiro - o mesmo texto que a mensagem de erro do build ja
1175
- * imprime hoje. `line`/`column` so vem quando da pra saber (hoje: erro de JSON;
1176
- * no WD-063, tambem para erros de schema). */
1177
- export type ValidationIssue = {
1178
- path: string;
1179
- message: string;
1180
- /** Codigo do Zod (`invalid_type`, `unrecognized_keys`, ...) ou `invalid_json`. */
1181
- code?: string;
1182
- line?: number;
1183
- column?: number;
1184
- /** WD-063: a mesma coisa que `message`, dita para gente. ADICIONAL, nunca
1185
- * substituto - `message` continua sendo o texto do Zod verbatim, que e o que
1186
- * o `writedocs build` imprime e o que o WD-062 grava em `validation_issues`.
1187
- * Quem exibe escolhe qual dos dois mostrar. */
1188
- humanMessage?: string;
1189
- /** O que fazer a respeito, quando da pra dizer algo concreto. */
1190
- suggestion?: string;
1191
- /** Chave ESTAVEL de documentacao (`config.styles`), nunca uma URL: uma URL
1192
- * cravada num pacote npm fica quebrada em toda instalacao ate a proxima
1193
- * release, e o mesmo erro e exibido pela CLI e pelo dashboard, que podem
1194
- * querer destinos diferentes. O mapa chave -> URL mora do lado de quem
1195
- * renderiza. */
1196
- docKey?: string;
1197
- };
1198
-
1199
- /** Sucesso carrega os dados ja validados (com os defaults do schema aplicados);
1200
- * falha carrega os problemas e diz de que tipo ela foi. `parseError` so aparece
1201
- * quando o JSON nao pode nem ser parseado, e existe para o chamador que quiser
1202
- * relancar exatamente o erro original (e o que o loadDocsConfig faz, pra nao
1203
- * mudar uma virgula do que o `writedocs build` ja imprime hoje). */
1204
- export type ValidationResult =
1205
- | { ok: true; data: DocsConfig; issues: ValidationIssue[] }
1206
- | {
1207
- ok: false;
1208
- data: null;
1209
- kind: 'invalid_json' | 'schema';
1210
- issues: ValidationIssue[];
1211
- parseError?: SyntaxError;
1212
- };
1213
-
1214
- /** "at position 22 (line 1 column 23)" -> { line: 1, column: 23 }.
1215
- * O formato da mensagem de erro do JSON.parse e do V8, nao do padrao, entao
1216
- * isto e melhor-esforco: se a mensagem nao trouxer posicao, devolve null e o
1217
- * problema simplesmente fica sem linha. */
1218
- function positionFromJsonError(message: string, rawText: string): { line: number; column: number } | null {
1219
- const comLinha = message.match(/line (\d+) column (\d+)/);
1220
- if (comLinha) return { line: Number(comLinha[1]), column: Number(comLinha[2]) };
1221
- const comPosicao = message.match(/position (\d+)/);
1222
- if (comPosicao) {
1223
- const pos = Math.min(Number(comPosicao[1]), rawText.length);
1224
- const antes = rawText.slice(0, pos);
1225
- const line = antes.split('\n').length;
1226
- return { line, column: pos - antes.lastIndexOf('\n') };
1227
- }
1228
- return null;
1229
- }
1230
-
1231
- /** O corpo da mensagem de erro, uma linha por problema - exatamente o formato
1232
- * que o `writedocs build` imprime desde sempre (` - campo: mensagem`). Fica
1233
- * aqui, e nao em cada chamador, pra que CLI e plataforma nao possam divergir.
1234
- *
1235
- * NAO mudou no WD-063, de proposito: continua imprimindo `message` (o texto do
1236
- * Zod). O que melhorou foi o CONTEUDO dos issues - a uniao desembrulhada faz o
1237
- * `path` apontar pro campo real em vez de parar em `navigation`. Quem quiser a
1238
- * versao com frase humana e linha usa formatValidationIssuesDetailed. */
1239
- export function formatValidationIssues(issues: ValidationIssue[]): string {
1240
- return issues.map((i) => ` - ${i.path}: ${i.message}`).join('\n');
1241
- }
1242
-
1243
- /** A versao longa, para quem tem uma tela inteira (a CLI hoje, o dashboard do
1244
- * WD-065 se quiser): caminho, linha, frase humana, sugestao, e a mensagem do
1245
- * Zod por ultimo, entre parenteses, pra quem precisa do texto exato.
1246
- *
1247
- * Mora aqui pelo mesmo motivo que a irma curta: se cada consumidor montasse a
1248
- * sua, a CLI e a plataforma divergiriam na primeira mudanca - que e exatamente
1249
- * o que o AC do WD-066 proibe. `fileName` so entra na referencia de linha. */
1250
- export function formatValidationIssuesDetailed(
1251
- issues: ValidationIssue[],
1252
- { fileName = 'writedocs.json' }: { fileName?: string } = {}
1253
- ): string {
1254
- return issues
1255
- .map((i) => {
1256
- const temCampo = i.path !== '(root)';
1257
- const local = i.line ? `${fileName}:${i.line}` : i.path;
1258
- const linhas = [` ${local}${i.line && temCampo ? ` (${i.path})` : ''}`];
1259
- linhas.push(` ${i.humanMessage ?? i.message}`);
1260
- if (i.suggestion) linhas.push(` ${i.suggestion}`);
1261
- if (i.humanMessage && i.message !== i.humanMessage) linhas.push(` (${i.message})`);
1262
- return linhas.join('\n');
1263
- })
1264
- .join('\n\n');
1265
- }
1266
-
1267
- // ---------------------------------------------------------------------
1268
- // WD-063 — do issue do Zod para "onde esta o erro, e o que fazer"
1269
- //
1270
- // Tres transformacoes, nesta ordem:
1271
- // 1. desembrulhar `invalid_union` (senao todo erro dentro da navigation vira
1272
- // `navigation: "Invalid input"`, que e inutil num arquivo de 10 KB);
1273
- // 2. achar a linha no texto, pelo caminho ja desembrulhado;
1274
- // 3. escrever a frase humana, a sugestao e a docKey - POR CODIGO do Zod, nao
1275
- // por campo: um mapa por campo teria 17 entradas so na raiz e centenas no
1276
- // total, e envelheceria a cada campo novo do schema.
1277
- // ---------------------------------------------------------------------
1278
-
1279
- /** Chaves que a raiz aceita sem ser campo do schema, e que por isso NAO devem
1280
- * gerar aviso de chave desconhecida. Deliberadamente minuscula: a raiz nao e
1281
- * `.strict()` justamente pra nao quebrar configs existentes, e `$schema` foi um
1282
- * dos argumentos dessa decisao - avisar sobre ele contradiria o que o protegeu.
1283
- * Se esta lista passar de dois ou tres nomes, o problema e outro e a raiz
1284
- * precisa de outra conversa. */
1285
- export const ROOT_ALLOWED_EXTRA_KEYS: readonly string[] = Object.freeze(['$schema']);
1286
-
1287
- type IssueCru = {
1288
- code?: string;
1289
- path?: (string | number)[];
1290
- message: string;
1291
- expected?: string;
1292
- values?: unknown[];
1293
- keys?: string[];
1294
- minimum?: number;
1295
- maximum?: number;
1296
- origin?: string;
1297
- format?: string;
1298
- errors?: unknown[];
1299
- unionErrors?: unknown[];
1300
- };
1301
-
1302
- type IssuePlano = IssueCru & { caminho: (string | number)[] };
1303
-
1304
- function issuesDoRamo(ramo: unknown): IssueCru[] {
1305
- if (Array.isArray(ramo)) return ramo as IssueCru[];
1306
- const comIssues = ramo as { issues?: IssueCru[] };
1307
- return comIssues?.issues ?? [];
1308
- }
1309
-
1310
- /** O maior valor de `f` sobre a lista, ou 0 se ela for vazia. Um `for` e nao
1311
- * `Math.max(0, ...lista.map(f))`: o spread vira argumentos de chamada, e uma
1312
- * lista grande o bastante (config com dezenas de milhares de erros) estoura o
1313
- * limite de argumentos com RangeError em vez de devolver um numero. */
1314
- function maiorProfundidade(lista: IssuePlano[]): number {
1315
- let maior = 0;
1316
- for (const issue of lista) {
1317
- const p = issue.caminho.length + (issue.code === 'unrecognized_keys' ? 1 : 0);
1318
- if (p > maior) maior = p;
1319
- }
1320
- return maior;
1321
- }
1322
-
1323
- /** Plano ACHATADO de um ramo, memoizado por identidade do ramo.
1324
- *
1325
- * A memoizacao nao e otimizacao, e o que torna o achatamento viavel. Pontuar um
1326
- * ramo exige desembrulhar as unioes DENTRO dele, e cada uma dessas tem os seus
1327
- * proprios ramos - sem cache, a pontuacao visita o mesmo sub-ramo uma vez por
1328
- * caminho que leva ate ele, o que e exponencial na profundidade do aninhamento.
1329
- * Medido com grupos aninhados e um erro no fundo: 3,7 ms com 4 niveis, 281 ms
1330
- * com 8, 69 SEGUNDOS com 12. Com o cache, os mesmos casos ficam em 0,2 ms,
1331
- * porque cada no da arvore de erro do Zod e achatado uma vez so.
1332
- *
1333
- * Se alguem remover este WeakMap por parecer supérfluo, o `writedocs validate`
1334
- * passa a travar em configs profundas. Nao remova. */
1335
- const planoPorRamo = new WeakMap<object, IssuePlano[]>();
1336
-
1337
- function planoDoRamo(ramo: unknown): IssuePlano[] {
1338
- const lista = issuesDoRamo(ramo);
1339
- if (typeof ramo !== 'object' || ramo === null) return desembrulharUnioes(lista);
1340
- const memoizado = planoPorRamo.get(ramo);
1341
- if (memoizado) return memoizado;
1342
- // Prefixo vazio de proposito: a pontuacao compara ramos entre si, entao a
1343
- // profundidade tem que ser relativa ao proprio ramo, nao ao documento.
1344
- const plano = desembrulharUnioes(lista);
1345
- planoPorRamo.set(ramo, plano);
1346
- return plano;
1347
- }
1348
-
1349
- /** Escolhe qual ramo de uma uniao o cliente PROVAVELMENTE quis.
1350
- *
1351
- * Criterio: caminho mais fundo primeiro; empate resolvido por menos issues. A
1352
- * intuicao e a do Gabriel na spec - o ramo certo e o que nao reclama da chave
1353
- * que o cliente usou -, e a profundidade importa porque um ramo que chegou
1354
- * fundo antes de falhar (`products.0.product`) reconheceu a forma, enquanto um
1355
- * que falha na raiz (`expected array, received object`) so recusou o shape.
1356
- *
1357
- * DUAS CORRECOES sobre a primeira versao (WD-063), as duas medidas contra o
1358
- * `00-kitchen-sink` real - ver o relato de revisao 43:
1359
- *
1360
- * 1. PONTUA O RAMO ACHATADO, nao a lista crua. Um ramo que e ele proprio uma
1361
- * uniao aparece como UM issue (`invalid_union`) no caminho vazio - ou seja,
1362
- * com a MENOR contagem e a MENOR profundidade possiveis, sem que isso diga
1363
- * nada sobre o quanto ele reconheceu. Era o caso mais comum que existe: um
1364
- * item de `pages` e `string | grupo | link`, e o grupo e outra uniao, entao
1365
- * todo erro estrutural dentro de um grupo empatava com o ramo `string` e
1366
- * perdia pela ordem de declaracao. O cliente que escrevia
1367
- * `{ "group": "G", "pages": 42 }` recebia "expected string, received
1368
- * object" - conselho errado, nao so inutil. Achatando primeiro, o mesmo caso
1369
- * vira `pages.0.pages: expected array, received number`.
1370
- *
1371
- * 2. PROFUNDIDADE EFETIVA: `unrecognized_keys` reporta no caminho do PAI, com a
1372
- * chave ofensora em `keys`, entao a profundidade dele sai subestimada em 1.
1373
- * Sem a correcao, um ramo que identificou a chave errada perde para um que
1374
- * so exigiu um campo ausente. (`validateDocsConfig` ja fazia a mesma conta
1375
- * para achar a LINHA; aqui ela entra tambem na pontuacao.)
1376
- *
1377
- * Medido sobre as 60 folhas da `navigation` do `00-kitchen-sink`, trocando o
1378
- * tipo de cada uma: a versao anterior apontava o campo exato em 42/60 e PARAVA
1379
- * RASO em 18/60 (sempre os mesmos 18: os que ficam sob um `pages`); esta aponta
1380
- * 60/60 para valor escalar errado e nunca para raso. Para um objeto vazio ou
1381
- * parcial no lugar de uma pagina, as duas ficam tecnicamente empatadas (41
1382
- * contra 42): a anterior diz "expected string", esta lista os campos que
1383
- * faltam para ser um grupo. E o custo aceito desta versao, e substitui o antigo
1384
- * (`tabs` e `products` escritos juntos, que agora sai como
1385
- * `Unrecognized key: "products"`).
1386
- *
1387
- * EMPATE TOTAL (mesma profundidade E mesmo numero de issues): vence o ramo
1388
- * declarado primeiro no schema. `Array.prototype.sort` e estavel desde a
1389
- * ES2019, entao ordenar e pegar o [0] ja entrega isso - se alguem trocar por
1390
- * uma ordenacao instavel, o desempate vira sorteio. Duas razoes para "o
1391
- * primeiro" em vez de "todos os empatados":
1392
- * - um engano do cliente tem que virar UMA mensagem. Emitir os 5 ramos
1393
- * empatados de um `"navigation": {}` produz cinco exigencias que se
1394
- * contradizem ("tabs e obrigatorio", "versions e obrigatorio", ...);
1395
- * - determinismo: a mesma config sempre da a mesma mensagem. Um palpite
1396
- * instavel seria pior que um palpite ruim.
1397
- * E nada se perde no palpite errado: `message` continua sendo o texto do Zod. */
1398
- function melhorRamo(ramos: unknown[]): IssueCru[] {
1399
- return ramos
1400
- .map((ramo) => {
1401
- const plano = planoDoRamo(ramo);
1402
- return {
1403
- lista: issuesDoRamo(ramo),
1404
- n: plano.length,
1405
- profundidade: maiorProfundidade(plano),
1406
- };
1407
- })
1408
- .sort((a, b) => b.profundidade - a.profundidade || a.n - b.n)[0].lista;
1409
- }
1410
-
1411
- /** Desembrulha `invalid_union` recursivamente - o ramo escolhido normalmente e
1412
- * outra uniao (cada produto da navigation e, por sua vez, uma uniao de formas),
1413
- * entao para so quando chega num erro concreto. Sem recursao, o
1414
- * `navigation.products.0` para em "Invalid input" de novo, um nivel abaixo. */
1415
- function desembrulharUnioes(issues: IssueCru[], prefixo: (string | number)[] = []): IssuePlano[] {
1416
- const saida: IssuePlano[] = [];
1417
- for (const issue of issues) {
1418
- const caminho = [...prefixo, ...(issue.path ?? [])];
1419
- const ramos = issue.code === 'invalid_union' ? issue.errors ?? issue.unionErrors : null;
1420
- if (Array.isArray(ramos) && ramos.length > 0) {
1421
- saida.push(...desembrulharUnioes(melhorRamo(ramos), caminho));
1422
- } else {
1423
- saida.push({ ...issue, caminho });
1424
- }
1425
- }
1426
- return saida;
1427
- }
1428
-
1429
- const LISTAS_DE_CONTAINER = ['tabs', 'versions', 'languages', 'dropdowns', 'products'] as const;
1430
- const ITENS_DE_CONTAINER: Record<string, { lista: string; nome: string }> = {
1431
- tab: { lista: 'tabs', nome: 'A tab' },
1432
- version: { lista: 'versions', nome: 'A version' },
1433
- language: { lista: 'languages', nome: 'A language' },
1434
- dropdown: { lista: 'dropdowns', nome: 'A dropdown' },
1435
- product: { lista: 'products', nome: 'A product' },
1436
- };
1437
-
1438
- /** Um container (`{ "tabs": [...] }`, ou um item como `{ "tab": "API", ... }`)
1439
- * dentro de uma lista de paginas - o `pages` de um grupo, de uma tab etc., ou
1440
- * a `navigation` em forma de lista. O Zod tenta os tres formatos de item
1441
- * (pagina, grupo, link) e reclama de cada um: "group is required", "pages is
1442
- * required", "tabs is not an option" - tres erros, nenhum dizendo o que houve.
1443
- * Aqui eles viram UM, no item, dizendo onde o container pode ficar. */
1444
- function containersEmPaginas(issues: IssuePlano[], raiz: unknown): IssuePlano[] {
1445
- const vistos = new Set<string>();
1446
- const saida: IssuePlano[] = [];
1447
- for (const issue of issues) {
1448
- const achado = containerEmPaginas(issue.caminho, raiz);
1449
- if (!achado) {
1450
- saida.push(issue);
1451
- continue;
1452
- }
1453
- const chave = achado.caminho.join('.');
1454
- if (vistos.has(chave)) continue;
1455
- vistos.add(chave);
1456
- saida.push({ ...issue, code: 'custom', caminho: achado.caminho, message: achado.mensagem, keys: undefined });
1457
- }
1458
- return saida;
1459
- }
1460
-
1461
- function containerEmPaginas(caminho: (string | number)[], raiz: unknown): { caminho: (string | number)[]; mensagem: string } | null {
1462
- for (let k = 1; k < caminho.length; k++) {
1463
- if (typeof caminho[k] !== 'number') continue;
1464
- const naRaiz = k === 1 && caminho[0] === 'navigation';
1465
- if (!naRaiz && caminho[k - 1] !== 'pages') continue;
1466
- const item = valorEm(raiz, caminho.slice(0, k + 1));
1467
- if (!item || typeof item !== 'object' || Array.isArray(item) || 'group' in item) continue;
1468
- const lugar = naRaiz ? 'the navigation list' : 'a "pages" list';
1469
- const rotulo = (texto: string) => (naRaiz ? 'The navigation list' : 'A "pages" list') + ` holds pages, groups and links only. ${texto}`;
1470
- const lista = LISTAS_DE_CONTAINER.find((l) => l in item);
1471
- if (lista) {
1472
- return {
1473
- caminho: caminho.slice(0, k + 1),
1474
- mensagem: `"${lista}" can't go inside ${lugar}. ` + rotulo(
1475
- naRaiz
1476
- ? `To use ${lista}, make "navigation" an object: "navigation": { "${lista}": [ ... ] }, with the groups inside each of them.`
1477
- : `Put "${lista}" on "navigation" itself, or on a tab, version, language, dropdown or product in place of its "pages".`
1478
- ),
1479
- };
1480
- }
1481
- const tipo = Object.keys(ITENS_DE_CONTAINER).find((t) => t in item);
1482
- if (tipo) {
1483
- const { lista: dela, nome } = ITENS_DE_CONTAINER[tipo];
1484
- const nomeDoItem = (item as Record<string, unknown>)[tipo];
1485
- return {
1486
- caminho: caminho.slice(0, k + 1),
1487
- mensagem: `${nome}${typeof nomeDoItem === 'string' ? ` ("${nomeDoItem}")` : ''} can't go inside ${lugar}. ` + rotulo(
1488
- naRaiz ? `${nome} goes in a "${dela}" list: "navigation": { "${dela}": [ ... ] }.` : `${nome} goes in a "${dela}" list.`
1489
- ),
1490
- };
1491
- }
1492
- }
1493
- return null;
1494
- }
1495
-
1496
- /** Exported for `writedocs validate`'s content pass (lib/content-check.js),
1497
- * which reports writedocs.json problems of its own - navigation entries
1498
- * with no page, unknown icons - with the same line numbers as the schema
1499
- * errors. Same function as criarLocalizador below. */
1500
- export function createJsonLocator(rawText: string): (path: (string | number)[]) => { line: number; column: number } | null {
1501
- return criarLocalizador(rawText);
1502
- }
1503
-
1504
- /** Parseia o texto UMA vez e devolve "caminho -> linha/coluna". Devolve null
1505
- * quando o no nao existe no texto (campo obrigatorio ausente e o caso comum):
1506
- * `line` ausente e melhor que `line` inventada. */
1507
- function criarLocalizador(rawText: string): (caminho: (string | number)[]) => { line: number; column: number } | null {
1508
- rawText = semBom(rawText);
1509
- let arvore: ReturnType<typeof parseTree> | undefined;
1510
- try {
1511
- arvore = parseTree(rawText);
1512
- } catch {
1513
- arvore = undefined;
1514
- }
1515
- return (caminho) => {
1516
- if (!arvore || caminho.length === 0) return null;
1517
- const no = findNodeAtLocation(arvore, caminho);
1518
- if (!no) return null;
1519
- const antes = rawText.slice(0, no.offset);
1520
- return { line: antes.split('\n').length, column: no.offset - antes.lastIndexOf('\n') };
1521
- };
1522
- }
1523
-
1524
- /** `styles.primaryColor` -> `config.styles`. Primeiro segmento so, com fallback
1525
- * pra `config`: o conjunto tem que ficar pequeno e estavel, porque vira
1526
- * superficie publica no instante em que alguem mapear chave -> URL. */
1527
- function docKeyDoCaminho(caminho: (string | number)[]): string {
1528
- const primeiro = caminho[0];
1529
- return typeof primeiro === 'string' && primeiro ? `config.${primeiro}` : 'config';
1530
- }
1531
-
1532
- const ARTIGO_POR_TIPO: Record<string, string> = {
1533
- string: 'a piece of text',
1534
- number: 'a number',
1535
- boolean: 'true or false',
1536
- array: 'a list',
1537
- object: 'an object',
1538
- null: 'null',
1539
- };
1540
-
1541
- const COMO_ESCREVER: Record<string, string> = {
1542
- string: 'Write the value in double quotes, like "Core Platform".',
1543
- number: 'Write the value as a bare number, like 3 - no quotes.',
1544
- boolean: 'Write true or false - no quotes.',
1545
- array: 'Write the value as a list in square brackets: [ ... ].',
1546
- object: 'Write the value as an object in curly braces: { ... }.',
1547
- };
1548
-
1549
- /** O tipo que o cliente REALMENTE escreveu, lido do JSON ja parseado em vez de
1550
- * extraido da mensagem do Zod por regex - o Zod v4 nao carrega `received` como
1551
- * propriedade, so dentro do texto, e depender do texto quebra na primeira vez
1552
- * que ele mudar de forma. */
1553
- function tipoReal(valor: unknown): string {
1554
- if (valor === undefined) return 'missing';
1555
- if (valor === null) return 'null';
1556
- if (Array.isArray(valor)) return 'array';
1557
- return typeof valor;
1558
- }
1559
-
1560
- function valorEm(raiz: unknown, caminho: (string | number)[]): unknown {
1561
- let atual: unknown = raiz;
1562
- for (const passo of caminho) {
1563
- if (atual === null || typeof atual !== 'object') return undefined;
1564
- atual = (atual as Record<string | number, unknown>)[passo];
1565
- }
1566
- return atual;
1567
- }
1568
-
1569
- function comoCampo(caminho: (string | number)[]): string {
1570
- return caminho.length > 0 ? `"${caminho.join('.')}"` : 'writedocs.json';
1571
- }
1572
-
1573
- /** A frase de chave desconhecida, num lugar so.
1574
- *
1575
- * Decisao 6: chave desconhecida em sub-objeto strict e ERRO e na raiz e AVISO -
1576
- * a assimetria de SEVERIDADE e intencional e fica. A de VOCABULARIO nao: os
1577
- * dois caminhos chamam esta funcao, entao os dois dizem exatamente a mesma
1578
- * coisa, e so quem chama decide o peso. */
1579
- function fraseChaveDesconhecida(chaves: string[], dentroDe: (string | number)[]) {
1580
- const onde = dentroDe.length > 0 ? ` inside "${dentroDe.join('.')}"` : '';
1581
- const lista = chaves.map((k) => `"${k}"`).join(', ');
1582
- return {
1583
- humanMessage:
1584
- chaves.length === 1
1585
- ? `${lista} is not a writedocs.json option${onde}.`
1586
- : `${lista} are not writedocs.json options${onde}.`,
1587
- suggestion: 'Remove it, or check the spelling - options are case-sensitive.',
1588
- };
1589
- }
1590
-
1591
- /** A frase humana + a sugestao, escolhidas pelo CODIGO do Zod. `raiz` e o JSON
1592
- * ja parseado, usado so pra saber o que o cliente escreveu de fato. */
1593
- function humanizar(issue: IssuePlano, raiz: unknown): { humanMessage?: string; suggestion?: string } {
1594
- const campo = comoCampo(issue.caminho);
1595
- switch (issue.code) {
1596
- case 'invalid_type': {
1597
- const esperado = issue.expected ?? 'a different type';
1598
- const recebido = tipoReal(valorEm(raiz, issue.caminho));
1599
- if (recebido === 'missing') {
1600
- return {
1601
- humanMessage: `${campo} is required, but writedocs.json does not set it.`,
1602
- suggestion: `Add ${campo} with ${ARTIGO_POR_TIPO[esperado] ?? `a ${esperado}`} as its value.`,
1603
- };
1604
- }
1605
- return {
1606
- humanMessage: `${campo} must be ${ARTIGO_POR_TIPO[esperado] ?? `a ${esperado}`}, but writedocs.json has ${ARTIGO_POR_TIPO[recebido] ?? `a ${recebido}`}.`,
1607
- suggestion: COMO_ESCREVER[esperado],
1608
- };
1609
- }
1610
- case 'unrecognized_keys': {
1611
- // O Zod agrega as chaves sobrando numa mensagem so, com o `path` no PAI.
1612
- const chaves = issue.keys ?? [];
1613
- if (chaves.length === 0) return {};
1614
- return fraseChaveDesconhecida(chaves, issue.caminho);
1615
- }
1616
- case 'invalid_value': {
1617
- const opcoes = (issue.values ?? []).map((v) => JSON.stringify(v)).join(', ');
1618
- return {
1619
- humanMessage: `${campo} must be one of: ${opcoes}.`,
1620
- suggestion: 'Replace the value with one of the options above.',
1621
- };
1622
- }
1623
- case 'too_small': {
1624
- const unidade = issue.origin === 'array' ? 'item' : 'character';
1625
- const minimo = issue.minimum ?? 1;
1626
- return {
1627
- humanMessage: `${campo} needs at least ${minimo} ${unidade}${minimo === 1 ? '' : 's'}.`,
1628
- suggestion: issue.origin === 'array' ? 'Add an entry, or remove the field entirely.' : undefined,
1629
- };
1630
- }
1631
- case 'too_big': {
1632
- const unidade = issue.origin === 'array' ? 'item' : 'character';
1633
- const maximo = issue.maximum ?? 0;
1634
- return { humanMessage: `${campo} allows at most ${maximo} ${unidade}${maximo === 1 ? '' : 's'}.` };
1635
- }
1636
- case 'invalid_format':
1637
- return {
1638
- humanMessage: `${campo} is not a valid ${issue.format ?? 'value'}.`,
1639
- suggestion: 'Check the format against the documentation for this field.',
1640
- };
1641
- case 'invalid_union':
1642
- // So chega aqui se o desembrulho nao achou ramo nenhum (uniao sem
1643
- // `errors`). Raro, mas melhor dizer o que aconteceu do que "Invalid input".
1644
- return {
1645
- humanMessage: `${campo} does not match any of the shapes writedocs.json accepts here.`,
1646
- suggestion: 'Check the documentation for the shapes this field accepts.',
1647
- };
1648
- case 'custom':
1649
- // As mensagens de `.refine()` deste schema ja sao frases escritas pra
1650
- // gente ("Each scripts.head/scripts.body entry needs exactly one of..."),
1651
- // entao reescrever seria piorar. Repassa como frase humana pra que quem
1652
- // exibe so `humanMessage` nao fique sem nada.
1653
- return { humanMessage: issue.message };
1654
- default:
1655
- return {};
1656
- }
1657
- }
1658
-
1659
- /** Avisos de chave desconhecida na RAIZ.
1660
- *
1661
- * A raiz nao e `.strict()` (decidido no E11-desenho-geral: tornar strict
1662
- * quebraria configs existentes), entao o Zod descarta a chave em silencio e
1663
- * nao ha issue nenhum. Quem quiser avisar chama isto. Mora aqui, e nao na
1664
- * plataforma, pelo motivo de sempre: era o unico texto escrito pela plataforma,
1665
- * e enquanto ele viver la os dois lados podem divergir.
1666
- *
1667
- * Severidade e de quem chama - isto so descreve o problema. `validateDocsConfig`
1668
- * deliberadamente NAO chama: um config valido continua saindo com `issues: []`,
1669
- * porque a plataforma repassa `issues` como `errors` e um aviso ali viraria
1670
- * erro. */
1671
- export function unknownRootKeyIssues(rawText: string): ValidationIssue[] {
1672
- rawText = semBom(rawText);
1673
- let raiz: unknown;
1674
- try {
1675
- raiz = JSON.parse(rawText);
1676
- } catch {
1677
- return [];
1678
- }
1679
- if (raiz === null || typeof raiz !== 'object' || Array.isArray(raiz)) return [];
1680
- const conhecidas = new Set([...Object.keys(docsConfigSchema.shape), ...ROOT_ALLOWED_EXTRA_KEYS]);
1681
- const localizar = criarLocalizador(rawText);
1682
- return Object.keys(raiz as Record<string, unknown>)
1683
- .filter((chave) => !conhecidas.has(chave))
1684
- .map((chave) => {
1685
- const frase = fraseChaveDesconhecida([chave], []);
1686
- return {
1687
- path: chave,
1688
- // O mesmo formato singular da mensagem `unrecognized_keys` do Zod, pra
1689
- // que aviso e erro sejam indistinguiveis por quem so le `message`.
1690
- message: `Unrecognized key: "${chave}"`,
1691
- code: 'unrecognized_keys',
1692
- ...(localizar([chave]) ?? {}),
1693
- ...frase,
1694
- // `config`, e NAO `config.<chave>`: a chave aqui e o que o cliente
1695
- // digitou errado, e derivar a docKey dela faria cada erro de digitacao
1696
- // inventar uma chave nova. O conjunto de docKeys tem que ser fechado -
1697
- // `config` mais um por campo do schema, nada alem disso -, senao quem
1698
- // mapeia chave -> URL do outro lado nao tem lista pra mapear.
1699
- docKey: 'config',
1700
- };
1701
- });
1702
- }
1703
-
1704
- /** Texto sem o BOM do UTF-8 no inicio. Editores do Windows (Bloco de Notas, o
1705
- * `Out-File` do PowerShell 5.1) gravam um, e o JSON.parse o rejeita com uma
1706
- * mensagem que culpa virgulas e colchetes. Copia local, e nao import de
1707
- * lib/config-file.js: este modulo so importa zod e jsonc-parser (ver o topo). */
1708
- function semBom(texto: string): string {
1709
- return texto.charCodeAt(0) === 0xfeff ? texto.slice(1) : texto;
1710
- }
1711
-
1712
- export function validateDocsConfig(rawText: string): ValidationResult {
1713
- rawText = semBom(rawText);
1714
- let raw: unknown;
1715
- try {
1716
- raw = JSON.parse(rawText);
1717
- } catch (err) {
1718
- const parseError = err as SyntaxError;
1719
- const posicao = positionFromJsonError(parseError.message, rawText);
1720
- return {
1721
- ok: false,
1722
- data: null,
1723
- kind: 'invalid_json',
1724
- parseError,
1725
- issues: [
1726
- {
1727
- path: '(root)',
1728
- message: parseError.message,
1729
- code: 'invalid_json',
1730
- ...(posicao ?? {}),
1731
- humanMessage: 'writedocs.json is not valid JSON, so none of it could be checked.',
1732
- suggestion: posicao
1733
- ? `Look at line ${posicao.line} - a missing comma, an extra trailing comma, or an unclosed bracket is the usual cause.`
1734
- : 'A missing comma, an extra trailing comma, or an unclosed bracket is the usual cause.',
1735
- docKey: 'config',
1736
- },
1737
- ],
1738
- };
1739
- }
1740
-
1741
- const result = docsConfigSchema.safeParse(raw);
1742
- if (!result.success) {
1743
- const localizar = criarLocalizador(rawText);
1744
- return {
1745
- ok: false,
1746
- data: null,
1747
- kind: 'schema',
1748
- issues: containersEmPaginas(desembrulharUnioes(result.error.issues as IssueCru[]), raw).map((i) => {
1749
- // Para chave desconhecida o `path` do Zod aponta pro PAI (`footer`), e a
1750
- // chave ofensora vem em `keys`. Para a LINHA vale a pena descer ate ela
1751
- // (`footer.banana`), que e onde o cliente precisa olhar; o `path` fica
1752
- // como o Zod deu, pra nao mudar o que a plataforma ja grava.
1753
- const alvoDaLinha =
1754
- i.code === 'unrecognized_keys' && i.keys?.length ? [...i.caminho, i.keys[0]] : i.caminho;
1755
- return {
1756
- path: i.caminho.join('.') || '(root)',
1757
- message: i.message,
1758
- code: i.code,
1759
- ...(localizar(alvoDaLinha) ?? localizar(i.caminho) ?? {}),
1760
- ...humanizar(i, raw),
1761
- docKey: docKeyDoCaminho(i.caminho),
1762
- };
1763
- }),
1764
- };
1765
- }
1766
-
1767
- return { ok: true, data: result.data, issues: [] };
1768
- }
1
+ // O schema do writedocs.json, e nada alem disso.
2
+ //
3
+ // Este arquivo era as primeiras 875 linhas do config.ts (que continua
4
+ // reexportando tudo daqui, entao nada que importa de './config.js' mudou). A
5
+ // separacao existe por um motivo concreto: o config.ts importa node:fs,
6
+ // node:path e gray-matter no topo pras funcoes que leem o disco, e o
7
+ // package.json passou a exportar './config-schema' pra que a plataforma
8
+ // (writedocs-application) possa importar o schema DE VERDADE - o mesmo que o
9
+ // build usa - em vez de manter uma copia que diverge em algumas semanas. Um
10
+ // Worker da Cloudflare nao consegue importar um modulo que traz node:fs junto.
11
+ //
12
+ // Por isso a unica dependencia aqui e o zod. Nada neste arquivo pode passar a
13
+ // tocar o sistema de arquivos: se precisar de fs/path, o lugar e o config.ts.
14
+ //
15
+ // ESTE arquivo e a fonte de verdade, mas NAO e o que o pacote publica: o script
16
+ // `prepare` (package.json) transpila ele pra ./config-schema.js, e e o `.js` que
17
+ // o `exports` e o bin/writedocs.js apontam. Sem isso o `writedocs validate`
18
+ // quebra pra quem instala o pacote - o Node recusa type stripping sob
19
+ // node_modules. Editou aqui, rode `npm run build:schema` (ou qualquer
20
+ // `npm install`) antes de testar o caminho da CLI ou da plataforma.
21
+ //
22
+ // (`zod` e nao `astro/zod`: as duas especificacoes resolvem pra mesma instalacao
23
+ // - node_modules/zod 4.4.3, que e o que astro@7.2.2 tambem pede via `^4.3.6` -
24
+ // entao a troca nao muda comportamento nenhum, so tira o astro do caminho de
25
+ // quem importa isto de fora do gerador.)
26
+ import { z } from 'zod';
27
+ // WD-063: `parseTree` + `findNodeAtLocation` traduzem o caminho de um erro
28
+ // (`navigation.products.0.product`) para o offset dele no TEXTO, que e o que
29
+ // vira linha. E o parser de JSON do VS Code: zero dependencias, nada de `node:`,
30
+ // entao continua bundlavel pro Worker da plataforma. Escrever o scanner a mao
31
+ // foi tentado e deu errado (perdia todo caminho aninhado, que e justamente o que
32
+ // importa aqui) - nao repita.
33
+ import { findNodeAtLocation, parseTree } from 'jsonc-parser';
34
+
35
+ // ---------------------------------------------------------------------
36
+ // Pages & groups - the leaf content any container ultimately bottoms out
37
+ // at. A group can nest other groups arbitrarily deep, and can optionally
38
+ // link its own label to a page (`page`) independent of expanding or
39
+ // collapsing its children - see NavTree.astro for how that renders.
40
+ // ---------------------------------------------------------------------
41
+
42
+ const navPageSchema = z.string();
43
+
44
+ // A group ordinarily lists its own children by hand (`pages`), but can
45
+ // instead auto-generate them from an OpenAPI spec via `openapi: { src,
46
+ // path }` - resolved by loadDocsConfig() (via expandOpenApiInNavigation()
47
+ // below, reading the manifest generate-api-pages.js writes for this exact
48
+ // group) into a real `{ group, pages }` node - one sub-group per tag -
49
+ // before anything else in this file ever sees it, so
50
+ // resolveSections()/flattenNav()/buildNavTree()/etc. only ever need to
51
+ // understand the ordinary pages-array shape. `.strict()` on both variants
52
+ // is load-bearing (see withChildren()'s own comment on this pattern
53
+ // below): without it, a group written with both `pages` and `openapi` at
54
+ // once would silently have one dropped instead of rejected.
55
+ const navGroupPagesSchema: z.ZodType<{ group: string; page?: string; pages: NavItem[] }> = z.lazy(() =>
56
+ z
57
+ .object({
58
+ group: z.string(),
59
+ page: z.string().optional(),
60
+ pages: z.array(navItemSchema),
61
+ })
62
+ .strict()
63
+ );
64
+
65
+ const navGroupOpenApiSchema = z.object({
66
+ group: z.string(),
67
+ openapi: z
68
+ .object({
69
+ // Path to an OpenAPI 3.x spec, relative to the content directory
70
+ // (alongside writedocs.json) - same convention the old top-level
71
+ // `openapi` field used. See generate-api-pages.js (the pre-Astro
72
+ // build/dev step that actually parses this and writes the
73
+ // manifest/operation JSON this group's pages are expanded from).
74
+ src: z.string(),
75
+ // Base URL path every page generated from this spec is namespaced
76
+ // under, e.g. "/api" -> pages served at /api/<tag>/<operation>/.
77
+ // Also doubles as this spec's own unique key under
78
+ // writedocsTempDir()'s openapi/<path>/ directory (manifest.json + operations/*.json),
79
+ // so two openapi groups in the same writedocs.json must use different
80
+ // `path` values - generate-api-pages.js throws a clear error if
81
+ // they collide.
82
+ path: z.string(),
83
+ })
84
+ .strict(),
85
+ }).strict();
86
+
87
+ export type GroupNavItem =
88
+ | { group: string; page?: string; pages: NavItem[] }
89
+ | { group: string; openapi: { src: string; path: string } };
90
+
91
+ const navGroupSchema: z.ZodType<GroupNavItem> = z.union([navGroupPagesSchema, navGroupOpenApiSchema]);
92
+
93
+ // A bare external link sitting directly in a `pages` array, alongside
94
+ // page slugs and groups - e.g. a "Support" link to an external help
95
+ // desk shown right in the sidebar, rather than only reachable via
96
+ // navigation.global.dropdowns. Discriminated from navGroupSchema by
97
+ // its required `label`/`href` keys (vs `group`/`pages`/`openapi`), so a
98
+ // plain (non-strict at the union level) schema is enough for Zod to pick
99
+ // the right branch; `.strict()` here still catches a typo'd extra key.
100
+ const navLinkSchema = z.object({ label: z.string(), href: z.string() }).strict();
101
+
102
+ const navItemSchema: z.ZodType<NavItem> = z.lazy(() =>
103
+ z.union([navPageSchema, navGroupSchema, navLinkSchema])
104
+ );
105
+
106
+ export type NavItem = string | GroupNavItem | { label: string; href: string };
107
+
108
+ // ---------------------------------------------------------------------
109
+ // Containers: tabs, versions, languages, dropdowns, products.
110
+ //
111
+ // This schema is modeled directly on Mintlify's writedocs.json
112
+ // (https://mintlify.com/writedocs.json / mintlify.com/docs/organize/navigation):
113
+ // all five container kinds are structurally identical except for their
114
+ // own identifying field. Each owns *exactly one* of {pages, tabs,
115
+ // versions, languages, dropdowns, products} as its content, or is a bare
116
+ // external `href` link with no content of its own. That symmetry is what
117
+ // lets any of them nest inside any other - a tab can contain versions, a
118
+ // version can contain languages, a language can contain tabs, and so on,
119
+ // bottoming out at a `pages` array. `withChildren()` is the single place
120
+ // that shape is defined, instead of hand-writing the union five times.
121
+ // ---------------------------------------------------------------------
122
+
123
+ export type NavChildren =
124
+ | { pages: NavItem[] }
125
+ | { tabs: TabItem[] }
126
+ | { versions: VersionItem[] }
127
+ | { languages: LanguageItem[] }
128
+ | { dropdowns: DropdownItem[] }
129
+ | { products: ProductItem[] }
130
+ | { href: string };
131
+
132
+ /** Any navigation item can be hidden: reachable only by its address - no
133
+ * switcher, tab or menu lists it, and its pages search only among
134
+ * themselves (plus the public ones, with `searchPublic`). See
135
+ * lib/hidden-sections.js.
136
+ * And any can have a `page` of its own: where choosing the item leads, in
137
+ * place of its first page - an overview of what's in it. In a sidebar too,
138
+ * it opens there; otherwise it opens inside the item (resolveLandings() in
139
+ * lib/config.ts). */
140
+ export type Hideable = { hidden?: boolean; searchPublic?: boolean; page?: string };
141
+
142
+ export type TabItem = { tab: string; icon?: string } & Hideable & NavChildren;
143
+ export type VersionItem = { version: string; label?: string; tag?: string; default?: boolean } & Hideable & NavChildren;
144
+ export type LanguageItem = { language: string; label?: string } & Hideable & NavChildren;
145
+ export type DropdownItem = { dropdown: string; icon?: string } & Hideable & NavChildren;
146
+ export type ProductItem = { product: string; icon?: string; description?: string } & Hideable & NavChildren;
147
+
148
+ // `.strict()` on every variant is load-bearing, not decoration: Zod
149
+ // objects silently strip unrecognized keys by default, so without it a
150
+ // node written with two children fields at once (e.g. both `pages` and
151
+ // `versions`) would just have the second one dropped instead of
152
+ // rejected - defeating the entire "exactly one child kind per level"
153
+ // rule this schema exists to enforce (mirroring Mintlify's own "a tab
154
+ // cannot contain both anchors and groups at the same level").
155
+ function withChildren<Base extends z.ZodRawShape>(ownFields: Base) {
156
+ const base = { ...ownFields, hidden: z.boolean().optional(), searchPublic: z.boolean().optional(), page: z.string().optional() };
157
+ return z.union([
158
+ z.object({ ...base, pages: z.array(navItemSchema) }).strict(),
159
+ z.object({ ...base, tabs: z.array(tabSchema).min(1) }).strict(),
160
+ z.object({ ...base, versions: z.array(versionSchema).min(1) }).strict(),
161
+ z.object({ ...base, languages: z.array(languageSchema).min(1) }).strict(),
162
+ z.object({ ...base, dropdowns: z.array(dropdownSchema).min(1) }).strict(),
163
+ z.object({ ...base, products: z.array(productSchema).min(1) }).strict(),
164
+ z.object({ ...base, href: z.string() }).strict(),
165
+ ]);
166
+ }
167
+
168
+ // Each of these five is defined via z.lazy() because withChildren()
169
+ // references all five by name (mutual recursion) - safe because none of
170
+ // them are actually *called* until a real writedocs.json is parsed, by which
171
+ // point every const below has been assigned. The same pattern already
172
+ // used for navItemSchema/navGroupSchema above.
173
+ const tabSchema: z.ZodType<TabItem> = z.lazy(() =>
174
+ withChildren({ tab: z.string(), icon: z.string().optional() })
175
+ );
176
+
177
+ const versionSchema: z.ZodType<VersionItem> = z.lazy(() =>
178
+ withChildren({
179
+ version: z.string(),
180
+ label: z.string().optional(),
181
+ tag: z.string().optional(),
182
+ default: z.boolean().optional(),
183
+ })
184
+ );
185
+
186
+ const languageSchema: z.ZodType<LanguageItem> = z.lazy(() =>
187
+ withChildren({ language: z.string(), label: z.string().optional() })
188
+ );
189
+
190
+ const dropdownSchema: z.ZodType<DropdownItem> = z.lazy(() =>
191
+ withChildren({ dropdown: z.string(), icon: z.string().optional() })
192
+ );
193
+
194
+ const productSchema: z.ZodType<ProductItem> = z.lazy(() =>
195
+ withChildren({ product: z.string(), icon: z.string().optional(), description: z.string().optional() })
196
+ );
197
+
198
+ // ---------------------------------------------------------------------
199
+ // Root navigation: a flat array (shorthand for one implicit section - the
200
+ // common case) or an object choosing exactly one primary organizational
201
+ // pattern, per Mintlify's convention ("choose one primary organizational
202
+ // pattern at the root level of your navigation").
203
+ //
204
+ // `global.dropdowns` is the one exception to "exactly one pattern": it's
205
+ // not a primary pattern, it's a persistent set of topbar dropdown
206
+ // triggers that render on every page regardless of which tab/version/
207
+ // language/product is active - equivalent to Mintlify's
208
+ // `navigation.global.anchors`. This replaces the earlier `{tabs,
209
+ // dropdowns}` shape (both present at once), which doesn't generalize
210
+ // once versions/languages/products are also root-level choices.
211
+ // ---------------------------------------------------------------------
212
+
213
+ export type NavigationConfig =
214
+ | NavItem[]
215
+ | { global?: { dropdowns: DropdownItem[] }; tabs: TabItem[] }
216
+ | { global?: { dropdowns: DropdownItem[] }; versions: VersionItem[] }
217
+ | { global?: { dropdowns: DropdownItem[] }; languages: LanguageItem[] }
218
+ | { global?: { dropdowns: DropdownItem[] }; dropdowns: DropdownItem[] }
219
+ | { global?: { dropdowns: DropdownItem[] }; products: ProductItem[] };
220
+
221
+ /** Levels of tabs a page can sit under - one row of the top bar each. */
222
+ export const MAX_TAB_LEVELS = 2;
223
+ /** Levels of dropdowns in a tab's menu - the menu, and a flyout beside an
224
+ * entry for the dropdowns inside it (lib/selector-placement.js). */
225
+ export const MAX_TAB_MENU_LEVELS = 2;
226
+
227
+ const globalSchema = z.object({ dropdowns: z.array(dropdownSchema).min(1) });
228
+
229
+ const navigationSchema = z.union([
230
+ z.array(navItemSchema),
231
+ z.object({ global: globalSchema.optional(), tabs: z.array(tabSchema).min(1) }).strict(),
232
+ z.object({ global: globalSchema.optional(), versions: z.array(versionSchema).min(1) }).strict(),
233
+ z.object({ global: globalSchema.optional(), languages: z.array(languageSchema).min(1) }).strict(),
234
+ z.object({ global: globalSchema.optional(), dropdowns: z.array(dropdownSchema).min(1) }).strict(),
235
+ z.object({ global: globalSchema.optional(), products: z.array(productSchema).min(1) }).strict(),
236
+ ]).superRefine((navigation, ctx) => {
237
+ // Every page under a language is in that language - a second `languages`
238
+ // inside it would make a page two languages at once. And tabs take a row
239
+ // of the top bar per level: two levels at most (TopBar.astro).
240
+ const CONTAINERS = ['tabs', 'versions', 'languages', 'dropdowns', 'products'] as const;
241
+ // `menu`: the dropdown levels in a tab's menu down to `node` - 0 outside
242
+ // one, 1 for a dropdown right inside a tab, 2 for a dropdown inside that.
243
+ const walk = (node: unknown, path: (string | number)[], language: string | null, tabs: string[], menu = 0) => {
244
+ if (!node || typeof node !== 'object' || Array.isArray(node)) return;
245
+ const own = node as Record<string, unknown>;
246
+ for (const key of CONTAINERS) {
247
+ const items = own[key];
248
+ if (!Array.isArray(items)) continue;
249
+ if (key === 'languages' && language !== null) {
250
+ ctx.addIssue({
251
+ code: 'custom',
252
+ path: [...path, key],
253
+ message: `The language "${language}" contains another "languages" list. A page can only be in one language - put the languages at one level, and the rest (tabs, versions, ...) inside each of them.`,
254
+ });
255
+ continue;
256
+ }
257
+ if (key === 'tabs' && tabs.length >= MAX_TAB_LEVELS) {
258
+ ctx.addIssue({
259
+ code: 'custom',
260
+ path: [...path, key],
261
+ message: `Tabs go at most ${MAX_TAB_LEVELS} levels deep, and these are a third level (inside "${tabs.join('" > "')}"). Each level of tabs is a row in the top bar - use a dropdown or groups for this level instead.`,
262
+ });
263
+ continue;
264
+ }
265
+ // Dropdowns right inside a tab are its menu; dropdowns inside one of
266
+ // those, a flyout beside its entry. Any other level of dropdowns starts
267
+ // its own count.
268
+ const menuLevel = key !== 'dropdowns' ? 0 : 'tab' in own ? 1 : 'dropdown' in own && menu > 0 ? menu + 1 : 0;
269
+ if (menuLevel > MAX_TAB_MENU_LEVELS) {
270
+ ctx.addIssue({
271
+ code: 'custom',
272
+ path: [...path, key],
273
+ message: `A tab's menu goes ${MAX_TAB_MENU_LEVELS} levels deep at most - its dropdowns, and the dropdowns inside each of them - and these are a third level (inside "${String(own.dropdown)}"). Use products or groups for this level instead.`,
274
+ });
275
+ continue;
276
+ }
277
+ items.forEach((item, i) => {
278
+ const own = item as { hidden?: unknown; searchPublic?: unknown; page?: unknown; href?: unknown };
279
+ if (own?.page !== undefined && own.href !== undefined) {
280
+ ctx.addIssue({
281
+ code: 'custom',
282
+ path: [...path, key, i, 'page'],
283
+ message: 'An item with `href` is a link, so it has no page of its own - remove `page`, or `href`.',
284
+ });
285
+ }
286
+ if (own?.searchPublic === true && own.hidden !== true) {
287
+ ctx.addIssue({
288
+ code: 'custom',
289
+ path: [...path, key, i, 'searchPublic'],
290
+ message: '`searchPublic` only applies to a hidden item - add "hidden": true, or remove `searchPublic`.',
291
+ });
292
+ }
293
+ const inner = key === 'languages' ? String((item as { language?: unknown })?.language ?? '') : language;
294
+ const tab = (item as { tab?: unknown })?.tab;
295
+ walk(item, [...path, key, i], inner, key === 'tabs' ? [...tabs, String(tab ?? '')] : tabs, menuLevel);
296
+ });
297
+ }
298
+ };
299
+ walk(navigation, [], null, []);
300
+ }) as z.ZodType<NavigationConfig>;
301
+
302
+ const DEFAULT_PRIMARY = '#6366f1';
303
+
304
+ // A logo is either one path used for both color modes, or a
305
+ // { light, dark, label } object - each image shown only while that mode
306
+ // is active (see BaseLayout.astro's .wd-logo-light/.wd-logo-dark CSS).
307
+ // The topbar shows *only* the image by default - no site name text next
308
+ // to it, since a real logo asset usually already is a wordmark. `label`
309
+ // is the opt-in way to add text back next to the image (e.g. a product
310
+ // name alongside a symbol-only mark); it only exists on the object form,
311
+ // since a single shared image path is just as easy to bake the label
312
+ // into directly.
313
+ //
314
+ // `light`/`dark` are themselves optional (unlike the string form, which
315
+ // is inherently "both"): a site with no logo *images* at all can still
316
+ // set `styles.logo: { label: "..." }` to override the topbar's fallback
317
+ // text without providing any image - see BaseLayout.astro's
318
+ // hasLogoImage/logoLabel/brandLabel derivation, where an object with
319
+ // only `label` set already resolves correctly (brandLabel = logoLabel,
320
+ // same as if an image were also present) without needing any change
321
+ // there; only this schema needed loosening; light/dark were previously
322
+ // both required whenever the object form was used at all.
323
+ //
324
+ // Standalone const (rather than inlined into stylesSchema.logo below) so
325
+ // footer.logo further down can share the exact same union instead of an
326
+ // independently-written copy - see footerSchema's own comment on why a
327
+ // footer logo needs this at all.
328
+ const logoSchema = z.union([
329
+ z.string(),
330
+ z.object({ light: z.string().optional(), dark: z.string().optional(), label: z.string().optional() }).strict(),
331
+ ]);
332
+
333
+ // Same {light, dark}-with-fallback shape applies to `colors.dark`: any
334
+ // of primary/text left unset there falls back to the light-mode value
335
+ // already given above, so a site only has to specify what actually
336
+ // differs in dark mode. There used to be a `background`/`dark.background`
337
+ // pair here too, doing effectively the same job as `background.colors`
338
+ // further down (see that field's own comment) - two writedocs.json fields
339
+ // both named "background" that visually looked interchangeable but
340
+ // weren't quite (one drove --wd-background site-wide, the other only
341
+ // the <body> canvas), which was confusing to author against and easy to
342
+ // half-configure by setting only one. Removed in favor of `background`
343
+ // alone being the single place to set any background color - see that
344
+ // field's comment for what it now covers.
345
+ // One side of `styles.navbar` (light or dark) - either a bare background
346
+ // color (the original shape) or `{ background, accent? }` once a site
347
+ // wants its own accent color (the active tab's underline)
348
+ // inside the navbar specifically, independent of the sitewide
349
+ // `styles.colors.primary`. Deliberately does NOT carry a text/icon color
350
+ // field at all - see `navbar`'s own comment below (stylesSchema) for why
351
+ // that's resolved automatically instead of being configurable. Kept as a
352
+ // standalone const rather than inlined so `light`/`dark` share the exact
353
+ // same union rather than two independently-written (and possibly
354
+ // drifting) copies of it.
355
+ const navbarColorValueSchema = z.union([
356
+ z.string(),
357
+ z
358
+ .object({
359
+ background: z.string(),
360
+ accent: z.string().optional(),
361
+ })
362
+ .strict(),
363
+ ]);
364
+
365
+ // One font declaration - almost exactly Mintlify's own `fonts` shape (see
366
+ // docs/dev/docs/site-config.mdx's own "Fonts" section for the research this
367
+ // was based on): a bare Google Fonts family name (`family` alone - Google
368
+ // Fonts loads it automatically, see googleFontsHref() below), or a local/
369
+ // externally-hosted font file (`source` + `format` together; `source` is
370
+ // either a project-relative path like the other five asset-fallback fields
371
+ // this schema already has - see collectConfiguredAssetPaths() - or a full
372
+ // https:// URL to an externally-hosted font). `weight` does two things at
373
+ // once, both driven by BaseLayout.astro: it narrows which file actually
374
+ // loads (folded into the Google Fonts URL's `:wght@` axis, or the
375
+ // generated `@font-face` rule's own `font-weight` descriptor for a
376
+ // `source` font - see googleFontsHref()/fontFaceRule() below), *and* it's
377
+ // applied as a real CSS `font-weight` on h1-h6 (for `heading`) or `body`
378
+ // (for `body`) - see BaseLayout's own `wdFontWeightHeading`/
379
+ // `wdFontWeightBody`. Both halves matter: loading only the 400-weight file
380
+ // while leaving h1-h6 at the browser's UA-default `font-weight: bold`
381
+ // faux-bolds that file back to looking bold anyway, with no visible
382
+ // change from configuring a lighter weight at all - the bug this second
383
+ // half fixes (caught from real user-reported behavior, not anticipated
384
+ // up front). Left unset anywhere in `styles.fonts` renders no font-weight
385
+ // rule at all, keeping today's plain browser-default bold headings/normal
386
+ // body text unchanged for a site that hasn't touched this field.
387
+ const fontVariantSchema = z
388
+ .object({
389
+ family: z.string(),
390
+ weight: z.number().optional(),
391
+ source: z.string().optional(),
392
+ format: z.enum(['woff', 'woff2']).optional(),
393
+ })
394
+ .strict();
395
+
396
+ export type FontVariant = z.infer<typeof fontVariantSchema>;
397
+
398
+ // The top-level shape adds `heading`/`body`: each independently optional,
399
+ // each falling back to the top-level family/weight/source/format when
400
+ // unset (see resolveFonts() below) - so a site can set one font for
401
+ // everything (`fonts.family` alone), or split headings and body text
402
+ // without needing to repeat itself for whichever side isn't changing.
403
+ const fontsSchema = z
404
+ .object({
405
+ family: z.string(),
406
+ weight: z.number().optional(),
407
+ source: z.string().optional(),
408
+ format: z.enum(['woff', 'woff2']).optional(),
409
+ heading: fontVariantSchema.optional(),
410
+ body: fontVariantSchema.optional(),
411
+ })
412
+ .strict();
413
+
414
+ export type FontsConfig = z.infer<typeof fontsSchema>;
415
+
416
+ const stylesSchema = z
417
+ .object({
418
+ colors: z
419
+ .object({
420
+ primary: z.string().default(DEFAULT_PRIMARY),
421
+ text: z.string().optional(),
422
+ dark: z
423
+ .object({
424
+ primary: z.string().optional(),
425
+ text: z.string().optional(),
426
+ })
427
+ .optional(),
428
+ })
429
+ .default({ primary: DEFAULT_PRIMARY }),
430
+ logo: logoSchema.optional(),
431
+ favicon: z.string().optional(),
432
+ // No default value here (unlike `colors.primary`'s DEFAULT_PRIMARY) -
433
+ // resolveFonts() below is where "Inter" actually gets applied as the
434
+ // site-wide default whenever this field is left unset entirely, so
435
+ // that fallback lives in one place alongside the rest of the
436
+ // resolution logic rather than being duplicated as a schema default
437
+ // *and* a resolver fallback.
438
+ fonts: fontsSchema.optional(),
439
+ // The Shiki theme *name* (not a full theme object/JSON - see
440
+ // https://shiki.style/themes for the built-in list) each fenced
441
+ // (```) MDX code block, and the API playground's request/response
442
+ // snippets, use in light/dark mode - read out of writedocs.json by both
443
+ // astro.config.mjs (Shiki's dual-theme markdown config) and
444
+ // ApiReferencePanel.astro (its own separate <Code/> usages, which
445
+ // don't inherit markdown.shikiConfig) via resolveCodeblockTheme()
446
+ // below, the single source of truth for the 'github-light'/
447
+ // 'github-dark' fallback. Left per-key optional (not defaulted in
448
+ // the schema itself) so a site can override just one side (e.g.
449
+ // only `dark`) and still get the ordinary default for the other.
450
+ codeblocks: z
451
+ .object({
452
+ light: z.string().optional(),
453
+ dark: z.string().optional(),
454
+ // Maps a fenced (```) block's own language tag to whichever real
455
+ // Shiki grammar actually highlights it, before that tag ever
456
+ // reaches Shiki - see resolveCodeblockLangAlias() below for the
457
+ // one built-in entry (mdx -> jsx) this ships with by default and
458
+ // why. A site can add its own entries for any other language tag
459
+ // that either doesn't tokenize well under its own grammar, or
460
+ // that a site wants to write under a shorter/friendlier fence tag
461
+ // than Shiki's own bundled id (e.g. `groovy: 'java'` for a close-
462
+ // enough approximation Shiki doesn't ship a dedicated grammar for
463
+ // at all) - merged with, not replacing, the built-in default, so
464
+ // adding one of a site's own doesn't require re-declaring mdx.
465
+ langAlias: z.record(z.string(), z.string()).optional(),
466
+ })
467
+ .strict()
468
+ .optional(),
469
+ // The topbar's own background, independent of `background` below (the
470
+ // page's) - a site may want its navbar to stand out (a dark or
471
+ // brand-colored bar over a light page) rather than blend into the
472
+ // page, which is the default when this is left unset. Same {light,
473
+ // dark} shape (and same per-key-optional, not defaulted here) as
474
+ // `codeblocks` right above, rather than nested under `colors` - it's a
475
+ // topbar-specific override, not a third general-purpose page color, so
476
+ // it reads more like "one more themed surface" alongside codeblocks
477
+ // than a sibling of primary/text. BaseLayout.astro's own
478
+ // lightNavbarBg/darkNavbarBg resolution is what falls each side back
479
+ // to the page background when unset.
480
+ //
481
+ // Each side (`light`/`dark`) is either a bare string - just the
482
+ // background color, exactly the original shape, kept for backwards
483
+ // compatibility - or `{ background, accent? }`, for when a site also
484
+ // wants the navbar's own active-tab underline color to
485
+ // differ from the sitewide `styles.colors.primary` (`accent`'s only
486
+ // job - see BaseLayout.astro's lightNavbarAccent). Deliberately no
487
+ // text/icon color field here at all: BaseLayout.astro always resolves
488
+ // the navbar's plain text/icon color itself, picking black or white by
489
+ // contrast against whatever `background` resolves to
490
+ // (contrastTextColor() below) the moment this field is configured at
491
+ // all (string or object) - never a value read from writedocs.json. A
492
+ // manually-set text color is a legibility footgun a site author can
493
+ // get wrong (or drift out of sync after later changing `background`
494
+ // without remembering to update it too) in a way "compute it
495
+ // correctly, every time" simply can't - there's no legitimate reason
496
+ // to want *illegible* navbar text, unlike `accent`, which is a real
497
+ // aesthetic choice. Real bug this fixes: a site setting `navbar.light`
498
+ // to the same value as `colors.primary` (a plausible thing to reach
499
+ // for - "brand-colored navbar") made every topbar label/icon/link
500
+ // render in the default near-black text color against that same
501
+ // saturated background, all but unreadable - and an earlier version of
502
+ // this feature that let a writedocs.json-supplied color double as the text
503
+ // color reintroduced the identical bug one level down, just requiring
504
+ // one more (still guessable-wrong) field to trigger it.
505
+ navbar: z
506
+ .object({
507
+ light: navbarColorValueSchema.optional(),
508
+ dark: navbarColorValueSchema.optional(),
509
+ })
510
+ .strict()
511
+ .optional(),
512
+ // The single place to configure any background color: `colors` is a
513
+ // solid color (falls back to '#ffffff'/'#0b1120' when unset - see
514
+ // BaseLayout.astro's lightBackground/darkBackground resolution), and
515
+ // `images` layers an image on top of it (or is the whole background
516
+ // by itself, if `colors` is left at its default). This one pair now
517
+ // drives everything background-related site-wide - --wd-background
518
+ // (dropdowns/modals/kbd chips/footer/topbar-fallback/etc., see every
519
+ // `var(--wd-background)` call site) *and* the <body> canvas behind the
520
+ // main/toc columns - rather than the two being independently
521
+ // configurable fields that happened to look alike but didn't affect
522
+ // the same things (see this schema's own comment on `colors.dark`
523
+ // above for why that split was removed). Both are per-mode optional,
524
+ // same "only specify what differs" pattern as codeblocks/navbar above.
525
+ // The topbar and footer still get their own explicit opaque
526
+ // background (topbar.css/footer.css) specifically so an `images`
527
+ // background doesn't show through them; see those files' own
528
+ // comments. The sidebar column has no background of its own (base.css)
529
+ // and lets it show through, same as the main/toc columns.
530
+ background: z
531
+ .object({
532
+ colors: z
533
+ .object({
534
+ light: z.string().optional(),
535
+ dark: z.string().optional(),
536
+ })
537
+ .strict()
538
+ .optional(),
539
+ images: z
540
+ .object({
541
+ light: z.string().optional(),
542
+ dark: z.string().optional(),
543
+ })
544
+ .strict()
545
+ .optional(),
546
+ })
547
+ .strict()
548
+ .optional(),
549
+ })
550
+ .default({ colors: { primary: DEFAULT_PRIMARY } });
551
+
552
+ // `href` is always required - a link with nowhere to go isn't a link.
553
+ // `label`/`icon` are each individually optional, but not both at once
554
+ // (enforced by the .refine() below, same shape as scriptEntrySchema's own
555
+ // exactly-one-of check above) - a link needs *something* visible to render,
556
+ // whichever of the two, and can have both (icon rendered to the left of the
557
+ // label - see TopBar.astro/SiteFooter.astro, the two renderers of this
558
+ // shape). An icon-only link (no label) is the common case for something
559
+ // like a bare GitHub mark in the topbar; label-only (no icon) is every
560
+ // plain text link this already supported before `icon` existed - both
561
+ // still need to keep working unchanged, hence neither field being outright
562
+ // required on its own.
563
+ const topbarLinkSchema = z
564
+ .object({
565
+ label: z.string().optional(),
566
+ href: z.string(),
567
+ // Same string shape as every other writedocs.json `icon` field (a plain
568
+ // Lucide name, or the explicit "collection:icon-name" form for
569
+ // anything else - see resolveIcon()/AppIcon.astro) - not documented
570
+ // again here since that convention is already established elsewhere
571
+ // in this file (tabs/switchers/socials all take the identical shape).
572
+ icon: z.string().optional(),
573
+ })
574
+ .strict()
575
+ .refine((link) => Boolean(link.label) || Boolean(link.icon), {
576
+ message: 'Each topbar.links/footer column link needs a "label", an "icon", or both - a link with neither has nothing to render.',
577
+ });
578
+
579
+ // One column of the footer (BaseLayout.astro's <footer class="wd-footer">) -
580
+ // an optional heading (e.g. "Resources", "Community") plus a list of links,
581
+ // reusing the exact same {label, icon, href} shape as topbar.links above (a
582
+ // footer link is the same thing rendered in a different place, no reason
583
+ // for a second, identical-but-differently-named schema). `title` is
584
+ // optional so a single-column footer with no heading (just a bare list of
585
+ // links) is valid too.
586
+ const footerColumnSchema = z
587
+ .object({
588
+ title: z.string().optional(),
589
+ links: z.array(topbarLinkSchema).default([]),
590
+ })
591
+ .strict();
592
+
593
+ // Off by default (empty `columns`, same convention as `topbar` above - a
594
+ // footer with nothing configured just doesn't render at all, see
595
+ // BaseLayout.astro's `hasFooterContent` check) rather than `.optional()`
596
+ // like contextMenu: unlike that field, an empty/default footer has no
597
+ // build-output or routing implications to gate, it's purely visual, so
598
+ // there's no reason to distinguish "unset" from "set to nothing" the way
599
+ // contextMenu needs to.
600
+ // Same {light, dark, label} union as `styles.logo` (via the shared
601
+ // logoSchema above) - unset by default, in which case the footer just
602
+ // shows the sitewide `styles.logo` (BaseLayout.astro's existing
603
+ // logoLight/logoDark/logoLabel, already threaded into SiteFooter as-is).
604
+ // Set here, it replaces that entirely rather than filling in only the
605
+ // missing side of it - a footer.logo with only `dark` set shows *just*
606
+ // the dark-mode image, not styles.logo's light image plus this dark one -
607
+ // the same all-or-nothing-relative-to-styles.logo resolution BaseLayout.astro
608
+ // already applies.
609
+ const footerSchema = z
610
+ .object({
611
+ columns: z.array(footerColumnSchema).default([]),
612
+ logo: logoSchema.optional(),
613
+ })
614
+ .strict()
615
+ .default({ columns: [] });
616
+
617
+ export type FooterColumn = z.infer<typeof footerColumnSchema>;
618
+ export type FooterConfig = z.infer<typeof footerSchema>;
619
+
620
+ // Shared by both writedocs.json's top-level `seo` (site-wide defaults) and a
621
+ // page's own frontmatter `seo` (per-page overrides) - see
622
+ // content.config.ts's docsSchema, which imports this exact schema rather
623
+ // than redeclaring the same shape a second time. mergeSeo() below is what
624
+ // actually combines the two, field by field, at render time.
625
+ export const seoFieldsSchema = z
626
+ .object({
627
+ // Open Graph / Twitter card image - a relative path (resolved against
628
+ // `domain` below into an absolute URL, since most social crawlers
629
+ // require one) or an already-absolute https:// URL.
630
+ ogImage: z.string().optional(),
631
+ // og:type - "website" for most pages, "article" for blog-post-shaped
632
+ // content, etc. Defaults to "website" if never set anywhere.
633
+ ogType: z.string().optional(),
634
+ twitterCard: z.enum(['summary', 'summary_large_image']).optional(),
635
+ keywords: z.array(z.string()).optional(),
636
+ // Renders <meta name="robots" content="noindex, nofollow" /> and
637
+ // (see astro.config.mjs's sitemap `filter`) excludes the page from
638
+ // sitemap.xml entirely - both driven off this one flag, since listing
639
+ // a page in the sitemap while also telling crawlers not to index it
640
+ // would be self-contradictory.
641
+ noindex: z.boolean().optional(),
642
+ // The whole <meta name="robots"> value, for anything `noindex` (always
643
+ // "noindex, nofollow") doesn't say - "noindex, follow", "max-snippet:50".
644
+ // Wins over `noindex`; a value with "noindex" keeps the page out of
645
+ // sitemap.xml and llms.txt the same way (isNoindex(), lib/seo-tags.js).
646
+ robots: z.string().optional(),
647
+ // Any other <meta> tag, name -> content: "google-site-verification",
648
+ // "twitter:site", "og:locale"... One with the name of a tag writedocs
649
+ // writes itself ("og:image", "twitter:image", "description") replaces
650
+ // it. Open Graph names become <meta property>, the rest <meta name> -
651
+ // see seoHead() in lib/seo-tags.js. A page's own are merged over the
652
+ // site's, name by name.
653
+ metatags: z.record(z.string(), z.string()).optional(),
654
+ })
655
+ .strict();
656
+
657
+ // A page's own `seo`: everything above, plus what only makes sense for one
658
+ // page - the site has no single title, description or canonical address.
659
+ export const pageSeoFieldsSchema = seoFieldsSchema
660
+ .extend({
661
+ // The <title> and og:title/twitter:title, exactly as written - no site
662
+ // name is added. The page's <h1> and sidebar entry keep `title`.
663
+ title: z.string().optional(),
664
+ // The <meta name="description"> and og/twitter descriptions, when they
665
+ // should differ from the `description` shown under the page's title.
666
+ description: z.string().optional(),
667
+ // The page's canonical URL, when it isn't its own address: a full URL,
668
+ // or a path on the site's domain. A page whose canonical is another
669
+ // address is left out of sitemap.xml.
670
+ canonical: z.string().optional(),
671
+ // The page's own structured data (schema.org JSON-LD): one block, or a
672
+ // list of them, written into the page after the ones writedocs
673
+ // generates (lib/json-ld.js). Any shape - it is the author's to get right.
674
+ jsonLd: z.union([z.record(z.string(), z.unknown()), z.array(z.record(z.string(), z.unknown()))]).optional(),
675
+ })
676
+ .strict();
677
+
678
+ // writedocs.json's `seo`: the shared fields, plus what describes the site
679
+ // as a whole.
680
+ export const siteSeoFieldsSchema = seoFieldsSchema
681
+ .extend({
682
+ // Who publishes the site - an Organization block in the home page's
683
+ // structured data, and the `publisher` of every page (lib/json-ld.js).
684
+ // Not derived from `name`: a site is called "Acme Docs", the
685
+ // organization "Acme".
686
+ organization: z
687
+ .object({
688
+ name: z.string(),
689
+ // The organization's own site. Default: this site's address.
690
+ url: z.string().optional(),
691
+ // A path in the project or a full URL. Default: the site's logo.
692
+ logo: z.string().optional(),
693
+ // Its profiles elsewhere. Default: the URLs in `socials`.
694
+ sameAs: z.array(z.string()).optional(),
695
+ })
696
+ .strict()
697
+ .optional(),
698
+ })
699
+ .strict();
700
+
701
+ export type SiteSeoFields = z.infer<typeof siteSeoFieldsSchema>;
702
+ export type SeoFields = z.infer<typeof pageSeoFieldsSchema>;
703
+
704
+ /** Field-by-field merge of a page's own `seo` frontmatter over writedocs.json's
705
+ * site-wide `seo` defaults - a page only overrides the specific fields it
706
+ * sets, falling back to the site default for everything else, rather than
707
+ * a page's (possibly partial) `seo` object replacing the site's wholesale. */
708
+ export function mergeSeo(site: SeoFields, page: SeoFields = {}): SeoFields {
709
+ // `robots` and `noindex` say the same thing two ways, so they're taken
710
+ // together: a page that sets either one decides for itself, and the
711
+ // site's value of the other doesn't leak into it. `noindex` then follows
712
+ // `robots` when there is one, so everything that reads `noindex` (the
713
+ // sitemap, llms.txt, the MCP index) agrees with the tag on the page.
714
+ const pageDecides = page.robots !== undefined || page.noindex !== undefined;
715
+ const robots = pageDecides ? page.robots : site.robots;
716
+ const noindex = robots !== undefined ? /\bnoindex\b|\bnone\b/i.test(robots) : pageDecides ? page.noindex : site.noindex;
717
+ const metatags = site.metatags || page.metatags ? { ...site.metatags, ...page.metatags } : undefined;
718
+ return {
719
+ ogImage: page.ogImage ?? site.ogImage,
720
+ ogType: page.ogType ?? site.ogType,
721
+ twitterCard: page.twitterCard ?? site.twitterCard,
722
+ keywords: page.keywords ?? site.keywords,
723
+ noindex,
724
+ robots,
725
+ metatags,
726
+ title: page.title,
727
+ description: page.description,
728
+ canonical: page.canonical,
729
+ jsonLd: page.jsonLd,
730
+ };
731
+ }
732
+
733
+ const MINTLIFY_MODE_ALIASES: Record<string, string> = { center: 'frame', assistant: 'default' };
734
+
735
+ /** A page's own frontmatter - the `pages` and `generatedDocs` content
736
+ * collections' schema (content.config.ts), and what `writedocs validate`
737
+ * checks every page against. */
738
+ export const pageFrontmatterSchema = z.object({
739
+ title: z.string(),
740
+ description: z.string().optional(),
741
+ // Overrides the URL this page is served at, independent of where the
742
+ // file actually lives - writedocs.json's `pages` arrays always keep
743
+ // referencing the file's own path regardless. This is Astro's own
744
+ // glob()-loader convention (a `slug` frontmatter field becomes
745
+ // `entry.id` verbatim - see generateIdDefault in
746
+ // astro/dist/content/loaders/glob.js), not writedocs-specific
747
+ // behavior; declaring it here just brings it into the schema (and
748
+ // its docs) rather than leaving it an undocumented Astro feature.
749
+ // See fileIdForEntry() in lib/config.ts for how routes/links still
750
+ // resolve a page by its file id once this diverges from `entry.id`.
751
+ // Leading/trailing slashes are fine either way ("/", "/guides/x",
752
+ // "guides/x" and "guides/x/" all mean the same thing) - see
753
+ // normalizeEntryId() in lib/config.ts, which is what actually
754
+ // strips them before this value is ever used as a route or href.
755
+ slug: z.string().optional(),
756
+ // Marks this page as an OpenAPI operation reference: "METHOD /path"
757
+ // matching an operation in the owning group's OpenAPI spec, e.g.
758
+ // "GET /pets/{petId}" - [...slug].astro renders <ApiPlayground /> for
759
+ // any page with this field set, below the page's own MDX body (if
760
+ // any). Sites don't write this by hand for most pages; it's either
761
+ // set on a generated stub in the `generatedDocs` collection below (see
762
+ // generate-api-pages.js) or hand-authored to "eject" one specific
763
+ // operation into a real file (in `docs`) with custom prose - either
764
+ // way, the value is always exactly the same "METHOD /path" key
765
+ // generate-api-pages.js uses to look up the operation's full resolved
766
+ // schema/examples at render time.
767
+ openapi: z.string().optional(),
768
+ // Controls how much of the site's own chrome (topbar, sidebar, table of
769
+ // contents) wraps this page - see BaseLayout.astro/[...slug].astro for
770
+ // what each value actually removes:
771
+ // default - the normal three-column reading layout (all chrome).
772
+ // wide - drops the table of contents; the article itself also
773
+ // renders wider, for content that wants the extra room
774
+ // (wide tables, side-by-side images).
775
+ // frame - drops the sidebar and table of contents, but keeps the
776
+ // topbar and the article's own normal presentation
777
+ // ("frame" as in: still inside the site's outer frame).
778
+ // custom - drops the sidebar and table of contents, the
779
+ // auto-rendered <h1>, and prev/next nav, and skips the
780
+ // article's own prose width/padding too - a blank canvas
781
+ // for a hand-built landing/home page made entirely of
782
+ // components - but keeps the topbar, so the page still
783
+ // has site branding/nav/search/theme-toggle available.
784
+ // blank - everything 'custom' drops, plus the topbar too: no site
785
+ // chrome at all, just <slot />. For a page that wants to
786
+ // look nothing like the rest of the site (an auth screen,
787
+ // a print-style page).
788
+ //
789
+ // Two Mintlify values are accepted so a migrated page doesn't fail the
790
+ // build (see MINTLIFY_MODE_ALIASES above): `center` is the same layout
791
+ // as our `frame`, and `assistant` (a full-page Mintlify AI chat, which
792
+ // writedocs doesn't have) falls back to `default`. Mintlify's own
793
+ // `frame` means something else (a canvas that keeps the sidebar) - it's
794
+ // left as our `frame`; see docs/dev/docs/mintlify-compat.mdx.
795
+ mode: z
796
+ .preprocess(
797
+ (value) => (typeof value === 'string' && value in MINTLIFY_MODE_ALIASES ? MINTLIFY_MODE_ALIASES[value] : value),
798
+ z.enum(['default', 'wide', 'frame', 'custom', 'blank']),
799
+ )
800
+ .default('default'),
801
+ // Per-page meta tag overrides - same shape as writedocs.json's top-level
802
+ // `seo` (see seoFieldsSchema in lib/config.ts, the single source of
803
+ // truth for this shape). A page only needs to set the specific fields
804
+ // it wants to override; mergeSeo() falls back to the site-wide default
805
+ // for anything left unset. See BaseLayout.astro for where this and the
806
+ // site-wide seo actually get merged and rendered.
807
+ seo: pageSeoFieldsSchema.optional(),
808
+ // Mintlify's spelling of `seo.noindex` - a top-level `noindex: true`.
809
+ // Folded into `seo` by the transform below, so everything downstream
810
+ // (the robots meta tag, sitemap.xml, llms.txt) keeps reading
811
+ // `seo.noindex` only.
812
+ noindex: z.boolean().optional(),
813
+ // Mintlify's spellings of `seo.robots` and `seo.canonical`, folded into
814
+ // `seo` the same way.
815
+ robots: z.string().optional(),
816
+ canonical: z.string().optional(),
817
+ // Mintlify's short navigation label - used for the sidebar and the
818
+ // topbar dropdown menus in place of `title` ([...slug].astro's
819
+ // navTitleForSlug). The page's own <h1> and prev/next links keep `title`.
820
+ sidebarTitle: z.string().optional(),
821
+ // Mintlify's spellings of `seo.keywords`, `seo.ogImage`, `seo.ogType`
822
+ // and `seo.twitterCard`, folded into `seo` below like `noindex`.
823
+ keywords: z.array(z.string()).optional(),
824
+ 'og:image': z.string().optional(),
825
+ 'og:type': z.string().optional(),
826
+ 'twitter:card': z.enum(['summary', 'summary_large_image']).optional(),
827
+ // Mintlify's sidebar/page-chrome fields - see NavTree.astro and
828
+ // [...slug].astro for where each is used:
829
+ // icon - shown before the page's label in the sidebar.
830
+ // tag - a short label after it (e.g. "NEW").
831
+ // deprecated - a "Deprecated" label in the sidebar and next
832
+ // to the page's <h1>.
833
+ // hidden - left out of the sidebar, dropdowns and
834
+ // prev/next, but still built and reachable by
835
+ // URL. Also noindexed, as on Mintlify.
836
+ // url - an external link: the page's sidebar entry
837
+ // links straight to it, and the page's own URL
838
+ // redirects there.
839
+ // hideFooterPagination - no prev/next links on this page.
840
+ // hideApiMarker - no HTTP method badge on this page's sidebar
841
+ // entry.
842
+ icon: z.string().optional(),
843
+ tag: z.string().optional(),
844
+ deprecated: z.boolean().optional(),
845
+ hidden: z.boolean().optional(),
846
+ url: z.string().optional(),
847
+ hideFooterPagination: z.boolean().optional(),
848
+ hideApiMarker: z.boolean().optional(),
849
+ }).transform(
850
+ ({ noindex, robots, canonical, keywords, 'og:image': ogImage, 'og:type': ogType, 'twitter:card': twitterCard, ...data }) => {
851
+ // Top-level Mintlify keys fill in `seo` only where the page's own `seo`
852
+ // doesn't already set that field - an explicit `seo` value always wins.
853
+ // A `hidden` page is noindexed unless it says otherwise.
854
+ const seo = { ...data.seo };
855
+ // `robots` says whether the page is indexed, so with one - the page's
856
+ // own, or the top-level spelling - `noindex` follows it, and a `hidden`
857
+ // page's automatic noindex doesn't apply.
858
+ const pageRobots = seo.robots ?? robots;
859
+ const fromMintlify = {
860
+ robots,
861
+ canonical,
862
+ noindex: pageRobots !== undefined ? undefined : (noindex ?? (data.hidden ? true : undefined)),
863
+ keywords,
864
+ ogImage,
865
+ ogType,
866
+ twitterCard,
867
+ };
868
+ let changed = false;
869
+ for (const [key, value] of Object.entries(fromMintlify)) {
870
+ if (value === undefined || seo[key as keyof typeof seo] !== undefined) continue;
871
+ (seo as Record<string, unknown>)[key] = value;
872
+ changed = true;
873
+ }
874
+ if (pageRobots !== undefined) {
875
+ seo.noindex = /\bnoindex\b|\bnone\b/i.test(pageRobots);
876
+ changed = true;
877
+ }
878
+ return changed ? { ...data, seo } : data;
879
+ },
880
+ );
881
+
882
+ // Controls for the OpenAPI API playground's "Try it" modal - separate
883
+ // from a group's own `openapi: { src, path }` field (which spec to use,
884
+ // and where) since this is about how a *request* it sends behaves, not
885
+ // about the spec itself.
886
+ const apiSchema = z
887
+ .object({
888
+ // Whether a Try-it request the browser blocks is retried through
889
+ // writedocs' own CORS proxy (https://proxy.writechoice.io/). The
890
+ // request always goes to the API directly first, so a reader's key
891
+ // reaches the proxy only when the API itself refuses browser calls.
892
+ // Almost no real-world API sends back Access-Control-Allow-Origin
893
+ // headers permitting an arbitrary docs site's origin, so the direct
894
+ // call fails for most real APIs - see the send handler and
895
+ // PROXY_BASE_URL in ApiReferencePanel.astro. Defaults to enabled; a
896
+ // site can set this to `false` to never involve a third party.
897
+ proxy: z.boolean().default(true),
898
+ })
899
+ .strict()
900
+ .default({ proxy: true });
901
+
902
+ // The "Copy page" menu shown next to a page's title - copy the page's
903
+ // Markdown, view it, or open it in an AI assistant - and the .md copy of
904
+ // every page it relies on ([...slug].md.ts). On by default, with every
905
+ // option, like the MCP server. writedocs.json narrows or turns it off:
906
+ //
907
+ // (absent) or true every option
908
+ // ["copy", "claude"] only these, in the menu's own order
909
+ // (copy, view, chatgpt, claude, perplexity,
910
+ // mcp, cursor, vscode - the last three connect
911
+ // AI tools to the site's MCP server, and are
912
+ // left out when `mcp` is false)
913
+ // false (or []) no menu, and no .md routes
914
+ // { "openIn": [...] } the earlier form: copy and view, plus these
915
+ // assistants - still accepted
916
+ //
917
+ // Read it through contextMenuOptions() below - never test the raw value for
918
+ // truthiness: absent now means on.
919
+ export const CONTEXT_MENU_OPTIONS = ['copy', 'view', 'chatgpt', 'claude', 'perplexity', 'mcp', 'cursor', 'vscode'] as const;
920
+ export type ContextMenuOption = (typeof CONTEXT_MENU_OPTIONS)[number];
921
+ const ASSISTANT_OPTIONS = ['chatgpt', 'claude', 'perplexity'] as const;
922
+ /** The options that point at the site's MCP server - see `mcp` below. */
923
+ export const MCP_MENU_OPTIONS = ['mcp', 'cursor', 'vscode'] as const;
924
+
925
+ const contextMenuSchema = z.union([
926
+ z.boolean(),
927
+ z.array(z.enum(CONTEXT_MENU_OPTIONS)),
928
+ z
929
+ .object({
930
+ openIn: z.array(z.enum(ASSISTANT_OPTIONS)).optional(),
931
+ })
932
+ .strict(),
933
+ ]);
934
+
935
+ export type ContextMenuConfig = z.infer<typeof contextMenuSchema>;
936
+
937
+ /** The menu options a writedocs.json `contextMenu` value turns on, in menu
938
+ * order - [] when the menu is off. Takes the raw value too (link-check.js
939
+ * reads writedocs.json without the schema), so absent means every option.
940
+ * With `mcp: false` (no MCP server), the MCP options are left out. */
941
+ export function contextMenuOptions(value: unknown, { mcp = true }: { mcp?: boolean } = {}): ContextMenuOption[] {
942
+ const available = CONTEXT_MENU_OPTIONS.filter((option) => mcp || !(MCP_MENU_OPTIONS as readonly string[]).includes(option));
943
+ if (value === false) return [];
944
+ if (value === undefined || value === null || value === true) return [...available];
945
+ if (Array.isArray(value)) return available.filter((option) => value.includes(option));
946
+ if (typeof value === 'object') {
947
+ const openIn = (value as { openIn?: unknown }).openIn;
948
+ const assistants = Array.isArray(openIn) ? openIn : [...ASSISTANT_OPTIONS];
949
+ return CONTEXT_MENU_OPTIONS.filter((option) => option === 'copy' || option === 'view' || assistants.includes(option));
950
+ }
951
+ return [];
952
+ }
953
+
954
+ // One entry in writedocs.json's `redirects` array - wired almost directly into
955
+ // Astro's own `redirects` config option (astro.config.mjs), which is what
956
+ // actually generates the redirect pages. `permanent` is deliberately not
957
+ // part of this schema: with no server/adapter (this project always builds
958
+ // `output: 'static'` with none installed), Astro's own docs say a static
959
+ // redirect "does not support status codes" at all - it's always a client-
960
+ // side `<meta http-equiv="refresh">` page, full stop. Accepting a
961
+ // `permanent` field here that silently did nothing would be worse than
962
+ // not offering it.
963
+ const redirectSchema = z
964
+ .object({
965
+ source: z.string(),
966
+ destination: z.string(),
967
+ })
968
+ .strict();
969
+
970
+ export type RedirectConfig = z.infer<typeof redirectSchema>;
971
+
972
+ // A site-wide banner rendered above the topbar on every page (except
973
+ // `mode: blank`, which drops all site chrome including this - see
974
+ // BaseLayout.astro). Optional/undefined by default, same convention as
975
+ // `contextMenu` above - a site with no banner configured gets no banner
976
+ // markup at all, not an empty one.
977
+ const bannerSchema = z
978
+ .object({
979
+ content: z.string(),
980
+ // Persisted via localStorage once dismissed (see BaseLayout.astro's
981
+ // initBanner()) - a static site has no server-side session to track
982
+ // this against, so "dismissed" only ever means "dismissed in this
983
+ // browser". A banner without `dismissible` reappears on every visit,
984
+ // appropriate for something that should stay visible until the site
985
+ // author removes it from writedocs.json themselves (e.g. "this version is
986
+ // deprecated"), not something a reader can permanently clear.
987
+ dismissible: z.boolean().default(false),
988
+ type: z.enum(['info', 'warning', 'critical']).default('info'),
989
+ })
990
+ .strict();
991
+
992
+ export type BannerConfig = z.infer<typeof bannerSchema>;
993
+
994
+ // Content for the custom 404 page (src/pages/404.astro) - Astro's own
995
+ // file-based convention (a static build emits this as 404.html at the
996
+ // site root; most static hosts pick it up automatically for unmatched
997
+ // routes). Both fields are optional with hardcoded fallbacks in 404.astro
998
+ // itself, so a site doesn't have to set either to get a reasonably
999
+ // branded 404 page (still rendered inside the normal BaseLayout/topbar
1000
+ // chrome, just with placeholder content).
1001
+ const notFoundSchema = z
1002
+ .object({
1003
+ title: z.string().optional(),
1004
+ description: z.string().optional(),
1005
+ })
1006
+ .strict()
1007
+ .default({});
1008
+
1009
+ export type NotFoundConfig = z.infer<typeof notFoundSchema>;
1010
+
1011
+ // One <script> tag to inject - exactly one of `src` (an external/local
1012
+ // file, rendered as `<script src="...">`) or `content` (inline JS,
1013
+ // rendered via `<script is:inline set:html="...">`) has to be set, not
1014
+ // both and not neither - enforced by the `.refine()` below rather than
1015
+ // leaving both optional and silently rendering an empty tag if a site
1016
+ // author gets this wrong.
1017
+ const scriptEntrySchema = z
1018
+ .object({
1019
+ src: z.string().optional(),
1020
+ content: z.string().optional(),
1021
+ // With `integrations.consent` on, a script marked `true` loads only
1022
+ // once the reader accepts, like the analytics integrations. Without the
1023
+ // banner it loads as any other script.
1024
+ consent: z.boolean().optional(),
1025
+ })
1026
+ .strict()
1027
+ .refine((v) => (v.src ? !v.content : !!v.content), {
1028
+ message: 'Each scripts.head/scripts.body entry needs exactly one of "src" or "content", not both or neither.',
1029
+ });
1030
+
1031
+ export type ScriptEntry = z.infer<typeof scriptEntrySchema>;
1032
+
1033
+ // Raw third-party script injection - analytics snippets, chat widgets,
1034
+ // anything that needs a real <script> tag writedocs.json's own structured
1035
+ // fields (styles, integrations-style config, ...) don't have a dedicated
1036
+ // slot for yet. `head` renders right before </head>; `body` renders right
1037
+ // before </body> (after everything else has already loaded/hydrated -
1038
+ // see BaseLayout.astro), matching where a third-party script's own
1039
+ // install instructions usually say to put it.
1040
+ const scriptsSchema = z
1041
+ .object({
1042
+ head: z.array(scriptEntrySchema).default([]),
1043
+ body: z.array(scriptEntrySchema).default([]),
1044
+ })
1045
+ .strict()
1046
+ .default({ head: [], body: [] });
1047
+
1048
+ export type ScriptsConfig = z.infer<typeof scriptsSchema>;
1049
+
1050
+ // writedocs.json's `integrations` - a curated, high-value subset of analytics
1051
+ // providers, each getting its own minimal config object (just the id(s)
1052
+ // it actually needs) rather than requiring a site author to hand-write
1053
+ // the provider's own install snippet through the generic `scripts` field
1054
+ // above. This is deliberately its own thing, not built as sugar over
1055
+ // `scripts` the way the roadmap once implied it might be - most of these
1056
+ // providers' real snippets need `defer`/`async`/`data-*` attributes
1057
+ // ScriptEntry's plain `{ src?, content? }` shape has no way to express,
1058
+ // so BaseLayout.astro renders each provider with its own bespoke markup
1059
+ // instead of generating a ScriptEntry array to feed through the generic
1060
+ // renderer. Every snippet shape below was sourced from that provider's
1061
+ // own current official docs (fetched directly, not recalled from
1062
+ // training data) while building this feature - see
1063
+ // docs/dev/docs/integrations.mdx for links and dates.
1064
+ //
1065
+ // Every provider field is optional and independent - a site can turn on
1066
+ // any subset (including all of them at once, for a migration period) or
1067
+ // none. No "the" analytics field; a site picks whichever provider(s) it
1068
+ // actually uses.
1069
+
1070
+ const ga4IntegrationSchema = z
1071
+ .object({
1072
+ // A GA4 "Measurement ID", always shaped like "G-XXXXXXXXXX" - not
1073
+ // validated against that shape here, since Google could change the
1074
+ // prefix/length without this schema needing to track it.
1075
+ measurementId: z.string(),
1076
+ })
1077
+ .strict();
1078
+
1079
+ const googleTagManagerIntegrationSchema = z
1080
+ .object({
1081
+ // A GTM container id, shaped like "GTM-XXXXXXX".
1082
+ containerId: z.string(),
1083
+ })
1084
+ .strict();
1085
+
1086
+ const plausibleIntegrationSchema = z
1087
+ .object({
1088
+ domain: z.string(),
1089
+ // Plausible's own hosted script URL by default - override for a
1090
+ // self-hosted instance, a reverse-proxy path (Plausible's own
1091
+ // documented way to dodge ad-blockers), or one of Plausible's
1092
+ // documented script *extensions* (e.g.
1093
+ // "https://plausible.io/js/script.hash.outbound-links.js").
1094
+ src: z.string().default('https://plausible.io/js/script.js'),
1095
+ })
1096
+ .strict();
1097
+
1098
+ const fathomIntegrationSchema = z
1099
+ .object({
1100
+ // Fathom's own short "Site ID", not a full URL or measurement id.
1101
+ siteId: z.string(),
1102
+ })
1103
+ .strict();
1104
+
1105
+ const posthogIntegrationSchema = z
1106
+ .object({
1107
+ // PostHog calls this a "project API key" (starts with "phc_") in its
1108
+ // own docs - `apiKey` here rather than that exact name, matching this
1109
+ // schema's own plainer naming convention for the equivalent id on
1110
+ // every other provider above.
1111
+ apiKey: z.string(),
1112
+ // PostHog is region-sharded (US/EU) with no single universal default
1113
+ // - "https://us.i.posthog.com" is PostHog's own default for a new
1114
+ // project, but a site on their EU cloud (or a self-hosted instance)
1115
+ // must override this to the host shown in their own project
1116
+ // settings, or events silently go nowhere.
1117
+ apiHost: z.string().default('https://us.i.posthog.com'),
1118
+ })
1119
+ .strict();
1120
+
1121
+ const umamiIntegrationSchema = z
1122
+ .object({
1123
+ websiteId: z.string(),
1124
+ // Unlike Plausible/PostHog, Umami has no single hosted default that
1125
+ // works for most users - it's commonly self-hosted, and even Umami
1126
+ // Cloud users get a per-region script URL. Defaults to Umami Cloud's
1127
+ // own documented script URL, which only happens to be correct for a
1128
+ // Cloud user on that specific region; anyone self-hosting (the more
1129
+ // common case for this particular provider) must override it to
1130
+ // their own instance's own /script.js path.
1131
+ src: z.string().default('https://cloud.umami.is/script.js'),
1132
+ })
1133
+ .strict();
1134
+
1135
+ // AI chat over the site's own docs content, via a third-party provider
1136
+ // (DocsBot, currently the only one wired up) rather than a self-hosted
1137
+ // RAG pipeline - see the roadmap's own "AI chat over docs content" line
1138
+ // in docs/dev/docs/roadmap.mdx, which this fulfills via integration
1139
+ // rather than by building the retrieval/generation stack in-house.
1140
+ // Deliberately named `askAi` here, not `docsbot` - this is the
1141
+ // writedocs.json-facing, provider-neutral name for the feature (matching
1142
+ // the "Ask AI" label this kind of button/widget is conventionally
1143
+ // given in docs sites generally), independent of which vendor happens
1144
+ // to sit behind it today. `id` matches DocsBot's own embed config
1145
+ // field name exactly (`DocsBotAI.init({ id: 'teamId/botId' })`) - it's
1146
+ // a single opaque "teamId/botId" string DocsBot treats as one value,
1147
+ // not two separate ids, so this schema doesn't split it either.
1148
+ const askAiIntegrationSchema = z
1149
+ .object({
1150
+ id: z.string(),
1151
+ })
1152
+ .strict();
1153
+
1154
+ // A consent banner for the analytics integrations above: with it, none of
1155
+ // their scripts load until the reader accepts (see lib/consent.js and
1156
+ // ConsentBanner.astro). `true` uses the default texts; an object changes
1157
+ // them. The reader's answer is kept in the browser's localStorage.
1158
+ const consentSchema = z.union([
1159
+ z.boolean(),
1160
+ z
1161
+ .object({
1162
+ message: z.string().optional(),
1163
+ acceptLabel: z.string().optional(),
1164
+ declineLabel: z.string().optional(),
1165
+ // A link after the message - a privacy or cookie policy.
1166
+ policyUrl: z.string().optional(),
1167
+ policyLabel: z.string().optional(),
1168
+ })
1169
+ .strict(),
1170
+ ]);
1171
+
1172
+ const integrationsSchema = z
1173
+ .object({
1174
+ ga4: ga4IntegrationSchema.optional(),
1175
+ googleTagManager: googleTagManagerIntegrationSchema.optional(),
1176
+ plausible: plausibleIntegrationSchema.optional(),
1177
+ fathom: fathomIntegrationSchema.optional(),
1178
+ posthog: posthogIntegrationSchema.optional(),
1179
+ umami: umamiIntegrationSchema.optional(),
1180
+ askAi: askAiIntegrationSchema.optional(),
1181
+ consent: consentSchema.optional(),
1182
+ })
1183
+ .strict()
1184
+ .default({});
1185
+
1186
+ export type IntegrationsConfig = z.infer<typeof integrationsSchema>;
1187
+
1188
+ export const docsConfigSchema = z.object({
1189
+ name: z.string(),
1190
+ description: z.string().optional(),
1191
+ styles: stylesSchema,
1192
+ navigation: navigationSchema,
1193
+ // Platform name -> profile/page URL (e.g. `{ "github": "https://
1194
+ // github.com/...", "twitter": "https://twitter.com/..." }`), free-form
1195
+ // rather than an enum of known platforms - the key doubles as the icon
1196
+ // reference BaseLayout.astro's footer resolves via resolveIcon() below
1197
+ // (bare `"github"` -> `lucide:github`; use an explicit
1198
+ // `"simple-icons:whatever"` key instead when the bare lucide name isn't
1199
+ // right for a given platform). Rendered as a row of icon links in the
1200
+ // footer - see hasFooterContent/`.wd-footer-socials` in BaseLayout.astro.
1201
+ socials: z.record(z.string(), z.string()).default({}),
1202
+ topbar: z
1203
+ .object({ links: z.array(topbarLinkSchema).default([]) })
1204
+ .default({ links: [] }),
1205
+ // Columns of links below the page content - see footerSchema/
1206
+ // footerColumnSchema above. Renders alongside `socials` above (as a row
1207
+ // of icon links) in the same <footer> - see BaseLayout.astro.
1208
+ footer: footerSchema,
1209
+ api: apiSchema,
1210
+ // The site's own deployed domain, e.g. "docs.example.com" or
1211
+ // "https://docs.example.com" (the scheme is optional - resolveSiteUrl()
1212
+ // below normalizes either form to a full https:// origin). Powers three
1213
+ // things that all need an absolute origin to work: sitemap.xml
1214
+ // generation (astro.config.mjs only registers @astrojs/sitemap when this
1215
+ // is set - a sitemap of relative URLs isn't meaningful), the canonical
1216
+ // <link> and og:url/twitter meta tags (BaseLayout.astro), and resolving
1217
+ // a relative `seo.ogImage` into an absolute URL for social crawlers.
1218
+ // Left optional and simply skipped (with a log message, not an error) at
1219
+ // every one of those call sites when unset - most fixtures/local builds
1220
+ // have no real deployed domain yet.
1221
+ domain: z.string().optional(),
1222
+ // Site-wide meta tag defaults - see seoFieldsSchema above. A page's own
1223
+ // frontmatter `seo` (content.config.ts's docsSchema) overrides these
1224
+ // field by field via mergeSeo(), rather than needing to repeat every
1225
+ // field on every page.
1226
+ seo: siteSeoFieldsSchema.default({}),
1227
+ // The "Copy page" menu - see contextMenuSchema above. Absent means on,
1228
+ // with every option; read it through contextMenuOptions().
1229
+ contextMenu: contextMenuSchema.optional(),
1230
+ // The site's MCP server - an AI tool connects to `/mcp` and searches and
1231
+ // reads the docs. On by default: `writedocs build` writes the page index
1232
+ // (mcp-index.json) and a Cloudflare-ready `_worker.js` into dist/ (see
1233
+ // src/cli/write-mcp-files.js). `false` leaves all of it out.
1234
+ mcp: z.boolean().default(true),
1235
+ // See redirectSchema above. Wired directly into Astro's own `redirects`
1236
+ // config option in astro.config.mjs.
1237
+ redirects: z.array(redirectSchema).default([]),
1238
+ // Site-wide `[[key]]` substitution values, applied to page prose text
1239
+ // at build time (see the remarkSubstituteVariables plugin wired into
1240
+ // astro.config.mjs) - e.g. `{ "productName": "Acme" }` lets every page
1241
+ // write `[[productName]]` once instead of hardcoding it everywhere.
1242
+ // Double square brackets, not the more familiar `{{key}}` - MDX
1243
+ // reserves single curly braces for embedded JS expressions, so
1244
+ // `{{productName}}` in an .mdx file parses as a JS object-literal
1245
+ // expression (`{productName}`, shorthand syntax) rather than literal
1246
+ // text, and throws `ReferenceError: productName is not defined` at
1247
+ // render time - see remarkSubstituteVariables' own comment in
1248
+ // mdx-substitute-variables.js for the full explanation. Deliberately a
1249
+ // flat string map, not typed values - this is text substitution into
1250
+ // prose, not a templating language.
1251
+ variables: z.record(z.string(), z.string()).default({}),
1252
+ // See bannerSchema above. Absent by default (no banner rendered).
1253
+ banner: bannerSchema.optional(),
1254
+ // See notFoundSchema above.
1255
+ notFound: notFoundSchema,
1256
+ // See scriptsSchema above.
1257
+ scripts: scriptsSchema,
1258
+ // See integrationsSchema above.
1259
+ integrations: integrationsSchema,
1260
+ });
1261
+
1262
+ export type DocsConfig = z.infer<typeof docsConfigSchema>;
1263
+
1264
+ // ---------------------------------------------------------------------
1265
+ // Ponto de entrada unico de validacao
1266
+ //
1267
+ // Existe pra que o gerador (`writedocs validate` e o `loadDocsConfig` que o
1268
+ // build usa) e a plataforma validem pelo MESMO codigo, com as MESMAS palavras -
1269
+ // o criterio de aceite do WD-066 e do WD-062. Se cada lado formatasse os erros
1270
+ // por conta propria, o cliente veria a plataforma aceitar um writedocs.json que
1271
+ // o build depois recusa, que e exatamente a classe de bug que a E11 existe pra
1272
+ // impedir.
1273
+ //
1274
+ // Recebe TEXTO CRU, e faz o JSON.parse por conta propria, por tres motivos:
1275
+ // 1. um JSON sintaticamente quebrado passa a ser um resultado de validacao
1276
+ // como qualquer outro, em vez de uma excecao solta do runtime;
1277
+ // 2. linha/coluna so existem no texto - e o WD-063 precisa reportar linha;
1278
+ // 3. do lado da plataforma, importProjectConfig ja tem os bytes crus em maos
1279
+ // antes de parsear, entao encaixa sem ginastica nenhuma.
1280
+ //
1281
+ // IMPORTANTE, e deliberado: as mensagens aqui sao as do Zod, VERBATIM. Melhorar
1282
+ // a linguagem delas e o WD-063, que precisa deste comportamento como ponto de
1283
+ // partida pra medir a melhora. Nada aqui reescreve, traduz ou embeleza mensagem.
1284
+ // ---------------------------------------------------------------------
1285
+
1286
+ /** Um problema encontrado na configuracao. `path` e o caminho do campo em
1287
+ * notacao de ponto (`navigation.tabs.0.label`), ou `(root)` quando o problema e
1288
+ * do documento inteiro - o mesmo texto que a mensagem de erro do build ja
1289
+ * imprime hoje. `line`/`column` so vem quando da pra saber (hoje: erro de JSON;
1290
+ * no WD-063, tambem para erros de schema). */
1291
+ export type ValidationIssue = {
1292
+ path: string;
1293
+ message: string;
1294
+ /** Codigo do Zod (`invalid_type`, `unrecognized_keys`, ...) ou `invalid_json`. */
1295
+ code?: string;
1296
+ line?: number;
1297
+ column?: number;
1298
+ /** WD-063: a mesma coisa que `message`, dita para gente. ADICIONAL, nunca
1299
+ * substituto - `message` continua sendo o texto do Zod verbatim, que e o que
1300
+ * o `writedocs build` imprime e o que o WD-062 grava em `validation_issues`.
1301
+ * Quem exibe escolhe qual dos dois mostrar. */
1302
+ humanMessage?: string;
1303
+ /** O que fazer a respeito, quando da pra dizer algo concreto. */
1304
+ suggestion?: string;
1305
+ /** Chave ESTAVEL de documentacao (`config.styles`), nunca uma URL: uma URL
1306
+ * cravada num pacote npm fica quebrada em toda instalacao ate a proxima
1307
+ * release, e o mesmo erro e exibido pela CLI e pelo dashboard, que podem
1308
+ * querer destinos diferentes. O mapa chave -> URL mora do lado de quem
1309
+ * renderiza. */
1310
+ docKey?: string;
1311
+ };
1312
+
1313
+ /** Sucesso carrega os dados ja validados (com os defaults do schema aplicados);
1314
+ * falha carrega os problemas e diz de que tipo ela foi. `parseError` so aparece
1315
+ * quando o JSON nao pode nem ser parseado, e existe para o chamador que quiser
1316
+ * relancar exatamente o erro original (e o que o loadDocsConfig faz, pra nao
1317
+ * mudar uma virgula do que o `writedocs build` ja imprime hoje). */
1318
+ export type ValidationResult =
1319
+ | { ok: true; data: DocsConfig; issues: ValidationIssue[] }
1320
+ | {
1321
+ ok: false;
1322
+ data: null;
1323
+ kind: 'invalid_json' | 'schema';
1324
+ issues: ValidationIssue[];
1325
+ parseError?: SyntaxError;
1326
+ };
1327
+
1328
+ /** "at position 22 (line 1 column 23)" -> { line: 1, column: 23 }.
1329
+ * O formato da mensagem de erro do JSON.parse e do V8, nao do padrao, entao
1330
+ * isto e melhor-esforco: se a mensagem nao trouxer posicao, devolve null e o
1331
+ * problema simplesmente fica sem linha. */
1332
+ function positionFromJsonError(message: string, rawText: string): { line: number; column: number } | null {
1333
+ const comLinha = message.match(/line (\d+) column (\d+)/);
1334
+ if (comLinha) return { line: Number(comLinha[1]), column: Number(comLinha[2]) };
1335
+ const comPosicao = message.match(/position (\d+)/);
1336
+ if (comPosicao) {
1337
+ const pos = Math.min(Number(comPosicao[1]), rawText.length);
1338
+ const antes = rawText.slice(0, pos);
1339
+ const line = antes.split('\n').length;
1340
+ return { line, column: pos - antes.lastIndexOf('\n') };
1341
+ }
1342
+ return null;
1343
+ }
1344
+
1345
+ /** O corpo da mensagem de erro, uma linha por problema - exatamente o formato
1346
+ * que o `writedocs build` imprime desde sempre (` - campo: mensagem`). Fica
1347
+ * aqui, e nao em cada chamador, pra que CLI e plataforma nao possam divergir.
1348
+ *
1349
+ * NAO mudou no WD-063, de proposito: continua imprimindo `message` (o texto do
1350
+ * Zod). O que melhorou foi o CONTEUDO dos issues - a uniao desembrulhada faz o
1351
+ * `path` apontar pro campo real em vez de parar em `navigation`. Quem quiser a
1352
+ * versao com frase humana e linha usa formatValidationIssuesDetailed. */
1353
+ export function formatValidationIssues(issues: ValidationIssue[]): string {
1354
+ return issues.map((i) => ` - ${i.path}: ${i.message}`).join('\n');
1355
+ }
1356
+
1357
+ /** A versao longa, para quem tem uma tela inteira (a CLI hoje, o dashboard do
1358
+ * WD-065 se quiser): caminho, linha, frase humana, sugestao, e a mensagem do
1359
+ * Zod por ultimo, entre parenteses, pra quem precisa do texto exato.
1360
+ *
1361
+ * Mora aqui pelo mesmo motivo que a irma curta: se cada consumidor montasse a
1362
+ * sua, a CLI e a plataforma divergiriam na primeira mudanca - que e exatamente
1363
+ * o que o AC do WD-066 proibe. `fileName` so entra na referencia de linha. */
1364
+ export function formatValidationIssuesDetailed(
1365
+ issues: ValidationIssue[],
1366
+ { fileName = 'writedocs.json' }: { fileName?: string } = {}
1367
+ ): string {
1368
+ return issues
1369
+ .map((i) => {
1370
+ const temCampo = i.path !== '(root)';
1371
+ const local = i.line ? `${fileName}:${i.line}` : i.path;
1372
+ const linhas = [` ${local}${i.line && temCampo ? ` (${i.path})` : ''}`];
1373
+ linhas.push(` ${i.humanMessage ?? i.message}`);
1374
+ if (i.suggestion) linhas.push(` ${i.suggestion}`);
1375
+ if (i.humanMessage && i.message !== i.humanMessage) linhas.push(` (${i.message})`);
1376
+ return linhas.join('\n');
1377
+ })
1378
+ .join('\n\n');
1379
+ }
1380
+
1381
+ // ---------------------------------------------------------------------
1382
+ // WD-063 — do issue do Zod para "onde esta o erro, e o que fazer"
1383
+ //
1384
+ // Tres transformacoes, nesta ordem:
1385
+ // 1. desembrulhar `invalid_union` (senao todo erro dentro da navigation vira
1386
+ // `navigation: "Invalid input"`, que e inutil num arquivo de 10 KB);
1387
+ // 2. achar a linha no texto, pelo caminho ja desembrulhado;
1388
+ // 3. escrever a frase humana, a sugestao e a docKey - POR CODIGO do Zod, nao
1389
+ // por campo: um mapa por campo teria 17 entradas so na raiz e centenas no
1390
+ // total, e envelheceria a cada campo novo do schema.
1391
+ // ---------------------------------------------------------------------
1392
+
1393
+ /** Chaves que a raiz aceita sem ser campo do schema, e que por isso NAO devem
1394
+ * gerar aviso de chave desconhecida. Deliberadamente minuscula: a raiz nao e
1395
+ * `.strict()` justamente pra nao quebrar configs existentes, e `$schema` foi um
1396
+ * dos argumentos dessa decisao - avisar sobre ele contradiria o que o protegeu.
1397
+ * Se esta lista passar de dois ou tres nomes, o problema e outro e a raiz
1398
+ * precisa de outra conversa. */
1399
+ export const ROOT_ALLOWED_EXTRA_KEYS: readonly string[] = Object.freeze(['$schema']);
1400
+
1401
+ type IssueCru = {
1402
+ code?: string;
1403
+ path?: (string | number)[];
1404
+ message: string;
1405
+ expected?: string;
1406
+ values?: unknown[];
1407
+ keys?: string[];
1408
+ minimum?: number;
1409
+ maximum?: number;
1410
+ origin?: string;
1411
+ format?: string;
1412
+ errors?: unknown[];
1413
+ unionErrors?: unknown[];
1414
+ };
1415
+
1416
+ type IssuePlano = IssueCru & { caminho: (string | number)[] };
1417
+
1418
+ function issuesDoRamo(ramo: unknown): IssueCru[] {
1419
+ if (Array.isArray(ramo)) return ramo as IssueCru[];
1420
+ const comIssues = ramo as { issues?: IssueCru[] };
1421
+ return comIssues?.issues ?? [];
1422
+ }
1423
+
1424
+ /** O maior valor de `f` sobre a lista, ou 0 se ela for vazia. Um `for` e nao
1425
+ * `Math.max(0, ...lista.map(f))`: o spread vira argumentos de chamada, e uma
1426
+ * lista grande o bastante (config com dezenas de milhares de erros) estoura o
1427
+ * limite de argumentos com RangeError em vez de devolver um numero. */
1428
+ function maiorProfundidade(lista: IssuePlano[]): number {
1429
+ let maior = 0;
1430
+ for (const issue of lista) {
1431
+ const p = issue.caminho.length + (issue.code === 'unrecognized_keys' ? 1 : 0);
1432
+ if (p > maior) maior = p;
1433
+ }
1434
+ return maior;
1435
+ }
1436
+
1437
+ /** Plano ACHATADO de um ramo, memoizado por identidade do ramo.
1438
+ *
1439
+ * A memoizacao nao e otimizacao, e o que torna o achatamento viavel. Pontuar um
1440
+ * ramo exige desembrulhar as unioes DENTRO dele, e cada uma dessas tem os seus
1441
+ * proprios ramos - sem cache, a pontuacao visita o mesmo sub-ramo uma vez por
1442
+ * caminho que leva ate ele, o que e exponencial na profundidade do aninhamento.
1443
+ * Medido com grupos aninhados e um erro no fundo: 3,7 ms com 4 niveis, 281 ms
1444
+ * com 8, 69 SEGUNDOS com 12. Com o cache, os mesmos casos ficam em 0,2 ms,
1445
+ * porque cada no da arvore de erro do Zod e achatado uma vez so.
1446
+ *
1447
+ * Se alguem remover este WeakMap por parecer supérfluo, o `writedocs validate`
1448
+ * passa a travar em configs profundas. Nao remova. */
1449
+ const planoPorRamo = new WeakMap<object, IssuePlano[]>();
1450
+
1451
+ function planoDoRamo(ramo: unknown): IssuePlano[] {
1452
+ const lista = issuesDoRamo(ramo);
1453
+ if (typeof ramo !== 'object' || ramo === null) return desembrulharUnioes(lista);
1454
+ const memoizado = planoPorRamo.get(ramo);
1455
+ if (memoizado) return memoizado;
1456
+ // Prefixo vazio de proposito: a pontuacao compara ramos entre si, entao a
1457
+ // profundidade tem que ser relativa ao proprio ramo, nao ao documento.
1458
+ const plano = desembrulharUnioes(lista);
1459
+ planoPorRamo.set(ramo, plano);
1460
+ return plano;
1461
+ }
1462
+
1463
+ /** Escolhe qual ramo de uma uniao o cliente PROVAVELMENTE quis.
1464
+ *
1465
+ * Criterio: caminho mais fundo primeiro; empate resolvido por menos issues. A
1466
+ * intuicao e a do Gabriel na spec - o ramo certo e o que nao reclama da chave
1467
+ * que o cliente usou -, e a profundidade importa porque um ramo que chegou
1468
+ * fundo antes de falhar (`products.0.product`) reconheceu a forma, enquanto um
1469
+ * que falha na raiz (`expected array, received object`) so recusou o shape.
1470
+ *
1471
+ * DUAS CORRECOES sobre a primeira versao (WD-063), as duas medidas contra o
1472
+ * `00-kitchen-sink` real - ver o relato de revisao 43:
1473
+ *
1474
+ * 1. PONTUA O RAMO ACHATADO, nao a lista crua. Um ramo que e ele proprio uma
1475
+ * uniao aparece como UM issue (`invalid_union`) no caminho vazio - ou seja,
1476
+ * com a MENOR contagem e a MENOR profundidade possiveis, sem que isso diga
1477
+ * nada sobre o quanto ele reconheceu. Era o caso mais comum que existe: um
1478
+ * item de `pages` e `string | grupo | link`, e o grupo e outra uniao, entao
1479
+ * todo erro estrutural dentro de um grupo empatava com o ramo `string` e
1480
+ * perdia pela ordem de declaracao. O cliente que escrevia
1481
+ * `{ "group": "G", "pages": 42 }` recebia "expected string, received
1482
+ * object" - conselho errado, nao so inutil. Achatando primeiro, o mesmo caso
1483
+ * vira `pages.0.pages: expected array, received number`.
1484
+ *
1485
+ * 2. PROFUNDIDADE EFETIVA: `unrecognized_keys` reporta no caminho do PAI, com a
1486
+ * chave ofensora em `keys`, entao a profundidade dele sai subestimada em 1.
1487
+ * Sem a correcao, um ramo que identificou a chave errada perde para um que
1488
+ * so exigiu um campo ausente. (`validateDocsConfig` ja fazia a mesma conta
1489
+ * para achar a LINHA; aqui ela entra tambem na pontuacao.)
1490
+ *
1491
+ * Medido sobre as 60 folhas da `navigation` do `00-kitchen-sink`, trocando o
1492
+ * tipo de cada uma: a versao anterior apontava o campo exato em 42/60 e PARAVA
1493
+ * RASO em 18/60 (sempre os mesmos 18: os que ficam sob um `pages`); esta aponta
1494
+ * 60/60 para valor escalar errado e nunca para raso. Para um objeto vazio ou
1495
+ * parcial no lugar de uma pagina, as duas ficam tecnicamente empatadas (41
1496
+ * contra 42): a anterior diz "expected string", esta lista os campos que
1497
+ * faltam para ser um grupo. E o custo aceito desta versao, e substitui o antigo
1498
+ * (`tabs` e `products` escritos juntos, que agora sai como
1499
+ * `Unrecognized key: "products"`).
1500
+ *
1501
+ * EMPATE TOTAL (mesma profundidade E mesmo numero de issues): vence o ramo
1502
+ * declarado primeiro no schema. `Array.prototype.sort` e estavel desde a
1503
+ * ES2019, entao ordenar e pegar o [0] ja entrega isso - se alguem trocar por
1504
+ * uma ordenacao instavel, o desempate vira sorteio. Duas razoes para "o
1505
+ * primeiro" em vez de "todos os empatados":
1506
+ * - um engano do cliente tem que virar UMA mensagem. Emitir os 5 ramos
1507
+ * empatados de um `"navigation": {}` produz cinco exigencias que se
1508
+ * contradizem ("tabs e obrigatorio", "versions e obrigatorio", ...);
1509
+ * - determinismo: a mesma config sempre da a mesma mensagem. Um palpite
1510
+ * instavel seria pior que um palpite ruim.
1511
+ * E nada se perde no palpite errado: `message` continua sendo o texto do Zod. */
1512
+ function melhorRamo(ramos: unknown[]): IssueCru[] {
1513
+ return ramos
1514
+ .map((ramo) => {
1515
+ const plano = planoDoRamo(ramo);
1516
+ return {
1517
+ lista: issuesDoRamo(ramo),
1518
+ n: plano.length,
1519
+ profundidade: maiorProfundidade(plano),
1520
+ };
1521
+ })
1522
+ .sort((a, b) => b.profundidade - a.profundidade || a.n - b.n)[0].lista;
1523
+ }
1524
+
1525
+ /** Desembrulha `invalid_union` recursivamente - o ramo escolhido normalmente e
1526
+ * outra uniao (cada produto da navigation e, por sua vez, uma uniao de formas),
1527
+ * entao para so quando chega num erro concreto. Sem recursao, o
1528
+ * `navigation.products.0` para em "Invalid input" de novo, um nivel abaixo. */
1529
+ function desembrulharUnioes(issues: IssueCru[], prefixo: (string | number)[] = []): IssuePlano[] {
1530
+ const saida: IssuePlano[] = [];
1531
+ for (const issue of issues) {
1532
+ const caminho = [...prefixo, ...(issue.path ?? [])];
1533
+ const ramos = issue.code === 'invalid_union' ? issue.errors ?? issue.unionErrors : null;
1534
+ if (Array.isArray(ramos) && ramos.length > 0) {
1535
+ saida.push(...desembrulharUnioes(melhorRamo(ramos), caminho));
1536
+ } else {
1537
+ saida.push({ ...issue, caminho });
1538
+ }
1539
+ }
1540
+ return saida;
1541
+ }
1542
+
1543
+ const LISTAS_DE_CONTAINER = ['tabs', 'versions', 'languages', 'dropdowns', 'products'] as const;
1544
+ const ITENS_DE_CONTAINER: Record<string, { lista: string; nome: string }> = {
1545
+ tab: { lista: 'tabs', nome: 'A tab' },
1546
+ version: { lista: 'versions', nome: 'A version' },
1547
+ language: { lista: 'languages', nome: 'A language' },
1548
+ dropdown: { lista: 'dropdowns', nome: 'A dropdown' },
1549
+ product: { lista: 'products', nome: 'A product' },
1550
+ };
1551
+
1552
+ /** Um container (`{ "tabs": [...] }`, ou um item como `{ "tab": "API", ... }`)
1553
+ * dentro de uma lista de paginas - o `pages` de um grupo, de uma tab etc., ou
1554
+ * a `navigation` em forma de lista. O Zod tenta os tres formatos de item
1555
+ * (pagina, grupo, link) e reclama de cada um: "group is required", "pages is
1556
+ * required", "tabs is not an option" - tres erros, nenhum dizendo o que houve.
1557
+ * Aqui eles viram UM, no item, dizendo onde o container pode ficar. */
1558
+ function containersEmPaginas(issues: IssuePlano[], raiz: unknown): IssuePlano[] {
1559
+ const vistos = new Set<string>();
1560
+ const saida: IssuePlano[] = [];
1561
+ for (const issue of issues) {
1562
+ const achado = containerEmPaginas(issue.caminho, raiz);
1563
+ if (!achado) {
1564
+ saida.push(issue);
1565
+ continue;
1566
+ }
1567
+ const chave = achado.caminho.join('.');
1568
+ if (vistos.has(chave)) continue;
1569
+ vistos.add(chave);
1570
+ saida.push({ ...issue, code: 'custom', caminho: achado.caminho, message: achado.mensagem, keys: undefined });
1571
+ }
1572
+ return saida;
1573
+ }
1574
+
1575
+ function containerEmPaginas(caminho: (string | number)[], raiz: unknown): { caminho: (string | number)[]; mensagem: string } | null {
1576
+ for (let k = 1; k < caminho.length; k++) {
1577
+ if (typeof caminho[k] !== 'number') continue;
1578
+ const naRaiz = k === 1 && caminho[0] === 'navigation';
1579
+ if (!naRaiz && caminho[k - 1] !== 'pages') continue;
1580
+ const item = valorEm(raiz, caminho.slice(0, k + 1));
1581
+ if (!item || typeof item !== 'object' || Array.isArray(item) || 'group' in item) continue;
1582
+ const lugar = naRaiz ? 'the navigation list' : 'a "pages" list';
1583
+ const rotulo = (texto: string) => (naRaiz ? 'The navigation list' : 'A "pages" list') + ` holds pages, groups and links only. ${texto}`;
1584
+ const lista = LISTAS_DE_CONTAINER.find((l) => l in item);
1585
+ if (lista) {
1586
+ return {
1587
+ caminho: caminho.slice(0, k + 1),
1588
+ mensagem: `"${lista}" can't go inside ${lugar}. ` + rotulo(
1589
+ naRaiz
1590
+ ? `To use ${lista}, make "navigation" an object: "navigation": { "${lista}": [ ... ] }, with the groups inside each of them.`
1591
+ : `Put "${lista}" on "navigation" itself, or on a tab, version, language, dropdown or product in place of its "pages".`
1592
+ ),
1593
+ };
1594
+ }
1595
+ const tipo = Object.keys(ITENS_DE_CONTAINER).find((t) => t in item);
1596
+ if (tipo) {
1597
+ const { lista: dela, nome } = ITENS_DE_CONTAINER[tipo];
1598
+ const nomeDoItem = (item as Record<string, unknown>)[tipo];
1599
+ return {
1600
+ caminho: caminho.slice(0, k + 1),
1601
+ mensagem: `${nome}${typeof nomeDoItem === 'string' ? ` ("${nomeDoItem}")` : ''} can't go inside ${lugar}. ` + rotulo(
1602
+ naRaiz ? `${nome} goes in a "${dela}" list: "navigation": { "${dela}": [ ... ] }.` : `${nome} goes in a "${dela}" list.`
1603
+ ),
1604
+ };
1605
+ }
1606
+ }
1607
+ return null;
1608
+ }
1609
+
1610
+ /** Exported for `writedocs validate`'s content pass (lib/content-check.js),
1611
+ * which reports writedocs.json problems of its own - navigation entries
1612
+ * with no page, unknown icons - with the same line numbers as the schema
1613
+ * errors. Same function as criarLocalizador below. */
1614
+ export function createJsonLocator(rawText: string): (path: (string | number)[]) => { line: number; column: number } | null {
1615
+ return criarLocalizador(rawText);
1616
+ }
1617
+
1618
+ /** Parseia o texto UMA vez e devolve "caminho -> linha/coluna". Devolve null
1619
+ * quando o no nao existe no texto (campo obrigatorio ausente e o caso comum):
1620
+ * `line` ausente e melhor que `line` inventada. */
1621
+ function criarLocalizador(rawText: string): (caminho: (string | number)[]) => { line: number; column: number } | null {
1622
+ rawText = semBom(rawText);
1623
+ let arvore: ReturnType<typeof parseTree> | undefined;
1624
+ try {
1625
+ arvore = parseTree(rawText);
1626
+ } catch {
1627
+ arvore = undefined;
1628
+ }
1629
+ return (caminho) => {
1630
+ if (!arvore || caminho.length === 0) return null;
1631
+ const no = findNodeAtLocation(arvore, caminho);
1632
+ if (!no) return null;
1633
+ const antes = rawText.slice(0, no.offset);
1634
+ return { line: antes.split('\n').length, column: no.offset - antes.lastIndexOf('\n') };
1635
+ };
1636
+ }
1637
+
1638
+ /** `styles.primaryColor` -> `config.styles`. Primeiro segmento so, com fallback
1639
+ * pra `config`: o conjunto tem que ficar pequeno e estavel, porque vira
1640
+ * superficie publica no instante em que alguem mapear chave -> URL. */
1641
+ function docKeyDoCaminho(caminho: (string | number)[]): string {
1642
+ const primeiro = caminho[0];
1643
+ return typeof primeiro === 'string' && primeiro ? `config.${primeiro}` : 'config';
1644
+ }
1645
+
1646
+ const ARTIGO_POR_TIPO: Record<string, string> = {
1647
+ string: 'a piece of text',
1648
+ number: 'a number',
1649
+ boolean: 'true or false',
1650
+ array: 'a list',
1651
+ object: 'an object',
1652
+ null: 'null',
1653
+ };
1654
+
1655
+ const COMO_ESCREVER: Record<string, string> = {
1656
+ string: 'Write the value in double quotes, like "Core Platform".',
1657
+ number: 'Write the value as a bare number, like 3 - no quotes.',
1658
+ boolean: 'Write true or false - no quotes.',
1659
+ array: 'Write the value as a list in square brackets: [ ... ].',
1660
+ object: 'Write the value as an object in curly braces: { ... }.',
1661
+ };
1662
+
1663
+ /** O tipo que o cliente REALMENTE escreveu, lido do JSON ja parseado em vez de
1664
+ * extraido da mensagem do Zod por regex - o Zod v4 nao carrega `received` como
1665
+ * propriedade, so dentro do texto, e depender do texto quebra na primeira vez
1666
+ * que ele mudar de forma. */
1667
+ function tipoReal(valor: unknown): string {
1668
+ if (valor === undefined) return 'missing';
1669
+ if (valor === null) return 'null';
1670
+ if (Array.isArray(valor)) return 'array';
1671
+ return typeof valor;
1672
+ }
1673
+
1674
+ function valorEm(raiz: unknown, caminho: (string | number)[]): unknown {
1675
+ let atual: unknown = raiz;
1676
+ for (const passo of caminho) {
1677
+ if (atual === null || typeof atual !== 'object') return undefined;
1678
+ atual = (atual as Record<string | number, unknown>)[passo];
1679
+ }
1680
+ return atual;
1681
+ }
1682
+
1683
+ function comoCampo(caminho: (string | number)[]): string {
1684
+ return caminho.length > 0 ? `"${caminho.join('.')}"` : 'writedocs.json';
1685
+ }
1686
+
1687
+ /** A frase de chave desconhecida, num lugar so.
1688
+ *
1689
+ * Decisao 6: chave desconhecida em sub-objeto strict e ERRO e na raiz e AVISO -
1690
+ * a assimetria de SEVERIDADE e intencional e fica. A de VOCABULARIO nao: os
1691
+ * dois caminhos chamam esta funcao, entao os dois dizem exatamente a mesma
1692
+ * coisa, e so quem chama decide o peso. */
1693
+ function fraseChaveDesconhecida(chaves: string[], dentroDe: (string | number)[]) {
1694
+ const onde = dentroDe.length > 0 ? ` inside "${dentroDe.join('.')}"` : '';
1695
+ const lista = chaves.map((k) => `"${k}"`).join(', ');
1696
+ return {
1697
+ humanMessage:
1698
+ chaves.length === 1
1699
+ ? `${lista} is not a writedocs.json option${onde}.`
1700
+ : `${lista} are not writedocs.json options${onde}.`,
1701
+ suggestion: 'Remove it, or check the spelling - options are case-sensitive.',
1702
+ };
1703
+ }
1704
+
1705
+ /** A frase humana + a sugestao, escolhidas pelo CODIGO do Zod. `raiz` e o JSON
1706
+ * ja parseado, usado so pra saber o que o cliente escreveu de fato. */
1707
+ function humanizar(issue: IssuePlano, raiz: unknown): { humanMessage?: string; suggestion?: string } {
1708
+ const campo = comoCampo(issue.caminho);
1709
+ switch (issue.code) {
1710
+ case 'invalid_type': {
1711
+ const esperado = issue.expected ?? 'a different type';
1712
+ const recebido = tipoReal(valorEm(raiz, issue.caminho));
1713
+ if (recebido === 'missing') {
1714
+ return {
1715
+ humanMessage: `${campo} is required, but writedocs.json does not set it.`,
1716
+ suggestion: `Add ${campo} with ${ARTIGO_POR_TIPO[esperado] ?? `a ${esperado}`} as its value.`,
1717
+ };
1718
+ }
1719
+ return {
1720
+ humanMessage: `${campo} must be ${ARTIGO_POR_TIPO[esperado] ?? `a ${esperado}`}, but writedocs.json has ${ARTIGO_POR_TIPO[recebido] ?? `a ${recebido}`}.`,
1721
+ suggestion: COMO_ESCREVER[esperado],
1722
+ };
1723
+ }
1724
+ case 'unrecognized_keys': {
1725
+ // O Zod agrega as chaves sobrando numa mensagem so, com o `path` no PAI.
1726
+ const chaves = issue.keys ?? [];
1727
+ if (chaves.length === 0) return {};
1728
+ return fraseChaveDesconhecida(chaves, issue.caminho);
1729
+ }
1730
+ case 'invalid_value': {
1731
+ const opcoes = (issue.values ?? []).map((v) => JSON.stringify(v)).join(', ');
1732
+ return {
1733
+ humanMessage: `${campo} must be one of: ${opcoes}.`,
1734
+ suggestion: 'Replace the value with one of the options above.',
1735
+ };
1736
+ }
1737
+ case 'too_small': {
1738
+ const unidade = issue.origin === 'array' ? 'item' : 'character';
1739
+ const minimo = issue.minimum ?? 1;
1740
+ return {
1741
+ humanMessage: `${campo} needs at least ${minimo} ${unidade}${minimo === 1 ? '' : 's'}.`,
1742
+ suggestion: issue.origin === 'array' ? 'Add an entry, or remove the field entirely.' : undefined,
1743
+ };
1744
+ }
1745
+ case 'too_big': {
1746
+ const unidade = issue.origin === 'array' ? 'item' : 'character';
1747
+ const maximo = issue.maximum ?? 0;
1748
+ return { humanMessage: `${campo} allows at most ${maximo} ${unidade}${maximo === 1 ? '' : 's'}.` };
1749
+ }
1750
+ case 'invalid_format':
1751
+ return {
1752
+ humanMessage: `${campo} is not a valid ${issue.format ?? 'value'}.`,
1753
+ suggestion: 'Check the format against the documentation for this field.',
1754
+ };
1755
+ case 'invalid_union':
1756
+ // So chega aqui se o desembrulho nao achou ramo nenhum (uniao sem
1757
+ // `errors`). Raro, mas melhor dizer o que aconteceu do que "Invalid input".
1758
+ return {
1759
+ humanMessage: `${campo} does not match any of the shapes writedocs.json accepts here.`,
1760
+ suggestion: 'Check the documentation for the shapes this field accepts.',
1761
+ };
1762
+ case 'custom':
1763
+ // As mensagens de `.refine()` deste schema ja sao frases escritas pra
1764
+ // gente ("Each scripts.head/scripts.body entry needs exactly one of..."),
1765
+ // entao reescrever seria piorar. Repassa como frase humana pra que quem
1766
+ // exibe so `humanMessage` nao fique sem nada.
1767
+ return { humanMessage: issue.message };
1768
+ default:
1769
+ return {};
1770
+ }
1771
+ }
1772
+
1773
+ /** Avisos de chave desconhecida na RAIZ.
1774
+ *
1775
+ * A raiz nao e `.strict()` (decidido no E11-desenho-geral: tornar strict
1776
+ * quebraria configs existentes), entao o Zod descarta a chave em silencio e
1777
+ * nao ha issue nenhum. Quem quiser avisar chama isto. Mora aqui, e nao na
1778
+ * plataforma, pelo motivo de sempre: era o unico texto escrito pela plataforma,
1779
+ * e enquanto ele viver la os dois lados podem divergir.
1780
+ *
1781
+ * Severidade e de quem chama - isto so descreve o problema. `validateDocsConfig`
1782
+ * deliberadamente NAO chama: um config valido continua saindo com `issues: []`,
1783
+ * porque a plataforma repassa `issues` como `errors` e um aviso ali viraria
1784
+ * erro. */
1785
+ export function unknownRootKeyIssues(rawText: string): ValidationIssue[] {
1786
+ rawText = semBom(rawText);
1787
+ let raiz: unknown;
1788
+ try {
1789
+ raiz = JSON.parse(rawText);
1790
+ } catch {
1791
+ return [];
1792
+ }
1793
+ if (raiz === null || typeof raiz !== 'object' || Array.isArray(raiz)) return [];
1794
+ const conhecidas = new Set([...Object.keys(docsConfigSchema.shape), ...ROOT_ALLOWED_EXTRA_KEYS]);
1795
+ const localizar = criarLocalizador(rawText);
1796
+ return Object.keys(raiz as Record<string, unknown>)
1797
+ .filter((chave) => !conhecidas.has(chave))
1798
+ .map((chave) => {
1799
+ const frase = fraseChaveDesconhecida([chave], []);
1800
+ return {
1801
+ path: chave,
1802
+ // O mesmo formato singular da mensagem `unrecognized_keys` do Zod, pra
1803
+ // que aviso e erro sejam indistinguiveis por quem so le `message`.
1804
+ message: `Unrecognized key: "${chave}"`,
1805
+ code: 'unrecognized_keys',
1806
+ ...(localizar([chave]) ?? {}),
1807
+ ...frase,
1808
+ // `config`, e NAO `config.<chave>`: a chave aqui e o que o cliente
1809
+ // digitou errado, e derivar a docKey dela faria cada erro de digitacao
1810
+ // inventar uma chave nova. O conjunto de docKeys tem que ser fechado -
1811
+ // `config` mais um por campo do schema, nada alem disso -, senao quem
1812
+ // mapeia chave -> URL do outro lado nao tem lista pra mapear.
1813
+ docKey: 'config',
1814
+ };
1815
+ });
1816
+ }
1817
+
1818
+ /** Texto sem o BOM do UTF-8 no inicio. Editores do Windows (Bloco de Notas, o
1819
+ * `Out-File` do PowerShell 5.1) gravam um, e o JSON.parse o rejeita com uma
1820
+ * mensagem que culpa virgulas e colchetes. Copia local, e nao import de
1821
+ * lib/config-file.js: este modulo so importa zod e jsonc-parser (ver o topo). */
1822
+ function semBom(texto: string): string {
1823
+ return texto.charCodeAt(0) === 0xfeff ? texto.slice(1) : texto;
1824
+ }
1825
+
1826
+ export function validateDocsConfig(rawText: string): ValidationResult {
1827
+ rawText = semBom(rawText);
1828
+ let raw: unknown;
1829
+ try {
1830
+ raw = JSON.parse(rawText);
1831
+ } catch (err) {
1832
+ const parseError = err as SyntaxError;
1833
+ const posicao = positionFromJsonError(parseError.message, rawText);
1834
+ return {
1835
+ ok: false,
1836
+ data: null,
1837
+ kind: 'invalid_json',
1838
+ parseError,
1839
+ issues: [
1840
+ {
1841
+ path: '(root)',
1842
+ message: parseError.message,
1843
+ code: 'invalid_json',
1844
+ ...(posicao ?? {}),
1845
+ humanMessage: 'writedocs.json is not valid JSON, so none of it could be checked.',
1846
+ suggestion: posicao
1847
+ ? `Look at line ${posicao.line} - a missing comma, an extra trailing comma, or an unclosed bracket is the usual cause.`
1848
+ : 'A missing comma, an extra trailing comma, or an unclosed bracket is the usual cause.',
1849
+ docKey: 'config',
1850
+ },
1851
+ ],
1852
+ };
1853
+ }
1854
+
1855
+ const result = docsConfigSchema.safeParse(raw);
1856
+ if (!result.success) {
1857
+ const localizar = criarLocalizador(rawText);
1858
+ return {
1859
+ ok: false,
1860
+ data: null,
1861
+ kind: 'schema',
1862
+ issues: containersEmPaginas(desembrulharUnioes(result.error.issues as IssueCru[]), raw).map((i) => {
1863
+ // Para chave desconhecida o `path` do Zod aponta pro PAI (`footer`), e a
1864
+ // chave ofensora vem em `keys`. Para a LINHA vale a pena descer ate ela
1865
+ // (`footer.banana`), que e onde o cliente precisa olhar; o `path` fica
1866
+ // como o Zod deu, pra nao mudar o que a plataforma ja grava.
1867
+ const alvoDaLinha =
1868
+ i.code === 'unrecognized_keys' && i.keys?.length ? [...i.caminho, i.keys[0]] : i.caminho;
1869
+ return {
1870
+ path: i.caminho.join('.') || '(root)',
1871
+ message: i.message,
1872
+ code: i.code,
1873
+ ...(localizar(alvoDaLinha) ?? localizar(i.caminho) ?? {}),
1874
+ ...humanizar(i, raw),
1875
+ docKey: docKeyDoCaminho(i.caminho),
1876
+ };
1877
+ }),
1878
+ };
1879
+ }
1880
+
1881
+ return { ok: true, data: result.data, issues: [] };
1882
+ }