blume 1.0.4 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/dist/cli/index.js +13255 -10232
  3. package/dist/cli/index.js.map +91 -60
  4. package/dist/types/core/config-input.d.ts +61 -1
  5. package/dist/types/core/data.d.ts +9 -0
  6. package/dist/types/core/deployment-env.d.ts +6 -0
  7. package/dist/types/core/diagnostics.d.ts +23 -0
  8. package/dist/types/core/i18n-ui.d.ts +8 -8
  9. package/dist/types/core/schema.d.ts +131 -22
  10. package/dist/types/core/sources/types.d.ts +3 -1
  11. package/dist/types/core/standard-schema.d.ts +41 -0
  12. package/dist/types/core/types.d.ts +13 -0
  13. package/dist/types/og/card.d.ts +63 -0
  14. package/dist/types/og/dimensions.d.ts +12 -0
  15. package/docs/01-quickstart.mdx +1 -1
  16. package/docs/02-deployment.mdx +9 -1
  17. package/docs/advanced/api-reference.mdx +11 -0
  18. package/docs/advanced/changelog.mdx +1 -1
  19. package/docs/advanced/skills.mdx +1 -1
  20. package/docs/configuration/ai.mdx +1 -1
  21. package/docs/configuration/customization.mdx +1 -1
  22. package/docs/configuration/export.mdx +1 -1
  23. package/docs/configuration/index.mdx +21 -1
  24. package/docs/configuration/search.mdx +28 -1
  25. package/docs/configuration/seo.mdx +21 -2
  26. package/docs/configuration/theming.mdx +1 -1
  27. package/docs/content/components.mdx +14 -0
  28. package/docs/content/index.mdx +1 -1
  29. package/docs/content/meta.mdx +1 -1
  30. package/docs/content/navigation.mdx +1 -1
  31. package/docs/content/sources.mdx +1 -1
  32. package/docs/reference/cli.mdx +79 -1
  33. package/docs/reference/frontmatter.mdx +29 -1
  34. package/package.json +3 -3
  35. package/skills/blume-migrate/SKILL.md +1 -1
  36. package/skills/blume-migrate/references/mintlify.md +3 -2
  37. package/skills/blume-migrate/scripts/mintlify-codemod.mjs +16 -4
  38. package/src/ai/llms.ts +15 -0
  39. package/src/astro/adapter-root.ts +70 -0
  40. package/src/astro/generate.ts +50 -19
  41. package/src/astro/index.ts +1 -0
  42. package/src/astro/pages.ts +18 -3
  43. package/src/astro/templates.ts +65 -22
  44. package/src/audit/agent.ts +114 -0
  45. package/src/audit/catalog.ts +826 -0
  46. package/src/audit/checks/assets.ts +177 -0
  47. package/src/audit/checks/content.ts +231 -0
  48. package/src/audit/checks/duplicates.ts +131 -0
  49. package/src/audit/checks/i18n.ts +246 -0
  50. package/src/audit/checks/indexability.ts +213 -0
  51. package/src/audit/checks/links.ts +223 -0
  52. package/src/audit/checks/llms.ts +135 -0
  53. package/src/audit/checks/network.ts +272 -0
  54. package/src/audit/checks/og-image.ts +113 -0
  55. package/src/audit/checks/redirects.ts +87 -0
  56. package/src/audit/checks/robots.ts +114 -0
  57. package/src/audit/checks/sitemap.ts +229 -0
  58. package/src/audit/checks/social.ts +238 -0
  59. package/src/audit/crawl.ts +259 -0
  60. package/src/audit/graph.ts +74 -0
  61. package/src/audit/html.ts +54 -0
  62. package/src/audit/image-size.ts +63 -0
  63. package/src/audit/locate.ts +33 -0
  64. package/src/audit/redirects.ts +74 -0
  65. package/src/audit/report.ts +278 -0
  66. package/src/audit/run.ts +198 -0
  67. package/src/audit/snapshot.ts +189 -0
  68. package/src/audit/types.ts +214 -0
  69. package/src/audit/url.ts +103 -0
  70. package/src/cli/commands/audit.ts +205 -0
  71. package/src/cli/commands/build.ts +51 -12
  72. package/src/cli/index.ts +2 -0
  73. package/src/components/content/Tabs.astro +98 -15
  74. package/src/components/layout/Breadcrumbs.astro +1 -1
  75. package/src/components/layout/Header.astro +1 -0
  76. package/src/components/layout/PageFeedback.astro +1 -1
  77. package/src/components/layout/PageLayout.astro +5 -1
  78. package/src/components/layout/Pagination.astro +1 -1
  79. package/src/components/layout/RootLayout.astro +5 -3
  80. package/src/components/layout/Search.astro +35 -6
  81. package/src/components/layout/TableOfContents.astro +1 -1
  82. package/src/components/openapi/Authorization.astro +80 -0
  83. package/src/components/openapi/Operation.astro +19 -1
  84. package/src/components/openapi/ParametersTable.astro +1 -1
  85. package/src/components/openapi/security.ts +201 -0
  86. package/src/components/openapi/snippets.ts +42 -13
  87. package/src/core/config-input.ts +66 -1
  88. package/src/core/data.ts +9 -1
  89. package/src/core/deployment-env.ts +9 -0
  90. package/src/core/diagnostics.ts +59 -12
  91. package/src/core/links.ts +2 -91
  92. package/src/core/nav-diagnostics.ts +48 -4
  93. package/src/core/probe.ts +136 -0
  94. package/src/core/project-graph.ts +8 -0
  95. package/src/core/schema.ts +86 -3
  96. package/src/core/sources/normalize.ts +198 -25
  97. package/src/core/sources/types.ts +3 -1
  98. package/src/core/standard-schema.ts +54 -0
  99. package/src/core/types.ts +13 -0
  100. package/src/deploy/adapter-output.ts +27 -15
  101. package/src/deploy/headers.ts +66 -0
  102. package/src/deploy/redirects.ts +49 -9
  103. package/src/og/card.ts +98 -33
  104. package/src/og/index.ts +1 -1
  105. package/src/search/popular.ts +33 -0
  106. package/src/theme/entry.ts +6 -1
@@ -55,10 +55,13 @@ const collectIcons = (
55
55
  };
56
56
 
57
57
  /** Warn about icon names that aren't in Blume's set (skipping image/SVG icons). */
58
- export const validateNavIcons = (navigation: Navigation): Diagnostic[] => {
58
+ const unknownIconDiagnostics = (
59
+ icons: { icon: string; where: string }[],
60
+ suggestion: string
61
+ ): Diagnostic[] => {
59
62
  const seen = new Set<string>();
60
63
  const diagnostics: Diagnostic[] = [];
61
- for (const { icon, where } of collectIcons(navigation)) {
64
+ for (const { icon, where } of icons) {
62
65
  if (isAssetIcon(icon) || hasIcon(icon) || seen.has(icon)) {
63
66
  continue;
64
67
  }
@@ -67,13 +70,54 @@ export const validateNavIcons = (navigation: Navigation): Diagnostic[] => {
67
70
  code: "BLUME_UNKNOWN_ICON",
68
71
  message: `Unknown icon "${icon}" (${where}) — it isn't in Blume's icon set.`,
69
72
  severity: "warning",
70
- suggestion:
71
- "Use a built-in icon name, an image path/URL, or inline SVG markup.",
73
+ suggestion,
72
74
  });
73
75
  }
74
76
  return diagnostics;
75
77
  };
76
78
 
79
+ /** Warn about icon names that aren't in Blume's set (skipping image/SVG icons). */
80
+ export const validateNavIcons = (navigation: Navigation): Diagnostic[] =>
81
+ unknownIconDiagnostics(
82
+ collectIcons(navigation),
83
+ "Use a built-in icon name, an image path/URL, or inline SVG markup."
84
+ );
85
+
86
+ /**
87
+ * Warn about unknown icons on curated `search.popular` links. Separate from
88
+ * {@link validateNavIcons} because these live under `search`, not the built
89
+ * navigation — and unlike nav icons they resolve in a *client* island, so only
90
+ * set names work (an image/SVG icon quietly falls back to the file glyph).
91
+ */
92
+ export const validateSearchPopularIcons = (
93
+ popular: { icon?: string; label: string }[]
94
+ ): Diagnostic[] => {
95
+ const icons = popular.flatMap((link) =>
96
+ link.icon
97
+ ? [{ icon: link.icon, where: `popular link "${link.label}"` }]
98
+ : []
99
+ );
100
+ // Asset icons are valid in the nav, so the shared helper skips them — but
101
+ // here they are exactly the silent failure this validator exists to catch.
102
+ const diagnostics: Diagnostic[] = [];
103
+ const seen = new Set<string>();
104
+ for (const { icon, where } of icons) {
105
+ if (isAssetIcon(icon) && !seen.has(icon)) {
106
+ seen.add(icon);
107
+ diagnostics.push({
108
+ code: "BLUME_UNKNOWN_ICON",
109
+ message: `Icon "${icon}" (${where}) is an image or inline SVG — popular links render in the client search island, where only built-in icon names resolve, so it falls back to the file glyph.`,
110
+ severity: "warning",
111
+ suggestion: "Use a built-in icon name.",
112
+ });
113
+ }
114
+ }
115
+ return [
116
+ ...diagnostics,
117
+ ...unknownIconDiagnostics(icons, "Use a built-in icon name."),
118
+ ];
119
+ };
120
+
77
121
  /** Whether an internal path resolves to a page or a section that has pages. */
78
122
  const resolvesToPages = (routes: Set<string>, path: string): boolean =>
79
123
  routes.has(path) || [...routes].some((route) => route.startsWith(`${path}/`));
@@ -0,0 +1,136 @@
1
+ import type { DiagnosticSeverity } from "./types.ts";
2
+
3
+ export const PROBE_CONCURRENCY = 8;
4
+ export const PROBE_TIMEOUT_MS = 10_000;
5
+
6
+ const STATUS_NOT_FOUND = 404;
7
+ const STATUS_GONE = 410;
8
+ const STATUS_METHOD_NOT_ALLOWED = 405;
9
+ const STATUS_NOT_IMPLEMENTED = 501;
10
+
11
+ /** The outcome of a single HTTP probe, with failures normalized rather than thrown. */
12
+ export interface ProbeResult {
13
+ ok: boolean;
14
+ status?: number;
15
+ timedOut?: boolean;
16
+ error?: string;
17
+ /** Whether the request was redirected before landing on `status`. */
18
+ redirected?: boolean;
19
+ /** The URL finally landed on, after following redirects. */
20
+ finalUrl?: string;
21
+ /** `Content-Encoding` of the response, when the server set one. */
22
+ encoding?: string | null;
23
+ /** Wall-clock milliseconds for the request. */
24
+ ms?: number;
25
+ /** `X-Robots-Tag` of the response, when the server set one. */
26
+ robotsTag?: string | null;
27
+ }
28
+
29
+ /** Probe a URL with the given method, normalizing failures to a result. */
30
+ const request = async (
31
+ url: string,
32
+ method: "GET" | "HEAD",
33
+ timeoutMs: number
34
+ ): Promise<ProbeResult> => {
35
+ const controller = new AbortController();
36
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
37
+ const started = performance.now();
38
+ try {
39
+ const response = await fetch(url, {
40
+ method,
41
+ redirect: "follow",
42
+ signal: controller.signal,
43
+ });
44
+ return {
45
+ encoding: response.headers.get("content-encoding"),
46
+ finalUrl: response.url,
47
+ ms: Math.round(performance.now() - started),
48
+ ok: response.ok,
49
+ redirected: response.redirected,
50
+ robotsTag: response.headers.get("x-robots-tag"),
51
+ status: response.status,
52
+ };
53
+ } catch (error) {
54
+ if (error instanceof Error && error.name === "AbortError") {
55
+ return { ok: false, timedOut: true };
56
+ }
57
+ return {
58
+ error: error instanceof Error ? error.message : String(error),
59
+ ok: false,
60
+ };
61
+ } finally {
62
+ clearTimeout(timer);
63
+ }
64
+ };
65
+
66
+ /**
67
+ * Probe a single URL: HEAD first, falling back to GET.
68
+ *
69
+ * Plenty of servers reject HEAD outright (405/501) or drop the connection, so a
70
+ * HEAD-only probe would report healthy pages as dead.
71
+ */
72
+ export const probe = async (
73
+ url: string,
74
+ options: { timeoutMs?: number } = {}
75
+ ): Promise<ProbeResult> => {
76
+ const timeoutMs = options.timeoutMs ?? PROBE_TIMEOUT_MS;
77
+ const head = await request(url, "HEAD", timeoutMs);
78
+ const unreachable = !head.ok && head.status === undefined && !head.timedOut;
79
+ const retry =
80
+ head.status === STATUS_METHOD_NOT_ALLOWED ||
81
+ head.status === STATUS_NOT_IMPLEMENTED ||
82
+ unreachable;
83
+ return retry ? await request(url, "GET", timeoutMs) : head;
84
+ };
85
+
86
+ /** Grade a probe result into a severity + detail, or null when the URL is fine. */
87
+ export const gradeExternal = (
88
+ result: ProbeResult
89
+ ): { severity: DiagnosticSeverity; detail: string } | null => {
90
+ if (result.ok) {
91
+ return null;
92
+ }
93
+ if (result.timedOut) {
94
+ return { detail: "request timed out", severity: "warning" };
95
+ }
96
+ if (result.status === undefined) {
97
+ return { detail: result.error ?? "unreachable", severity: "error" };
98
+ }
99
+ // A 404/410 is definitively dead. A 403/429/5xx may well be rate limiting or a
100
+ // transient blip, which is not the author's bug to fix.
101
+ if (result.status === STATUS_NOT_FOUND || result.status === STATUS_GONE) {
102
+ return { detail: `HTTP ${result.status}`, severity: "error" };
103
+ }
104
+ return { detail: `HTTP ${result.status}`, severity: "warning" };
105
+ };
106
+
107
+ /**
108
+ * Probe many URLs with bounded concurrency, deduplicating first. Returns a map
109
+ * from URL to its result — the caller decides what each one means.
110
+ */
111
+ export const probeAll = async (
112
+ urls: readonly string[],
113
+ options: { concurrency?: number; timeoutMs?: number } = {}
114
+ ): Promise<Map<string, ProbeResult>> => {
115
+ const unique = [...new Set(urls)];
116
+ const results = new Map<string, ProbeResult>();
117
+ const limit = Math.min(
118
+ options.concurrency ?? PROBE_CONCURRENCY,
119
+ unique.length
120
+ );
121
+
122
+ let cursor = 0;
123
+ const worker = async (): Promise<void> => {
124
+ while (cursor < unique.length) {
125
+ const url = unique[cursor];
126
+ cursor += 1;
127
+ if (url !== undefined) {
128
+ // oxlint-disable-next-line no-await-in-loop -- bounded-concurrency pool
129
+ results.set(url, await probe(url, options));
130
+ }
131
+ }
132
+ };
133
+ await Promise.all(Array.from({ length: limit }, worker));
134
+
135
+ return results;
136
+ };
@@ -190,6 +190,13 @@ export const scanProject = async (
190
190
  discoverFolderMeta(metaSources, { localeDirs }),
191
191
  ]);
192
192
 
193
+ // Only thread `frontmatter.extend` through when a project opts in, so the
194
+ // known-key split in `normalizeEntry` stays off the default path.
195
+ const frontmatterExtend =
196
+ Object.keys(config.frontmatter.extend).length > 0
197
+ ? config.frontmatter.extend
198
+ : undefined;
199
+
193
200
  const allPages: PageRecord[] = [];
194
201
  const contentDiagnostics: Diagnostic[] = [];
195
202
  for (const { source, entries, diagnostics } of loaded) {
@@ -198,6 +205,7 @@ export const scanProject = async (
198
205
  const normalized = normalizeEntry(entry, {
199
206
  basePath: config.basePath,
200
207
  defaultType: config.content.defaultType,
208
+ frontmatterExtend,
201
209
  i18n: config.i18n,
202
210
  source: {
203
211
  name: source.name,
@@ -7,6 +7,8 @@ import { FONT_SLUGS, isFontSlug } from "../theme/fonts.ts";
7
7
  import { normalizeBasePath } from "./base-path.ts";
8
8
  import { uiLocaleOverridesSchema } from "./i18n-ui.ts";
9
9
  import type { ContentSource } from "./sources/types.ts";
10
+ import { isStandardSchema } from "./standard-schema.ts";
11
+ import type { StandardSchema } from "./standard-schema.ts";
10
12
 
11
13
  /**
12
14
  * Public Blume schemas.
@@ -514,6 +516,13 @@ const PROVIDER_CONFIG_KEY = {
514
516
  typesense: "typesense",
515
517
  } as const;
516
518
 
519
+ /** Curated link for the search dialog empty state (internal route or external URL). */
520
+ const searchPopularLinkSchema = z.strictObject({
521
+ href: z.string(),
522
+ icon: iconName.optional(),
523
+ label: z.string(),
524
+ });
525
+
517
526
  const searchConfigSchema = z
518
527
  .strictObject({
519
528
  algolia: algoliaSearchSchema.optional(),
@@ -524,6 +533,8 @@ const searchConfigSchema = z
524
533
  .default({}),
525
534
  mixedbread: mixedbreadSearchSchema.optional(),
526
535
  oramaCloud: oramaCloudSearchSchema.optional(),
536
+ /** Curated links for the Cmd+K empty state; defaults to the first sidebar pages. */
537
+ popular: z.array(searchPopularLinkSchema).default([]),
527
538
  provider: z.enum(searchProviders).default("orama"),
528
539
  typesense: typesenseSearchSchema.optional(),
529
540
  })
@@ -802,9 +813,14 @@ const xConfigSchema = z.strictObject({
802
813
  handle: xHandleSchema,
803
814
  });
804
815
 
805
- const ogColorSchema = z
806
- .string()
807
- .regex(/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/iu);
816
+ /**
817
+ * Any CSS color. Takumi parses the full grammar, so this stays unvalidated
818
+ * here and a bad value fails the OG prerender with a parse error naming it —
819
+ * the same fail-fast the card's accent relies on. Validating hex-only here
820
+ * would reject `oklch(…)`, which `theme.accent` (the card's default accent)
821
+ * already accepts.
822
+ */
823
+ const ogColorSchema = z.string();
808
824
 
809
825
  const ogPaletteSchema = z.strictObject({
810
826
  accent: ogColorSchema.optional(),
@@ -814,6 +830,28 @@ const ogPaletteSchema = z.strictObject({
814
830
  muted: ogColorSchema.optional(),
815
831
  });
816
832
 
833
+ /**
834
+ * A Google Font family to load into the OG card renderer. A bare string is the
835
+ * family name; the object form pins the weight (a number, a list, or a variable
836
+ * range like `"100..900"`) and style. Fetched from Google Fonts at build and
837
+ * handed to Takumi, which does per-glyph fallback so a family covering a script
838
+ * (e.g. Noto Sans JP for CJK) fixes tofu without touching how Latin renders.
839
+ */
840
+ const ogFontWeightSchema = z.union([
841
+ z.number().int().positive(),
842
+ z.array(z.number().int().positive()),
843
+ z.string().regex(/^\d+\.\.\d+$/u),
844
+ ]);
845
+ const ogFontStyleSchema = z.enum(["normal", "italic"]);
846
+ const ogFontSchema = z.union([
847
+ z.string(),
848
+ z.strictObject({
849
+ name: z.string(),
850
+ style: z.union([ogFontStyleSchema, z.array(ogFontStyleSchema)]).optional(),
851
+ weight: ogFontWeightSchema.optional(),
852
+ }),
853
+ ]);
854
+
817
855
  const ogConfigSchema = z.strictObject({
818
856
  /**
819
857
  * Generate a per-page Open Graph image. Defaults to on once a deployment
@@ -822,6 +860,12 @@ const ogConfigSchema = z.strictObject({
822
860
  * `loadConfig`. An explicit value here always wins.
823
861
  */
824
862
  enabled: z.boolean().optional(),
863
+ /**
864
+ * Google Font families for the generated card, extending Takumi's Latin-only
865
+ * default so non-Latin titles (CJK, and so on) render instead of tofu.
866
+ * Fetched from Google Fonts at build.
867
+ */
868
+ fonts: z.array(ogFontSchema).optional(),
825
869
  /** Local SVG used in the generated card instead of the site logo. */
826
870
  logo: z.string().optional(),
827
871
  /** Optional generated-card colors. */
@@ -1041,6 +1085,41 @@ const asyncapiConfigSchema = z.strictObject({
1041
1085
  theme: z.string().optional(),
1042
1086
  });
1043
1087
 
1088
+ /**
1089
+ * Opt-in custom frontmatter keys. `extend` maps each extra key a project's
1090
+ * pages may carry (e.g. `owner`, `reviewedAt`) to a validation schema; the
1091
+ * page schema stays strict for everything else, so typo-catching is preserved.
1092
+ * Schemas are consumed through the Standard Schema `~standard` contract —
1093
+ * never Zod's own API — so the consumer's zod (any version), Valibot, or
1094
+ * ArkType all work (see `standard-schema.ts`). Every declared key is validated
1095
+ * on every page, absent ones included, so a required schema enforces the key
1096
+ * site-wide; mark it `.optional()` to validate only when present. Built-in
1097
+ * frontmatter fields can't be redeclared — they're load-bearing (routing,
1098
+ * sidebar, SEO), and shadowing one would silently change its semantics.
1099
+ */
1100
+ const frontmatterConfigSchema = z.strictObject({
1101
+ extend: z
1102
+ .record(
1103
+ z.string(),
1104
+ z.custom<StandardSchema>(isStandardSchema, {
1105
+ message:
1106
+ "Expected a Standard Schema (e.g. a Zod schema — any Zod version works).",
1107
+ })
1108
+ )
1109
+ .default({})
1110
+ .superRefine((value, ctx) => {
1111
+ for (const key of Object.keys(value)) {
1112
+ if (Object.hasOwn(pageMetaBaseSchema.shape, key)) {
1113
+ ctx.addIssue({
1114
+ code: z.ZodIssueCode.custom,
1115
+ message: `"${key}" is a built-in frontmatter field and cannot be redeclared via frontmatter.extend.`,
1116
+ path: [key],
1117
+ });
1118
+ }
1119
+ }
1120
+ }),
1121
+ });
1122
+
1044
1123
  /** Full user-facing config schema. All fields optional with defaults. */
1045
1124
  /**
1046
1125
  * Table-of-contents config. `true`/`false` toggles it; an object narrows the
@@ -1101,6 +1180,8 @@ export const blumeConfigSchema = z.strictObject({
1101
1180
  examples: examplesConfigSchema.default("examples"),
1102
1181
  export: exportConfigSchema.default(false),
1103
1182
  feedback: z.boolean().default(true),
1183
+ /** Opt-in custom frontmatter keys, validated by user-supplied schemas. */
1184
+ frontmatter: frontmatterConfigSchema.default({}),
1104
1185
  github: githubConfigSchema.optional(),
1105
1186
  i18n: i18nConfigSchema.optional(),
1106
1187
  lastModified: lastModifiedConfigSchema.default(false),
@@ -1119,6 +1200,8 @@ export const blumeConfigSchema = z.strictObject({
1119
1200
 
1120
1201
  /** Resolved config: every field present after defaults are applied. */
1121
1202
  export type ResolvedConfig = z.infer<typeof blumeConfigSchema>;
1203
+ /** Resolved `frontmatter.extend`: custom key → user-supplied schema. */
1204
+ export type FrontmatterExtend = Record<string, StandardSchema>;
1122
1205
  /** Resolved i18n block (present only when the project opts into i18n). */
1123
1206
  export type ResolvedI18nConfig = z.infer<typeof i18nConfigSchema>;
1124
1207
  /** A configured locale with display metadata. */
@@ -4,10 +4,10 @@ import GithubSlugger from "github-slugger";
4
4
  import { extname } from "pathe";
5
5
 
6
6
  import { withBasePath } from "../base-path.ts";
7
- import { diagnosticsFromZod } from "../diagnostics.ts";
7
+ import { diagnosticsFromIssues, diagnosticsFromZod } from "../diagnostics.ts";
8
8
  import { localePlacement, localizeRoute } from "../i18n.ts";
9
9
  import { pageMetaSchema } from "../schema.ts";
10
- import type { PageMeta } from "../schema.ts";
10
+ import type { FrontmatterExtend, PageMeta } from "../schema.ts";
11
11
  import type { Diagnostic, Heading, PageLink, PageRecord } from "../types.ts";
12
12
  import type { NormalizeContext, SourceEntry } from "./types.ts";
13
13
 
@@ -131,6 +131,21 @@ const PARAGRAPH_INTERRUPT = /^ {0,3}(?:[-+*][ \t]|\d{1,9}[.)][ \t]|>)/u;
131
131
  const THEMATIC_BREAK =
132
132
  /^ {0,3}(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})$/u;
133
133
  const FRONT_MATTER_CLOSE = /^(?:-{3}|\.{3})\s*$/u;
134
+ // `<Prompt>` renders its children into a permanently `hidden` DOM node (see
135
+ // `Prompt.astro`) — the agent-facing prompt text is never visible page
136
+ // content, only read by client JS for the copy button. Any `##` inside it
137
+ // must not surface in the page's heading-derived table of contents. Tracked
138
+ // as an open/close depth, the same way fenced code blocks are tracked above.
139
+ // The opening tag is matched only at the start of a trimmed line: block-level
140
+ // JSX in MDX starts its own line, so a mention mid-prose or mid-heading —
141
+ // "the `<Prompt>` component", `## Using <Prompt>` — never opens a hidden
142
+ // region (an unanchored match here silently ate every heading after the
143
+ // mention). The lookahead rejects longer tag names that share the prefix,
144
+ // like `<PromptCard>` or `<Prompt-Custom>`.
145
+ const PROMPT_OPEN = /^<Prompt(?![\w-])/u;
146
+ // Unanchored: while inside a prompt the close tag may trail the hidden
147
+ // children text (`...copy this.</Prompt>`), not just sit on its own line.
148
+ const PROMPT_CLOSE = /<\/Prompt>/u;
134
149
 
135
150
  /**
136
151
  * The body lines, minus a leading front matter block. Bodies from the
@@ -155,13 +170,46 @@ interface HeadingScanState {
155
170
  fence: FenceState;
156
171
  /** Consecutive paragraph lines — the candidate text for a setext underline. */
157
172
  paragraph: string[];
173
+ /** Nesting depth inside `<Prompt>...</Prompt>` — 0 when outside one. */
174
+ promptDepth: number;
175
+ /** True inside a multi-line `<Prompt` opening tag, awaiting its `>`. */
176
+ promptTag: boolean;
158
177
  }
159
178
 
179
+ /**
180
+ * Consume the rest of a `<Prompt` opening tag, scanning a trimmed line from
181
+ * `start`. The tag's attributes may spread over several lines
182
+ * (`state.promptTag` carries the search onto the next one), and until the
183
+ * terminating `>` arrives it isn't known whether the tag even has children —
184
+ * so the depth only rises once that `>` is found, and not when it turns out
185
+ * to be `/>` or when the element also closes on the same line
186
+ * (`<Prompt ...>copy this</Prompt>`). Attribute values containing `>` are not
187
+ * parsed: the first `>` ends the tag, which errs toward opening a region a
188
+ * real close tag will still exit.
189
+ */
190
+ const finishPromptTag = (
191
+ line: string,
192
+ start: number,
193
+ state: HeadingScanState
194
+ ): void => {
195
+ const end = line.indexOf(">", start);
196
+ if (end === -1) {
197
+ state.promptTag = true;
198
+ return;
199
+ }
200
+ state.promptTag = false;
201
+ if (line[end - 1] === "/" || line.includes("</Prompt>", end)) {
202
+ return;
203
+ }
204
+ state.promptDepth += 1;
205
+ };
206
+
160
207
  /**
161
208
  * Extract ATX and setext headings from a markdown body, skipping fenced code
162
- * blocks, exactly as the renderer sees them: ATX headings may be indented up
163
- * to 3 spaces, and a paragraph underlined with `=`/`-` is a level 1/2 setext
164
- * heading. Each heading's anchor slug comes from a per-document
209
+ * blocks and `<Prompt>` children, exactly as the renderer sees them: ATX
210
+ * headings may be indented up to 3 spaces, and a paragraph underlined with
211
+ * `=`/`-` is a level 1/2 setext heading. Each heading's anchor slug comes
212
+ * from a per-document
165
213
  * `github-slugger` — the exact slugger the renderer uses
166
214
  * (`markdown/heading-anchors`) — advanced over every heading in document
167
215
  * order. Matching it (rather than a hand-rolled slugify) keeps the manifest's
@@ -185,6 +233,28 @@ const scanHeadingLine = (
185
233
  state.paragraph = [];
186
234
  return;
187
235
  }
236
+ // Prompt tags may be indented arbitrarily (MDX has no indented code
237
+ // blocks), so they match against the trimmed line. A tag line can't also
238
+ // be a heading, so each just updates the state and moves on, same as a
239
+ // fence delimiter line. Outside a prompt, a `</Prompt>` line is plain text.
240
+ const trimmed = line.trimStart();
241
+ if (state.promptTag) {
242
+ finishPromptTag(trimmed, 0, state);
243
+ state.paragraph = [];
244
+ return;
245
+ }
246
+ if (PROMPT_OPEN.test(trimmed)) {
247
+ finishPromptTag(trimmed, "<Prompt".length, state);
248
+ state.paragraph = [];
249
+ return;
250
+ }
251
+ if (state.promptDepth > 0) {
252
+ if (PROMPT_CLOSE.test(line)) {
253
+ state.promptDepth -= 1;
254
+ }
255
+ state.paragraph = [];
256
+ return;
257
+ }
188
258
  const atx = line.match(ATX_HEADING);
189
259
  if (atx?.groups) {
190
260
  const depth = atx.groups.hashes?.length ?? 1;
@@ -220,7 +290,12 @@ const scanHeadingLine = (
220
290
  export const extractHeadings = (body: string): Heading[] => {
221
291
  const headings: Heading[] = [];
222
292
  const slugger = new GithubSlugger();
223
- const state: HeadingScanState = { fence: null, paragraph: [] };
293
+ const state: HeadingScanState = {
294
+ fence: null,
295
+ paragraph: [],
296
+ promptDepth: 0,
297
+ promptTag: false,
298
+ };
224
299
 
225
300
  for (const line of linesWithoutFrontMatter(body)) {
226
301
  scanHeadingLine(line, state, slugger, headings);
@@ -364,6 +439,118 @@ const withPrefix = (prefix: string | undefined, path: string): string => {
364
439
  return clean ? `${clean}/${path}` : path;
365
440
  };
366
441
 
442
+ /** A custom-key validation failure, lowered to a joinable diagnostic path. */
443
+ interface CustomKeyIssue {
444
+ message: string;
445
+ path: (string | number)[];
446
+ }
447
+
448
+ /** Lower a Standard Schema path segment (`key` or `{ key }`) for joining. */
449
+ const segmentKey = (
450
+ segment: PropertyKey | { readonly key: PropertyKey }
451
+ ): string | number => {
452
+ const key =
453
+ typeof segment === "object" && segment !== null ? segment.key : segment;
454
+ return typeof key === "symbol" ? String(key) : key;
455
+ };
456
+
457
+ /**
458
+ * Validate the opt-in custom frontmatter keys (`frontmatter.extend`) through
459
+ * the Standard Schema contract — the consumer's own Zod (any version),
460
+ * Valibot, or ArkType, never Blume's bundled zod (see `standard-schema.ts`).
461
+ * Every declared key is checked, absent ones included, so a required schema
462
+ * enforces its key on every page. Async schemas are rejected with a
463
+ * diagnostic: this funnel is synchronous, and frontmatter validation has no
464
+ * business awaiting I/O.
465
+ */
466
+ const validateCustomKeys = (
467
+ data: Record<string, unknown>,
468
+ extend: FrontmatterExtend
469
+ ): { custom?: Record<string, unknown>; issues: CustomKeyIssue[] } => {
470
+ const custom: Record<string, unknown> = {};
471
+ const issues: CustomKeyIssue[] = [];
472
+ for (const [key, schema] of Object.entries(extend)) {
473
+ const outcome = schema["~standard"].validate(data[key]);
474
+ if (outcome instanceof Promise) {
475
+ issues.push({
476
+ message: "Async schemas are not supported in frontmatter.extend.",
477
+ path: [key],
478
+ });
479
+ continue;
480
+ }
481
+ if (outcome.issues !== undefined) {
482
+ issues.push(
483
+ ...outcome.issues.map((issue) => ({
484
+ message: issue.message,
485
+ path: [key, ...(issue.path ?? []).map(segmentKey)],
486
+ }))
487
+ );
488
+ continue;
489
+ }
490
+ // Preserve the validated (schema-output) value; skip keys that are absent
491
+ // and stay absent, so `.optional()` extras don't materialize as undefined.
492
+ if (outcome.value !== undefined || Object.hasOwn(data, key)) {
493
+ custom[key] = outcome.value;
494
+ }
495
+ }
496
+ return {
497
+ custom: Object.keys(custom).length > 0 ? custom : undefined,
498
+ issues,
499
+ };
500
+ };
501
+
502
+ /**
503
+ * Parse an entry's frontmatter: built-in keys through the strict page schema,
504
+ * custom keys (`frontmatter.extend`) through their user-supplied schemas. The
505
+ * custom keys are carved out before the strict parse, so the page schema stays
506
+ * strict for everything else and unknown-key typo catching is unchanged.
507
+ * Returns diagnostics instead of meta when either side rejects.
508
+ */
509
+ const parseEntryMeta = (
510
+ entry: SourceEntry,
511
+ ctx: NormalizeContext
512
+ ):
513
+ | { meta: PageMeta; custom?: Record<string, unknown>; diagnostics?: never }
514
+ | { meta?: never; diagnostics: Diagnostic[] } => {
515
+ const extend = ctx.frontmatterExtend;
516
+ const known = extend
517
+ ? Object.fromEntries(
518
+ Object.entries(entry.data).filter(
519
+ ([key]) => !Object.hasOwn(extend, key)
520
+ )
521
+ )
522
+ : entry.data;
523
+
524
+ const result = pageMetaSchema.safeParse(known);
525
+ const customResult = extend ? validateCustomKeys(entry.data, extend) : null;
526
+
527
+ if (result.success && (customResult?.issues.length ?? 0) === 0) {
528
+ return { custom: customResult?.custom, meta: result.data };
529
+ }
530
+
531
+ // Source text lets the error carry a line/column into the frontmatter block:
532
+ // `entry.raw` for non-filesystem sources, else the file itself (read only on
533
+ // this rare error path, so filesystem entries stay cheap in the happy path).
534
+ const source =
535
+ entry.raw ??
536
+ (entry.sourcePath && existsSync(entry.sourcePath)
537
+ ? readFileSync(entry.sourcePath, "utf-8")
538
+ : undefined);
539
+ const location = {
540
+ code: "BLUME_FRONTMATTER_INVALID",
541
+ file: entry.sourcePath ?? `${ctx.source.name}:${entry.ref}`,
542
+ source,
543
+ };
544
+ return {
545
+ diagnostics: [
546
+ ...(result.success ? [] : diagnosticsFromZod(result.error, location)),
547
+ ...(customResult
548
+ ? diagnosticsFromIssues(customResult.issues, location)
549
+ : []),
550
+ ],
551
+ };
552
+ };
553
+
367
554
  /**
368
555
  * Normalize one source entry into per-locale `PageRecord`s. This is the single
369
556
  * funnel every adapter's entries pass through, so route mapping, heading/link
@@ -376,27 +563,12 @@ export const normalizeEntry = (
376
563
  const { format } = entry.body;
377
564
  const ext = format === "mdx" ? ".mdx" : ".md";
378
565
 
379
- const result = pageMetaSchema.safeParse(entry.data);
380
- if (!result.success) {
381
- // Source text lets the error carry a line/column into the frontmatter block:
382
- // `entry.raw` for non-filesystem sources, else the file itself (read only on
383
- // this rare error path, so filesystem entries stay cheap in the happy path).
384
- const source =
385
- entry.raw ??
386
- (entry.sourcePath && existsSync(entry.sourcePath)
387
- ? readFileSync(entry.sourcePath, "utf-8")
388
- : undefined);
389
- return {
390
- diagnostics: diagnosticsFromZod(result.error, {
391
- code: "BLUME_FRONTMATTER_INVALID",
392
- file: entry.sourcePath ?? `${ctx.source.name}:${entry.ref}`,
393
- source,
394
- }),
395
- pages: [],
396
- };
566
+ const parsed = parseEntryMeta(entry, ctx);
567
+ if (parsed.diagnostics) {
568
+ return { diagnostics: parsed.diagnostics, pages: [] };
397
569
  }
398
570
 
399
- const meta = result.data;
571
+ const { meta } = parsed;
400
572
 
401
573
  // Top-level `hidden`/`noindex` are accepted as shorthands for their nested
402
574
  // equivalents — the schema declares them, so silently ignoring them would
@@ -439,6 +611,7 @@ export const normalizeEntry = (
439
611
  componentsUsed:
440
612
  format === "mdx" ? extractComponentTags(entry.body.text) : undefined,
441
613
  contentType: meta.type ?? ctx.defaultType,
614
+ custom: parsed.custom,
442
615
  description: meta.description,
443
616
  editUrl: entry.editUrl,
444
617
  entryId: staged ? `${ctx.source.name}/${entry.ref}` : undefined,
@@ -1,4 +1,4 @@
1
- import type { ResolvedI18nConfig } from "../schema.ts";
1
+ import type { FrontmatterExtend, ResolvedI18nConfig } from "../schema.ts";
2
2
  import type { Diagnostic } from "../types.ts";
3
3
 
4
4
  /**
@@ -109,5 +109,7 @@ export interface NormalizeContext {
109
109
  /** Site-wide route mount point (`""` or `/seg`), prepended to every route. */
110
110
  basePath?: string;
111
111
  defaultType: string;
112
+ /** Opt-in custom frontmatter keys (`frontmatter.extend`), schema per key. */
113
+ frontmatterExtend?: FrontmatterExtend;
112
114
  i18n?: ResolvedI18nConfig;
113
115
  }