blume 2.0.1 → 2.0.3

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 (492) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/dist/cli/{chunk-qwsrynx5.js → chunk-1d7ve1dm.js} +38 -19
  3. package/dist/cli/{chunk-qwsrynx5.js.map → chunk-1d7ve1dm.js.map} +4 -4
  4. package/dist/cli/{chunk-s6jhgk0q.js → chunk-2eytanqx.js} +2 -2
  5. package/dist/cli/{chunk-kdp5q7ke.js → chunk-2hsdwb9n.js} +18 -19
  6. package/dist/cli/{chunk-kdp5q7ke.js.map → chunk-2hsdwb9n.js.map} +2 -2
  7. package/dist/cli/{chunk-hdpx1tax.js → chunk-2z928egk.js} +5 -5
  8. package/dist/cli/{chunk-jwyddg7y.js → chunk-35d4wj9f.js} +30 -24
  9. package/dist/cli/chunk-35d4wj9f.js.map +15 -0
  10. package/dist/cli/{chunk-ah61y8py.js → chunk-364znk6q.js} +2 -2
  11. package/dist/cli/{chunk-jts8mvcz.js → chunk-3em5wd2y.js} +25 -6
  12. package/dist/cli/{chunk-jts8mvcz.js.map → chunk-3em5wd2y.js.map} +3 -3
  13. package/dist/cli/{chunk-s1p84fyh.js → chunk-5f86nr5m.js} +63 -22
  14. package/dist/cli/chunk-5f86nr5m.js.map +11 -0
  15. package/dist/cli/{chunk-2hn4b8z7.js → chunk-5m5nmvyq.js} +170 -76
  16. package/dist/cli/chunk-5m5nmvyq.js.map +13 -0
  17. package/dist/cli/{chunk-epjnccmv.js → chunk-5xvm6tfj.js} +18 -15
  18. package/dist/cli/chunk-5xvm6tfj.js.map +10 -0
  19. package/dist/cli/{chunk-fz5wtpmh.js → chunk-6dsbexzp.js} +18 -15
  20. package/dist/cli/chunk-6dsbexzp.js.map +10 -0
  21. package/dist/cli/{chunk-vtk4a6dg.js → chunk-8ktnccpt.js} +1 -1
  22. package/dist/cli/{chunk-6hsn950k.js → chunk-9t7a85s3.js} +178 -48
  23. package/dist/cli/chunk-9t7a85s3.js.map +10 -0
  24. package/dist/cli/{chunk-fxypxtvm.js → chunk-a58773jm.js} +2 -2
  25. package/dist/cli/{chunk-mb2919y2.js → chunk-acanzt5p.js} +17 -6
  26. package/dist/cli/chunk-acanzt5p.js.map +10 -0
  27. package/dist/cli/{chunk-27g6wdth.js → chunk-akbpwfxc.js} +90 -26
  28. package/dist/cli/chunk-akbpwfxc.js.map +10 -0
  29. package/dist/cli/{chunk-wm7js3j9.js → chunk-b07cmahc.js} +2 -2
  30. package/dist/cli/{chunk-wgm7m9qk.js → chunk-c8chx29p.js} +179 -51
  31. package/dist/cli/chunk-c8chx29p.js.map +36 -0
  32. package/dist/cli/{chunk-qs4q5p4e.js → chunk-crgn1q09.js} +32 -14
  33. package/dist/cli/chunk-crgn1q09.js.map +10 -0
  34. package/dist/cli/chunk-e04dxsz1.js +39 -0
  35. package/dist/cli/chunk-e04dxsz1.js.map +10 -0
  36. package/dist/cli/{chunk-yt5n7ppj.js → chunk-ey84smr6.js} +17 -7
  37. package/dist/cli/chunk-ey84smr6.js.map +10 -0
  38. package/dist/cli/{chunk-f2z5v128.js → chunk-g4hq16wv.js} +14 -15
  39. package/dist/cli/{chunk-f2z5v128.js.map → chunk-g4hq16wv.js.map} +2 -2
  40. package/dist/cli/{chunk-fa25z98p.js → chunk-ga0pf4aj.js} +9 -8
  41. package/dist/cli/chunk-ga0pf4aj.js.map +11 -0
  42. package/dist/cli/{chunk-kpf8rrjc.js → chunk-hm3vjy5s.js} +109 -58
  43. package/dist/cli/chunk-hm3vjy5s.js.map +19 -0
  44. package/dist/cli/{chunk-fs23ddbb.js → chunk-j85vccga.js} +625 -750
  45. package/dist/cli/chunk-j85vccga.js.map +36 -0
  46. package/dist/cli/{chunk-ch6g3ar0.js → chunk-p3v96n38.js} +6 -6
  47. package/dist/cli/{chunk-ch6g3ar0.js.map → chunk-p3v96n38.js.map} +3 -3
  48. package/dist/cli/{chunk-q5163e60.js → chunk-p73c0m7w.js} +21 -19
  49. package/dist/cli/chunk-p73c0m7w.js.map +11 -0
  50. package/dist/cli/{chunk-dh8cwk36.js → chunk-pehfxfta.js} +24 -9
  51. package/dist/cli/chunk-pehfxfta.js.map +10 -0
  52. package/dist/cli/{chunk-qkqwkpte.js → chunk-pv29h0wf.js} +3688 -1313
  53. package/dist/cli/chunk-pv29h0wf.js.map +190 -0
  54. package/dist/cli/{chunk-6vm74dry.js → chunk-q58y5e6a.js} +10 -10
  55. package/dist/cli/{chunk-6vm74dry.js.map → chunk-q58y5e6a.js.map} +3 -3
  56. package/dist/cli/{chunk-zxcczpyx.js → chunk-r20tn01b.js} +1 -1
  57. package/dist/cli/{chunk-m3vmjgmq.js → chunk-r9rcc4w7.js} +16 -8
  58. package/dist/cli/chunk-r9rcc4w7.js.map +10 -0
  59. package/dist/cli/{chunk-5shv93fd.js → chunk-tkacnehg.js} +2 -2
  60. package/dist/cli/{chunk-zxh4d9vy.js → chunk-tzmab476.js} +4 -4
  61. package/dist/cli/{chunk-yw7dm696.js → chunk-vg9r4eb9.js} +24 -11
  62. package/dist/cli/chunk-vg9r4eb9.js.map +14 -0
  63. package/dist/cli/{chunk-79jhk4py.js → chunk-wrr3j9w9.js} +260 -132
  64. package/dist/cli/chunk-wrr3j9w9.js.map +35 -0
  65. package/dist/cli/{chunk-6crbhc3x.js → chunk-yfyb25rh.js} +54 -27
  66. package/dist/cli/chunk-yfyb25rh.js.map +14 -0
  67. package/dist/cli/index.js +162 -35
  68. package/dist/cli/index.js.map +4 -4
  69. package/dist/types/ai/agent-surface.d.ts +32 -0
  70. package/dist/types/ai/api-catalog.d.ts +7 -1
  71. package/dist/types/ai/ask-context.d.ts +7 -0
  72. package/dist/types/ai/component-markdown.d.ts +4 -4
  73. package/dist/types/ai/link-headers.d.ts +8 -1
  74. package/dist/types/ai/openapi-components.d.ts +5 -2
  75. package/dist/types/ai/relative-links.d.ts +11 -4
  76. package/dist/types/ai/skills.d.ts +4 -1
  77. package/dist/types/ai/static-expression.d.ts +28 -0
  78. package/dist/types/ai/tar.d.ts +1 -3
  79. package/dist/types/analytics/databuddy.d.ts +43 -0
  80. package/dist/types/analytics/index.d.ts +4 -0
  81. package/dist/types/analytics/one-dollar-stats.d.ts +48 -0
  82. package/dist/types/analytics/schema.d.ts +28 -0
  83. package/dist/types/astro/integration.d.ts +3 -2
  84. package/dist/types/cli/env.d.ts +5 -0
  85. package/dist/types/cli/init/scaffold.d.ts +19 -3
  86. package/dist/types/cli/init/starter-spec.d.ts +11 -0
  87. package/dist/types/core/base-path.d.ts +24 -1
  88. package/dist/types/core/config-input.d.ts +13 -11
  89. package/dist/types/core/config.d.ts +2 -2
  90. package/dist/types/core/directive-diagnostics.d.ts +12 -0
  91. package/dist/types/core/graph.d.ts +2 -0
  92. package/dist/types/core/heading-markers.d.ts +5 -7
  93. package/dist/types/core/i18n-ui.d.ts +31 -0
  94. package/dist/types/core/i18n.d.ts +9 -1
  95. package/dist/types/core/last-modified.d.ts +10 -0
  96. package/dist/types/core/links.d.ts +3 -1
  97. package/dist/types/core/load-module.d.ts +10 -0
  98. package/dist/types/core/locale-links.d.ts +12 -2
  99. package/dist/types/core/meta.d.ts +13 -1
  100. package/dist/types/core/nav-diagnostics.d.ts +10 -0
  101. package/dist/types/core/navigation.d.ts +38 -0
  102. package/dist/types/core/ordering-prefix.d.ts +4 -0
  103. package/dist/types/core/safe-links.d.ts +3 -1
  104. package/dist/types/core/schema.d.ts +59 -13
  105. package/dist/types/core/sources/github-releases.d.ts +5 -0
  106. package/dist/types/core/sources/lower.d.ts +38 -13
  107. package/dist/types/core/sources/normalize.d.ts +23 -2
  108. package/dist/types/core/sources/remote.d.ts +11 -1
  109. package/dist/types/core/sources/resolve.d.ts +12 -0
  110. package/dist/types/core/sources/types.d.ts +31 -0
  111. package/dist/types/core/sources/watch.d.ts +12 -5
  112. package/dist/types/core/standard-schema.d.ts +5 -0
  113. package/dist/types/core/types.d.ts +9 -0
  114. package/dist/types/deploy/adapters/node.d.ts +5 -2
  115. package/dist/types/deploy/adapters/types.d.ts +7 -0
  116. package/dist/types/deploy/artifacts.d.ts +6 -4
  117. package/dist/types/deploy/cloudflare-negotiation.d.ts +3 -2
  118. package/dist/types/deploy/headers.d.ts +36 -7
  119. package/dist/types/deploy/node-headers.d.ts +43 -8
  120. package/dist/types/deploy/platforms/netlify.d.ts +27 -2
  121. package/dist/types/deploy/platforms/node.d.ts +6 -5
  122. package/dist/types/deploy/platforms/types.d.ts +15 -0
  123. package/dist/types/deploy/platforms/vercel.d.ts +3 -2
  124. package/dist/types/deploy/redirects.d.ts +31 -15
  125. package/dist/types/deploy/vercel-negotiation.d.ts +3 -2
  126. package/dist/types/markdown/directives.d.ts +62 -0
  127. package/dist/types/markdown/features.d.ts +21 -0
  128. package/dist/types/markdown/mdast.d.ts +63 -0
  129. package/dist/types/openapi/asyncapi.d.ts +4 -2
  130. package/dist/types/openapi/model.d.ts +20 -6
  131. package/dist/types/search/sync/algolia.d.ts +3 -1
  132. package/docs/01-quickstart.mdx +3 -2
  133. package/docs/02-deployment.mdx +20 -9
  134. package/docs/08-faq.mdx +10 -3
  135. package/docs/advanced/changelog.mdx +1 -1
  136. package/docs/advanced/custom-pages.mdx +7 -5
  137. package/docs/cli/audit.mdx +19 -3
  138. package/docs/cli/doctor.mdx +2 -2
  139. package/docs/cli/evals.mdx +4 -4
  140. package/docs/cli/index.mdx +4 -1
  141. package/docs/cli/translate.mdx +4 -4
  142. package/docs/cli/version.mdx +1 -1
  143. package/docs/configuration/analytics.mdx +42 -2
  144. package/docs/configuration/assistant.mdx +1 -1
  145. package/docs/configuration/customization.mdx +6 -3
  146. package/docs/configuration/index.mdx +5 -3
  147. package/docs/configuration/search.mdx +2 -2
  148. package/docs/content/components.mdx +2 -2
  149. package/docs/content/frontmatter.mdx +5 -1
  150. package/docs/content/i18n.mdx +3 -1
  151. package/docs/content/index.mdx +8 -4
  152. package/docs/content/islands.mdx +1 -1
  153. package/docs/content/meta.mdx +7 -3
  154. package/docs/content/navigation.mdx +29 -4
  155. package/docs/content/sources.mdx +18 -16
  156. package/docs/content/syntax.mdx +14 -0
  157. package/docs/content/versioning.mdx +2 -1
  158. package/docs/discoverability/agent-discovery.mdx +22 -8
  159. package/docs/discoverability/index.mdx +4 -3
  160. package/docs/discoverability/llms-txt.mdx +2 -5
  161. package/docs/discoverability/markdown.mdx +6 -4
  162. package/docs/discoverability/mcp.mdx +4 -0
  163. package/docs/discoverability/metadata.mdx +3 -2
  164. package/docs/discoverability/open-graph.mdx +8 -4
  165. package/docs/discoverability/rss.mdx +4 -2
  166. package/docs/references/asyncapi.mdx +2 -2
  167. package/docs/references/graphql.mdx +2 -2
  168. package/docs/references/openapi.mdx +6 -4
  169. package/package.json +1 -1
  170. package/skills/blume-migrate/SKILL.md +6 -6
  171. package/skills/blume-migrate/references/docusaurus.md +6 -6
  172. package/skills/blume-migrate/references/fumadocs.md +1 -1
  173. package/skills/blume-migrate/references/mintlify.md +3 -3
  174. package/skills/blume-migrate/references/monorepo.md +1 -1
  175. package/skills/blume-migrate/references/nextra.md +2 -2
  176. package/skills/blume-migrate/references/starlight.md +5 -5
  177. package/skills/blume-migrate/scripts/mintlify-codemod.mjs +9 -4
  178. package/skills/blume-update-docs/references/audit-checklist.md +1 -1
  179. package/src/ai/agent-readability.ts +2 -2
  180. package/src/ai/agent-surface.ts +56 -0
  181. package/src/ai/ai-catalog.ts +6 -2
  182. package/src/ai/api/handlers.ts +2 -2
  183. package/src/ai/api/spec.ts +17 -4
  184. package/src/ai/api-catalog.ts +13 -3
  185. package/src/ai/ask-context.ts +14 -2
  186. package/src/ai/ask-data.ts +26 -12
  187. package/src/ai/changelog-markdown.ts +2 -2
  188. package/src/ai/component-markdown.ts +43 -37
  189. package/src/ai/link-headers.ts +22 -8
  190. package/src/ai/llms.ts +22 -10
  191. package/src/ai/markdown.ts +23 -11
  192. package/src/ai/mcp/discovery.ts +2 -2
  193. package/src/ai/mcp/query.ts +2 -2
  194. package/src/ai/mcp/server.ts +80 -9
  195. package/src/ai/openapi-components.ts +22 -6
  196. package/src/ai/relative-links.ts +99 -15
  197. package/src/ai/serializers.ts +2 -1
  198. package/src/ai/skills.ts +14 -1
  199. package/src/ai/static-expression.ts +416 -0
  200. package/src/ai/tar.ts +139 -12
  201. package/src/ai/visibility.ts +45 -14
  202. package/src/analytics/databuddy.ts +67 -0
  203. package/src/analytics/head.ts +8 -0
  204. package/src/analytics/index.ts +7 -0
  205. package/src/analytics/one-dollar-stats.ts +86 -0
  206. package/src/analytics/posthog.ts +21 -3
  207. package/src/analytics/schema.ts +4 -0
  208. package/src/astro/generate.ts +72 -28
  209. package/src/astro/include-hmr.ts +31 -12
  210. package/src/astro/include-refresh.ts +19 -8
  211. package/src/astro/integration.ts +108 -14
  212. package/src/astro/runtime-modules.ts +28 -13
  213. package/src/astro/templates.ts +139 -57
  214. package/src/audit/catalog.ts +2 -2
  215. package/src/audit/checks/assets.ts +25 -5
  216. package/src/audit/checks/content.ts +20 -2
  217. package/src/audit/checks/i18n.ts +46 -8
  218. package/src/audit/checks/indexability.ts +39 -19
  219. package/src/audit/checks/links.ts +22 -1
  220. package/src/audit/checks/llms.ts +6 -3
  221. package/src/audit/checks/network.ts +3 -1
  222. package/src/audit/checks/og-image.ts +10 -0
  223. package/src/audit/checks/robots.ts +6 -1
  224. package/src/audit/checks/sitemap.ts +56 -31
  225. package/src/audit/checks/social.ts +21 -2
  226. package/src/audit/crawl.ts +88 -15
  227. package/src/audit/graph.ts +3 -1
  228. package/src/audit/report.ts +54 -17
  229. package/src/audit/run.ts +13 -9
  230. package/src/audit/snapshot.ts +5 -0
  231. package/src/audit/types.ts +18 -0
  232. package/src/audit/url.ts +37 -6
  233. package/src/cli/args.ts +32 -0
  234. package/src/cli/build-failure.ts +50 -0
  235. package/src/cli/commands/audit.ts +11 -1
  236. package/src/cli/commands/build.ts +19 -5
  237. package/src/cli/commands/check.ts +2 -0
  238. package/src/cli/commands/doctor.ts +3 -1
  239. package/src/cli/commands/eval.ts +20 -18
  240. package/src/cli/commands/init.ts +15 -5
  241. package/src/cli/commands/preview.ts +15 -0
  242. package/src/cli/commands/sync.ts +2 -0
  243. package/src/cli/commands/translate.ts +18 -18
  244. package/src/cli/commands/upgrade.ts +11 -0
  245. package/src/cli/commands/validate.ts +3 -1
  246. package/src/cli/dev-lock.ts +157 -37
  247. package/src/cli/eject-scripts.ts +32 -7
  248. package/src/cli/env.ts +12 -1
  249. package/src/cli/init/scaffold.ts +117 -11
  250. package/src/cli/init/starter-spec.ts +235 -0
  251. package/src/cli/report-format.ts +11 -6
  252. package/src/components/colors.ts +19 -0
  253. package/src/components/content/AccordionItem.astro +26 -22
  254. package/src/components/content/Badge.astro +7 -12
  255. package/src/components/content/Card.astro +2 -2
  256. package/src/components/content/Component.astro +11 -5
  257. package/src/components/content/Expandable.astro +5 -1
  258. package/src/components/content/Frame.astro +2 -7
  259. package/src/components/content/GithubInfo.astro +12 -2
  260. package/src/components/content/Prompt.astro +2 -7
  261. package/src/components/content/Tab.astro +0 -1
  262. package/src/components/content/Tabs.astro +58 -5
  263. package/src/components/content/Tile.astro +1 -1
  264. package/src/components/content/Tooltip.astro +69 -7
  265. package/src/components/content/Tree.astro +7 -2
  266. package/src/components/content/TypeTable.astro +10 -5
  267. package/src/components/content/Update.astro +8 -2
  268. package/src/components/content/auto-type-table.ts +4 -1
  269. package/src/components/content/badge-color.ts +20 -0
  270. package/src/components/content/base-href.ts +14 -22
  271. package/src/components/content/inline-markdown.ts +27 -7
  272. package/src/components/copy-feedback.ts +35 -8
  273. package/src/components/islands/assistant.tsx +37 -6
  274. package/src/components/islands/base-path.ts +47 -10
  275. package/src/components/islands/hooks.ts +42 -21
  276. package/src/components/islands/webmcp.ts +16 -10
  277. package/src/components/layout/Banner.astro +23 -4
  278. package/src/components/layout/Breadcrumbs.astro +5 -2
  279. package/src/components/layout/DiscoveryLinks.astro +9 -5
  280. package/src/components/layout/Header.astro +23 -10
  281. package/src/components/layout/LanguageSwitcher.astro +2 -2
  282. package/src/components/layout/Logo.astro +5 -0
  283. package/src/components/layout/NavSelector.astro +8 -3
  284. package/src/components/layout/NavTabMenu.astro +133 -0
  285. package/src/components/layout/NavTree.astro +31 -12
  286. package/src/components/layout/NavTreeCache.astro +5 -2
  287. package/src/components/layout/NavTreeScript.astro +45 -5
  288. package/src/components/layout/PageActions.astro +4 -3
  289. package/src/components/layout/PageLayout.astro +28 -13
  290. package/src/components/layout/Pagination.astro +3 -3
  291. package/src/components/layout/ReferenceLayout.astro +4 -1
  292. package/src/components/layout/RootLayout.astro +25 -12
  293. package/src/components/layout/Search.astro +38 -14
  294. package/src/components/layout/VersionBanner.astro +2 -2
  295. package/src/components/layout/analytics-client.ts +14 -0
  296. package/src/components/layout/toc-active.ts +41 -0
  297. package/src/components/layout/toc-element.ts +8 -14
  298. package/src/components/openapi/ApiTagOperations.astro +2 -2
  299. package/src/components/openapi/AsyncApiOperation.astro +7 -4
  300. package/src/components/openapi/GraphqlChip.astro +2 -2
  301. package/src/components/openapi/GraphqlType.astro +11 -3
  302. package/src/components/openapi/MessageComposer.astro +1 -1
  303. package/src/components/openapi/Operation.astro +23 -5
  304. package/src/components/openapi/PanelTabs.astro +4 -1
  305. package/src/components/openapi/Playground.astro +8 -2
  306. package/src/components/openapi/RequestPanel.astro +13 -6
  307. package/src/components/openapi/SchemaProperty.astro +11 -33
  308. package/src/components/openapi/SchemaTable.astro +34 -52
  309. package/src/components/openapi/async.ts +38 -6
  310. package/src/components/openapi/helpers.ts +100 -12
  311. package/src/components/openapi/message-composer.ts +14 -1
  312. package/src/components/openapi/message-model.ts +12 -2
  313. package/src/components/openapi/message.ts +21 -3
  314. package/src/components/openapi/operation-model.ts +119 -17
  315. package/src/components/openapi/panel.ts +31 -5
  316. package/src/components/openapi/param-style.ts +181 -0
  317. package/src/components/openapi/playground-client.ts +110 -23
  318. package/src/components/openapi/playground-schema.ts +25 -6
  319. package/src/components/openapi/request.ts +192 -26
  320. package/src/components/openapi/schema-tree.ts +209 -0
  321. package/src/components/openapi/snippets.ts +113 -19
  322. package/src/components/openapi/validate-json.ts +1 -1
  323. package/src/components/openapi/ws-client.ts +18 -2
  324. package/src/core/base-path.ts +69 -8
  325. package/src/core/config-input.ts +13 -11
  326. package/src/core/config.ts +18 -4
  327. package/src/core/diagnostics.ts +219 -30
  328. package/src/core/directive-diagnostics.ts +99 -0
  329. package/src/core/frontmatter.ts +21 -18
  330. package/src/core/graph.ts +120 -11
  331. package/src/core/heading-markers.ts +5 -18
  332. package/src/core/i18n-ui.ts +39 -2
  333. package/src/core/i18n.ts +44 -5
  334. package/src/core/last-modified.ts +25 -3
  335. package/src/core/links.ts +7 -4
  336. package/src/core/load-module.ts +20 -0
  337. package/src/core/locale-links.ts +22 -18
  338. package/src/core/manifest.ts +3 -2
  339. package/src/core/meta.ts +89 -12
  340. package/src/core/nav-diagnostics.ts +56 -1
  341. package/src/core/navigation.ts +272 -83
  342. package/src/core/ordering-prefix.ts +27 -0
  343. package/src/core/project-graph.ts +50 -6
  344. package/src/core/safe-href.ts +53 -1
  345. package/src/core/safe-links.ts +11 -2
  346. package/src/core/schema.ts +94 -18
  347. package/src/core/sources/assets.ts +83 -41
  348. package/src/core/sources/contentful-rich-text.ts +28 -20
  349. package/src/core/sources/contentful.ts +25 -12
  350. package/src/core/sources/filesystem.ts +25 -3
  351. package/src/core/sources/github-releases.ts +131 -11
  352. package/src/core/sources/lexical.ts +30 -20
  353. package/src/core/sources/lower.ts +276 -56
  354. package/src/core/sources/mdx-remote.ts +52 -16
  355. package/src/core/sources/normalize.ts +456 -119
  356. package/src/core/sources/notion.ts +77 -34
  357. package/src/core/sources/obsidian.ts +40 -9
  358. package/src/core/sources/payload.ts +1 -0
  359. package/src/core/sources/portable-text.ts +85 -49
  360. package/src/core/sources/remote.ts +18 -2
  361. package/src/core/sources/resolve.ts +52 -33
  362. package/src/core/sources/sanity.ts +1 -0
  363. package/src/core/sources/strapi-blocks.ts +28 -19
  364. package/src/core/sources/strapi.ts +1 -0
  365. package/src/core/sources/types.ts +31 -0
  366. package/src/core/sources/watch.ts +20 -7
  367. package/src/core/standard-schema.ts +10 -6
  368. package/src/core/types.ts +9 -0
  369. package/src/core/ui-packs/ar.ts +13 -0
  370. package/src/core/ui-packs/bg.ts +13 -0
  371. package/src/core/ui-packs/bn.ts +13 -0
  372. package/src/core/ui-packs/ca.ts +13 -0
  373. package/src/core/ui-packs/cs.ts +13 -0
  374. package/src/core/ui-packs/da.ts +13 -0
  375. package/src/core/ui-packs/de.ts +13 -0
  376. package/src/core/ui-packs/el.ts +13 -0
  377. package/src/core/ui-packs/es.ts +13 -0
  378. package/src/core/ui-packs/fa.ts +13 -0
  379. package/src/core/ui-packs/fi.ts +13 -0
  380. package/src/core/ui-packs/fr.ts +13 -0
  381. package/src/core/ui-packs/he.ts +13 -0
  382. package/src/core/ui-packs/hi.ts +13 -0
  383. package/src/core/ui-packs/hr.ts +13 -0
  384. package/src/core/ui-packs/hu.ts +13 -0
  385. package/src/core/ui-packs/id.ts +13 -0
  386. package/src/core/ui-packs/it.ts +13 -0
  387. package/src/core/ui-packs/ja.ts +13 -0
  388. package/src/core/ui-packs/ko.ts +13 -0
  389. package/src/core/ui-packs/nl.ts +13 -0
  390. package/src/core/ui-packs/no.ts +13 -0
  391. package/src/core/ui-packs/pl.ts +13 -0
  392. package/src/core/ui-packs/pt-br.ts +13 -0
  393. package/src/core/ui-packs/pt.ts +13 -0
  394. package/src/core/ui-packs/ro.ts +13 -0
  395. package/src/core/ui-packs/ru.ts +13 -0
  396. package/src/core/ui-packs/sk.ts +13 -0
  397. package/src/core/ui-packs/sr.ts +13 -0
  398. package/src/core/ui-packs/sv.ts +13 -0
  399. package/src/core/ui-packs/th.ts +13 -0
  400. package/src/core/ui-packs/tr.ts +13 -0
  401. package/src/core/ui-packs/uk.ts +13 -0
  402. package/src/core/ui-packs/vi.ts +13 -0
  403. package/src/core/ui-packs/zh-tw.ts +13 -0
  404. package/src/core/ui-packs/zh.ts +13 -0
  405. package/src/core/version-cut.ts +69 -17
  406. package/src/core/versions.ts +4 -1
  407. package/src/deploy/adapters/node.ts +5 -2
  408. package/src/deploy/adapters/registry.ts +2 -1
  409. package/src/deploy/adapters/types.ts +13 -1
  410. package/src/deploy/artifacts.ts +52 -11
  411. package/src/deploy/cloudflare-negotiation.ts +27 -16
  412. package/src/deploy/headers.ts +75 -55
  413. package/src/deploy/node-headers.ts +148 -27
  414. package/src/deploy/platforms/cloudflare.ts +13 -3
  415. package/src/deploy/platforms/netlify.ts +83 -5
  416. package/src/deploy/platforms/node.ts +8 -5
  417. package/src/deploy/platforms/static.ts +2 -0
  418. package/src/deploy/platforms/types.ts +15 -0
  419. package/src/deploy/platforms/vercel.ts +10 -3
  420. package/src/deploy/redirects.ts +68 -21
  421. package/src/deploy/robots.ts +2 -2
  422. package/src/deploy/rss.ts +4 -3
  423. package/src/deploy/sitemap.ts +7 -5
  424. package/src/deploy/vercel-negotiation.ts +35 -3
  425. package/src/eval/agents.ts +10 -2
  426. package/src/eval/run.ts +25 -0
  427. package/src/markdown/base-links.ts +74 -29
  428. package/src/markdown/directives.ts +242 -36
  429. package/src/markdown/features.ts +17 -0
  430. package/src/markdown/index.ts +13 -9
  431. package/src/markdown/mdast.ts +5 -2
  432. package/src/markdown/relative-links.ts +15 -27
  433. package/src/markdown/route-snapshot.ts +37 -0
  434. package/src/og/card.ts +149 -9
  435. package/src/og/derive.ts +156 -5
  436. package/src/og/index.ts +1 -0
  437. package/src/openapi/asyncapi.ts +4 -2
  438. package/src/openapi/graphql-build.ts +28 -2
  439. package/src/openapi/model.ts +99 -27
  440. package/src/openapi/proxy.ts +63 -10
  441. package/src/openapi/render-mdx.ts +51 -3
  442. package/src/registry/eject.ts +297 -43
  443. package/src/search/adapters/version-scope.ts +30 -0
  444. package/src/search/documents.ts +89 -27
  445. package/src/search/popular.ts +2 -1
  446. package/src/search/sync/algolia.ts +36 -2
  447. package/src/seo/jsonld.ts +7 -3
  448. package/src/sources/registry.ts +5 -0
  449. package/src/theme/entry.ts +11 -4
  450. package/src/translate/agents.ts +6 -1
  451. package/src/translate/ledger.ts +26 -3
  452. package/src/translate/meta.ts +76 -24
  453. package/src/translate/run.ts +14 -8
  454. package/src/translate/validate.ts +14 -2
  455. package/src/translate/work-list.ts +91 -19
  456. package/src/upgrade/upgrade.ts +36 -4
  457. package/dist/cli/chunk-27g6wdth.js.map +0 -10
  458. package/dist/cli/chunk-2hn4b8z7.js.map +0 -12
  459. package/dist/cli/chunk-6crbhc3x.js.map +0 -14
  460. package/dist/cli/chunk-6hsn950k.js.map +0 -10
  461. package/dist/cli/chunk-79jhk4py.js.map +0 -35
  462. package/dist/cli/chunk-82bbrxdn.js +0 -51
  463. package/dist/cli/chunk-82bbrxdn.js.map +0 -10
  464. package/dist/cli/chunk-abh8yjkn.js +0 -31
  465. package/dist/cli/chunk-abh8yjkn.js.map +0 -10
  466. package/dist/cli/chunk-ce574jw2.js +0 -23
  467. package/dist/cli/chunk-ce574jw2.js.map +0 -10
  468. package/dist/cli/chunk-dh8cwk36.js.map +0 -10
  469. package/dist/cli/chunk-epjnccmv.js.map +0 -10
  470. package/dist/cli/chunk-fa25z98p.js.map +0 -11
  471. package/dist/cli/chunk-fs23ddbb.js.map +0 -35
  472. package/dist/cli/chunk-fz5wtpmh.js.map +0 -10
  473. package/dist/cli/chunk-jwyddg7y.js.map +0 -15
  474. package/dist/cli/chunk-kpf8rrjc.js.map +0 -19
  475. package/dist/cli/chunk-m3vmjgmq.js.map +0 -10
  476. package/dist/cli/chunk-mb2919y2.js.map +0 -10
  477. package/dist/cli/chunk-q5163e60.js.map +0 -11
  478. package/dist/cli/chunk-qkqwkpte.js.map +0 -182
  479. package/dist/cli/chunk-qs4q5p4e.js.map +0 -10
  480. package/dist/cli/chunk-s1p84fyh.js.map +0 -10
  481. package/dist/cli/chunk-wgm7m9qk.js.map +0 -36
  482. package/dist/cli/chunk-yt5n7ppj.js.map +0 -10
  483. package/dist/cli/chunk-yw7dm696.js.map +0 -14
  484. /package/dist/cli/{chunk-s6jhgk0q.js.map → chunk-2eytanqx.js.map} +0 -0
  485. /package/dist/cli/{chunk-hdpx1tax.js.map → chunk-2z928egk.js.map} +0 -0
  486. /package/dist/cli/{chunk-ah61y8py.js.map → chunk-364znk6q.js.map} +0 -0
  487. /package/dist/cli/{chunk-vtk4a6dg.js.map → chunk-8ktnccpt.js.map} +0 -0
  488. /package/dist/cli/{chunk-fxypxtvm.js.map → chunk-a58773jm.js.map} +0 -0
  489. /package/dist/cli/{chunk-wm7js3j9.js.map → chunk-b07cmahc.js.map} +0 -0
  490. /package/dist/cli/{chunk-zxcczpyx.js.map → chunk-r20tn01b.js.map} +0 -0
  491. /package/dist/cli/{chunk-5shv93fd.js.map → chunk-tkacnehg.js.map} +0 -0
  492. /package/dist/cli/{chunk-zxh4d9vy.js.map → chunk-tzmab476.js.map} +0 -0
@@ -1,35 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/core/manifest.ts", "../src/core/project-graph.ts", "../src/theme/icon-kind.ts", "../src/theme/icons.ts", "../src/core/nav-diagnostics.ts", "../src/core/navigation.ts", "../src/core/graph.ts", "../src/core/last-modified.ts", "../src/core/meta.ts", "../src/core/sources/resolve.ts", "../src/core/sources/json.ts", "../src/core/sources/contentful-rich-text.ts", "../src/core/sources/remote.ts", "../src/core/sources/contentful.ts", "../src/core/sources/filesystem.ts", "../src/core/sources/github-releases.ts", "../src/core/sources/mdx-remote.ts", "../src/core/sources/notion.ts", "../src/core/sources/assets.ts", "../src/core/sources/obsidian.ts", "../src/core/sources/lexical.ts", "../src/core/sources/payload.ts", "../src/core/sources/sanity.ts", "../src/core/sources/portable-text.ts", "../src/core/sources/strapi-blocks.ts", "../src/core/sources/strapi.ts"],
4
- "sourcesContent": [
5
- "import { withBasePath } from \"./base-path.ts\";\nimport { localizeRoute, resolveFallbackLocale } from \"./i18n.ts\";\nimport type { ResolvedConfig } from \"./schema.ts\";\nimport type {\n BlumeManifest,\n ContentGraph,\n PageRecord,\n ProjectContext,\n RouteAlternate,\n RouteManifestEntry,\n VersionAlternate,\n} from \"./types.ts\";\nimport { getBlumeVersion } from \"./version.ts\";\n\n/**\n * Key for the same logical page across versions within one locale: the\n * version- and locale-agnostic route plus the locale code. NUL never appears\n * in either part, so the join is unambiguous.\n */\nconst versionAlternateKey = (versionKey: string, locale: string): string =>\n `${versionKey}\\u0000${locale}`;\n\n/**\n * Get-or-create the shared alternate list for a (versionKey, locale) pair.\n * Lists are attached to route entries by reference and mutated as fallback\n * routes materialize, then sorted once at the end — every holder sees the\n * final list.\n */\nconst versionAlternatesFor = (\n byKey: Map<string, VersionAlternate[]>,\n versionKey: string,\n locale: string\n): VersionAlternate[] => {\n const key = versionAlternateKey(versionKey, locale);\n const existing = byKey.get(key);\n if (existing) {\n return existing;\n }\n const list: VersionAlternate[] = [];\n byKey.set(key, list);\n return list;\n};\n\n/** The current manifest schema version. */\nexport const MANIFEST_VERSION = 1;\n\n/**\n * Whether a page may be indexed on its own merits — not author-excluded and not\n * hidden (unless hidden pages are opted in). This is independent of whether the\n * site search provider is enabled, so features like the MCP server can index\n * docs even when on-page search is off.\n */\nexport const contentIndexable = (\n page: PageRecord,\n config: ResolvedConfig\n): boolean =>\n !page.meta.search.exclude &&\n (!page.meta.sidebar.hidden || config.search.indexing.includeHiddenPages);\n\n/**\n * Fallback materialization: render the fallback locale's content at the\n * localized URL for any translation a non-default locale is missing, so static\n * output is fully prerendered (render-fallback, no client redirect). Fallback\n * routes are not indexed and carry no `hreflang` of their own.\n */\n/**\n * The description a page's `<head>` emits — `seo.description` over the front\n * matter `description` — mirrored onto its route so the OG card's subtitle\n * matches the page's `og:description`.\n */\nconst routeDescription = (page: PageRecord): string | undefined =>\n page.meta.seo.description ?? page.description;\n\nconst buildFallbackRoutes = (\n graph: ContentGraph,\n i18n: NonNullable<ResolvedConfig[\"i18n\"]>,\n alternatesByKey: Map<string, RouteAlternate[]>,\n basePath: string,\n versionAlternatesByKey: Map<string, VersionAlternate[]> | undefined\n): RouteManifestEntry[] => {\n const fallback = resolveFallbackLocale(i18n);\n if (!fallback) {\n return [];\n }\n // A monolingual page (a GitHub release) publishes in one language only, so it\n // gets no copy at every other locale's URL: those would be duplicates of the\n // same text under a translated chrome.\n const fallbackPages = new Map(\n graph.pages.flatMap((page) =>\n page.locale === fallback && !page.monolingual\n ? [[page.translationKey, page] as const]\n : []\n )\n );\n const routes: RouteManifestEntry[] = [];\n for (const { code } of i18n.locales) {\n if (code === fallback) {\n continue;\n }\n const present = new Set(\n graph.pages.flatMap((page) =>\n page.locale === code ? [page.translationKey] : []\n )\n );\n for (const [key, source] of fallbackPages) {\n if (present.has(key)) {\n continue;\n }\n const path = withBasePath(basePath, localizeRoute(key, code, i18n));\n // A fallback route is a real prerendered page, so it registers as a\n // version alternate too — the switcher on a sibling version's page\n // lands here instead of bouncing to the version root. Its own path is\n // recorded (not the fallback source's), keeping the target in-locale.\n const versionAlternates: VersionAlternate[] = versionAlternatesByKey\n ? versionAlternatesFor(versionAlternatesByKey, source.versionKey, code)\n : [];\n if (versionAlternatesByKey) {\n versionAlternates.push({ path, version: source.version });\n }\n routes.push({\n alternates: alternatesByKey.get(key) ?? [],\n collection: source.collection ?? \"docs\",\n contentType: source.contentType,\n description: routeDescription(source),\n draft: source.meta.draft,\n editUrl: source.editUrl,\n entryId: source.entryId ?? source.source.ref,\n fallback: true,\n hidden: source.meta.sidebar.hidden,\n id: source.id,\n indexable: false,\n lastModified: source.lastModified,\n locale: code,\n monolingual: source.monolingual,\n path,\n source: source.source,\n sourcePath: source.sourcePath,\n title: source.title,\n version: source.version,\n versionAlternates,\n });\n }\n }\n return routes;\n};\n\n/** Build the runtime manifest that bridges core and the generated Astro app. */\nexport const buildManifest = (options: {\n context: ProjectContext;\n config: ResolvedConfig;\n graph: ContentGraph;\n}): BlumeManifest => {\n const { context, config, graph } = options;\n const searchEnabled = config.search.provider.mode !== \"none\";\n const { i18n } = config;\n\n // Real translations per logical page, for `hreflang` and the switcher. Built\n // only under i18n; a single-locale page has no alternates.\n const alternatesByKey = new Map<string, RouteAlternate[]>();\n if (i18n) {\n for (const page of graph.pages) {\n const list = alternatesByKey.get(page.translationKey) ?? [];\n list.push({ locale: page.locale, path: page.route });\n alternatesByKey.set(page.translationKey, list);\n }\n }\n\n // The same logical page across versions, within each locale — for the\n // version switcher and the canonical-to-latest lookup. Built only under\n // versioning; lists are shared by reference and finalized (fallback routes\n // appended, then sorted) before the manifest is returned.\n const versionAlternatesByKey = config.versions\n ? new Map<string, VersionAlternate[]>()\n : undefined;\n if (versionAlternatesByKey) {\n for (const page of graph.pages) {\n versionAlternatesFor(\n versionAlternatesByKey,\n page.versionKey,\n page.locale\n ).push({ path: page.route, version: page.version });\n }\n }\n\n const routes: RouteManifestEntry[] = graph.pages.map((page) => ({\n alternates: alternatesByKey.get(page.translationKey) ?? [],\n collection: page.collection ?? \"docs\",\n contentType: page.contentType,\n description: routeDescription(page),\n draft: page.meta.draft,\n editUrl: page.editUrl,\n entryId: page.entryId ?? page.source.ref,\n hidden: page.meta.sidebar.hidden,\n id: page.id,\n indexable: searchEnabled && contentIndexable(page, config),\n lastModified: page.lastModified,\n locale: page.locale,\n monolingual: page.monolingual,\n path: page.route,\n source: page.source,\n sourcePath: page.sourcePath,\n title: page.title,\n version: page.version,\n versionAlternates: versionAlternatesByKey\n ? versionAlternatesFor(\n versionAlternatesByKey,\n page.versionKey,\n page.locale\n )\n : [],\n }));\n\n if (i18n) {\n routes.push(\n ...buildFallbackRoutes(\n graph,\n i18n,\n alternatesByKey,\n config.basePath,\n versionAlternatesByKey\n )\n );\n }\n\n // Alternate lists read current-first, then archived versions in configured\n // (switcher) order. Sorted once here — every route holding a list by\n // reference sees the final ordering.\n if (versionAlternatesByKey && config.versions) {\n const rank = new Map<string, number>(\n config.versions.archived.map((version, index) => [version.id, index + 1])\n );\n for (const list of versionAlternatesByKey.values()) {\n list.sort(\n (a, b) => (rank.get(a.version) ?? 0) - (rank.get(b.version) ?? 0)\n );\n }\n }\n\n routes.sort((a, b) => a.path.localeCompare(b.path));\n\n return {\n blumeVersion: getBlumeVersion(),\n contentRoot: context.contentRoot,\n output: config.deployment.options.output,\n projectRoot: context.root,\n routes,\n version: MANIFEST_VERSION,\n };\n};\n",
6
- "import { isAbsolute, relative } from \"pathe\";\n\nimport { CHANGELOG_INDEX_ROUTE, hasChangelogIndex } from \"./changelog-index.ts\";\nimport { loadConfig } from \"./config.ts\";\nimport { customStaticRoutes, discoverPages } from \"./custom-pages.ts\";\nimport { buildContentGraph } from \"./graph.ts\";\nimport { i18nDiagnostics } from \"./i18n.ts\";\nimport { expandIncludes, hasIncludeStatements } from \"./includes.ts\";\nimport {\n gitLastModifiedTimes,\n gitRepositoryRoot,\n lastModifiedShallowWarning,\n resolveLastModifiedConfig,\n} from \"./last-modified.ts\";\nimport { buildManifest } from \"./manifest.ts\";\nimport { discoverFolderMeta } from \"./meta.ts\";\nimport type { FolderMetaSource } from \"./meta.ts\";\nimport { resolveProjectContext } from \"./project.ts\";\nimport type { ResolvedConfig } from \"./schema.ts\";\nimport { normalizeEntry, strippedLineOffset } from \"./sources/normalize.ts\";\nimport { resolveDocsCollection, resolveSources } from \"./sources/resolve.ts\";\nimport type { ContentSource, SourceLoadResult } from \"./sources/types.ts\";\nimport type {\n BlumeManifest,\n ContentGraph,\n Diagnostic,\n ExampleLookup,\n PageRecord,\n ProjectContext,\n} from \"./types.ts\";\nimport { versionsDiagnostics } from \"./versions.ts\";\n\n/** Build mode: drafts are kept in `dev` and dropped in `build`. */\nexport type BuildMode = \"dev\" | \"build\";\n\n/** CLI-supplied overrides applied over the loaded config (see `scanProject`). */\nexport interface ConfigOverrides {\n /** Override `content.root` (`blume dev --content-dir`). */\n contentRoot?: string;\n}\n\n/**\n * Whether `path` sits at or under `dir`. A relative result that is itself\n * absolute means a different drive root on Windows, which is outside too.\n */\nexport const isWithin = (dir: string, path: string): boolean => {\n const rel = relative(dir, path);\n return !(rel.startsWith(\"..\") || isAbsolute(rel));\n};\n\n/** Apply CLI config overrides onto a resolved config (returns a new object). */\nconst applyConfigOverrides = (\n config: ResolvedConfig,\n overrides?: ConfigOverrides\n): ResolvedConfig => {\n if (!overrides) {\n return config;\n }\n // `--content-dir` re-roots every filesystem source: with one (the\n // zero-config case) it is exactly the old `content.root` override, and\n // several must share a root anyway (see `resolveDocsCollection`).\n const { contentRoot } = overrides;\n const sources = contentRoot\n ? config.content.sources.map((source) =>\n source.kind === \"filesystem\"\n ? { ...source, options: { ...source.options, root: contentRoot } }\n : source\n )\n : config.content.sources;\n return {\n ...config,\n content: { ...config.content, sources },\n };\n};\n\n/** Everything Blume knows about a project after a full scan. */\nexport interface BlumeProject {\n mode: BuildMode;\n context: ProjectContext;\n config: ResolvedConfig;\n graph: ContentGraph;\n manifest: BlumeManifest;\n diagnostics: Diagnostic[];\n /** Entries excluded from the graph because their frontmatter failed validation. */\n droppedPages: number;\n /** The instantiated content sources, for lazy entry reads (search/AI/raw). */\n sources: ContentSource[];\n /**\n * Whether the config file set `theme.fonts` itself (see\n * {@link ConfigLoadResult.themeFontsConfigured}); gates OG font derivation.\n */\n themeFontsConfigured: boolean;\n /**\n * Discovered `examples/` sources keyed by `<Component path>`, attached by the\n * runtime/eject layer after {@link scanProject} (example discovery is an Astro\n * concern, so core doesn't run it). Undefined until then; the agent-facing\n * Markdown downleveler reads it to turn `<Component path=\"…\" />` into the\n * example's source. Empty when the project has no examples.\n */\n examples?: ExampleLookup;\n}\n\n/**\n * Guard the invariant that ties a filesystem page to the `docs` collection:\n * Astro ids each collection entry by its path relative to the collection base,\n * so `getEntry(\"docs\", entryId)` only resolves when that entry id equals\n * `relative(base, file)`. A filesystem source ids entries relative to its own\n * root; when that root can't be the collection base (e.g. a second filesystem\n * source rooted elsewhere), the ids diverge and every one of that source's pages\n * would 404 in dev (a static build silently masks it). Emit a hard error naming\n * the mismatch so it can't ship, instead of a silent runtime failure. One\n * diagnostic per file (locale duplicates share a source path).\n */\nconst entryIdDiagnostics = (\n pages: PageRecord[],\n collectionBase: string\n): Diagnostic[] => {\n const diagnostics: Diagnostic[] = [];\n const seen = new Set<string>();\n for (const page of pages) {\n // Only filesystem entries render through the base-rooted `docs` collection;\n // staged sources carry their own id and collection.\n if (page.collection || !page.sourcePath || seen.has(page.sourcePath)) {\n continue;\n }\n seen.add(page.sourcePath);\n const expected = relative(collectionBase, page.sourcePath)\n .split(\"\\\\\")\n .join(\"/\");\n const entryId = page.entryId ?? page.source.ref;\n if (expected !== entryId) {\n diagnostics.push({\n code: \"BLUME_ENTRY_ID_MISMATCH\",\n file: page.sourcePath,\n message: `Content source \"${page.source.name}\" is rooted outside the docs collection base, so ${page.route} resolves entry id \"${entryId}\" but the collection would generate \"${expected}\" — the page would 404 at runtime.`,\n severity: \"error\",\n suggestion:\n \"Use a single filesystem() source (the docs collection roots at it), or give every filesystem() source the same root and partition them with include globs — a root at a subdirectory of the first source's root still mismatches.\",\n });\n }\n }\n return diagnostics;\n};\n\n/**\n * Funnel every loaded source's entries through the shared `normalizeEntry`,\n * collecting pages, diagnostics, and the count of entries dropped outright —\n * an entry that yields no pages but did yield diagnostics was rejected for\n * invalid frontmatter, and callers surface that count so a build with missing\n * pages can't read as clean.\n */\nconst normalizeLoadedEntries = (\n loaded: ({ source: ContentSource } & SourceLoadResult)[],\n config: ResolvedConfig\n) => {\n // Only thread `frontmatter.extend` / `content.types` through when a project\n // opts in, so the known-key split in `normalizeEntry` stays off the default\n // path.\n const frontmatterExtend =\n Object.keys(config.frontmatter.extend).length > 0\n ? config.frontmatter.extend\n : undefined;\n const declaredTypes = Object.entries(config.content.types).filter(\n ([, type]) => Object.keys(type.frontmatter).length > 0\n );\n const typeFrontmatter =\n declaredTypes.length > 0\n ? Object.fromEntries(\n declaredTypes.map(([name, type]) => [name, type.frontmatter])\n )\n : undefined;\n\n const pages: PageRecord[] = [];\n const allDiagnostics: Diagnostic[] = [];\n let droppedPages = 0;\n for (const { source, entries, diagnostics } of loaded) {\n allDiagnostics.push(...diagnostics);\n for (const entry of entries) {\n const normalized = normalizeEntry(entry, {\n basePath: config.basePath,\n defaultType: config.content.defaultType,\n frontmatterExtend,\n i18n: config.i18n,\n source: {\n monolingual: source.monolingual,\n name: source.name,\n prefix: source.prefix,\n staged: source.staged,\n },\n typeFrontmatter,\n versions: config.versions,\n });\n if (normalized.pages.length === 0 && normalized.diagnostics.length > 0) {\n droppedPages += 1;\n }\n pages.push(...normalized.pages);\n allDiagnostics.push(...normalized.diagnostics);\n }\n }\n return { diagnostics: allDiagnostics, droppedPages, pages };\n};\n\n/**\n * Run the full core pipeline for a project root: load config, resolve paths,\n * discover content and folder meta, build the graph, and assemble the manifest.\n * Collects all diagnostics without throwing on content-level problems so\n * callers can decide how strict to be.\n */\n/** Narrows the logo config's image shorthand from its object form. */\nconst isLogoShorthand = (\n logo: NonNullable<ResolvedConfig[\"logo\"]>\n): logo is string => typeof logo === \"string\";\n\n/** The configured brand link: `logo.href`, else the site root. */\nconst logoHref = (logo: ResolvedConfig[\"logo\"]): string =>\n logo === undefined || isLogoShorthand(logo) ? \"/\" : (logo.href ?? \"/\");\n\nexport const scanProject = async (\n root: string,\n options: {\n devServerUrl?: string;\n mode?: BuildMode;\n preview?: boolean;\n refresh?: boolean;\n /** CLI overrides applied over the loaded config (e.g. `--output`). */\n overrides?: ConfigOverrides;\n /** Relocate the generated runtime (e.g. `.blume-verify` for isolation). */\n runtimeDir?: string;\n } = {}\n): Promise<BlumeProject> => {\n const mode = options.mode ?? \"dev\";\n const preview = options.preview ?? false;\n const configResult = await loadConfig(root, {\n devServerUrl: options.devServerUrl,\n });\n const config = applyConfigOverrides(configResult.config, options.overrides);\n const context = resolveProjectContext(root, config, {\n runtimeDir: options.runtimeDir,\n });\n\n // Each source validates itself (e.g. the filesystem source checks its root\n // exists), replacing the single hard `contentRoot` check.\n const sources = resolveSources(config, context, {\n mode,\n preview,\n refresh: options.refresh,\n });\n for (const source of sources) {\n source.validate?.();\n }\n\n // Folder meta is discovered per filesystem source, under each source's own\n // root and keyed by its route prefix, so a prefixed/root-differing source's\n // `meta.ts` still lines up with its (prefixed) sidebar group path.\n const metaSources: FolderMetaSource[] = sources.flatMap((source) =>\n source.staged || !source.contentRoot\n ? []\n : [{ prefix: source.prefix, root: source.contentRoot }]\n );\n\n // Run every source's `load()` in parallel, then funnel each entry through the\n // shared `normalizeEntry` so route mapping is identical regardless of origin.\n // Under the `dir` parser, non-default locales are top-level directories whose\n // meta keys must carry the locale in front of the source prefix (see\n // `discoverFolderMeta`).\n const localeDirs =\n config.i18n && config.i18n.parser === \"dir\"\n ? config.i18n.locales.flatMap((locale) =>\n locale.code === config.i18n?.defaultLocale ? [] : [locale.code]\n )\n : undefined;\n\n const [loaded, folderMeta] = await Promise.all([\n Promise.all(\n sources.map(async (source) => ({ source, ...(await source.load()) }))\n ),\n discoverFolderMeta(metaSources, {\n localeDirs,\n versionDirs: config.versions?.archived.map((version) => version.id),\n }),\n ]);\n\n // Expand `<include>` statements before normalization, so heading/link/\n // component extraction sees the spliced content every render surface shows.\n // Filesystem entries only: includes resolve as filesystem paths bounded by\n // the owning source's content root. Unresolvable statements stay verbatim\n // and surface as error diagnostics here.\n const includeDiagnostics: Diagnostic[] = [];\n await Promise.all(\n loaded.flatMap(({ source, entries }) => {\n if (source.staged || !source.contentRoot) {\n return [];\n }\n return entries.map(async (entry) => {\n if (!entry.sourcePath || !hasIncludeStatements(entry.body.text)) {\n return;\n }\n const expansion = await expandIncludes(entry.body.text, {\n contentRoot: source.contentRoot,\n lineOffset: strippedLineOffset(entry.raw, entry.body.text),\n sourcePath: entry.sourcePath,\n });\n entry.expanded = expansion;\n includeDiagnostics.push(...expansion.errors);\n });\n })\n );\n\n // Folder meta contributed by the sources themselves (the OpenAPI source\n // labels each tag directory with the spec's own tag name). It applies to\n // every locale, so it merges into the shared map — beneath user-authored\n // entries, which are spread last and win.\n const sharedFolderMeta = new Map([\n ...loaded.flatMap(({ folderMeta: sourceMeta }) =>\n Object.entries(sourceMeta ?? {})\n ),\n ...folderMeta.shared,\n ]);\n\n const {\n diagnostics: contentDiagnostics,\n droppedPages,\n pages: allPages,\n } = normalizeLoadedEntries(loaded, config);\n\n // Drafts render in dev and in preview, but are excluded from production builds.\n const pages =\n mode === \"build\" && !preview\n ? allPages.filter((page) => !page.meta.draft)\n : allPages;\n\n // Resolve \"last updated\" dates before the graph is built so the manifest\n // (which shares these page objects) picks them up. Frontmatter always wins;\n // git applies to filesystem entries, other sources supply dates on the entry.\n const lastModified = resolveLastModifiedConfig(config.lastModified);\n const lastModifiedWarnings: Diagnostic[] = [];\n if (lastModified.enabled && lastModified.source === \"git\") {\n const fsPaths = pages\n .map((page) => page.sourcePath)\n .filter((path): path is string => path !== undefined);\n // The git pathspecs must cover where the pages actually live: each local\n // source's own on-disk root — a filesystem source's `root`, or a staged\n // local source's tree (an Obsidian vault) — which diverges from the global\n // `content.root`. A root outside the repository would fail the log outright\n // and can never yield dates, so those are dropped up front.\n const gitRoot = gitRepositoryRoot(context.root);\n const contentRoots = sources\n .flatMap((source) => (source.contentRoot ? [source.contentRoot] : []))\n .filter((dir) => gitRoot !== null && isWithin(gitRoot, dir));\n const gitTimes = gitLastModifiedTimes(\n context.root,\n contentRoots,\n fsPaths,\n gitRoot\n );\n for (const page of pages) {\n if (!page.lastModified && page.sourcePath) {\n page.lastModified = gitTimes.get(page.sourcePath);\n }\n }\n // A shallow CI clone (Vercel, actions/checkout) silently drops most dates;\n // surface that instead of letting production diverge from local builds.\n // Only pages the log could have dated count — a page outside every covered\n // root stays undated no matter how deep the clone is, and the warning's\n // suggested fix cannot help it.\n const undated = pages.filter(\n (page) =>\n page.sourcePath &&\n !page.lastModified &&\n contentRoots.some((dir) => isWithin(dir, page.sourcePath ?? \"\"))\n ).length;\n lastModifiedWarnings.push(\n ...lastModifiedShallowWarning(context.root, undated)\n );\n }\n\n // Custom `.astro` pages and the generated changelog index aren't content\n // pages, so name them for navigation: a `/changelog` tab should open the\n // timeline, not the newest entry, and a tab or brand link to a custom page\n // must stay on its route in every locale.\n const customPages = context.pagesRoot\n ? await discoverPages(context.pagesRoot)\n : [];\n const graph = buildContentGraph(pages, {\n basePath: config.basePath,\n brandHref: logoHref(config.logo),\n extraRoutes: new Set([\n ...customStaticRoutes(customPages),\n ...(hasChangelogIndex(pages, config) ? [CHANGELOG_INDEX_ROUTE] : []),\n ]),\n folderMeta: folderMeta.meta,\n i18n: config.i18n,\n navigation: config.navigation,\n sharedFolderMeta,\n versions: config.versions,\n });\n const manifest = buildManifest({ config, context, graph });\n\n const i18nWarnings = config.i18n\n ? i18nDiagnostics(pages, config.i18n, config.versions)\n : [];\n const versionWarnings = config.versions\n ? versionsDiagnostics(pages, config.versions)\n : [];\n\n return {\n config,\n context,\n diagnostics: [\n ...contentDiagnostics,\n ...includeDiagnostics,\n ...folderMeta.diagnostics,\n ...entryIdDiagnostics(\n pages,\n resolveDocsCollection(config, context.root).base\n ),\n ...graph.diagnostics,\n ...i18nWarnings,\n ...versionWarnings,\n ...lastModifiedWarnings,\n ],\n droppedPages,\n graph,\n manifest,\n mode,\n sources,\n themeFontsConfigured: configResult.themeFontsConfigured,\n };\n};\n",
7
- "/**\n * Classify author-supplied icon strings — built-in Lucide names vs image\n * paths/URLs vs inline SVG. Shared by nav diagnostics, `<Icon>`, and the\n * Cmd+K popular-icon resolver so the three shapes stay in sync.\n */\n\nconst IMAGE_ICON =\n /^(?:https?:\\/\\/|data:image\\/|\\/|\\.{1,2}\\/)|\\.(?:avif|gif|jpe?g|png|svg|webp)$/iu;\n\nconst INLINE_SVG = /^\\s*<svg[\\s\\S]*<\\/svg>\\s*$/u;\n\n/** Image path, remote URL, or data URI — not a Lucide name or inline SVG. */\nexport const isImageIcon = (value: string): boolean => IMAGE_ICON.test(value);\n\n/** Full `<svg>…</svg>` markup (whitespace-tolerant). */\nexport const isInlineSvg = (value: string): boolean => INLINE_SVG.test(value);\n\n/** Image or inline SVG — anything that is not a built-in icon name. */\nexport const isAssetIcon = (value: string): boolean =>\n isInlineSvg(value) || isImageIcon(value);\n",
8
- "/**\n * Icon resolution backed by the open Iconify Lucide set. Resolution runs at\n * **build time, server-side**, and returns ready-to-inline SVG, so icons stay\n * zero-JS and fully self-contained (no runtime CDN fetch).\n *\n * Because the Iconify set data is large, this module must only be imported from\n * server contexts (`.astro` frontmatter, the CLI). Client scripts use the tiny\n * hand-inlined set in `./chrome-icons.ts` instead.\n */\nimport { createRequire } from \"node:module\";\n\nimport type { IconifyJSON } from \"@iconify/types\";\nimport { getIconData, iconToSVG } from \"@iconify/utils\";\n\n// Load the icon-set JSON with a CJS `require` rather than an `import ... with\n// { type: \"json\" }`: the bundled Node CLI drops the import attribute (Bun.build\n// strips it when externalizing) and then rejects the module, whereas `require`\n// of a JSON file needs no attribute and works under both Node and Bun.\nconst requireJson = createRequire(import.meta.url);\n// SAFETY: the required file is the Iconify-published icon-set JSON, whose\n// shape is exactly `IconifyJSON`.\nconst loadSet = (pkg: string): IconifyJSON => requireJson(pkg) as IconifyJSON;\n\nconst SETS = {\n lucide: loadSet(\"@iconify-json/lucide/icons.json\"),\n};\n\n/** Blume's only icon library. */\nconst DEFAULT_SET = \"lucide\";\n\n/** Explicit `prefix:name` prefixes. Lucide is the only bundled set. */\nconst PREFIX_SETS = {\n lucide: \"lucide\",\n};\n\n/**\n * Own-property map lookup. Icon names come from content and config, so a value\n * like `constructor:x` would otherwise resolve an Object.prototype member (a\n * function) and crash resolution deep in the build with no pointer to the\n * offending page.\n */\nconst ownEntry = <T>(map: Record<string, T>, key: string): T | undefined =>\n Object.hasOwn(map, key) ? map[key] : undefined;\n\nexport interface ResolvedIcon {\n /** Inner SVG markup (self-styled: carries its own fill/stroke). */\n body: string;\n /** The resolved icon name. */\n name: string;\n /** The icon's viewBox (Lucide is 24×24). */\n viewBox: string;\n}\n\nconst normalize = (name: string): string =>\n name\n .trim()\n .toLowerCase()\n .replaceAll(/[\\s_]+/gu, \"-\");\n\nconst fromSet = (setName: string, iconName: string): ResolvedIcon | null => {\n const set = ownEntry(SETS, setName);\n const data = set && getIconData(set, iconName);\n if (!data) {\n return null;\n }\n const { attributes, body } = iconToSVG(data, { height: \"auto\" });\n return { body, name: iconName, viewBox: attributes.viewBox };\n};\n\n/**\n * Resolve an icon name to inline SVG. Honors an explicit `lucide:name` prefix;\n * a bare name resolves against Lucide.\n */\nexport const resolveIcon = (name: string): ResolvedIcon | null => {\n const normalized = normalize(name);\n const colon = normalized.indexOf(\":\");\n if (colon > 0) {\n const setName = ownEntry(PREFIX_SETS, normalized.slice(0, colon));\n return setName ? fromSet(setName, normalized.slice(colon + 1)) : null;\n }\n return fromSet(DEFAULT_SET, normalized);\n};\n\n/**\n * Whether a name resolves to a renderable icon. Exactly mirrors\n * {@link resolveIcon}: a laxer check (e.g. matching the bare name under an\n * unknown prefix) would let callers suppress their fallback and diagnostics\n * for a name `<Icon>` then renders as nothing.\n */\nexport const hasIcon = (name: string): boolean => resolveIcon(name) !== null;\n",
9
- "import { isAssetIcon } from \"../theme/icon-kind.ts\";\nimport { hasIcon } from \"../theme/icons.ts\";\nimport { isInternalPath } from \"./base-path.ts\";\nimport type { Diagnostic, NavNode, Navigation, PageRecord } from \"./types.ts\";\n\n/**\n * Navigation diagnostics: catch icon typos and structural mistakes (missing\n * pages, duplicate labels) that otherwise fail silently — a wrong icon just\n * doesn't render, a bad tab path just 404s. Run over the built navigation so it\n * covers every source (config, folder meta, frontmatter) at once.\n */\n\nconst ICON_FORMAT_HINT =\n \"Use a built-in icon name, an image path/URL, or inline SVG markup.\";\n\n/** Flatten a sidebar tree to every node, descending into groups. */\nconst flattenNodes = (nodes: NavNode[]): NavNode[] =>\n nodes.flatMap((node) =>\n node.kind === \"group\" ? [node, ...flattenNodes(node.children)] : [node]\n );\n\n/** Every icon string referenced anywhere in the navigation, with a label. */\nconst collectIcons = (\n navigation: Navigation\n): { icon: string; where: string }[] => {\n const icons: { icon: string; where: string }[] = [];\n const push = (icon: string | undefined, where: string): void => {\n if (icon) {\n icons.push({ icon, where });\n }\n };\n for (const tab of navigation.tabs) {\n push(tab.icon, `tab \"${tab.label}\"`);\n for (const item of tab.items ?? []) {\n push(item.icon, `tab item \"${item.label}\"`);\n }\n }\n for (const selector of navigation.selectors) {\n for (const item of selector.items) {\n push(item.icon, `selector \"${item.label}\"`);\n }\n }\n for (const link of navigation.featured) {\n push(link.icon, `featured link \"${link.label}\"`);\n }\n const sidebars = [navigation.sidebar];\n for (const sidebar of sidebars) {\n for (const node of flattenNodes(sidebar)) {\n push(node.icon, `\"${node.label}\"`);\n }\n }\n return icons;\n};\n\n/** Warn about icon names that aren't in Blume's set (skipping image/SVG icons). */\nconst unknownIconDiagnostics = (\n icons: { icon: string; where: string }[],\n suggestion: string\n): Diagnostic[] => {\n const seen = new Set<string>();\n const diagnostics: Diagnostic[] = [];\n for (const { icon, where } of icons) {\n if (isAssetIcon(icon) || hasIcon(icon) || seen.has(icon)) {\n continue;\n }\n seen.add(icon);\n // Markup that isn't a complete <svg> element (an <img> tag, a truncated\n // svg) is a shape problem, not a set-name typo — say so.\n const message = icon.trimStart().startsWith(\"<\")\n ? `Icon markup \"${icon}\" (${where}) isn't a complete inline <svg> element, so it won't render.`\n : `Unknown icon \"${icon}\" (${where}) — it isn't in Blume's icon set.`;\n diagnostics.push({\n code: \"BLUME_UNKNOWN_ICON\",\n message,\n severity: \"warning\",\n suggestion,\n });\n }\n return diagnostics;\n};\n\n/** Warn about icon names that aren't in Blume's set (skipping image/SVG icons). */\nexport const validateNavIcons = (navigation: Navigation): Diagnostic[] =>\n unknownIconDiagnostics(collectIcons(navigation), ICON_FORMAT_HINT);\n\n/**\n * Warn about unknown icons on curated `search.popular` links. Same accepted\n * input shapes as nav icons — resolved to markup on the server for the island.\n */\nexport const validateSearchPopularIcons = (\n popular: { icon?: string; label: string }[]\n): Diagnostic[] => {\n const icons = popular.flatMap((link) =>\n link.icon\n ? [{ icon: link.icon, where: `popular link \"${link.label}\"` }]\n : []\n );\n return unknownIconDiagnostics(icons, ICON_FORMAT_HINT);\n};\n\n/** Whether an internal path resolves to a page or a section that has pages. */\nconst resolvesToPages = (routes: Set<string>, path: string): boolean =>\n routes.has(path) || [...routes].some((route) => route.startsWith(`${path}/`));\n\n/**\n * Warn when a config-linked tab/selector target has no matching page. `routes`\n * must be the full set of servable routes — content, custom `.astro` pages, and\n * generated routes — so this runs where all three are known (`generateRuntime`),\n * not in the content-only graph build.\n */\nexport const validateNavTargets = (\n navigation: Navigation,\n routes: Set<string>\n): Diagnostic[] => {\n const targets: { label: string; path: string }[] = [\n ...navigation.tabs.map((tab) => ({ label: tab.label, path: tab.path })),\n ...navigation.selectors.flatMap((selector) =>\n selector.items.map((item) => ({ label: item.label, path: item.path }))\n ),\n ...navigation.featured.map((link) => ({\n label: link.label,\n path: link.href,\n })),\n ...(navigation.actions ?? []).map((action) => ({\n label: action.label,\n path: action.href,\n })),\n ...(navigation.cta\n ? [{ label: navigation.cta.label, path: navigation.cta.href }]\n : []),\n ];\n const diagnostics: Diagnostic[] = [];\n const seen = new Set<string>();\n for (const { label, path } of targets) {\n // Only internal, non-anchor paths can be checked against routes. A\n // protocol-relative `//host/path` is external despite its leading slash.\n if (!isInternalPath(path) || path.startsWith(\"/#\") || seen.has(path)) {\n continue;\n }\n if (!resolvesToPages(routes, path.split(\"#\")[0] ?? path)) {\n seen.add(path);\n diagnostics.push({\n code: \"BLUME_NAV_MISSING_PAGE\",\n message: `Navigation entry \"${label}\" points to ${path}, but no page matches it.`,\n severity: \"warning\",\n suggestion: \"Fix the path, or add a page at that route.\",\n });\n }\n }\n return diagnostics;\n};\n\n/** Warn about two nav items sharing a label at the same sidebar level. */\nconst duplicateLabelDiagnostics = (navigation: Navigation): Diagnostic[] => {\n const diagnostics: Diagnostic[] = [];\n const checkLevel = (nodes: NavNode[], where: string): void => {\n const counts = new Map<string, number>();\n for (const node of nodes) {\n counts.set(node.label, (counts.get(node.label) ?? 0) + 1);\n }\n for (const [label, count] of counts) {\n if (count > 1) {\n diagnostics.push({\n code: \"BLUME_NAV_DUPLICATE_LABEL\",\n message: `Duplicate sidebar label \"${label}\" appears ${count} times ${where}.`,\n severity: \"warning\",\n suggestion: \"Give the entries distinct titles.\",\n });\n }\n }\n for (const node of nodes) {\n if (node.kind === \"group\") {\n checkLevel(node.children, `under \"${node.label}\"`);\n }\n }\n };\n const sidebars: { nodes: NavNode[]; where: string }[] = [\n { nodes: navigation.sidebar, where: \"at the top level\" },\n ];\n for (const { nodes, where } of sidebars) {\n checkLevel(nodes, where);\n }\n return diagnostics;\n};\n\n/** Warn when a page shown in the sidebar is marked hidden (so pagination hits it). */\nconst hiddenInSidebarDiagnostics = (\n navigation: Navigation,\n pages: PageRecord[]\n): Diagnostic[] => {\n const hidden = new Set(\n pages.flatMap((page) => (page.meta.sidebar.hidden ? [page.id] : []))\n );\n if (hidden.size === 0) {\n return [];\n }\n const sidebars = [navigation.sidebar];\n const diagnostics: Diagnostic[] = [];\n const seen = new Set<string>();\n for (const sidebar of sidebars) {\n for (const node of flattenNodes(sidebar)) {\n if (\n node.kind === \"page\" &&\n hidden.has(node.pageId) &&\n !seen.has(node.pageId)\n ) {\n seen.add(node.pageId);\n diagnostics.push({\n code: \"BLUME_NAV_HIDDEN_IN_SIDEBAR\",\n message: `Page \"${node.label}\" is marked hidden but appears in the sidebar (and its pagination).`,\n severity: \"warning\",\n suggestion:\n \"Remove it from the navigation config, or unset sidebar.hidden.\",\n });\n }\n }\n }\n return diagnostics;\n};\n\n/**\n * Structural navigation diagnostics that need only the built navigation +\n * content pages: duplicate sidebar labels at a level, and hidden pages that\n * still surface in the sidebar (so pagination lands on them). Target existence\n * is checked separately by {@link validateNavTargets}, which needs the full\n * route set.\n */\nexport const validateNavStructure = (\n navigation: Navigation,\n pages: PageRecord[]\n): Diagnostic[] => [\n ...duplicateLabelDiagnostics(navigation),\n ...hiddenInSidebarDiagnostics(navigation, pages),\n];\n",
10
- "import { extname } from \"pathe\";\n\nimport { stripBasePath, withBasePath } from \"./base-path.ts\";\nimport type {\n FolderMeta,\n SidebarDisplay,\n SidebarItemConfig,\n} from \"./schema.ts\";\nimport type {\n Diagnostic,\n FeaturedLink,\n HeaderAction,\n NavNode,\n Navigation,\n NavSelector,\n NavTab,\n PageRecord,\n} from \"./types.ts\";\n\nconst NUMERIC_PREFIX = /^(?<order>\\d+)[-_.]/u;\nconst GROUP_FOLDER = /^\\((?<label>.+)\\)$/u;\nconst WORD_SPLIT = /[-_]/u;\n\n/**\n * Whether `route` is the section root `base` or nested beneath it. Requires a\n * path boundary, so `/api-reference` is not under `/api`. The root `/` spans\n * every route.\n */\nexport const isUnderPath = (route: string, base: string): boolean =>\n base === \"/\" || route === base || route.startsWith(`${base}/`);\n\n/**\n * Whether `tab` is the root tab of the tree rooted at `root` — the tab that\n * spans the whole sidebar rather than one section. Tab paths and the root\n * normally share one path space, so the root tab sits at `root` exactly (`/`,\n * `/en`, `/docs`); in an archived version tree the root is versionized\n * (`/v1.0`, `/docs/v1.0`) while tab paths stay in current-docs space, so the\n * root tab is any tab the whole root sits under. The one definition shared by\n * sidebar scoping, tab-section hoisting, and the header's current-tab state —\n * consumers that disagree on which tab is the root tab prune an archived\n * sidebar or highlight the wrong tab over it.\n */\nexport const isRootTab = (tab: NavTab, root: string): boolean =>\n isUnderPath(root, tab.path);\n\n/**\n * A page's sidebar icon: `sidebar.icon`, or the top-level `icon` shorthand\n * (the Mintlify-style spelling) when the nested key is unset.\n */\nconst sidebarIcon = (page: PageRecord): string | undefined =>\n page.meta.sidebar.icon ?? page.meta.icon;\n\n/**\n * Words a folder name spells in lowercase that read wrong capitalized: the\n * acronyms and brand casings docs folders are named after (`api-reference`\n * is \"API Reference\", not \"Api Reference\").\n */\nconst WORD_FORMS = new Map([\n [\"ai\", \"AI\"],\n [\"api\", \"API\"],\n [\"apis\", \"APIs\"],\n [\"asyncapi\", \"AsyncAPI\"],\n [\"cli\", \"CLI\"],\n [\"css\", \"CSS\"],\n [\"faq\", \"FAQ\"],\n [\"faqs\", \"FAQs\"],\n [\"graphql\", \"GraphQL\"],\n [\"html\", \"HTML\"],\n [\"http\", \"HTTP\"],\n [\"https\", \"HTTPS\"],\n [\"id\", \"ID\"],\n [\"ids\", \"IDs\"],\n [\"ios\", \"iOS\"],\n [\"js\", \"JS\"],\n [\"json\", \"JSON\"],\n [\"jwt\", \"JWT\"],\n [\"llm\", \"LLM\"],\n [\"llms\", \"LLMs\"],\n [\"macos\", \"macOS\"],\n [\"mcp\", \"MCP\"],\n [\"oauth\", \"OAuth\"],\n [\"openapi\", \"OpenAPI\"],\n [\"rss\", \"RSS\"],\n [\"sdk\", \"SDK\"],\n [\"sdks\", \"SDKs\"],\n [\"seo\", \"SEO\"],\n [\"sql\", \"SQL\"],\n [\"sso\", \"SSO\"],\n [\"ts\", \"TS\"],\n [\"ui\", \"UI\"],\n [\"url\", \"URL\"],\n [\"urls\", \"URLs\"],\n [\"xml\", \"XML\"],\n [\"yaml\", \"YAML\"],\n]);\n\nconst humanize = (segment: string): string =>\n segment\n .replace(NUMERIC_PREFIX, \"\")\n .split(WORD_SPLIT)\n .filter(Boolean)\n .map(\n (word) =>\n WORD_FORMS.get(word) ?? word.charAt(0).toUpperCase() + word.slice(1)\n )\n .join(\" \");\n\nconst numericOrder = (segment: string): number => {\n const value = segment.match(NUMERIC_PREFIX)?.groups?.order;\n return value ? Math.trunc(Number(value)) : Number.POSITIVE_INFINITY;\n};\n\n/** The nav key of a raw path segment: group label or numeric-stripped name. */\nconst segmentKey = (raw: string): string => {\n const group = raw.match(GROUP_FOLDER)?.groups?.label;\n return (group ?? raw).replace(NUMERIC_PREFIX, \"\");\n};\n\n/**\n * Whether a filename stem is a directory index, ignoring an ordering prefix:\n * route mapping strips the prefix before dropping `index`, so `01-index` routes\n * exactly like `index` and must be treated as one here too.\n */\nconst isIndexStem = (stem: string): boolean =>\n stem.replace(NUMERIC_PREFIX, \"\") === \"index\";\n\n/** A filename's stem: the name with its extension stripped. */\nconst stemOf = (filename: string): string =>\n filename.replace(extname(filename), \"\");\n\n/**\n * The stem of a nav path's last segment. The single index-detection input for\n * the warn path (`sidebarDisplayIgnoredDiagnostics`) and the apply path\n * (`buildFileSystemSidebar`), so the two can't drift apart on what counts as\n * a folder's index page.\n */\nconst navStem = (navPath: string): string =>\n stemOf(navPath.split(\"/\").at(-1) ?? navPath);\n\ninterface MutablePage {\n kind: \"page\";\n key: string;\n label: string;\n route: string;\n description?: string;\n icon?: string;\n badge?: string;\n deprecated?: boolean;\n pageId: string;\n /** Absolute source path (filesystem adapter only), to anchor diagnostics. */\n file?: string;\n order: number;\n /**\n * Whether `order` reflects a deliberate authoring choice (explicit\n * `sidebar.order`, a numeric filename prefix, or a folder-meta `pages` rank)\n * rather than a derived value like a changelog entry's publish date — two\n * changelog entries published on the same day aren't an authoring mistake,\n * so they're excluded from the duplicate-order diagnostic.\n */\n orderIsAuthored: boolean;\n}\n\ninterface MutableGroup {\n kind: \"group\";\n key: string;\n path: string;\n /** The group's URL path (folder route prefix); set as pages are inserted. */\n routePath?: string;\n /** The folder's index page route, when it has one; the group row's link. */\n route?: string;\n label: string;\n icon?: string;\n collapsed?: boolean;\n display?: SidebarDisplay;\n order: number;\n children: MutableNode[];\n index: Map<string, MutableGroup>;\n}\n\ntype MutableNode = MutablePage | MutableGroup;\n\nconst createGroup = (\n key: string,\n path: string,\n label: string,\n order: number\n): MutableGroup => ({\n children: [],\n index: new Map(),\n key,\n kind: \"group\",\n label,\n order,\n path,\n});\n\nconst ensureGroup = (\n parent: MutableGroup,\n rawSegment: string\n): MutableGroup => {\n const existing = parent.index.get(rawSegment);\n if (existing) {\n return existing;\n }\n const path = parent.path ? `${parent.path}/${rawSegment}` : rawSegment;\n const group = createGroup(\n segmentKey(rawSegment),\n path,\n humanize(rawSegment.match(GROUP_FOLDER)?.groups?.label ?? rawSegment),\n numericOrder(rawSegment)\n );\n parent.index.set(rawSegment, group);\n parent.children.push(group);\n return group;\n};\n\ninterface PageOrder {\n order: number;\n /** Whether the order came from the author (frontmatter or a rank prefix). */\n orderIsAuthored: boolean;\n}\n\nconst pageOrder = (page: PageRecord, filename: string): PageOrder => {\n if (page.meta.sidebar.order !== undefined) {\n return { order: page.meta.sidebar.order, orderIsAuthored: true };\n }\n if (isIndexStem(stemOf(filename))) {\n return { order: Number.NEGATIVE_INFINITY, orderIsAuthored: false };\n }\n // Changelog entries read newest-first, matching the generated timeline. Sort\n // on the negated publish timestamp so a later date yields a smaller order\n // under the ascending comparator; undated entries fall back to filename order.\n // The date is derived, not an authoring choice, so same-day entries aren't a\n // duplicate-order mistake.\n if (page.contentType === \"changelog\") {\n const iso = page.meta.date ?? page.meta.changelog?.date;\n const time = iso ? Date.parse(iso) : Number.NaN;\n if (!Number.isNaN(time)) {\n return { order: -time, orderIsAuthored: false };\n }\n }\n // An undated changelog entry's numeric filename prefix is usually a date\n // (`2024-01-05-release.md`) rather than a rank, so it is derived too.\n const order = numericOrder(filename);\n return {\n order,\n orderIsAuthored: page.contentType !== \"changelog\" && Number.isFinite(order),\n };\n};\n\n/**\n * Folder-meta lookup key for a group path. Under i18n the meta files live in\n * the locale directory (`fr/guides/meta.ts` -> key `fr/guides`) while the\n * nav group path is locale-stripped (`guides`), so prepend the locale prefix.\n */\nconst metaKey = (path: string, metaPrefix: string): string => {\n if (!metaPrefix) {\n return path;\n }\n return path ? `${metaPrefix}/${path}` : metaPrefix;\n};\n\n/**\n * Apply folder meta (title/order/icon/collapsed/display and explicit page\n * order), plus the index-frontmatter display sugar collected per folder path.\n */\nconst applyFolderMeta = (\n group: MutableGroup,\n folderMeta: Map<string, FolderMeta>,\n sharedMeta: Map<string, FolderMeta>,\n metaPrefix: string,\n sharedMetaPrefix: string,\n indexDisplay: Map<string, SidebarDisplay>,\n indexRoute: Map<string, string>\n): void => {\n // A folder with an index page links its group row to it — the same shape\n // as an explicit-config group's `root`, and the only sidebar link to the\n // section's own page once the index row is hidden. Index-less folders keep\n // no link: their row would 404.\n group.route = indexRoute.get(group.path);\n // Locale-specific meta wins; a shared `meta.$.*` (keyed by the locale-stripped\n // group path — version-prefixed inside a snapshot) applies to every locale\n // otherwise.\n const meta =\n folderMeta.get(metaKey(group.path, metaPrefix)) ??\n sharedMeta.get(metaKey(group.path, sharedMetaPrefix));\n // The group's own render mode, resolved index frontmatter first, then folder\n // meta; `toNavNode` falls back to the global mode. Applies to this group\n // only — nested subgroups resolve their own value through the same chain.\n group.display = indexDisplay.get(group.path) ?? meta?.display;\n if (meta) {\n group.label = meta.title ?? group.label;\n group.icon = meta.icon ?? group.icon;\n group.order = meta.order ?? group.order;\n group.collapsed = meta.collapsed ?? group.collapsed;\n\n if (meta.pages) {\n const rank = new Map(meta.pages.map((key, i) => [key, i]));\n for (const child of group.children) {\n const position = rank.get(child.key);\n if (position !== undefined) {\n child.order = position;\n if (child.kind === \"page\") {\n child.orderIsAuthored = true;\n }\n }\n }\n }\n }\n\n for (const child of group.children) {\n if (child.kind === \"group\") {\n applyFolderMeta(\n child,\n folderMeta,\n sharedMeta,\n metaPrefix,\n sharedMetaPrefix,\n indexDisplay,\n indexRoute\n );\n }\n }\n};\n\n/**\n * Warn when an index page's own frontmatter title diverges from its folder's\n * explicit `meta.title`. The sidebar label and the page's own `<title>`/heading\n * are resolved from two independent sources — under i18n, a translator can\n * update the folder's `meta.ts` and forget the index page's own frontmatter\n * (or vice versa), and a correct-looking sidebar hides the mismatch.\n *\n * Only fires when the index page's own sidebar row is hidden\n * (`sidebar.hidden`), so the linked group header is the only sidebar label the\n * page has. A visible index row shows the page's own label beneath the header,\n * so the sidebar already carries both titles and a divergence there is a\n * deliberate pairing (\"CLI\" over \"Overview\"), not drift.\n *\n * Only fires when the page has an explicit frontmatter `title` of its own:\n * when it's absent, `page.title` is derived from the first heading or the\n * filename, so it almost never coincidentally matches a custom folder title —\n * flagging that would be noise on exactly the plain-landing-page case this is\n * least worth warning about. The root group's `meta.title` (an empty\n * `folderPath`) is also skipped: nothing ever renders it as a sidebar label,\n * so a mismatch there wouldn't correspond to anything visible.\n *\n * Fallback-filled pages are exempt: their title belongs to the fallback\n * locale, so comparing it against this locale's `meta.title` would flag every\n * not-yet-translated index page (once per locale) and point the suggestion at\n * the fallback locale's source file, where \"fixing\" it would break that\n * locale. The default locale's own build still checks the real page.\n */\nconst indexTitleMismatchDiagnostic = (\n page: PageRecord,\n folderPath: string,\n folderMeta: Map<string, FolderMeta>,\n sharedMeta: Map<string, FolderMeta>,\n metaPrefix: string,\n sharedMetaPrefix: string\n): Diagnostic | undefined => {\n if (\n !(page.meta.title && page.meta.sidebar.hidden) ||\n page.fallback ||\n folderPath === \"\"\n ) {\n return undefined;\n }\n const meta =\n folderMeta.get(metaKey(folderPath, metaPrefix)) ??\n sharedMeta.get(metaKey(folderPath, sharedMetaPrefix));\n if (!meta?.title || meta.title === page.title) {\n return undefined;\n }\n return {\n code: \"BLUME_NAV_INDEX_TITLE_MISMATCH\",\n file: page.sourcePath ?? page.id,\n message: `Index page \"${page.navPath}\" has title \"${page.title}\", but its folder's meta.title is \"${meta.title}\" — the sidebar shows the folder title while the page's own <title>/heading still say \"${page.title}\".`,\n severity: \"warning\",\n suggestion: `Update the page's frontmatter title to match (\"${meta.title}\"), or leave it if the divergence is intentional.`,\n };\n};\n\n/**\n * Warn wherever a page's `sidebar.display` is dead weight, instead of\n * silently dropping it:\n *\n * - On any page under an explicit `navigation.sidebar` config: the config\n * items own each group's display mode, and neither index frontmatter nor\n * folder meta is read — index pages included.\n * - On the content root's own index page: the root is not a sidebar group,\n * so there is nothing for the value to configure; the sidebar-wide mode\n * lives in `navigation.sidebar.display`.\n * - On any other non-index page: only a folder's index page can configure\n * its group's display mode.\n *\n * A non-root folder index under the generated sidebar is the one placement\n * that IS honored, so it alone is exempt. Under i18n fallback fill the same\n * source file is checked once per locale with an identical message, and the\n * graph-level code+file+message dedupe collapses the copies.\n */\nconst sidebarDisplayIgnoredDiagnostics = (\n pages: PageRecord[],\n explicitSidebar: boolean\n): Diagnostic[] => {\n const diagnostics: Diagnostic[] = [];\n for (const page of pages) {\n if (!page.meta.sidebar.display) {\n continue;\n }\n const isIndex = isIndexStem(navStem(page.navPath));\n if (explicitSidebar) {\n diagnostics.push({\n code: \"BLUME_SIDEBAR_DISPLAY_IGNORED\",\n file: page.sourcePath ?? page.id,\n message: `\"${page.navPath}\" sets sidebar.display, but the explicit navigation.sidebar config owns each group's display mode — the value is ignored.`,\n severity: \"warning\",\n suggestion:\n \"Set display on the matching group in navigation.sidebar, or remove the frontmatter key.\",\n });\n continue;\n }\n if (isIndex && !page.navPath.includes(\"/\")) {\n diagnostics.push({\n code: \"BLUME_SIDEBAR_DISPLAY_IGNORED\",\n file: page.sourcePath ?? page.id,\n message: `\"${page.navPath}\" sets sidebar.display, but the content root is not a sidebar group — the value is ignored.`,\n severity: \"warning\",\n suggestion:\n \"Set navigation.sidebar.display in blume.config to change the sidebar-wide mode.\",\n });\n continue;\n }\n if (isIndex) {\n continue;\n }\n diagnostics.push({\n code: \"BLUME_SIDEBAR_DISPLAY_IGNORED\",\n file: page.sourcePath ?? page.id,\n message: `\"${page.navPath}\" sets sidebar.display, but only a folder's index page can set its group's display mode — the value is ignored.`,\n severity: \"warning\",\n suggestion:\n \"Move display to the folder's index page frontmatter, or set it in the folder's meta.ts.\",\n });\n }\n return diagnostics;\n};\n\n/** Whether a node's `order` reflects a deliberate authoring choice. */\nconst isAuthoredOrder = (node: MutableNode): boolean =>\n node.kind === \"group\" || node.orderIsAuthored;\n\n/**\n * Warn when two sibling nodes share an explicit/numeric order (frontmatter\n * `sidebar.order`, a numeric filename prefix, or folder-meta `order`) — they'd\n * otherwise fall back to a silent, arbitrary alphabetical tiebreak. Nodes at\n * the default fallback order (no numeric prefix, no explicit order) are\n * excluded: that's the common, intentional case of \"just sort alphabetically.\"\n * So is a derived, non-authored order (e.g. two changelog entries published\n * on the same day) — not an authoring mistake.\n */\nconst duplicateOrderDiagnostics = (nodes: MutableNode[]): Diagnostic[] => {\n const byOrder = new Map<number, MutableNode[]>();\n for (const node of nodes) {\n if (!Number.isFinite(node.order) || !isAuthoredOrder(node)) {\n continue;\n }\n const tied = byOrder.get(node.order);\n if (tied) {\n tied.push(node);\n } else {\n byOrder.set(node.order, [node]);\n }\n }\n const diagnostics: Diagnostic[] = [];\n for (const [order, tied] of byOrder) {\n if (tied.length > 1) {\n const names = tied.map((node) => `\"${node.label}\"`);\n const list =\n names.length > 2\n ? `${names.slice(0, -1).join(\", \")}, and ${names.at(-1)}`\n : names.join(\" and \");\n const verb = tied.length > 2 ? \"all have\" : \"both have\";\n // Anchor the diagnostic to one tied source file so tooling can point\n // somewhere concrete; the message names the rest. Folder-only ties\n // (folder-meta `order`) have no single file, so `file` stays unset.\n const file = tied.find(\n (node): node is MutablePage => node.kind === \"page\"\n )?.file;\n diagnostics.push({\n code: \"BLUME_DUPLICATE_SIDEBAR_ORDER\",\n file,\n message: `${list} ${verb} sidebar order ${order}; falling back to alphabetical order.`,\n severity: \"warning\",\n suggestion:\n \"Give each item a distinct sidebar.order (or folder meta order).\",\n });\n }\n }\n return diagnostics;\n};\n\nconst sortNodes = (nodes: MutableNode[], diagnostics: Diagnostic[]): void => {\n diagnostics.push(...duplicateOrderDiagnostics(nodes));\n nodes.sort((a, b) => {\n if (a.order !== b.order) {\n return a.order - b.order;\n }\n return a.label.localeCompare(b.label);\n });\n for (const node of nodes) {\n if (node.kind === \"group\") {\n sortNodes(node.children, diagnostics);\n }\n }\n};\n\n/**\n * Hoist loose pages above groups so they read as their own level's entries\n * rather than a preceding group's trailing children (relative order otherwise\n * preserved). The root level always hoists, in every display mode. A deeper\n * level hoists only when a sibling group renders flat — a flat group is a\n * plain section header, so a loose page sorted after it would visually read\n * as its last child — while `group`/`page` groups are self-delimiting\n * disclosure/drill-in rows, so authored interleaving is kept. Each group's\n * render mode is its own resolved `display` falling back to the global mode,\n * mirroring `toNavNode`.\n */\nconst hoistPages = (\n nodes: MutableNode[],\n display: SidebarDisplay,\n hoist: boolean\n): void => {\n const groups = nodes.filter((node) => node.kind === \"group\");\n if (hoist || groups.some((group) => (group.display ?? display) === \"flat\")) {\n const pages = nodes.filter((node) => node.kind === \"page\");\n nodes.splice(0, nodes.length, ...pages, ...groups);\n }\n for (const group of groups) {\n hoistPages(group.children, display, false);\n }\n};\n\n/**\n * With tabs configured, the sidebar shown under a tab is that tab-section\n * group's *children*, not the tree root — so hoisting only the root leaves a\n * tab section's loose pages interleaved with its groups. Hoist the top level of\n * every group that owns a tab (matched on its URL path), mirroring the root.\n */\nconst hoistTabSections = (\n nodes: MutableNode[],\n tabPaths: Set<string>,\n display: SidebarDisplay\n): void => {\n for (const node of nodes) {\n if (node.kind !== \"group\") {\n continue;\n }\n if (node.routePath !== undefined && tabPaths.has(node.routePath)) {\n hoistPages(node.children, display, true);\n }\n hoistTabSections(node.children, tabPaths, display);\n }\n};\n\nconst toNavNode = (node: MutableNode, display: SidebarDisplay): NavNode => {\n if (node.kind === \"page\") {\n return {\n badge: node.badge,\n deprecated: node.deprecated || undefined,\n description: node.description,\n icon: node.icon,\n kind: \"page\",\n label: node.label,\n pageId: node.pageId,\n route: node.route,\n };\n }\n return {\n children: node.children.map((child) => toNavNode(child, display)),\n collapsed: node.collapsed,\n display: node.display ?? display,\n icon: node.icon,\n kind: \"group\",\n label: node.label,\n path: node.routePath,\n route: node.route,\n };\n};\n\n/** Build the sidebar tree from the file system and folder meta. */\nconst buildFileSystemSidebar = (\n pages: PageRecord[],\n folderMeta: Map<string, FolderMeta>,\n sharedMeta: Map<string, FolderMeta>,\n metaPrefix: string,\n sharedMetaPrefix: string,\n display: SidebarDisplay,\n tabPaths: Set<string>,\n diagnostics: Diagnostic[] = []\n): NavNode[] => {\n const root = createGroup(\"\", \"\", \"\", 0);\n // Folder path -> `sidebar.display` from that folder's index page frontmatter.\n // Collected before the hidden filter (like the title check): hiding the index\n // row from the panel shouldn't stop it configuring its group.\n const indexDisplay = new Map<string, SidebarDisplay>();\n // Folder path -> that folder's index page route, for the group row's link.\n // Also collected before the hidden filter: hiding the index row is how a\n // site drops the duplicate label under a linked header, so the link must\n // survive it. The content root is not a group, so its index is skipped.\n const indexRoute = new Map<string, string>();\n\n for (const page of pages) {\n // Group by the locale-stripped path so the locale dir is not a nav group.\n const parts = page.navPath.split(\"/\");\n const filename = parts.at(-1) ?? page.navPath;\n const stem = stemOf(filename);\n const dirs = parts.slice(0, -1);\n\n // Checked before the hidden filter: the title check fires only for a\n // sidebar-hidden index page, whose own <title> the header label stands in\n // for, so it must see the pages the filter drops.\n if (isIndexStem(stem)) {\n const diagnostic = indexTitleMismatchDiagnostic(\n page,\n dirs.join(\"/\"),\n folderMeta,\n sharedMeta,\n metaPrefix,\n sharedMetaPrefix\n );\n if (diagnostic) {\n diagnostics.push(diagnostic);\n }\n // Fallback-filled pages are exempt (like the title check above): their\n // frontmatter belongs to the fallback locale, and letting it through\n // would override this locale's own authored `meta.ts` display — then\n // silently flip again the day the index gets translated.\n if (page.meta.sidebar.display && !page.fallback) {\n indexDisplay.set(dirs.join(\"/\"), page.meta.sidebar.display);\n }\n if (dirs.length > 0) {\n indexRoute.set(dirs.join(\"/\"), page.route);\n }\n }\n\n if (page.meta.sidebar.hidden) {\n continue;\n }\n\n // Each group's URL path is the matching prefix of the page's route. navPath\n // is locale-stripped while the route may carry a locale/base prefix, so\n // align the folder segments from the right (the extra leading segments are\n // that prefix). Under such a prefix the path won't match a logical tab path,\n // so tab-scoping simply no-ops — same as the header's active-tab logic.\n // An index page's route IS its folder's route (no page segment to drop),\n // and `(group)` folders contribute no route segment at all.\n const routeSegments = page.route.split(\"/\").filter(Boolean);\n const folderParts = isIndexStem(stem)\n ? routeSegments\n : routeSegments.slice(0, -1);\n const routeDirCount = dirs.filter((dir) => !GROUP_FOLDER.test(dir)).length;\n const offset = Math.max(0, folderParts.length - routeDirCount);\n\n let parent = root;\n let consumed = offset;\n for (const dir of dirs) {\n parent = ensureGroup(parent, dir);\n if (!GROUP_FOLDER.test(dir)) {\n consumed += 1;\n }\n parent.routePath ??= `/${folderParts.slice(0, consumed).join(\"/\")}`;\n }\n\n const { order, orderIsAuthored } = pageOrder(page, filename);\n parent.children.push({\n badge: page.meta.sidebar.badge,\n deprecated: page.meta.deprecated || undefined,\n description: page.description,\n file: page.sourcePath,\n icon: sidebarIcon(page),\n key: segmentKey(stem),\n kind: \"page\",\n label: page.meta.sidebar.label ?? page.title,\n order,\n orderIsAuthored,\n pageId: page.id,\n route: page.route,\n });\n }\n\n applyFolderMeta(\n root,\n folderMeta,\n sharedMeta,\n metaPrefix,\n sharedMetaPrefix,\n indexDisplay,\n indexRoute\n );\n sortNodes(root.children, diagnostics);\n hoistPages(root.children, display, true);\n hoistTabSections(root.children, tabPaths, display);\n return root.children.map((child) => toNavNode(child, display));\n};\n\nconst normalizeRef = (ref: string): string => {\n if (ref === \"index\") {\n return \"/\";\n }\n const withSlash = ref.startsWith(\"/\") ? ref : `/${ref}`;\n // Routes are stored slashless (`/guides`, not `/guides/`); a hand-written\n // `\"guides/\"` ref must still find its page instead of being silently\n // dropped from the sidebar.\n const noTrailing = withSlash.replace(/\\/+$/u, \"\");\n const trimmed = noTrailing.endsWith(\"/index\")\n ? noTrailing.slice(0, -\"/index\".length)\n : noTrailing;\n // \"/index\" trims to \"\" — that's the root, not an empty route.\n return trimmed === \"\" ? \"/\" : trimmed;\n};\n\nconst routeForRef = (\n ref: string | undefined,\n byRoute: Map<string, PageRecord>,\n basePath: string\n): string | undefined => {\n if (!ref) {\n return undefined;\n }\n const normalized = normalizeRef(ref);\n // A matched page carries an already-based `route`; an unmatched ref is an\n // author-written root-relative path that still needs the base applied.\n return byRoute.get(normalized)?.route ?? withBasePath(basePath, normalized);\n};\n\n/** An explicit-config sidebar item written as a bare page-ref string. */\nconst isPageRef = (item: SidebarItemConfig): item is string =>\n typeof item === \"string\";\n\n/**\n * Convert one non-group explicit-config sidebar item (string ref, `root`, or\n * `href`) to a nav node, or null to skip. Group items (`item.items`) are handled\n * by `buildConfigSidebar` itself so it owns the recursion.\n */\nconst configItemToNode = (\n item: SidebarItemConfig,\n byRoute: Map<string, PageRecord>,\n basePath: string\n): NavNode | null => {\n if (isPageRef(item)) {\n const page = byRoute.get(normalizeRef(item));\n if (!page) {\n return null;\n }\n return {\n badge: page.meta.sidebar.badge,\n deprecated: page.meta.deprecated || undefined,\n description: page.description,\n icon: sidebarIcon(page),\n kind: \"page\",\n label: page.meta.sidebar.label ?? page.title,\n pageId: page.id,\n route: page.route,\n };\n }\n\n if (item.root) {\n const page = byRoute.get(normalizeRef(item.root));\n return {\n badge: item.badge,\n deprecated: page?.meta.deprecated || undefined,\n icon: item.icon,\n kind: \"page\",\n label: item.label,\n pageId: page?.id ?? \"\",\n route: page?.route ?? withBasePath(basePath, normalizeRef(item.root)),\n };\n }\n\n if (item.href) {\n return {\n badge: item.badge,\n icon: item.icon,\n kind: \"page\",\n label: item.label,\n pageId: \"\",\n route: withBasePath(basePath, item.href),\n };\n }\n\n return null;\n};\n\n/** Build the sidebar tree from an explicit config spec. */\nconst buildConfigSidebar = (\n items: SidebarItemConfig[],\n byRoute: Map<string, PageRecord>,\n display: SidebarDisplay,\n basePath: string\n): NavNode[] => {\n const nodes: NavNode[] = [];\n for (const item of items) {\n if (!isPageRef(item) && item.items) {\n nodes.push({\n badge: item.badge,\n children: buildConfigSidebar(item.items, byRoute, display, basePath),\n collapsed: item.collapsed,\n directory: item.directory,\n display: item.display ?? display,\n icon: item.icon,\n kind: \"group\",\n label: item.label,\n route: routeForRef(item.root, byRoute, basePath),\n });\n continue;\n }\n const node = configItemToNode(item, byRoute, basePath);\n if (node) {\n nodes.push(node);\n }\n }\n return nodes;\n};\n\n/**\n * Resolve a tab's clickable target. A tab's `path` scopes its sidebar section\n * but need not be a real route — a section with no index page would 404 if the\n * tab linked straight to it. Prefer the path itself when it's served outside\n * the content tree (the generated changelog index) or is a page/group in the\n * tree; otherwise fall back to the first linkable route in the section\n * (sidebar order).\n *\n * Routes outside the content tree are served at their own path, not under\n * `basePath` (`pages/changelog.astro` answers `/changelog` on a `/docs`-based\n * site), while tab paths arrive based (`/docs/changelog`). So when the based\n * path is neither an outside route nor a tree node, the base-less path is\n * checked against the outside routes before the section's first page wins.\n */\nconst resolveTabHref = (\n sidebar: NavNode[],\n path: string,\n extraRoutes: ReadonlySet<string>,\n basePath: string\n): string => {\n if (extraRoutes.has(path)) {\n return path;\n }\n let first: string | undefined;\n const walk = (nodes: NavNode[]): boolean => {\n for (const node of nodes) {\n const { route } = node;\n if (route === path) {\n return true;\n }\n if (\n first === undefined &&\n route !== undefined &&\n route.startsWith(`${path}/`)\n ) {\n first = route;\n }\n if (node.kind === \"group\" && walk(node.children)) {\n return true;\n }\n }\n return false;\n };\n if (walk(sidebar)) {\n return path;\n }\n const bare = stripBasePath(basePath, path);\n return extraRoutes.has(bare) ? bare : (first ?? path);\n};\n\n/**\n * Attach a resolved `href` to each tab whose section has no index page. An\n * author-declared `href` is the tab's stated target, so it's kept as-is —\n * resolution only fills in the tabs that didn't declare one. That's what lets a\n * tab point at a route outside the content tree that resolution can't see (a\n * custom `.astro` page); the generated changelog index arrives in\n * `extraRoutes`, so a `/changelog` tab needs no `href`.\n */\nconst withTabHrefs = (\n tabs: NavTab[],\n sidebar: NavNode[],\n extraRoutes: ReadonlySet<string>,\n basePath: string\n): NavTab[] =>\n tabs.map((tab) => {\n const href =\n tab.href ?? resolveTabHref(sidebar, tab.path, extraRoutes, basePath);\n return href === tab.path ? tab : { ...tab, href };\n });\n\n/**\n * Rebase config-provided nav chrome (featured links, selectors, tabs) under the\n * site base path. Config paths are authored as if mounted at root, so the base\n * is applied here (idempotently, and only to internal paths — external URLs\n * pass through). With no base this is a pure pass-through — the arrays keep\n * their exact authored shape.\n */\ninterface NavChrome {\n actions: HeaderAction[];\n cta: HeaderAction | null;\n featured: FeaturedLink[];\n selectors: NavSelector[];\n tabs: NavTab[];\n}\n\nconst rebaseNavChrome = (\n basePath: string,\n options: {\n actions?: HeaderAction[];\n cta?: HeaderAction | null;\n featured?: FeaturedLink[];\n selectors?: NavSelector[];\n tabs?: NavTab[];\n }\n): NavChrome => {\n const actions = options.actions ?? [];\n const cta = options.cta ?? null;\n const featured = options.featured ?? [];\n const selectors = options.selectors ?? [];\n const tabs = options.tabs ?? [];\n if (!basePath) {\n return { actions, cta, featured, selectors, tabs };\n }\n const rebaseHref = <T extends { href: string }>(item: T): T => ({\n ...item,\n href: withBasePath(basePath, item.href),\n });\n const rebasePath = <T extends { path: string }>(item: T): T => ({\n ...item,\n path: withBasePath(basePath, item.path),\n });\n return {\n actions: actions.map(rebaseHref),\n cta: cta ? rebaseHref(cta) : null,\n featured: featured.map(rebaseHref),\n selectors: selectors.map((selector) => ({\n ...selector,\n items: selector.items.map(rebasePath),\n })),\n tabs: tabs.map((tab) => {\n const rebased: NavTab = {\n ...tab,\n items: tab.items?.map(rebasePath),\n path: withBasePath(basePath, tab.path),\n };\n if (tab.href) {\n rebased.href = withBasePath(basePath, tab.href);\n }\n return rebased;\n }),\n };\n};\n\n/** Build the complete navigation model from pages, meta, and config. */\nexport const buildNavigation = (\n pages: PageRecord[],\n options: {\n /** Plain links in the header, left of the icon buttons. */\n actions?: HeaderAction[];\n /** Site-wide route mount point (`\"\"` or `/seg`); applied to config paths. */\n basePath?: string;\n /** The single primary call to action in the header. */\n cta?: HeaderAction | null;\n folderMeta: Map<string, FolderMeta>;\n /** Global display mode for every sidebar group (default `flat`). */\n display?: SidebarDisplay;\n featured?: FeaturedLink[];\n selectors?: NavSelector[];\n tabs?: NavTab[];\n sidebar?: SidebarItemConfig[];\n /**\n * Folder-meta lookup prefix (`\"\"` for the default locale of the current\n * version): the version dir and/or locale dir hoisted in front of the\n * group path, e.g. `fr`, `v1.0`, or `v1.0/fr`.\n */\n metaPrefix?: string;\n /**\n * Prefix for shared `meta.$.*` lookups — the version dir inside a\n * snapshot (`v1.0`), since shared meta is locale-agnostic but still\n * version-specific. `\"\"` for the current version.\n */\n sharedMetaPrefix?: string;\n /**\n * Resolve explicit-sidebar references against each page's locale-agnostic\n * `translationKey` instead of its localized `route`. Used under i18n so a\n * single authored sidebar maps onto every locale's pages.\n */\n refByLogical?: boolean;\n /** Shared `meta.$.*` meta, keyed by locale-stripped dir path. */\n sharedFolderMeta?: Map<string, FolderMeta>;\n /**\n * The tree's root route before `basePath` (`\"/\"`, or the locale prefix\n * under i18n, e.g. `/fr` — tab paths arrive already localized). The tab\n * pointing here spans the whole tree, so it is excluded from tab-section\n * scoping.\n */\n localizedRoot?: string;\n /**\n * Sink for diagnostics produced while building the tree (duplicate sidebar\n * `order` values, index-page title/folder-meta-title mismatches). Pushed\n * into in place; omit to discard.\n */\n diagnostics?: Diagnostic[];\n /**\n * Routes served outside the content tree that a tab `path` may name\n * directly (the generated changelog index), so the tab links there instead\n * of falling back to its section's first page.\n */\n extraRoutes?: ReadonlySet<string>;\n }\n): Navigation => {\n const basePath = options.basePath ?? \"\";\n const display = options.display ?? \"flat\";\n const metaPrefix = options.metaPrefix ?? \"\";\n const sharedMetaPrefix = options.sharedMetaPrefix ?? \"\";\n const sharedFolderMeta = options.sharedFolderMeta ?? new Map();\n const extraRoutes = options.extraRoutes ?? new Set<string>();\n\n // Content-derived sidebar routes are already based via `page.route`; the\n // based tab paths also feed tab-scoping below, so they must agree with the\n // based content routes.\n const { actions, cta, featured, selectors, tabs } = rebaseNavChrome(\n basePath,\n options\n );\n const byRoute = new Map(\n pages.map((page) => [\n options.refByLogical ? page.translationKey : page.route,\n page,\n ])\n );\n // Explicit-sidebar refs (`\"foo/index\"`) are authored as if mounted at root,\n // but `page.route` carries the base — alias each page under its base-less\n // route so a bare ref still resolves. (The i18n `refByLogical` map is already\n // keyed by the base-less `translationKey`, so it needs no alias.)\n if (basePath && !options.refByLogical) {\n for (const page of pages) {\n const bare = stripBasePath(basePath, page.route);\n if (!byRoute.has(bare)) {\n byRoute.set(bare, page);\n }\n }\n }\n\n // A tab pointing at the tree root spans the whole sidebar rather than one\n // section, so it must not feed tab-section hoisting. `tabs` carries final\n // paths (localized, then based), so the root is compared in the same space —\n // a root-level `(group)` folder's routePath is exactly the based/localized\n // prefix (`/docs`, `/fr`) and a bare `\"/\"` check would miss the match (or,\n // under a base, falsely scope a group named like the prefix). Carried on the\n // returned navigation so render-time scoping compares in the same space too.\n // In a version snapshot the root arrives versionized (`/v1.0`) while tab\n // paths stay in current-docs space, so root-tab checks use `isRootTab`\n // containment, not equality.\n const rootTabPath = withBasePath(basePath, options.localizedRoot ?? \"/\");\n\n // Emitted here, before the sidebar-mode branch: an explicit config sidebar\n // ignores a stray `sidebar.display` just like the filesystem sidebar does\n // (and ignores it on index pages too), so both paths must warn.\n const diagnostics = options.diagnostics ?? [];\n diagnostics.push(\n ...sidebarDisplayIgnoredDiagnostics(pages, Boolean(options.sidebar))\n );\n\n if (options.sidebar) {\n const sidebar = buildConfigSidebar(\n options.sidebar,\n byRoute,\n display,\n basePath\n );\n return {\n actions,\n cta,\n featured,\n root: rootTabPath,\n selectors,\n sidebar,\n tabs: withTabHrefs(tabs, sidebar, extraRoutes, basePath),\n };\n }\n\n const sidebar = buildFileSystemSidebar(\n pages,\n options.folderMeta,\n sharedFolderMeta,\n metaPrefix,\n sharedMetaPrefix,\n display,\n new Set(\n tabs.flatMap((tab) => (isRootTab(tab, rootTabPath) ? [] : [tab.path]))\n ),\n diagnostics\n );\n return {\n actions,\n cta,\n featured,\n root: rootTabPath,\n selectors,\n sidebar,\n tabs: withTabHrefs(tabs, sidebar, extraRoutes, basePath),\n };\n};\n",
11
- "import { withBasePath } from \"./base-path.ts\";\nimport {\n localizeInternalPath,\n localizeRoute,\n resolveFallbackLocale,\n} from \"./i18n.ts\";\nimport { validateNavIcons, validateNavStructure } from \"./nav-diagnostics.ts\";\nimport { buildNavigation } from \"./navigation.ts\";\nimport type {\n FolderMeta,\n LocalizableLabel,\n ResolvedConfig,\n ResolvedI18nConfig,\n ResolvedVersionsConfig,\n} from \"./schema.ts\";\nimport type {\n ContentGraph,\n Diagnostic,\n Navigation,\n NavTab,\n PageRecord,\n} from \"./types.ts\";\nimport { versionizeRoute } from \"./versions.ts\";\n\ninterface BuildContentGraphOptions {\n /** Site-wide route mount point (`\"\"` or `/seg`); invisible to the nav tree. */\n basePath?: string;\n /** The header brand link as configured (`logo.href`, default `/`). */\n brandHref?: string;\n /** Routes served outside the content tree that tabs may link to directly. */\n extraRoutes?: ReadonlySet<string>;\n folderMeta: Map<string, FolderMeta>;\n sharedFolderMeta?: Map<string, FolderMeta>;\n navigation: ResolvedConfig[\"navigation\"];\n i18n?: ResolvedI18nConfig;\n versions?: ResolvedVersionsConfig;\n}\n\ntype FallbackLocale = ReturnType<typeof resolveFallbackLocale>;\n\n/** Build the route → page-id map, flagging any duplicate-route collisions. */\nconst collectRoutes = (pages: PageRecord[]) => {\n const routes = new Map<string, string>();\n const diagnostics: Diagnostic[] = [];\n for (const page of pages) {\n const existing = routes.get(page.route);\n if (existing) {\n diagnostics.push({\n code: \"BLUME_DUPLICATE_ROUTE\",\n file: page.sourcePath ?? page.id,\n message: `Two files resolve to ${page.route}: ${existing} and ${page.id}`,\n severity: \"error\",\n suggestion: \"Rename or move one of the files so each route is unique.\",\n });\n continue;\n }\n routes.set(page.route, page.id);\n }\n return { diagnostics, routes };\n};\n\n/**\n * A locale's pages, padded with fallback-locale entries for any translation it\n * hasn't authored yet, so navigation mirrors the default structure instead of\n * showing an empty (or partial) tree.\n */\nconst localePagesFor = (\n code: string,\n real: PageRecord[],\n fallback: FallbackLocale,\n fallbackByKey: Map<string, PageRecord>,\n i18n: ResolvedI18nConfig,\n basePath: string\n): PageRecord[] => {\n if (!(fallback && code !== fallback)) {\n return real;\n }\n const present = new Set(real.map((page) => page.translationKey));\n const filled: PageRecord[] = [];\n for (const [key, source] of fallbackByKey) {\n if (!present.has(key)) {\n filled.push({\n ...source,\n fallback: true,\n locale: code,\n route: withBasePath(basePath, localizeRoute(key, code, i18n)),\n });\n }\n }\n return [...real, ...filled];\n};\n\n/**\n * Resolve a possibly-per-locale header label to the string a locale renders:\n * the active locale's entry, else the default locale's, else the map's first\n * entry (which is also what a single-locale site gets).\n */\n/** A label is either one string for every locale or a per-locale map. */\nconst isSingleLabel = (label: LocalizableLabel): label is string =>\n typeof label === \"string\";\n\nconst resolveLabel = (\n label: LocalizableLabel,\n locale: string,\n defaultLocale?: string\n): string => {\n if (isSingleLabel(label)) {\n return label;\n }\n return (\n label[locale] ??\n (defaultLocale === undefined ? undefined : label[defaultLocale]) ??\n Object.values(label)[0] ??\n \"\"\n );\n};\n\n/** Resolve every localizable label in the configured tabs for one locale. */\nconst resolveTabLabels = (\n tabs: BuildContentGraphOptions[\"navigation\"][\"tabs\"],\n locale: string,\n defaultLocale?: string\n): NavTab[] =>\n (tabs ?? []).map((tab) => ({\n ...tab,\n items: tab.items?.map((item) => ({\n ...item,\n label: resolveLabel(item.label, locale, defaultLocale),\n })),\n label: resolveLabel(tab.label, locale, defaultLocale),\n }));\n\n/**\n * Build one locale's navigation tree from its own pages and folder meta.\n * `version` is the archived version id when building a snapshot's tree\n * (`\"\"` for the current docs): it shifts the folder-meta lookups into the\n * snapshot's key space and roots the tree at the localized version root.\n */\nconst buildLocaleNavigation = (\n code: string,\n pages: PageRecord[],\n fallback: FallbackLocale,\n fallbackByKey: Map<string, PageRecord>,\n options: BuildContentGraphOptions,\n i18n: ResolvedI18nConfig,\n diagnostics: Diagnostic[],\n version = \"\"\n): Navigation => {\n const basePath = options.basePath ?? \"\";\n const real = pages.filter((page) => page.locale === code);\n const localePages = localePagesFor(\n code,\n real,\n fallback,\n fallbackByKey,\n i18n,\n basePath\n );\n // Every route the build serves: each locale's pages (this locale's fallback\n // copies included) plus the routes outside the content tree — custom pages\n // and the generated changelog index, which mount outside `basePath`.\n const pageRoutes = [\n ...new Set([...pages, ...localePages].map((page) => page.route)),\n ];\n const extraRoutes = options.extraRoutes ?? new Set<string>();\n // Whether `path` (authored at root, like a tab path) is served — exactly, or\n // with `section`, as the prefix of a served page (a tab resolves to its\n // section's first page, a plain link doesn't).\n const serves = (path: string, section: boolean): boolean => {\n if (extraRoutes.has(path)) {\n return true;\n }\n const based = withBasePath(basePath, path);\n const prefix = based === \"/\" ? \"/\" : `${based}/`;\n return pageRoutes.some(\n (route) => route === based || (section && route.startsWith(prefix))\n );\n };\n // Localize an internal link so it points to its in-locale route (e.g. `/docs`\n // -> `/fr/docs`); external paths pass through. A route this locale doesn't\n // serve while the default one does — a custom page, the generated changelog\n // index — exists only at its own path, so the link stays there instead of\n // 404ing. Tab paths (and their dropdown items') resolve to a section's first\n // page, so a translated section counts; hrefs must be served exactly.\n // Selectors are left alone: a language selector's items intentionally target\n // specific locales. The header's brand link resolves the same way, so the\n // logo and the tabs beside it always agree on the reader's locale.\n const localizeServed = (path: string, section: boolean): string => {\n const localized = localizeInternalPath(path, code, i18n);\n return localized === path ||\n serves(localized, section) ||\n !serves(path, section)\n ? localized\n : path;\n };\n const localizePath = (path: string): string => localizeServed(path, true);\n const tabs = resolveTabLabels(\n options.navigation.tabs,\n code,\n i18n.defaultLocale\n ).map((tab) => {\n const localized = {\n ...tab,\n items: tab.items?.map((item) => ({\n ...item,\n path: localizePath(item.path),\n })),\n path: localizePath(tab.path),\n };\n if (localized.href) {\n localized.href = localizeServed(localized.href, false);\n }\n return localized;\n });\n // Meta files live in locale directories only under the `dir` parser\n // (`fr/guides/meta.ts` -> key `fr/guides`). Under `dot`, translations sit\n // next to the originals and `guides/meta.ts` applies to every locale —\n // prefixing would look up keys that can never exist. Inside a snapshot the\n // version dir is hoisted in front (`v1.0/fr`), matching `discoverFolderMeta`.\n const localeDir =\n i18n.parser === \"dir\" && code !== i18n.defaultLocale ? code : \"\";\n // Internal featured and header hrefs are localized like tab paths — a pinned\n // `/changelog` link rendered on `/fr/…` pages must stay inside the reader's\n // locale, not kick them back to the default one.\n const localizeHref = <T extends { href: string }>(item: T): T => ({\n ...item,\n href: localizeServed(item.href, false),\n });\n const { actions, cta, featured } = options.navigation;\n\n const navigation = buildNavigation(localePages, {\n actions: actions?.map(localizeHref),\n basePath,\n cta: cta ? localizeHref(cta) : null,\n diagnostics,\n display: options.navigation.sidebar.display,\n extraRoutes: options.extraRoutes,\n featured: featured?.map(localizeHref),\n folderMeta: options.folderMeta,\n // The localized tree root (\"/\" for the hidden default, \"/fr\" otherwise;\n // \"/fr/v1.0\" inside a snapshot): the tab pointing here spans the whole\n // tree and must not be treated as a tab section.\n localizedRoot: localizeRoute(versionizeRoute(\"/\", version), code, i18n),\n metaPrefix: [version, localeDir].filter(Boolean).join(\"/\"),\n refByLogical: true,\n selectors: options.navigation.selectors,\n sharedFolderMeta: options.sharedFolderMeta,\n // Shared `meta.$.*` files are locale-agnostic but version-specific: a\n // snapshot's shared meta keys under its version dir.\n sharedMetaPrefix: version,\n // A configured explicit sidebar describes the current docs; a frozen\n // snapshot's structure comes from the snapshot itself, so archived trees\n // always build from the filesystem.\n sidebar: version ? undefined : options.navigation.sidebar.items,\n tabs,\n });\n return options.brandHref === undefined\n ? navigation\n : { ...navigation, brandHref: localizeServed(options.brandHref, false) };\n};\n\n/**\n * Per-locale navigation trees plus the default-locale tree for i18n sites.\n * Called once for the current docs and once per archived version (with that\n * version's pages and its id as `version`).\n */\nconst buildI18nNavigation = (\n pages: PageRecord[],\n options: BuildContentGraphOptions,\n i18n: ResolvedI18nConfig,\n diagnostics: Diagnostic[],\n version = \"\"\n) => {\n // Pages of the fallback locale, by translation key — used to fill in a\n // locale's sidebar for pages it hasn't translated yet.\n const fallback = resolveFallbackLocale(i18n);\n // Monolingual pages (GitHub releases) are left out: they aren't served at the\n // other locales' URLs (see the route manifest), so no sidebar may link there.\n const fallbackByKey = new Map<string, PageRecord>();\n if (fallback) {\n for (const page of pages) {\n if (page.locale === fallback && !page.monolingual) {\n fallbackByKey.set(page.translationKey, page);\n }\n }\n }\n\n // Each locale gets an independent tree, so navigation may diverge per language.\n // Untranslated pages are padded into every locale from the fallback, so a tie\n // in shared content would otherwise be re-reported once per locale — dedupe on\n // code + file + message, which are all locale-stable for padded pages. A\n // locale-specific tie names its own translated files/labels and survives.\n const navigationByLocale: Record<string, Navigation> = {};\n const seen = new Set<string>();\n for (const { code } of i18n.locales) {\n const localeDiagnostics: Diagnostic[] = [];\n navigationByLocale[code] = buildLocaleNavigation(\n code,\n pages,\n fallback,\n fallbackByKey,\n options,\n i18n,\n localeDiagnostics,\n version\n );\n for (const diagnostic of localeDiagnostics) {\n const key = `${diagnostic.code}\\n${diagnostic.file ?? \"\"}\\n${diagnostic.message}`;\n if (!seen.has(key)) {\n seen.add(key);\n diagnostics.push(diagnostic);\n }\n }\n }\n const navigation: Navigation = navigationByLocale[i18n.defaultLocale] ?? {\n featured: [],\n selectors: [],\n sidebar: [],\n tabs: [],\n };\n return { navigation, navigationByLocale };\n};\n\n/** One archived version's navigation trees, keyed by locale (`\"\"` sans i18n). */\nconst buildVersionNavigation = (\n id: string,\n versionPages: PageRecord[],\n options: BuildContentGraphOptions,\n diagnostics: Diagnostic[]\n) => {\n const { i18n } = options;\n if (i18n) {\n return buildI18nNavigation(versionPages, options, i18n, diagnostics, id)\n .navigationByLocale;\n }\n return {\n \"\": buildNavigation(versionPages, {\n actions: options.navigation.actions,\n basePath: options.basePath ?? \"\",\n cta: options.navigation.cta,\n diagnostics,\n display: options.navigation.sidebar.display,\n extraRoutes: options.extraRoutes,\n featured: options.navigation.featured,\n folderMeta: options.folderMeta,\n localizedRoot: versionizeRoute(\"/\", id),\n metaPrefix: id,\n selectors: options.navigation.selectors,\n sharedFolderMeta: options.sharedFolderMeta,\n sharedMetaPrefix: id,\n // A configured explicit sidebar describes the current docs; a snapshot's\n // structure comes from the snapshot itself.\n tabs: resolveTabLabels(options.navigation.tabs, \"\"),\n }),\n };\n};\n\n/** Assemble the content graph: routes map, nav, and duplicate diagnostics. */\nexport const buildContentGraph = (\n pages: PageRecord[],\n options: BuildContentGraphOptions\n): ContentGraph => {\n const { diagnostics, routes } = collectRoutes(pages);\n const { i18n } = options;\n\n // Under versioning, each version gets independent trees: navPath is\n // version-stripped, so mixing versions into one build would collide the\n // same logical page once per version.\n const currentPages = options.versions\n ? pages.filter((page) => page.version === \"\")\n : pages;\n\n // A single-locale site has no per-locale trees; the empty map is its\n // navigationByLocale.\n let navigationByLocale: Record<string, Navigation> = {};\n let navigation: Navigation;\n if (i18n) {\n ({ navigation, navigationByLocale } = buildI18nNavigation(\n currentPages,\n options,\n i18n,\n diagnostics\n ));\n } else {\n navigation = buildNavigation(currentPages, {\n actions: options.navigation.actions,\n basePath: options.basePath ?? \"\",\n cta: options.navigation.cta,\n diagnostics,\n display: options.navigation.sidebar.display,\n extraRoutes: options.extraRoutes,\n featured: options.navigation.featured,\n folderMeta: options.folderMeta,\n selectors: options.navigation.selectors,\n sharedFolderMeta: options.sharedFolderMeta,\n sidebar: options.navigation.sidebar.items,\n // No locale to prefer: a per-locale label map resolves to its first\n // entry on a single-locale site.\n tabs: resolveTabLabels(options.navigation.tabs, \"\"),\n });\n }\n\n const navigationByVersion: Record<string, Record<string, Navigation>> = {};\n for (const { id } of options.versions?.archived ?? []) {\n navigationByVersion[id] = buildVersionNavigation(\n id,\n pages.filter((page) => page.version === id),\n options,\n diagnostics\n );\n }\n\n // Icon typos, duplicate labels, and hidden-page-in-sidebar are validated on\n // the built navigation. Missing-target detection needs the full route set\n // (incl. custom + generated pages), so it runs later in generateRuntime.\n diagnostics.push(\n ...validateNavIcons(navigation),\n ...validateNavStructure(navigation, currentPages)\n );\n\n return {\n diagnostics,\n navigation,\n navigationByLocale,\n navigationByVersion,\n pages,\n routes,\n };\n};\n",
12
- "import { execFileSync } from \"node:child_process\";\n\nimport { relative } from \"pathe\";\n\nimport type { Diagnostic } from \"./types.ts\";\n\n/** Normalized form of the `lastModified` config. */\nexport interface ResolvedLastModified {\n enabled: boolean;\n source: \"git\" | \"frontmatter\";\n}\n\n/**\n * Env for git invocations, with the repo-locating GIT_* variables stripped. A\n * parent git process exports an absolute GIT_DIR (and friends) to its hooks —\n * husky pre-commit in a linked worktree, post-merge, CI wrappers — and an\n * inherited GIT_DIR overrides `-C` discovery, silently pointing every call at\n * the parent's repository instead of the project's.\n */\nconst GIT_LOCATION_VARS = new Set([\n \"GIT_COMMON_DIR\",\n \"GIT_DIR\",\n \"GIT_INDEX_FILE\",\n \"GIT_OBJECT_DIRECTORY\",\n \"GIT_PREFIX\",\n \"GIT_WORK_TREE\",\n]);\n\nconst gitEnv = (): NodeJS.ProcessEnv =>\n Object.fromEntries(\n Object.entries(process.env).filter(([key]) => !GIT_LOCATION_VARS.has(key))\n );\n\n/** Normalize the `lastModified` config (`false | \"git\" | \"frontmatter\"`) into `{ enabled, source }`. */\nexport const resolveLastModifiedConfig = (\n value: false | \"git\" | \"frontmatter\"\n): ResolvedLastModified =>\n value === false\n ? { enabled: false, source: \"git\" }\n : { enabled: true, source: value };\n\n/**\n * Parse `git log --format=%x00%cI --name-only` output into a map of\n * repo-root-relative path → most recent committer ISO date. Each commit emits a\n * NUL-prefixed date line followed by the paths it touched; since git logs\n * newest-first, the first date seen for a path wins. Blank lines are ignored.\n */\nexport const parseGitLog = (output: string): Map<string, string> => {\n const times = new Map<string, string>();\n let current: string | null = null;\n for (const line of output.split(\"\\n\")) {\n if (line.startsWith(\"\\0\")) {\n current = line.slice(1);\n } else if (line && current && !times.has(line)) {\n times.set(line, current);\n }\n }\n return times;\n};\n\n/**\n * The toplevel of the repository containing `root`, or null when git is\n * unavailable or the project isn't a repo. Callers use it to decide which\n * content roots a `git log` pathspec can cover at all — a root outside the\n * repository would fail the log outright and can never yield dates.\n */\nexport const gitRepositoryRoot = (root: string): string | null => {\n try {\n return execFileSync(\n // oxlint-disable-next-line sonarjs/no-os-command-from-path -- git is a required dev-tool dependency resolved from PATH\n \"git\",\n [\"-C\", root, \"rev-parse\", \"--show-toplevel\"],\n // stderr silenced: outside a repository the probe fails by design.\n { encoding: \"utf-8\", env: gitEnv(), stdio: [\"ignore\", \"pipe\", \"ignore\"] }\n ).trim();\n } catch {\n return null;\n }\n};\n\n/**\n * Resolve each source file's last-modified date from git history, keyed by\n * absolute source path. Runs a single `git log` over the given content roots\n * (each local source's own root, which may diverge from `content.root`)\n * and maps repo-root-relative paths back to the given absolute paths\n * (monorepo-safe via `rev-parse --show-toplevel`). Returns an empty map if git\n * is unavailable or the project isn't a repo — the feature then simply shows\n * no dates.\n */\nexport const gitLastModifiedTimes = (\n root: string,\n contentRoots: string[],\n sourcePaths: string[],\n repositoryRoot?: string | null\n): Map<string, string> => {\n // Nothing to date, or nowhere bounded to look — either way, don't pay for a\n // git scan. Both guards matter: `git log -- ` with no pathspec logs the\n // entire repository, which is what an all-staged project produces (a staged\n // source contributes no content root, yet its entries can still carry a\n // `sourcePath`).\n if (sourcePaths.length === 0 || contentRoots.length === 0) {\n return new Map();\n }\n // The caller that bounded `contentRoots` already resolved the repo root;\n // reuse it rather than spawning `rev-parse` a second time per scan.\n const gitRoot =\n repositoryRoot === undefined ? gitRepositoryRoot(root) : repositoryRoot;\n if (gitRoot === null) {\n return new Map();\n }\n try {\n const output = execFileSync(\n // oxlint-disable-next-line sonarjs/no-os-command-from-path -- git is a required dev-tool dependency resolved from PATH\n \"git\",\n [\n \"-C\",\n root,\n \"-c\",\n \"core.quotePath=false\",\n \"log\",\n \"--format=%x00%cI\",\n \"--name-only\",\n \"--\",\n ...contentRoots,\n ],\n { encoding: \"utf-8\", env: gitEnv(), maxBuffer: 256 * 1024 * 1024 }\n );\n const byRepoPath = parseGitLog(output);\n const result = new Map<string, string>();\n for (const sourcePath of sourcePaths) {\n const iso = byRepoPath.get(relative(gitRoot, sourcePath));\n if (iso) {\n result.set(sourcePath, iso);\n }\n }\n return result;\n } catch {\n return new Map();\n }\n};\n\n/**\n * Whether the repository containing `root` is a shallow clone. Returns false\n * when git is unavailable or the project isn't a repo — those cases already\n * yield no dates at all, and the shallow warning would only mislead.\n */\nexport const isShallowGitRepository = (root: string): boolean => {\n try {\n return (\n execFileSync(\n // oxlint-disable-next-line sonarjs/no-os-command-from-path -- git is a required dev-tool dependency resolved from PATH\n \"git\",\n [\"-C\", root, \"rev-parse\", \"--is-shallow-repository\"],\n // stderr silenced: outside a repository the probe fails by design.\n {\n encoding: \"utf-8\",\n env: gitEnv(),\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }\n ).trim() === \"true\"\n );\n } catch {\n return false;\n }\n};\n\n/**\n * A warning for git-derived dates silently missing because the build ran in a\n * shallow clone — the default on Vercel and `actions/checkout`, where `git log`\n * only sees the last few commits, so most pages get no date and the sitemap's\n * `<lastmod>` / \"Last updated\" stamps quietly disappear in production while\n * working locally. Empty when every page got a date or the clone isn't\n * shallow.\n */\nexport const lastModifiedShallowWarning = (\n root: string,\n undatedCount: number\n): Diagnostic[] => {\n if (undatedCount === 0 || !isShallowGitRepository(root)) {\n return [];\n }\n return [\n {\n code: \"BLUME_SHALLOW_GIT_HISTORY\",\n message: `lastModified is on, but this build runs in a shallow git clone, so ${undatedCount} page(s) have no git-derived date — their sitemap <lastmod> and \"Last updated\" stamps are omitted.`,\n severity: \"warning\",\n suggestion:\n \"Fetch full history in CI: set the VERCEL_DEEP_CLONE=true environment variable on Vercel, or fetch-depth: 0 for actions/checkout.\",\n },\n ];\n};\n",
13
- "import { basename, dirname, relative } from \"pathe\";\nimport { glob } from \"tinyglobby\";\n\nimport { diagnosticsFromZod } from \"./diagnostics.ts\";\nimport { createModuleLoader } from \"./load-module.ts\";\nimport { folderMetaSchema } from \"./schema.ts\";\nimport type { FolderMeta } from \"./schema.ts\";\nimport { trimChar } from \"./trim.ts\";\nimport type { Diagnostic } from \"./types.ts\";\n\nconst META_FILES = [\n \"**/meta.ts\",\n \"**/meta.js\",\n \"**/meta.mjs\",\n // Shared, locale-agnostic folder meta (applies to every locale).\n \"**/meta.$.ts\",\n \"**/meta.$.js\",\n \"**/meta.$.mjs\",\n];\n\n/**\n * A meta module's default export before validation: `folderMetaSchema` parses\n * it only after any factory is resolved, so it carries the loader's raw type.\n */\ntype MetaModuleExport = Awaited<\n ReturnType<ReturnType<typeof createModuleLoader>>\n>;\n\n/** A factory-style meta module default-exports a function returning the meta. */\nconst isMetaFactory = (\n mod: MetaModuleExport\n): mod is () => MetaModuleExport | Promise<MetaModuleExport> =>\n typeof mod === \"function\";\n\n/** Resolve a meta module's default export, calling it if it is a factory. */\nconst resolveMeta = async (mod: MetaModuleExport) =>\n isMetaFactory(mod) ? await mod() : mod;\n\n/** A filesystem content source to scan for folder meta: its on-disk root and\n * optional route prefix. The prefix is folded into every key so meta lines up\n * with the sidebar group path, which carries the same prefix. */\nexport interface FolderMetaSource {\n root: string;\n prefix?: string;\n}\n\n/**\n * The folder-meta key for a directory. Mirrors the sidebar group path: the\n * source's route prefix (`docs`) followed by the directory relative to the\n * source root (`provider`) — so `docs/provider/meta.ts` under a `prefix: \"docs\"`\n * source keys to `docs/provider`, exactly the group path navigation builds.\n */\nconst metaKeyFor = (prefix: string | undefined, dir: string): string => {\n const clean = prefix ? trimChar(prefix, \"/\") : \"\";\n if (!clean) {\n return dir;\n }\n return dir ? `${clean}/${dir}` : clean;\n};\n\n/**\n * Discover `meta.{ts,js,mjs}` files across the given filesystem sources. Keys are\n * the source's route prefix joined with the directory relative to that source's\n * root (`\"\"`/the prefix itself for a source's root directory), so meta matches\n * the prefixed sidebar group path. A bare string is shorthand for a single,\n * unprefixed source (the default project layout). `meta.$.*` files are returned\n * in `shared` — folder meta that applies to that directory in every locale (a\n * locale-specific `meta.*` overrides it). Each file default-exports an object or\n * a (sync/async) function returning one.\n *\n * `localeDirs` names the top-level locale directories of a `dir`-parser i18n\n * project. Navigation looks locale meta up as `locale/<group path>` where the\n * group path starts with the source prefix, so a locale directory found at a\n * source root is hoisted in front of the prefix (`docs/fr/guides/meta.ts` keys\n * to `fr/docs/guides`, not `docs/fr/guides`).\n *\n * `versionDirs` names the archived-version snapshot directories, which sit\n * outermost on disk — a locale directory inside a snapshot is one level deeper.\n * Both are hoisted, version first (`v1.0/fr/guides/meta.ts` keys to\n * `v1.0/fr/<prefix>/guides`), matching navigation's version-aware meta prefix.\n */\nexport const discoverFolderMeta = async (\n sources: string | FolderMetaSource[],\n options: {\n localeDirs?: readonly string[];\n versionDirs?: readonly string[];\n } = {}\n): Promise<{\n meta: Map<string, FolderMeta>;\n shared: Map<string, FolderMeta>;\n diagnostics: Diagnostic[];\n}> => {\n const list: FolderMetaSource[] = Array.isArray(sources)\n ? sources\n : [{ root: sources }];\n const localeDirs = new Set(options.localeDirs);\n const versionDirs = new Set(options.versionDirs);\n\n const load = createModuleLoader();\n const meta = new Map<string, FolderMeta>();\n const shared = new Map<string, FolderMeta>();\n const diagnostics: Diagnostic[] = [];\n\n // Scan every source under its own root so a source rooted outside\n // `content.root` still contributes its folder meta.\n const perSource = await Promise.all(\n list.map(async (source) => {\n const files = await glob(META_FILES, {\n absolute: true,\n cwd: source.root,\n // Never descend into dependencies or build output — relevant when the\n // root is the project root (e.g. a `.`-rooted or all-staged project).\n ignore: [\"**/node_modules/**\", \"**/.blume/**\", \"**/dist/**\"],\n onlyFiles: true,\n });\n const loaded = await Promise.all(\n files.map(\n async (\n file\n ): Promise<\n | { ok: true; file: string; value: unknown }\n | { ok: false; file: string; error: Error }\n > => {\n try {\n return {\n file,\n ok: true,\n value: await resolveMeta(await load(file)),\n };\n } catch (error) {\n // SAFETY: jiti surfaces load/evaluate failures as Error\n // instances, and only `message` is read downstream.\n return { error: error as Error, file, ok: false };\n }\n }\n )\n );\n return { loaded, source };\n })\n );\n\n for (const { loaded, source } of perSource) {\n for (const entry of loaded) {\n const dir = relative(source.root, dirname(entry.file));\n // A version snapshot dir is outermost, with a locale dir one level\n // deeper; both are hoisted in front of the (prefixed) group path, in\n // that order — the lookup key reads `version/locale/prefix/dir`.\n const [head, ...tail] = dir.split(\"/\");\n const version = head && versionDirs.has(head) ? head : \"\";\n const afterVersion = version ? tail : [head ?? \"\", ...tail];\n const [localeHead, ...localeTail] = afterVersion;\n const locale = localeHead && localeDirs.has(localeHead) ? localeHead : \"\";\n const rest = (locale ? localeTail : afterVersion)\n .filter(Boolean)\n .join(\"/\");\n const key = [version, locale, metaKeyFor(source.prefix, rest)]\n .filter(Boolean)\n .join(\"/\");\n\n if (!entry.ok) {\n diagnostics.push({\n code: \"BLUME_META_LOAD_FAILED\",\n file: entry.file,\n message: `Could not load meta file: ${entry.error.message}`,\n severity: \"error\",\n });\n continue;\n }\n\n const result = folderMetaSchema.safeParse(entry.value);\n if (result.success) {\n const target = basename(entry.file).startsWith(\"meta.$.\")\n ? shared\n : meta;\n target.set(key, result.data);\n } else {\n diagnostics.push(\n ...diagnosticsFromZod(result.error, {\n code: \"BLUME_META_INVALID\",\n file: entry.file,\n })\n );\n }\n }\n }\n\n return { diagnostics, meta, shared };\n};\n",
14
- "import { join } from \"pathe\";\n\nimport { blumeReferences } from \"../../openapi/references.ts\";\nimport { openApiSource } from \"../../openapi/source.ts\";\nimport type { ContentSourceAdapter } from \"../../sources/registry.ts\";\nimport type { ResolvedConfig } from \"../schema.ts\";\nimport type { ProjectContext } from \"../types.ts\";\nimport { contentfulSource } from \"./contentful.ts\";\nimport { filesystemSource } from \"./filesystem.ts\";\nimport { githubReleasesSource } from \"./github-releases.ts\";\nimport { mdxRemoteSource } from \"./mdx-remote.ts\";\nimport { notionSource } from \"./notion.ts\";\nimport { obsidianSource } from \"./obsidian.ts\";\nimport { payloadSource } from \"./payload.ts\";\nimport { sanitySource } from \"./sanity.ts\";\nimport { strapiSource } from \"./strapi.ts\";\nimport type { ContentSource, SourceContext } from \"./types.ts\";\n\nexport {\n resolveDocsCollection,\n resolveSourceRoot,\n sourcesOfKind,\n} from \"./collection.ts\";\nexport type { DocsCollection } from \"./collection.ts\";\n\n/** Allocate a unique, stable source name from a base (prefix or kind). */\nconst uniqueNamer = (): ((base: string) => string) => {\n const used = new Set<string>();\n return (base) => {\n let name = base;\n let n = 2;\n while (used.has(name)) {\n name = `${base}-${n}`;\n n += 1;\n }\n used.add(name);\n return name;\n };\n};\n\n/** Runtime knobs for a scan: dev/build mode, preview, and cache refresh. */\nexport interface SourceRuntime {\n mode: \"dev\" | \"build\";\n preview?: boolean;\n refresh?: boolean;\n}\n\nconst sourceContext = (\n context: ProjectContext,\n name: string,\n runtime: SourceRuntime\n): SourceContext => ({\n assetsBaseUrl: `/blume-assets/${name}`,\n assetsDir: join(context.outDir, \"public\", \"blume-assets\", name),\n cacheDir: join(context.outDir, \"cache\", name),\n mode: runtime.mode,\n preview: runtime.preview,\n projectRoot: context.root,\n refresh: runtime.refresh ?? runtime.mode === \"build\",\n});\n\n/**\n * The frontmatter keys each content type declares (`content.types[*].frontmatter`),\n * keyed by type — so a source that drops unknown keys keeps, per note, exactly\n * the ones `normalizeEntry` will accept for that note's type.\n */\nconst typeFrontmatterKeys = (\n config: ResolvedConfig\n): Record<string, string[]> =>\n Object.fromEntries(\n Object.entries(config.content.types).map(([type, def]) => [\n type,\n Object.keys(def.frontmatter),\n ])\n );\n\n/**\n * Instantiate the engine-side source for a descriptor. Each adapter's options\n * spread straight into its engine factory: the descriptor carries exactly the\n * fields the factory documents, plus the shared `prefix`/`pollInterval`.\n */\nconst buildSource = (\n adapter: ContentSourceAdapter,\n name: string,\n config: ResolvedConfig,\n context: ProjectContext,\n runtime: SourceRuntime\n): ContentSource => {\n switch (adapter.kind) {\n case \"filesystem\": {\n const { pollInterval: _ignored, ...options } = adapter.options;\n return filesystemSource({ ...options, name, projectRoot: context.root });\n }\n case \"custom\": {\n // A user-provided instance manages its own context/caching; we only ensure\n // its name is unique across the project for id namespacing.\n const source = adapter.options;\n return source.name === name ? source : { ...source, name };\n }\n case \"sanity\": {\n return sanitySource(\n { ...adapter.options, name },\n sourceContext(context, name, runtime)\n );\n }\n case \"notion\": {\n return notionSource(\n { ...adapter.options, name },\n sourceContext(context, name, runtime)\n );\n }\n case \"contentful\": {\n return contentfulSource(\n { ...adapter.options, name },\n sourceContext(context, name, runtime)\n );\n }\n case \"payload\": {\n return payloadSource(\n { ...adapter.options, name },\n sourceContext(context, name, runtime)\n );\n }\n case \"strapi\": {\n return strapiSource(\n { ...adapter.options, name },\n sourceContext(context, name, runtime)\n );\n }\n case \"obsidian\": {\n const { pollInterval: _ignored, ...options } = adapter.options;\n return obsidianSource(\n {\n ...options,\n defaultType: config.content.defaultType,\n frontmatterKeys: Object.keys(config.frontmatter.extend),\n i18n: config.i18n,\n name,\n typeFrontmatterKeys: typeFrontmatterKeys(config),\n versions: config.versions,\n },\n sourceContext(context, name, runtime)\n );\n }\n case \"github-releases\": {\n return githubReleasesSource(\n { ...adapter.options, name },\n sourceContext(context, name, runtime)\n );\n }\n default: {\n // Only `mdx-remote` is left, and TypeScript has narrowed `adapter` to it.\n // It returns after the switch rather than from a last case block: Bun\n // 1.4.0's line coverage never credits the closing brace of a switch's\n // final block, which would fail the 100% gate in CI.\n break;\n }\n }\n return mdxRemoteSource(\n { ...adapter.options, name },\n sourceContext(context, name, runtime)\n );\n};\n\n/** The base name to allocate for a descriptor (before deduplication). */\nconst baseName = (adapter: ContentSourceAdapter): string => {\n if (adapter.kind === \"custom\") {\n return adapter.options.name;\n }\n return adapter.options.prefix ?? adapter.kind;\n};\n\n/**\n * Build the ordered list of content sources for a project. The config schema\n * already desugared the zero-config shorthand into a single `filesystem()`\n * descriptor, so every project has at least one entry here. A Blume-rendered\n * OpenAPI reference contributes an internal staged source that lowers each\n * operation into a real content page (routing/nav/search/OG).\n */\nexport const resolveSources = (\n config: ResolvedConfig,\n context: ProjectContext,\n runtime: SourceRuntime\n): ContentSource[] => {\n const nameFor = uniqueNamer();\n const sources = config.content.sources.map((adapter) =>\n buildSource(adapter, nameFor(baseName(adapter)), config, context, runtime)\n );\n\n const references = blumeReferences(config);\n if (references.length > 0) {\n sources.push(\n openApiSource(references, sourceContext(context, \"openapi\", runtime))\n );\n }\n\n return sources;\n};\n",
15
- "/**\n * The JSON a CMS API returns: arbitrary values a query or REST endpoint\n * hands back, typed as a closed union so a source narrows with predicates\n * instead of casting.\n */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\n/** A JSON object: a document, a node in a rich-text tree, an API envelope. */\nexport interface JsonObject {\n [key: string]: JsonValue;\n}\n\n/**\n * A node a dot path can descend into. Arrays pass too (matching their runtime\n * string-key indexing, e.g. `items.0`), so the predicate types them as the\n * keyed form both traverse through.\n */\nexport const isJsonObject = (\n value: JsonValue | undefined\n): value is JsonObject => typeof value === \"object\" && value !== null;\n\n/** Resolve a dot path (`slug.current`) against a document. */\nexport const getPath = (\n doc: JsonObject,\n path: string\n): JsonValue | undefined => {\n let current: JsonValue | undefined = doc;\n for (const key of path.split(\".\")) {\n if (isJsonObject(current)) {\n current = current[key];\n } else {\n return;\n }\n }\n return current;\n};\n\nexport const isStringValue = (value: JsonValue | undefined): value is string =>\n typeof value === \"string\";\n\nexport const asString = (value: JsonValue | undefined): string | undefined =>\n isStringValue(value) ? value : undefined;\n\n/** The elements of an array value, or none when the value is not an array. */\nexport const asArray = (value: JsonValue | undefined): JsonValue[] =>\n Array.isArray(value) ? value : [];\n\n/** The object form of a value, or none when it is a scalar, array, or absent. */\nexport const asObject = (\n value: JsonValue | undefined\n): JsonObject | undefined =>\n isJsonObject(value) && !Array.isArray(value) ? value : undefined;\n\nexport const isNumberValue = (value: JsonValue | undefined): value is number =>\n typeof value === \"number\";\n\nexport const asNumber = (value: JsonValue | undefined): number | undefined =>\n isNumberValue(value) ? value : undefined;\n\n/** The object elements of an array value; scalars and nested arrays are dropped. */\nexport const objectsIn = (value: JsonValue | undefined): JsonObject[] =>\n asArray(value).flatMap((item) => {\n const object = asObject(item);\n return object ? [object] : [];\n });\n",
16
- "/**\n * Contentful rich text → Markdown. Covers the block, inline, and mark types\n * the Rich Text editor emits; embedded entries fall through to a serializer\n * keyed by content type or are noted in a comment. Links to assets and\n * entries arrive unresolved from the Delivery API (`data.target` is a\n * `sys` link), so the source hands in resolvers over the response's\n * `includes`; a document the SDK already resolved (with `fields` inline)\n * lowers the same way.\n */\nimport type { JsonObject } from \"./json.ts\";\nimport { asString, getPath, objectsIn } from \"./json.ts\";\nimport type { InlineMarks } from \"./lower.ts\";\nimport {\n absoluteUrl,\n blockquote,\n headingPrefix,\n image,\n joinBlocks,\n listItem,\n markdownDocument,\n renderInline,\n renderLink,\n unsupported,\n writesMdx,\n} from \"./lower.ts\";\n\n/** An asset's file as a Markdown image needs it. */\nexport interface ContentfulAsset {\n description?: string;\n title?: string;\n url: string;\n}\n\nexport interface ContentfulRichTextOptions {\n /** Resolve an asset link (`data.target.sys.id`) to its file. */\n resolveAsset?: (id: string) => ContentfulAsset | null;\n /** Resolve an entry link to the entry (`sys` plus `fields`). */\n resolveEntry?: (id: string) => JsonObject | null;\n /**\n * Serializers for embedded entries, keyed by content type id; return\n * Markdown or MDX. Setting any writes the source's entries as MDX.\n */\n serializers?: Record<string, (entry: JsonObject) => string>;\n}\n\nconst HEADING = /^heading-(?<level>[1-6])$/u;\nconst CELL_PIPE = /\\|/gu;\nconst CELL_BREAK = /\\n+/gu;\n\n/** The file behind an asset entry, or null when it carries none. */\nexport const assetFromEntry = (asset: JsonObject): ContentfulAsset | null => {\n const url = asString(getPath(asset, \"fields.file.url\"));\n if (!url) {\n return null;\n }\n return {\n description: asString(getPath(asset, \"fields.description\")),\n title: asString(getPath(asset, \"fields.title\")),\n url: absoluteUrl(url),\n };\n};\n\nconst children = (node: JsonObject): JsonObject[] => objectsIn(node.content);\n\nconst marksOf = (node: JsonObject): InlineMarks => {\n const marks: InlineMarks = {};\n for (const mark of objectsIn(node.marks)) {\n switch (asString(mark.type)) {\n case \"bold\": {\n marks.bold = true;\n break;\n }\n case \"italic\": {\n marks.italic = true;\n break;\n }\n case \"code\": {\n marks.code = true;\n break;\n }\n case \"strikethrough\": {\n marks.strike = true;\n break;\n }\n default:\n }\n }\n return marks;\n};\n\n/**\n * The linked object a node points at: inline when the document was resolved\n * (`data.target.fields`), else through the resolver by `data.target.sys.id`.\n */\nconst linkedTarget = (\n node: JsonObject,\n resolve?: (id: string) => JsonObject | null\n): JsonObject | null => {\n const target = getPath(node, \"data.target\");\n if (getPath(node, \"data.target.fields\") !== undefined) {\n // SAFETY: `data.target.fields` resolved through the object, so `target`\n // is that object.\n return target as JsonObject;\n }\n const id = asString(getPath(node, \"data.target.sys.id\"));\n return id ? (resolve?.(id) ?? null) : null;\n};\n\nconst linkedAsset = (\n node: JsonObject,\n options: ContentfulRichTextOptions\n): ContentfulAsset | null => {\n if (getPath(node, \"data.target.fields\") !== undefined) {\n const inline = linkedTarget(node);\n return inline ? assetFromEntry(inline) : null;\n }\n const id = asString(getPath(node, \"data.target.sys.id\"));\n return id ? (options.resolveAsset?.(id) ?? null) : null;\n};\n\nconst embeddedEntry = (\n node: JsonObject,\n options: ContentfulRichTextOptions\n): string => {\n const entry = linkedTarget(node, options.resolveEntry);\n const contentType = entry\n ? asString(getPath(entry, \"sys.contentType.sys.id\"))\n : undefined;\n const serializer = contentType\n ? options.serializers?.[contentType]\n : undefined;\n if (entry && serializer) {\n return serializer(entry);\n }\n return unsupported(\n `Contentful embedded entry${contentType ? `: ${contentType}` : \"\"}`,\n writesMdx(options.serializers)\n );\n};\n\nconst renderInlines = (\n nodes: JsonObject[],\n options: ContentfulRichTextOptions\n): string =>\n nodes\n // oxlint-disable-next-line no-use-before-define -- mutual recursion: a link's label is itself inline content\n .map((node) => renderInlineNode(node, options))\n .join(\"\");\n\nconst renderInlineNode = (\n node: JsonObject,\n options: ContentfulRichTextOptions\n): string => {\n switch (asString(node.nodeType)) {\n case \"text\": {\n return renderInline(asString(node.value) ?? \"\", marksOf(node));\n }\n case \"hyperlink\": {\n return renderLink(\n renderInlines(children(node), options),\n asString(getPath(node, \"data.uri\"))\n );\n }\n case \"asset-hyperlink\": {\n return renderLink(\n renderInlines(children(node), options),\n linkedAsset(node, options)?.url\n );\n }\n case \"embedded-entry-inline\": {\n return embeddedEntry(node, options);\n }\n default: {\n // entry-hyperlink (no route to point at) and anything unknown: the label.\n return renderInlines(children(node), options);\n }\n }\n};\n\nconst renderList = (\n items: JsonObject[],\n marker: (index: number) => string,\n options: ContentfulRichTextOptions\n): string =>\n items\n .map((item, index) =>\n listItem(\n marker(index),\n // A single newline between an item's paragraph and its nested list\n // keeps the list tight.\n children(item)\n // oxlint-disable-next-line no-use-before-define -- mutual recursion: an item holds blocks, including nested lists\n .map((child) => renderBlock(child, options))\n .filter((block) => block !== \"\")\n .join(\"\\n\")\n )\n )\n .join(\"\\n\");\n\nconst cellText = (\n cell: JsonObject,\n options: ContentfulRichTextOptions\n): string =>\n children(cell)\n .map((paragraph) => renderInlines(children(paragraph), options))\n .join(\" \")\n .replaceAll(CELL_BREAK, \" \")\n .replaceAll(CELL_PIPE, String.raw`\\|`);\n\nconst tableRow = (cells: string[]): string => `| ${cells.join(\" | \")} |`;\n\nconst renderTable = (\n node: JsonObject,\n options: ContentfulRichTextOptions\n): string => {\n const rows = children(node).map((row) =>\n children(row).map((cell) => cellText(cell, options))\n );\n const [head, ...body] = rows;\n if (!head) {\n return \"\";\n }\n return [\n tableRow(head),\n tableRow(head.map(() => \"---\")),\n ...body.map((cells) => tableRow(cells)),\n ].join(\"\\n\");\n};\n\nconst renderBlock = (\n node: JsonObject,\n options: ContentfulRichTextOptions\n): string => {\n const type = asString(node.nodeType) ?? \"\";\n const heading = HEADING.exec(type)?.groups?.level;\n if (heading) {\n return `${headingPrefix(Number(heading))}${renderInlines(children(node), options)}`;\n }\n switch (type) {\n case \"paragraph\": {\n return renderInlines(children(node), options);\n }\n case \"blockquote\": {\n return blockquote(\n joinBlocks(children(node).map((child) => renderBlock(child, options)))\n );\n }\n case \"unordered-list\": {\n return renderList(children(node), () => \"-\", options);\n }\n case \"ordered-list\": {\n return renderList(children(node), (index) => `${index + 1}.`, options);\n }\n case \"hr\": {\n return \"---\";\n }\n case \"embedded-asset-block\": {\n const asset = linkedAsset(node, options);\n // Contentful's own rich-text renderer uses the description as alt text\n // and the title only as a fallback.\n return asset\n ? image(asset.description ?? asset.title ?? \"\", asset.url)\n : \"\";\n }\n case \"embedded-entry-block\": {\n return embeddedEntry(node, options);\n }\n case \"table\": {\n return renderTable(node, options);\n }\n default: {\n return unsupported(\n `Contentful node: ${type}`,\n writesMdx(options.serializers)\n );\n }\n }\n};\n\n/** Serialize a rich text document (`nodeType: \"document\"`) to Markdown. */\nexport const contentfulRichTextToMarkdown = (\n doc: JsonObject,\n options: ContentfulRichTextOptions = {}\n): string =>\n markdownDocument(children(doc).map((node) => renderBlock(node, options)));\n",
17
- "import { join } from \"pathe\";\n\nimport matter from \"../frontmatter.ts\";\nimport {\n hashText,\n loadWithCache,\n pollingWatch,\n snapshotCache,\n} from \"./cache.ts\";\nimport type { JsonObject, JsonValue } from \"./json.ts\";\nimport { asString, getPath, isStringValue } from \"./json.ts\";\nimport { slugify, slugifyPath } from \"./normalize.ts\";\nimport type {\n ContentSource,\n SourceContext,\n SourceEntry,\n SourceLoadResult,\n} from \"./types.ts\";\n\n/** What every REST-backed CMS source needs to be a staged, cached source. */\nexport interface RemoteSourceOptions {\n /** Pull every entry from the API; called on refresh and on each poll. */\n fetchEntries: () => Promise<SourceEntry[]>;\n name: string;\n /** Opt-in dev polling interval (seconds); omit to freeze for the session. */\n pollInterval?: number;\n prefix?: string;\n}\n\n/**\n * The staged-source scaffolding a CMS adapter shares: a snapshot cache under\n * `.blume/cache/<source>/` (or a name-derived dir when constructed directly\n * as a custom source, without a context), cache-first dev loads, offline\n * fallback, `read()` for raw export, and an opt-in polling `watch`.\n */\nexport const remoteSource = (\n options: RemoteSourceOptions,\n ctx?: SourceContext\n): ContentSource => {\n const cache = snapshotCache(\n ctx?.cacheDir ?? join(\".blume\", \"cache\", options.name)\n );\n let snapshot = new Map<string, SourceEntry>();\n\n const load = async (\n refresh = ctx?.refresh ?? true\n ): Promise<SourceLoadResult> => {\n const result = await loadWithCache(\n options.name,\n cache,\n options.fetchEntries,\n refresh\n );\n snapshot = new Map(result.entries.map((entry) => [entry.ref, entry]));\n return result;\n };\n\n const read = async (ref: string): Promise<string> => {\n const cached = snapshot.get(ref);\n if (cached) {\n return cached.raw ?? cached.body.text;\n }\n const all = await cache.read();\n return all.find((entry) => entry.ref === ref)?.raw ?? \"\";\n };\n\n return {\n load,\n name: options.name,\n prefix: options.prefix,\n read,\n staged: true,\n watch: options.pollInterval\n ? pollingWatch(\n () => load(true),\n options.pollInterval,\n () => load()\n )\n : undefined,\n };\n};\n\n/** The frontmatter a CMS document maps to. */\nexport interface RemoteFrontmatter {\n description?: string;\n draft?: boolean;\n title?: string;\n}\n\n/**\n * A staged entry: Markdown body plus the frontmatter it was mapped from,\n * written as `.mdx` when the body carries serializer output (see\n * `writesMdx`).\n */\nexport const stagedEntry = (\n slug: string,\n data: RemoteFrontmatter,\n markdown: string,\n lastModified: string | undefined,\n format: \"md\" | \"mdx\" = \"md\"\n): SourceEntry => {\n const raw = matter.stringify(markdown, data);\n return {\n body: { format, text: markdown },\n // Spread into a fresh literal: `SourceEntry.data` wants an\n // index-signature type, which the named interface lacks.\n data: { ...data },\n hash: hashText(raw),\n lastModified,\n raw,\n ref: `${slug}.${format}`,\n };\n};\n\n/** How a source calls its CMS: the API's auth headers and an injectable fetch. */\nexport interface RestClient {\n /** Injected for tests; defaults to the global `fetch`. */\n fetchImpl?: typeof fetch;\n headers?: Record<string, string>;\n}\n\n/**\n * How long one CMS request may take before the source gives up on it. A\n * stalled CMS would otherwise hold `scanProject()` — and every `blume dev`\n * rescan — indefinitely, and the cache fallback can only kick in once the\n * request rejects.\n */\nexport const REMOTE_TIMEOUT_MS = 30_000;\n\n/**\n * GET a JSON endpoint. A non-2xx response is an error naming the status, so\n * the source's cache fallback reports why (`401 Unauthorized`) instead of a\n * parse failure on an error body; a request past {@link REMOTE_TIMEOUT_MS}\n * rejects with a `TimeoutError`.\n */\nexport const fetchJson = async (\n url: string,\n client: RestClient\n): Promise<JsonValue> => {\n const doFetch = client.fetchImpl ?? globalThis.fetch;\n const res = await doFetch(url, {\n headers: { accept: \"application/json\", ...client.headers },\n signal: AbortSignal.timeout(REMOTE_TIMEOUT_MS),\n });\n if (!res.ok) {\n throw new Error(`${url} responded ${res.status} ${res.statusText}`.trim());\n }\n // SAFETY: the endpoint answered 2xx with a JSON body; whatever shape it\n // holds is narrowed by the caller's predicates before use.\n return (await res.json()) as JsonValue;\n};\n\n/** A query string from the fixed params plus a user's extra ones. */\nexport const queryString = (\n params: Record<string, string | undefined>\n): string => {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n search.set(key, value);\n }\n }\n return search.toString();\n};\n\n/** Field paths mapping a CMS document onto Blume meta + body. */\nexport interface RemoteFieldMap {\n /** Field holding the renderable body (rich text, or a Markdown string). */\n body?: string;\n /** Field holding the page description. */\n description?: string;\n /** Field holding the last-modified ISO date. */\n lastModified?: string;\n /** Field holding the route slug. */\n slug?: string;\n /** Field holding the page title. */\n title?: string;\n}\n\n/**\n * Map a document to a staged entry. The slug falls back to the document's id\n * when the slug field is missing or slugifies to nothing (pure punctuation),\n * so distinct documents never collapse onto one `untitled.md`; a slashed\n * slug keeps its segments. A string body is Markdown and passes through as\n * `.md`; any other shape goes to the CMS's lowerer, and is written as `.mdx`\n * when `lowersToMdx` (the source has serializers, see `writesMdx`).\n */\nexport const documentEntry = (\n doc: JsonObject,\n fields: Required<RemoteFieldMap>,\n id: string,\n lower: (body: JsonValue) => string,\n draft = false,\n lowersToMdx = false\n): SourceEntry => {\n const slugValue = asString(getPath(doc, fields.slug)) ?? id;\n const slug = slugifyPath(slugValue) || slugify(id) || \"untitled\";\n const data: RemoteFrontmatter = {};\n const title = asString(getPath(doc, fields.title));\n const description = asString(getPath(doc, fields.description));\n if (title) {\n data.title = title;\n }\n if (description) {\n data.description = description;\n }\n if (draft) {\n data.draft = true;\n }\n const body = getPath(doc, fields.body);\n let markdown = \"\";\n let format: \"md\" | \"mdx\" = \"md\";\n if (isStringValue(body)) {\n markdown = `${body.trimEnd()}\\n`;\n } else if (body !== undefined) {\n markdown = lower(body);\n format = lowersToMdx ? \"mdx\" : \"md\";\n }\n return stagedEntry(\n slug,\n data,\n markdown,\n asString(getPath(doc, fields.lastModified)),\n format\n );\n};\n",
18
- "import {\n assetFromEntry,\n contentfulRichTextToMarkdown,\n} from \"./contentful-rich-text.ts\";\nimport type { JsonObject } from \"./json.ts\";\nimport {\n asNumber,\n asObject,\n asString,\n getPath,\n isJsonObject,\n objectsIn,\n} from \"./json.ts\";\nimport { writesMdx } from \"./lower.ts\";\nimport type { RemoteFieldMap, RestClient } from \"./remote.ts\";\nimport {\n documentEntry,\n fetchJson,\n queryString,\n remoteSource,\n} from \"./remote.ts\";\nimport type { ContentSource, SourceContext, SourceEntry } from \"./types.ts\";\n\nexport interface ContentfulSourceOptions {\n name: string;\n prefix?: string;\n /** Space id. */\n space: string;\n /** Environment id; default `master`. */\n environment?: string;\n /** The content type id whose entries become pages. */\n contentType: string;\n /** Locale code to fetch; omit for the space's default locale. */\n locale?: string;\n /**\n * Field ids mapping an entry onto Blume meta + body. Paths resolve against\n * the entry's `fields`, with `sys` reachable as `sys.<key>`. Defaults:\n * `title`, `description`, `slug`, `body`, `sys.updatedAt`.\n */\n fields?: RemoteFieldMap;\n /** Extra query parameters for the entries request (`fields.section: \"sdk\"`). */\n params?: Record<string, string>;\n /** Serializers for embedded entries, keyed by content type id. */\n serializers?: Record<string, (entry: JsonObject) => string>;\n /** Delivery API token; defaults to `CONTENTFUL_ACCESS_TOKEN`. */\n token?: string;\n /** Preview API token for `--preview`; defaults to `CONTENTFUL_PREVIEW_TOKEN`. */\n previewToken?: string;\n /** Opt-in dev polling interval (seconds); omit to freeze for the session. */\n pollInterval?: number;\n /** Injected for tests; defaults to the global `fetch`. */\n fetchImpl?: typeof fetch;\n}\n\nconst DELIVERY_HOST = \"https://cdn.contentful.com\";\nconst PREVIEW_HOST = \"https://preview.contentful.com\";\nconst PAGE_SIZE = 100;\n\nconst DEFAULT_FIELDS: Required<RemoteFieldMap> = {\n body: \"body\",\n description: \"description\",\n lastModified: \"sys.updatedAt\",\n slug: \"slug\",\n title: \"title\",\n};\n\n/** The included objects of a page, keyed by `sys.id`. */\nconst byId = (objects: JsonObject[]): Map<string, JsonObject> =>\n new Map(\n objects.map((object) => [asString(getPath(object, \"sys.id\")) ?? \"\", object])\n );\n\n/**\n * Contentful content source. Pages through the Delivery API (the Preview API\n * under `--preview`), maps each entry's fields to frontmatter, and lowers its\n * rich text body to Markdown with the page's `includes` resolving asset and\n * entry links.\n */\nexport const contentfulSource = (\n options: ContentfulSourceOptions,\n ctx?: SourceContext\n): ContentSource => {\n const fields = { ...DEFAULT_FIELDS, ...options.fields };\n\n const toEntry = (\n item: JsonObject,\n assets: Map<string, JsonObject>,\n linked: Map<string, JsonObject>\n ): SourceEntry => {\n const sys = asObject(item.sys) ?? {};\n const id = asString(sys.id) ?? \"\";\n // Field paths resolve against the entry's fields, with `sys` beside them.\n const view: JsonObject = { ...asObject(item.fields), sys };\n return documentEntry(\n view,\n fields,\n id,\n (body) =>\n isJsonObject(body)\n ? contentfulRichTextToMarkdown(body, {\n resolveAsset: (assetId) => {\n const asset = assets.get(assetId);\n return asset ? assetFromEntry(asset) : null;\n },\n resolveEntry: (entryId) => linked.get(entryId) ?? null,\n serializers: options.serializers,\n })\n : \"\",\n false,\n writesMdx(options.serializers)\n );\n };\n\n const fetchEntries = async (): Promise<SourceEntry[]> => {\n const preview = ctx?.preview ?? false;\n const deliveryToken = options.token ?? process.env.CONTENTFUL_ACCESS_TOKEN;\n const previewToken =\n options.previewToken ?? process.env.CONTENTFUL_PREVIEW_TOKEN;\n // The Preview API rejects delivery tokens, so falling back to one would\n // only trade a clear config error for a 401.\n if (preview && !previewToken) {\n throw new Error(\n \"Contentful --preview needs a Preview API token: set previewToken or CONTENTFUL_PREVIEW_TOKEN.\"\n );\n }\n const token = preview ? previewToken : deliveryToken;\n const client: RestClient = {\n fetchImpl: options.fetchImpl,\n headers: token ? { authorization: `Bearer ${token}` } : {},\n };\n const host = preview ? PREVIEW_HOST : DELIVERY_HOST;\n const base = `${host}/spaces/${options.space}/environments/${options.environment ?? \"master\"}/entries`;\n const entries: SourceEntry[] = [];\n let skip = 0;\n let more = true;\n while (more) {\n // The user's params go first so the paging controls always win — a\n // `params` key that shadowed them would refetch the same page forever.\n const query = queryString({\n ...options.params,\n content_type: options.contentType,\n include: \"2\",\n limit: String(PAGE_SIZE),\n locale: options.locale,\n skip: String(skip),\n });\n // oxlint-disable-next-line no-await-in-loop -- pages are sequential: each response says whether another exists.\n const page = asObject(await fetchJson(`${base}?${query}`, client));\n if (!page) {\n throw new Error(\"Contentful returned a non-object response\");\n }\n const assets = byId(objectsIn(getPath(page, \"includes.Asset\")));\n const linked = byId(objectsIn(getPath(page, \"includes.Entry\")));\n const items = objectsIn(page.items);\n for (const item of items) {\n entries.push(toEntry(item, assets, linked));\n }\n skip += items.length;\n more = items.length > 0 && skip < (asNumber(page.total) ?? 0);\n }\n return entries;\n };\n\n return remoteSource(\n {\n fetchEntries,\n name: options.name,\n pollInterval: options.pollInterval,\n prefix: options.prefix,\n },\n ctx\n );\n};\n",
19
- "import { existsSync, watch as fsWatch } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\n\nimport { extname, isAbsolute, join, relative, resolve } from \"pathe\";\nimport { glob } from \"tinyglobby\";\n\nimport { BlumeError } from \"../diagnostics.ts\";\nimport matter from \"../frontmatter.ts\";\nimport type { ContentSource, SourceEntry, SourceLoadResult } from \"./types.ts\";\nimport {\n baselineScanIgnore,\n BLUME_WATCH_IGNORE_DIRS,\n excludeDirSegments,\n ignoringWatchListener,\n} from \"./watch.ts\";\n\n/** Options for the built-in filesystem source. */\nexport interface FilesystemSourceOptions {\n /** Stable source name; namespaces ids and diagnostics. */\n name: string;\n /** Optional route prefix. */\n prefix?: string;\n /** Content root, absolute or relative to `projectRoot`. */\n root: string;\n include: string[];\n exclude: string[];\n /** Absolute project root, used to resolve a relative `root`. */\n projectRoot: string;\n /** When set, a missing root throws this code instead of the generic one. */\n missingCode?: string;\n}\n\n/**\n * The built-in content source: discover and read `.md`/`.mdx` files under a\n * content root. This is the extraction of the original `discoverContent()` scan\n * into a `ContentSource`; every other adapter follows the same contract.\n */\nexport const filesystemSource = (\n options: FilesystemSourceOptions\n): ContentSource & { readonly contentRoot: string } => {\n const contentRoot = isAbsolute(options.root)\n ? options.root\n : join(resolve(options.projectRoot), options.root);\n\n const load = async (): Promise<SourceLoadResult> => {\n const files = await glob(options.include, {\n absolute: true,\n cwd: contentRoot,\n // Union the user's `exclude` with the baseline never-content dirs so a\n // broadly-scoped root (`.` or an app dir) can't glob `node_modules`,\n // `dist`, `.blume`, etc. — even when the user overrode `exclude`.\n ignore: [...options.exclude, ...baselineScanIgnore()],\n onlyFiles: true,\n });\n files.sort();\n\n const entries = await Promise.all(\n files.map(async (file): Promise<SourceEntry> => {\n const source = await readFile(file, \"utf-8\");\n const ext = extname(file).toLowerCase();\n const format = ext === \".mdx\" ? \"mdx\" : \"md\";\n const parsed = matter(source);\n return {\n body: { format, text: parsed.content },\n data: parsed.data,\n // The unstripped text: lets `normalizeEntry` offset link line numbers\n // by the frontmatter block's height, so diagnostics point at the real\n // file line (and spares a re-read on the frontmatter-error path).\n raw: source,\n ref: relative(contentRoot, file),\n sourcePath: file,\n };\n })\n );\n\n return { diagnostics: [], entries };\n };\n\n const validate = (): void => {\n if (!existsSync(contentRoot)) {\n throw new BlumeError({\n code: options.missingCode ?? \"BLUME_CONTENT_ROOT_MISSING\",\n file: contentRoot,\n message: `Content root not found: ${options.root}`,\n severity: \"error\",\n suggestion: `Create a \"${options.root}\" folder with at least one .md or .mdx file, or set content.root in blume.config.ts.`,\n });\n }\n };\n\n // When `content.root` is the project root (a migrated `.`-rooted project),\n // the recursive dev watcher would otherwise see Blume's own `.blume/` output\n // and loop; skip it, VCS/dependency trees, and every excluded dir so the\n // watcher stays in sync with what `load()` globs. See {@link ignoringWatchListener}.\n const watchIgnoreDirs = new Set([\n ...BLUME_WATCH_IGNORE_DIRS,\n ...excludeDirSegments(options.exclude),\n ]);\n\n const watch = (onChange: () => void): (() => void) => {\n if (!existsSync(contentRoot)) {\n return () => {\n // Nothing to dispose when the root doesn't exist yet.\n };\n }\n const watcher = fsWatch(\n contentRoot,\n { recursive: true },\n ignoringWatchListener(onChange, watchIgnoreDirs)\n );\n return () => watcher.close();\n };\n\n return {\n contentRoot,\n load,\n name: options.name,\n prefix: options.prefix,\n read: (ref: string): Promise<string> =>\n readFile(join(contentRoot, ref), \"utf-8\"),\n staged: false,\n validate,\n watch,\n };\n};\n",
20
- "import type { Heading, Nodes } from \"mdast\";\nimport { fromMarkdown } from \"mdast-util-from-markdown\";\nimport { gfmFromMarkdown } from \"mdast-util-gfm\";\nimport { toString as mdastToString } from \"mdast-util-to-string\";\nimport { gfm } from \"micromark-extension-gfm\";\nimport stringWidth from \"string-width\";\n\nimport matter from \"../frontmatter.ts\";\nimport { PUBLIC_API_URL } from \"../github.ts\";\nimport { neutralizeUnsafeLinks } from \"../safe-links.ts\";\nimport { columnsPrefix } from \"../text-width.ts\";\nimport {\n hashText,\n loadWithCache,\n pollingWatch,\n snapshotCache,\n} from \"./cache.ts\";\nimport type {\n ContentSource,\n SourceContext,\n SourceEntry,\n SourceLoadResult,\n} from \"./types.ts\";\n\n/** Options for the built-in GitHub Releases changelog source. */\nexport interface GithubReleasesSourceOptions {\n /** GitHub REST API base; overridable for GitHub Enterprise / tests. */\n baseUrl?: string;\n /** Include draft releases (needs a token with repo write access). Default off. */\n drafts?: boolean;\n /** Injected for tests; defaults to the global `fetch`. */\n fetchImpl?: typeof fetch;\n /** Cap the number of releases materialized, newest-first. Default 100. */\n limit?: number;\n name: string;\n /** Repository owner (user or org). */\n owner: string;\n /** Opt-in dev polling interval (seconds); omit to freeze for the session. */\n pollInterval?: number;\n /** Namespaces the source's routes under `/<prefix>/`; e.g. `changelog`. */\n prefix?: string;\n /** Include prereleases. Default off. */\n prereleases?: boolean;\n /** Repository name. */\n repo: string;\n}\n\n/** The subset of the GitHub release payload the adapter reads. */\ninterface GithubRelease {\n body: string | null;\n created_at: string;\n draft: boolean;\n html_url: string;\n id: number;\n name: string | null;\n prerelease: boolean;\n published_at: string | null;\n tag_name: string;\n}\n\nconst DEFAULT_LIMIT = 100;\nconst PER_PAGE = 100;\n\nconst LEADING_V = /^v/iu;\nconst NON_SLUG = /[^a-z0-9]+/gu;\nconst EDGE_DASHES = /^-+|-+$/gu;\n\n// `blume audit` grades meta descriptions against the 110–160 display-column\n// search snippet range (audit/types.ts thresholds), so the derived summary\n// budgets in the same columns and aims for the longest word-boundary cut\n// under the cap.\nconst DESCRIPTION_MAX = 160;\nconst DESCRIPTION_MIN = 110;\n\n// Changesets-generated release bullets open with the changeset's short commit\n// hash (`- cf8fa22: Fix …`) — noise in a search snippet. Stripped from the\n// raw lines (where the bullet anchor still exists) before parsing.\nconst CHANGESET_HASH = /^(?<mark>\\s*(?:[-*+]|\\d+[.)])\\s+)[0-9a-f]{7,40}:\\s+/gmu;\nconst WHITESPACE = /\\s+/gu;\nconst TRAILING_FRAGMENT = /[\\s,;:.—–-]+$/u;\n\n/** Block nodes with no place in a search snippet. */\nconst NON_PROSE = new Set([\"code\", \"heading\", \"html\", \"thematicBreak\"]);\n\n/**\n * Derive a meta description from release notes: GitHub-flavored markdown\n * parsed to mdast and reduced to the plain text of its prose blocks —\n * section headings (\"### Patch Changes\"), code fences, and changesets'\n * commit-hash bullet prefixes dropped; link/emphasis text and inline code\n * content kept — then cut at a word boundary to fit the search snippet cap.\n * Undefined when the notes have no prose at all.\n */\nconst releaseDescription = (body: string): string | undefined => {\n const tree = fromMarkdown(body.replaceAll(CHANGESET_HASH, \"$<mark>\"), {\n extensions: [gfm()],\n mdastExtensions: [gfmFromMarkdown()],\n });\n const text = tree.children\n .filter((node) => !NON_PROSE.has(node.type))\n // Images vanish (their alt is not prose) and raw HTML/JSX tags drop,\n // matching what a reader of the rendered notes would see as text.\n .map((node) =>\n mdastToString(node, { includeHtml: false, includeImageAlt: false })\n )\n .join(\" \")\n .replaceAll(WHITESPACE, \" \")\n .trim();\n if (!text) {\n return undefined;\n }\n if (stringWidth(text) <= DESCRIPTION_MAX) {\n return text;\n }\n // Cut before the cap at a word boundary (kept only when it doesn't drop the\n // summary under the minimum), shed any dangling punctuation, and mark the cut.\n const slice = columnsPrefix(text, DESCRIPTION_MAX - 1);\n const boundary = slice.lastIndexOf(\" \");\n const head = (\n boundary !== -1 && stringWidth(slice.slice(0, boundary)) >= DESCRIPTION_MIN\n ? slice.slice(0, boundary)\n : slice\n ).replace(TRAILING_FRAGMENT, \"\");\n return `${head}…`;\n};\n\n/** Every heading in a tree, in document order (lists and quotes included). */\nconst headingsIn = (node: Nodes): Heading[] => {\n if (node.type === \"heading\") {\n return [node];\n }\n const found: Heading[] = [];\n if (\"children\" in node) {\n for (const child of node.children) {\n found.push(...headingsIn(child));\n }\n }\n return found;\n};\n\n/**\n * Lift the notes' headings so the shallowest is an h2. The release page's\n * title is its h1, and changesets opens every section at `### Patch Changes`,\n * which would skip a level on every page. Only ATX headings can sit deeper\n * than h2, so each lift drops leading `#`s; headings are read from the parsed\n * tree, so a `#` inside a code fence is never touched.\n */\nconst liftHeadings = (body: string): string => {\n const headings = headingsIn(\n fromMarkdown(body, {\n extensions: [gfm()],\n mdastExtensions: [gfmFromMarkdown()],\n })\n );\n const lift = Math.min(...headings.map((heading) => heading.depth)) - 2;\n if (headings.length === 0 || lift <= 0) {\n return body;\n }\n let lifted = body;\n // Back to front, so each cut leaves the earlier offsets valid.\n for (const heading of headings.toReversed()) {\n const marker = lifted.indexOf(\"#\", heading.position?.start.offset);\n lifted = lifted.slice(0, marker) + lifted.slice(marker + lift);\n }\n return lifted;\n};\n\n/** Slugify a tag into a stable, URL-safe source ref (`v1.2.0` -> `v1-2-0`). */\nconst slugifyTag = (tag: string): string =>\n tag.toLowerCase().replaceAll(NON_SLUG, \"-\").replaceAll(EDGE_DASHES, \"\");\n\n/** Build request headers, reading `GITHUB_TOKEN` fresh at call time. */\nconst githubHeaders = (): Headers => {\n const headers = new Headers({ Accept: \"application/vnd.github+json\" });\n const token = process.env.GITHUB_TOKEN;\n if (token) {\n headers.set(\"Authorization\", `Bearer ${token}`);\n }\n return headers;\n};\n\n/**\n * The changelog frontmatter one release lowers to. `title`/`type` are always\n * assigned (optional only so assignment order can keep the emitted YAML key\n * order — and so each entry's content hash — stable).\n */\ninterface ChangelogFrontmatter {\n changelog: { category: string; version: string };\n date: string;\n seo?: { description: string };\n title?: string;\n type?: string;\n}\n\n/**\n * Lower one release to a staged Markdown entry: the notes become the body,\n * `type: changelog` frontmatter (title/date/version/category) drives the\n * generated `/changelog` timeline and RSS feed, and a summary derived from the\n * notes becomes the release page's meta description.\n */\nconst releaseToEntry = (release: GithubRelease): SourceEntry => {\n const version = release.tag_name.replace(LEADING_V, \"\");\n const title = release.name?.trim() || release.tag_name;\n const date = release.published_at ?? release.created_at;\n const category = release.prerelease ? \"Prerelease\" : \"Release\";\n // Release notes are the repository's content, not the site author's, so a\n // link whose destination isn't a web, mail, or relative address\n // (`javascript:`, `data:`) keeps only its label (see `safe-links.ts`).\n const body = liftHeadings(\n neutralizeUnsafeLinks((release.body ?? \"\").replaceAll(\"\\r\\n\", \"\\n\")).trim()\n );\n // A summary in `seo.description` gives each release page a unique meta\n // description (instead of the site-wide fallback) without also rendering the\n // visible lede paragraph a top-level `description` would add.\n const description = releaseDescription(body);\n // Assignment order matters: js-yaml serializes keys in insertion order, so\n // `seo` lands between `date` and `title` exactly as it always has.\n const data: ChangelogFrontmatter = {\n changelog: { category, version },\n date,\n };\n if (description) {\n data.seo = { description };\n }\n data.title = title;\n data.type = \"changelog\";\n const raw = matter.stringify(`${body}\\n`, data);\n const fallbackRef = `release-${release.id}`;\n const ref = `${slugifyTag(release.tag_name) || fallbackRef}.md`;\n return {\n body: { format: \"md\", text: body },\n // Spread: `SourceEntry.data` is an open dictionary, which the interface\n // (no index signature) only satisfies as a fresh object literal.\n data: { ...data },\n editUrl: release.html_url,\n hash: hashText(raw),\n lastModified: date,\n raw,\n ref,\n };\n};\n\n/**\n * GitHub Releases content source. Pulls a repo's releases from the REST API and\n * materializes each as a `type: changelog` entry, so a project's release notes\n * become its changelog with no files to maintain. A private repo authenticates\n * with `GITHUB_TOKEN`. A snapshot under `.blume/cache/<source>/` keeps rebuilds\n * offline-tolerant.\n */\nexport const githubReleasesSource = (\n options: GithubReleasesSourceOptions,\n ctx: SourceContext\n): ContentSource => {\n const doFetch = options.fetchImpl ?? globalThis.fetch;\n const base = (options.baseUrl ?? PUBLIC_API_URL).replace(/\\/$/u, \"\");\n const max = options.limit ?? DEFAULT_LIMIT;\n const cache = snapshotCache(ctx.cacheDir);\n let snapshot = new Map<string, SourceEntry>();\n\n const include = (release: GithubRelease): boolean =>\n (options.drafts || !release.draft) &&\n (options.prereleases || !release.prerelease);\n\n const fetchPage = async (page: number): Promise<GithubRelease[]> => {\n const url = `${base}/repos/${options.owner}/${options.repo}/releases?per_page=${PER_PAGE}&page=${page}`;\n const res = await doFetch(url, { headers: githubHeaders() });\n if (!res.ok) {\n throw new Error(`${url} -> ${res.status}`);\n }\n // SAFETY: GitHub's releases endpoint returns a JSON array of release\n // objects; `GithubRelease` models only the fields the adapter reads.\n return (await res.json()) as GithubRelease[];\n };\n\n const fetchReleases = async (): Promise<GithubRelease[]> => {\n const collected: GithubRelease[] = [];\n let page = 1;\n while (collected.length < max) {\n // oxlint-disable-next-line no-await-in-loop -- pages are sequential: each page's length decides whether another exists.\n const batch = await fetchPage(page);\n collected.push(...batch.filter(include));\n if (batch.length < PER_PAGE) {\n break;\n }\n page += 1;\n }\n return collected.slice(0, max);\n };\n\n const load = async (\n refresh = ctx.refresh ?? true\n ): Promise<SourceLoadResult> => {\n try {\n const result = await loadWithCache(\n options.name,\n cache,\n async () => {\n const releases = await fetchReleases();\n return releases.map(releaseToEntry);\n },\n refresh\n );\n snapshot = new Map(result.entries.map((entry) => [entry.ref, entry]));\n return result;\n } catch (error) {\n // A changelog is supplementary. When releases can't be fetched and nothing\n // is cached (e.g. CI or a deploy without a `GITHUB_TOKEN` for a private\n // repo), degrade to an empty changelog with a warning rather than failing\n // the whole build.\n snapshot = new Map();\n // SAFETY: everything thrown on this path is an Error — fetch rejects\n // with a TypeError, fetchPage and loadWithCache throw Error instances.\n return {\n diagnostics: [\n {\n code: \"BLUME_SOURCE_UNAVAILABLE\",\n message: `Source \"${options.name}\" could not fetch GitHub releases (${(error as Error).message}); the changelog will be empty. Set GITHUB_TOKEN to include it (required for a private repository).`,\n severity: \"warning\",\n },\n ],\n entries: [],\n };\n }\n };\n\n const read = async (ref: string): Promise<string> => {\n const cached = snapshot.get(ref);\n if (cached) {\n return cached.raw ?? cached.body.text;\n }\n const all = await cache.read();\n const entry = all.find((e) => e.ref === ref);\n return entry?.raw ?? entry?.body.text ?? \"\";\n };\n\n return {\n load,\n // Releases are written once, in one language: no locale can translate them.\n monolingual: true,\n name: options.name,\n prefix: options.prefix,\n read,\n staged: true,\n watch: options.pollInterval\n ? pollingWatch(\n () => load(true),\n options.pollInterval,\n () => load()\n )\n : undefined,\n };\n};\n",
21
- "import picomatch from \"picomatch\";\n\nimport { BlumeError } from \"../diagnostics.ts\";\nimport matter from \"../frontmatter.ts\";\nimport type { Diagnostic } from \"../types.ts\";\nimport {\n hashText,\n loadWithCache,\n pollingWatch,\n snapshotCache,\n} from \"./cache.ts\";\nimport type {\n ContentSource,\n SourceContext,\n SourceEntry,\n SourceLoadResult,\n} from \"./types.ts\";\n\n/** Options for the built-in remote Markdown/MDX source. */\nexport interface MdxRemoteSourceOptions {\n name: string;\n prefix?: string;\n /** Raw base URL for `files`, e.g. `https://raw.githubusercontent.com/o/r/main/docs`. */\n url?: string;\n /** Explicit source-relative file paths to fetch from `url`. */\n files?: string[];\n /** Enumerate a GitHub repo subtree via the git-trees API. */\n github?: { owner: string; repo: string; ref: string; path: string };\n include: string[];\n /** Opt-in dev polling interval (seconds); omit to freeze for the session. */\n pollInterval?: number;\n /** Injected for tests; defaults to the global `fetch`. */\n fetchImpl?: typeof fetch;\n}\n\n// Include globs compile through picomatch — what the filesystem source's\n// tinyglobby uses under the hood — so the same `include` array means the same\n// thing on every source type: negation, character classes, nested braces, and\n// extglobs included. Compiled once per enumeration, not per ref.\n\n/** A file to fetch: its source-local ref plus where to read it from. */\ninterface RemoteRef {\n ref: string;\n fetchUrl: string;\n editUrl?: string;\n}\n\n// Hosts the GITHUB_TOKEN may be sent to. A configured `url` base can point at\n// any server, and leaking the token there would hand a repo credential to an\n// arbitrary third party.\nconst GITHUB_HOSTS = new Set([\"api.github.com\", \"raw.githubusercontent.com\"]);\n\nconst githubHeaders = (url: string): Record<string, string> => {\n const token = process.env.GITHUB_TOKEN;\n if (!token) {\n return {};\n }\n let host = \"\";\n try {\n host = new URL(url).hostname;\n } catch {\n return {};\n }\n return GITHUB_HOSTS.has(host) ? { authorization: `Bearer ${token}` } : {};\n};\n\ninterface GithubTreeEntry {\n path: string;\n type: string;\n}\n\n/** Enumerate a GitHub repo subtree, mapping blobs to remote refs. */\nconst enumerateGithub = async (\n github: { owner: string; repo: string; ref: string; path: string },\n include: string[],\n doFetch: typeof fetch\n): Promise<{ refs: RemoteRef[]; truncated: boolean }> => {\n const { owner, repo, ref } = github;\n const base = github.path.replaceAll(/^\\/|\\/$/gu, \"\");\n const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${ref}?recursive=1`;\n const res = await doFetch(treeUrl, { headers: githubHeaders(treeUrl) });\n if (!res.ok) {\n throw new Error(`${treeUrl} -> ${res.status}`);\n }\n // SAFETY: GitHub's git/trees endpoint returns this envelope; a missing or\n // differently-typed field falls through the `?? []` and blob filters below.\n const body = (await res.json()) as {\n tree?: GithubTreeEntry[];\n truncated?: boolean;\n };\n const prefix = base ? `${base}/` : \"\";\n const included = picomatch(include);\n const refs = (body.tree ?? []).flatMap((node) => {\n if (!(node.type === \"blob\" && node.path.startsWith(prefix))) {\n return [];\n }\n const rel = node.path.slice(prefix.length);\n if (!included(rel)) {\n return [];\n }\n return [\n {\n editUrl: `https://github.com/${owner}/${repo}/edit/${ref}/${prefix}${rel}`,\n fetchUrl: `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${prefix}${rel}`,\n ref: rel,\n },\n ];\n });\n // GitHub caps the recursive tree response (~100k entries / 7MB) and flags it\n // with `truncated`; ignoring it would silently import only part of the repo.\n return { refs, truncated: body.truncated === true };\n};\n\n/**\n * Remote Markdown/MDX content source. Fetches raw `.md`/`.mdx` over HTTP and\n * passes the text straight through `normalizeEntry`. A snapshot under\n * `.blume/cache/<source>/` makes rebuilds offline-tolerant.\n */\nexport const mdxRemoteSource = (\n options: MdxRemoteSourceOptions,\n ctx: SourceContext\n): ContentSource => {\n const doFetch = options.fetchImpl ?? globalThis.fetch;\n const cache = snapshotCache(ctx.cacheDir);\n let snapshot = new Map<string, SourceEntry>();\n\n // Validated up front in `load`, *before* the cached-fetch path: thrown from\n // inside `loadWithCache`'s fetch callback, a misconfiguration would be masked\n // as BLUME_SOURCE_FETCH_FAILED (no cache) or downgraded to a stale-cache\n // BLUME_SOURCE_OFFLINE warning (cache present).\n const assertConfigured = (): void => {\n if (options.github || (options.files && options.url)) {\n return;\n }\n throw new BlumeError({\n code: \"BLUME_SOURCE_MISCONFIGURED\",\n message: `Source \"${options.name}\" needs either { github } or { url, files }.`,\n severity: \"error\",\n });\n };\n\n const enumerate = async (): Promise<{\n refs: RemoteRef[];\n truncated: boolean;\n }> => {\n if (options.github) {\n return await enumerateGithub(options.github, options.include, doFetch);\n }\n const base = (options.url ?? \"\").replace(/\\/$/u, \"\");\n const included = picomatch(options.include);\n const refs = (options.files ?? []).flatMap((ref) =>\n included(ref)\n ? [{ editUrl: `${base}/${ref}`, fetchUrl: `${base}/${ref}`, ref }]\n : []\n );\n return { refs, truncated: false };\n };\n\n const fetchEntry = async (item: RemoteRef): Promise<SourceEntry> => {\n const res = await doFetch(item.fetchUrl, {\n headers: githubHeaders(item.fetchUrl),\n });\n if (!res.ok) {\n throw new Error(`${item.fetchUrl} -> ${res.status}`);\n }\n const text = await res.text();\n const parsed = matter(text);\n const format = item.ref.toLowerCase().endsWith(\".mdx\") ? \"mdx\" : \"md\";\n return {\n body: { format, text: parsed.content },\n data: parsed.data,\n editUrl: item.editUrl,\n hash: hashText(text),\n raw: text,\n ref: item.ref,\n };\n };\n\n const load = async (\n refresh = ctx.refresh ?? true\n ): Promise<SourceLoadResult> => {\n assertConfigured();\n const skipped: Diagnostic[] = [];\n const result = await loadWithCache(\n options.name,\n cache,\n async () => {\n const { refs, truncated } = await enumerate();\n if (truncated) {\n skipped.push({\n code: \"BLUME_SOURCE_TRUNCATED\",\n message: `Source \"${options.name}\" hit GitHub's tree listing limit; some files were not enumerated. Narrow the source path or split the repo.`,\n severity: \"warning\",\n });\n }\n const settled = await Promise.all(\n refs.map(async (ref) => {\n try {\n return await fetchEntry(ref);\n } catch (error) {\n skipped.push({\n code: \"BLUME_SOURCE_FETCH_FAILED\",\n // SAFETY: fetch and decode failures throw Error instances;\n // only the message is read for the skip diagnostic.\n message: `Source \"${options.name}\" skipped \"${ref.ref}\" (${(error as Error).message}); the rest were imported.`,\n severity: \"warning\",\n });\n return null;\n }\n })\n );\n const entries = settled.filter(\n (entry): entry is SourceEntry => entry !== null\n );\n // Only a total wipeout is a hard failure — let loadWithCache fall back\n // to cache or fail loudly rather than silently importing nothing. A\n // partial failure keeps the healthy pages and warns about the rest.\n if (refs.length > 0 && entries.length === 0) {\n skipped.length = 0;\n throw new Error(`all ${refs.length} remote file(s) failed to fetch`);\n }\n return entries;\n },\n refresh\n );\n snapshot = new Map(result.entries.map((entry) => [entry.ref, entry]));\n return {\n ...result,\n diagnostics: [...result.diagnostics, ...skipped],\n };\n };\n\n const read = async (ref: string): Promise<string> => {\n const cached = snapshot.get(ref);\n if (cached) {\n return cached.raw ?? cached.body.text;\n }\n const all = await cache.read();\n const entry = all.find((e) => e.ref === ref);\n return entry?.raw ?? entry?.body.text ?? \"\";\n };\n\n return {\n load,\n name: options.name,\n prefix: options.prefix,\n read,\n staged: true,\n watch: options.pollInterval\n ? pollingWatch(\n () => load(true),\n options.pollInterval,\n () => load()\n )\n : undefined,\n };\n};\n",
22
- "import { setTimeout as sleep } from \"node:timers/promises\";\n\nimport pLimit from \"p-limit\";\nimport { join } from \"pathe\";\n\nimport { parseYouTubeId } from \"../../components/content/youtube.ts\";\nimport { BlumeError } from \"../diagnostics.ts\";\nimport matter from \"../frontmatter.ts\";\nimport { nodeRequire } from \"../node-require.ts\";\nimport type { Diagnostic } from \"../types.ts\";\nimport { materializeAssets } from \"./assets.ts\";\nimport {\n hashText,\n loadWithCache,\n pollingWatch,\n snapshotCache,\n} from \"./cache.ts\";\nimport { codeFence, image, renderInline, renderLink } from \"./lower.ts\";\nimport { slugifyPath } from \"./normalize.ts\";\nimport type {\n ContentSource,\n SourceContext,\n SourceEntry,\n SourceLoadResult,\n} from \"./types.ts\";\n\ninterface NotionRichText {\n plain_text: string;\n href?: string | null;\n annotations?: {\n bold?: boolean;\n italic?: boolean;\n code?: boolean;\n strikethrough?: boolean;\n };\n}\n\ninterface NotionProperty {\n type: string;\n title?: NotionRichText[];\n rich_text?: NotionRichText[];\n select?: { name: string } | null;\n status?: { name: string } | null;\n number?: number | null;\n}\n\ninterface NotionPage {\n id: string;\n properties: Record<string, NotionProperty>;\n last_edited_time?: string;\n}\n\n/** The per-type payload a block carries under the key matching its `type`. */\ninterface NotionBlockPayload {\n caption?: NotionRichText[];\n checked?: boolean;\n external?: { url: string };\n file?: { url: string };\n language?: string;\n rich_text?: NotionRichText[];\n}\n\ninterface NotionBlock {\n id: string;\n type: string;\n has_children?: boolean;\n [key: string]: NotionBlockPayload | boolean | string | undefined;\n}\n\ninterface NotionList<T> {\n results: T[];\n has_more: boolean;\n next_cursor: string | null;\n}\n\n/**\n * The slice of `@notionhq/client` (v5+) this adapter relies on, so it's\n * mockable. Since API version 2025-09-03 a database's rows live in a data\n * source: `databases.retrieve` names the data sources and\n * `dataSources.query` pages through one of them.\n */\nexport interface NotionClientLike {\n databases: {\n retrieve: (args: { database_id: string }) => Promise<{\n data_sources: { id: string; name: string }[];\n }>;\n };\n dataSources: {\n query: (args: {\n data_source_id: string;\n start_cursor?: string;\n }) => Promise<NotionList<NotionPage>>;\n };\n blocks: {\n children: {\n list: (args: {\n block_id: string;\n start_cursor?: string;\n }) => Promise<NotionList<NotionBlock>>;\n };\n };\n}\n\n/** Notion property names mapped onto Blume meta. */\nexport interface NotionPropertyMap {\n /** Title property name; defaults to the database's `title`-typed property. */\n title?: string;\n /** Description property (rich_text); default `Description`. */\n description?: string;\n /** Slug property (rich_text); default `Slug`, else the slugified title. */\n slug?: string;\n /** Status property (select/status); default `Status`. */\n status?: string;\n /** Sidebar order property (number); default `Order`. */\n order?: string;\n}\n\nexport interface NotionSourceOptions {\n name: string;\n prefix?: string;\n /** The Notion database id. */\n database: string;\n /**\n * Maximum concurrent Notion API requests. Notion allows an average of 3\n * requests per second per integration, so a large database must pace its\n * block-tree fan-out or every request 429s. Default 3.\n */\n concurrency?: number;\n /** Integration token; defaults to `NOTION_TOKEN`. */\n token?: string;\n properties?: NotionPropertyMap;\n /**\n * The `Status` property is treated as a publish signal: any value other than\n * this maps to `draft: true`. Defaults to `Published`; pages without a\n * Status/select property are always imported as published.\n */\n publishedValue?: string;\n /** Opt-in dev polling interval (seconds); omit to freeze for the session. */\n pollInterval?: number;\n /** Injected for tests; otherwise built from `@notionhq/client`. */\n client?: NotionClientLike;\n /** Injected for tests; used to download images. */\n fetchImpl?: typeof fetch;\n}\n\n/** The frontmatter Blume derives from a Notion page's properties. */\ninterface NotionFrontmatter {\n description?: string;\n draft?: boolean;\n sidebar?: { order: number };\n title?: string;\n // Frontmatter stays an open bag downstream (`SourceEntry.data`), so admit\n // the value shapes this source writes under any future key.\n [key: string]: boolean | string | { order: number } | undefined;\n}\n\n/**\n * Rich text as Markdown for an MDX body. Each run goes through the shared\n * lowering, so a literal `{`, `<`, `*`, or `[` typed in Notion renders as\n * itself instead of opening a JSX expression, a tag, or emphasis, and a code\n * run keeps its text verbatim inside a long-enough code span.\n */\nconst richToMarkdown = (rich: NotionRichText[] = []): string =>\n rich\n .map(({ annotations = {}, href, plain_text: text }) =>\n renderLink(\n renderInline(text, {\n bold: annotations.bold,\n code: annotations.code,\n italic: annotations.italic,\n strike: annotations.strikethrough,\n }),\n href ?? undefined\n )\n )\n .join(\"\");\n\nconst isBlockPayload = (\n value: NotionBlockPayload | boolean | string | undefined\n): value is NotionBlockPayload => typeof value === \"object\";\n\n/** The payload object stored under a block's own `type` key, if present. */\nconst payloadOf = (block: NotionBlock): NotionBlockPayload | undefined => {\n const value = block[block.type];\n return isBlockPayload(value) ? value : undefined;\n};\n\nconst blockField = (block: NotionBlock): NotionRichText[] =>\n payloadOf(block)?.rich_text ?? [];\n\nconst RATE_LIMITED = 429;\nconst MAX_RETRIES = 4;\nconst BASE_DELAY_MS = 500;\nconst SECOND_MS = 1000;\nconst DEFAULT_CONCURRENCY = 3;\nconst ASSET_DOWNLOAD_CONCURRENCY = 4;\n\n/**\n * Retry a Notion API call on a `429 rate_limited`, honoring the `Retry-After`\n * header and otherwise backing off exponentially. A large workspace fans out\n * many concurrent block-children requests, so without this a single 429 would\n * reject the batch and abort the whole import. The exponential wait is\n * jittered so calls rate-limited together don't retry in lockstep and trip\n * the limit again as a herd.\n */\nconst withNotionRetry = async <T>(\n call: () => Promise<T>,\n attempt = 0\n): Promise<T> => {\n try {\n return await call();\n } catch (error) {\n // SAFETY: Notion SDK failures are APIResponseError-shaped, carrying the\n // failed request's HTTP status; anything else reads `undefined` and is\n // rethrown below.\n const { status } = error as { status?: number };\n if (status !== RATE_LIMITED || attempt === MAX_RETRIES) {\n throw error;\n }\n // SAFETY: same APIResponseError shape — `headers` maps lower-cased HTTP\n // header names to their values; a missing header yields `NaN` and falls\n // back to exponential backoff.\n const retryAfter = Number(\n (error as { headers?: Record<string, string> }).headers?.[\"retry-after\"]\n );\n const wait =\n retryAfter > 0\n ? retryAfter * SECOND_MS\n : BASE_DELAY_MS * 2 ** attempt * (1 + Math.random());\n await sleep(wait);\n return withNotionRetry(call, attempt + 1);\n }\n};\n\n/** Paginate a Notion list endpoint via recursion (no await-in-loop). */\nconst collectAll = async <T>(\n page: (cursor?: string) => Promise<NotionList<T>>,\n cursor?: string,\n acc: T[] = []\n): Promise<T[]> => {\n const res = await page(cursor);\n const all = [...acc, ...res.results];\n return res.has_more && res.next_cursor\n ? collectAll(page, res.next_cursor, all)\n : all;\n};\n\nconst LIST_BLOCKS = new Set([\n \"bulleted_list_item\",\n \"numbered_list_item\",\n \"to_do\",\n]);\n\n/** Whether a block is a list item (so consecutive ones render as a tight list). */\nconst isListItem = (block: NotionBlock | undefined): boolean =>\n block !== undefined && LIST_BLOCKS.has(block.type);\n\nconst richToPlain = (rich: NotionRichText[] = []): string =>\n rich.map((node) => node.plain_text).join(\"\");\n\n/**\n * A string prop in JSX expression form. The quoted form (`title=\"…\"`) keeps\n * `\\\"` and `\\n` as literal characters — MDX decodes no escapes there, so a\n * caption holding a double quote fails to compile the whole page — where the\n * expression form (`title={\"…\"}`) is a JSON string literal and decodes them.\n */\nconst jsxString = (value: string): string => `{${JSON.stringify(value)}}`;\n\nconst YOUTUBE_HOST = /(?:^|\\.)(?:youtube(?:-nocookie)?\\.com|youtu\\.be)$/u;\n\n// `parseYouTubeId` is host-agnostic on purpose (the component accepts bare\n// ids), so gate on the hostname first: `https://cdn.example.com/live/promo.mp4`\n// matches its `/live/<11 chars>` shape but is a media file, not an embed.\nconst isYouTubeUrl = (url: string): boolean => {\n const host = URL.parse(url)?.hostname ?? \"\";\n return YOUTUBE_HOST.test(host) && parseYouTubeId(url) !== null;\n};\n\n/**\n * Render a Notion `video` block. Kept out of `renderLeaf`'s switch so that\n * function stays under the complexity limit.\n */\nconst renderVideo = (data: NotionBlockPayload): string => {\n const url = data.external?.url ?? data.file?.url;\n if (!url) {\n return \"\";\n }\n const caption = richToMarkdown(data.caption);\n // A YouTube link pasted into Notion becomes a `video` block holding an\n // external URL. That URL is a watch page, not a media file, so it has to\n // become the embed component — a `<video src>` pointing at it plays nothing,\n // and `materializeAssets` would download the HTML page. The iframe's title\n // is its accessible name, so it gets the caption's plain text; the Markdown\n // rendering goes to the Frame's caption, as it does for an upload.\n const title = caption ? ` title=${jsxString(richToPlain(data.caption))}` : \"\";\n // Everything else (a Notion upload, or a direct link to a media file) is a\n // real video file: `materializeAssets` rewrites the `src`, which matters most\n // for uploads, whose Notion URLs are signed and expire.\n const media = isYouTubeUrl(url)\n ? `<YouTube${title} url=${JSON.stringify(url)} />`\n : `<video controls src=${JSON.stringify(url)} />`;\n return caption\n ? `<Frame caption=${jsxString(caption)}>\\n${media}\\n</Frame>`\n : media;\n};\n\n/** Render a leaf (non-container) block to Markdown, or null for containers. */\nconst renderLeaf = (block: NotionBlock): string | null => {\n const data = payloadOf(block) ?? {};\n const text = richToMarkdown(blockField(block));\n switch (block.type) {\n case \"paragraph\": {\n return text;\n }\n case \"heading_1\": {\n return `# ${text}`;\n }\n case \"heading_2\": {\n return `## ${text}`;\n }\n case \"heading_3\": {\n return `### ${text}`;\n }\n case \"bulleted_list_item\": {\n return `- ${text}`;\n }\n case \"numbered_list_item\": {\n return `1. ${text}`;\n }\n case \"to_do\": {\n return `- [${data.checked ? \"x\" : \" \"}] ${text}`;\n }\n case \"quote\": {\n return `> ${text}`;\n }\n case \"divider\": {\n return \"---\";\n }\n case \"code\": {\n // The code's own text, verbatim: escapes would show inside the fence.\n return codeFence(richToPlain(blockField(block)), data.language ?? \"\");\n }\n case \"image\": {\n const url = data.external?.url ?? data.file?.url;\n return url ? image(richToPlain(data.caption), url) : \"\";\n }\n case \"video\": {\n return renderVideo(data);\n }\n default: {\n return null;\n }\n }\n};\n\n/**\n * Notion content source. Maps a database to a collection: each page becomes an\n * entry, its properties become frontmatter, and its block tree is converted to\n * MDX with Blume components. Images are materialized so signed URLs don't rot.\n */\nexport const notionSource = (\n options: NotionSourceOptions,\n ctx?: SourceContext\n): ContentSource => {\n const props = options.properties ?? {};\n // A FIFO semaphore: at most N calls run at once, the rest queue. Notion's\n // rate limit is per-integration (an average of 3 req/s), and a large\n // database fans out one block-children request per page plus one per nested\n // container — an unbounded burst guarantees 429s that even the retry loop\n // can't recover from, so every API call funnels through this limiter.\n const limit = pLimit(Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY));\n // Asset downloads get their own gate: they go to Notion's S3, not its rate-\n // limited API, and a slow video must not hold API slots. One gate per source\n // bounds the fan-out across every page, not just within one.\n const downloads = pLimit(ASSET_DOWNLOAD_CONCURRENCY);\n // Shared with the gate so two pages naming one asset share one download.\n const inFlight = new Map<string, Promise<string>>();\n // Every Notion API call goes through the limiter, inside the retry — so a\n // call sleeping through a backoff doesn't hold a slot while it waits.\n const notionCall = <T>(call: () => Promise<T>): Promise<T> =>\n withNotionRetry(() => limit(call));\n const cache = snapshotCache(\n ctx?.cacheDir ?? join(\".blume\", \"cache\", options.name)\n );\n const assetsDir =\n ctx?.assetsDir ?? join(\".blume\", \"public\", \"blume-assets\", options.name);\n const assetsBaseUrl = ctx?.assetsBaseUrl ?? `/blume-assets/${options.name}`;\n let snapshot = new Map<string, SourceEntry>();\n\n const resolveClient = (): NotionClientLike => {\n if (options.client) {\n return options.client;\n }\n let Client: new (config: { auth?: string }) => NotionClientLike;\n try {\n // `require`, not `import()`: an ejected app scans in\n // `astro:build:done` (see `core/node-require.ts`). The module is\n // widened first because the SDK's response unions are broader than the\n // NotionClientLike slice, so a direct assertion is rejected as\n // non-overlapping.\n const sdk: unknown = nodeRequire(\"@notionhq/client\");\n // SAFETY: `@notionhq/client` exports a `Client` class constructable with\n // an `auth` token whose instances cover the NotionClientLike slice; the\n // local type keeps the SDK mockable without importing its types.\n ({ Client } = sdk as {\n Client: new (config: { auth?: string }) => NotionClientLike;\n });\n } catch {\n throw new BlumeError({\n code: \"BLUME_SOURCE_SDK_MISSING\",\n message: `Source \"${options.name}\" needs \"@notionhq/client\". Install it (e.g. \\`npm install @notionhq/client\\`).`,\n severity: \"error\",\n });\n }\n return new Client({ auth: options.token ?? process.env.NOTION_TOKEN });\n };\n\n const childrenOf = (\n client: NotionClientLike,\n blockId: string\n ): Promise<NotionBlock[]> =>\n collectAll((cursor) =>\n notionCall(() =>\n client.blocks.children.list({ block_id: blockId, start_cursor: cursor })\n )\n );\n\n // `render` is injected (rather than referenced) so this stays a forward-free\n // definition; `renderBlocks` passes itself, the way `collectAll` recurses.\n const renderContainer = async (\n client: NotionClientLike,\n block: NotionBlock,\n render: (c: NotionClientLike, b: NotionBlock[]) => Promise<string>\n ): Promise<string> => {\n const children = async (target: NotionBlock): Promise<string> => {\n if (!target.has_children) {\n return \"\";\n }\n return render(client, await childrenOf(client, target.id));\n };\n\n if (block.type === \"callout\") {\n const body = [richToMarkdown(blockField(block)), await children(block)]\n .filter(Boolean)\n .join(\"\\n\\n\");\n return `<Callout>\\n${body}\\n</Callout>`;\n }\n if (block.type === \"toggle\") {\n // The item's title renders as text, not Markdown.\n const title = jsxString(richToPlain(blockField(block)));\n return `<Accordion>\\n<AccordionItem title=${title}>\\n${await children(block)}\\n</AccordionItem>\\n</Accordion>`;\n }\n if (block.type === \"column_list\") {\n const cols = await childrenOf(client, block.id);\n const rendered = await Promise.all(\n cols.map(async (col) => `<Column>\\n${await children(col)}\\n</Column>`)\n );\n return `<Columns>\\n${rendered.join(\"\\n\")}\\n</Columns>`;\n }\n return `{/* unsupported Notion block: ${block.type} */}`;\n };\n\n const renderBlocks = async (\n client: NotionClientLike,\n blocks: NotionBlock[]\n ): Promise<string> => {\n const parts = await Promise.all(\n blocks.map(async (block) => {\n const leaf = renderLeaf(block);\n if (leaf === null) {\n return renderContainer(client, block, renderBlocks);\n }\n // Leaf blocks can still carry children (nested list items, indented\n // paragraphs); dropping them would silently lose content.\n if (!block.has_children) {\n return leaf;\n }\n const nested = await renderBlocks(\n client,\n await childrenOf(client, block.id)\n );\n if (!nested) {\n return leaf;\n }\n if (isListItem(block)) {\n // Indent past the list marker so the children belong to the item\n // (`1. ` needs three columns, `- `/`- [x] ` two).\n const indent = \" \".repeat(\n block.type === \"numbered_list_item\" ? 3 : 2\n );\n const indented = nested\n .split(\"\\n\")\n .map((line) => (line ? `${indent}${line}` : line))\n .join(\"\\n\");\n return `${leaf}\\n${indented}`;\n }\n // Other leaves (paragraph, quote) keep their children as following\n // sibling blocks — the indentation semantics are lost but the content\n // survives.\n return `${leaf}\\n\\n${nested}`;\n })\n );\n // Join with a blank line, except between consecutive list items, which stay\n // tight so they render as a single list rather than separate loose ones.\n const pairs = blocks.flatMap((block, i) => {\n const text = parts[i] ?? \"\";\n return text ? [{ block, text }] : [];\n });\n return pairs\n .map((pair, i) => {\n if (i === 0) {\n return pair.text;\n }\n const tight = isListItem(pairs[i - 1]?.block) && isListItem(pair.block);\n return `${tight ? \"\\n\" : \"\\n\\n\"}${pair.text}`;\n })\n .join(\"\");\n };\n\n const titleProperty = (page: NotionPage): NotionProperty | undefined => {\n if (props.title) {\n return page.properties[props.title];\n }\n return Object.values(page.properties).find((p) => p.type === \"title\");\n };\n\n const isDraft = (page: NotionPage): boolean => {\n const prop = page.properties[props.status ?? \"Status\"];\n const status = prop?.status?.name ?? prop?.select?.name;\n // A page without a Status/select property stays published; one with a\n // status is a draft unless it matches the published value.\n return Boolean(\n status && status !== (options.publishedValue ?? \"Published\")\n );\n };\n\n const orderOf = (page: NotionPage): number | undefined => {\n const order = page.properties[props.order ?? \"Order\"]?.number;\n return order === null ? undefined : order;\n };\n\n const frontmatter = (page: NotionPage) => {\n const data: NotionFrontmatter = {};\n // Frontmatter holds plain text: Markdown marks or escapes would show.\n const title = richToPlain(titleProperty(page)?.title);\n if (title) {\n data.title = title;\n }\n const description = richToPlain(\n page.properties[props.description ?? \"Description\"]?.rich_text\n );\n if (description) {\n data.description = description;\n }\n if (isDraft(page)) {\n data.draft = true;\n }\n const order = orderOf(page);\n if (order !== undefined) {\n data.sidebar = { order };\n }\n const slugProp = richToPlain(\n page.properties[props.slug ?? \"Slug\"]?.rich_text\n );\n // Path-aware: a `guides/setup` slug keeps its `/` (per-segment slugging)\n // instead of mashing into `guidessetup`.\n const slug = slugifyPath(slugProp || title) || page.id;\n return { data, slug };\n };\n\n const toEntry = async (\n client: NotionClientLike,\n page: NotionPage\n ): Promise<{ entry: SourceEntry; diagnostics: Diagnostic[] }> => {\n const { data, slug } = frontmatter(page);\n const mdx = await renderBlocks(client, await childrenOf(client, page.id));\n const assets = await materializeAssets(mdx, {\n assetsBaseUrl,\n assetsDir,\n fetchImpl: options.fetchImpl,\n inFlight,\n limit: downloads,\n });\n const raw = matter.stringify(assets.markdown, data);\n return {\n diagnostics: assets.diagnostics,\n entry: {\n body: { format: \"mdx\", text: assets.markdown },\n data,\n hash: hashText(raw),\n lastModified: page.last_edited_time,\n raw,\n ref: `${slug}.mdx`,\n },\n };\n };\n\n // A database's rows live in its data source (API 2025-09-03). Blume reads\n // the first one, which is the only one a database created in Notion has.\n const resolveDataSource = async (\n client: NotionClientLike\n ): Promise<string> => {\n const database = await notionCall(() =>\n client.databases.retrieve({ database_id: options.database })\n );\n const [dataSource] = database.data_sources;\n if (!dataSource) {\n throw new BlumeError({\n code: \"BLUME_SOURCE_MISCONFIGURED\",\n message: `Source \"${options.name}\": Notion database \"${options.database}\" has no data source to read pages from.`,\n severity: \"error\",\n });\n }\n return dataSource.id;\n };\n\n // Hoisted out of `load` so the retry closure doesn't nest past the linter's\n // 4-level limit (source factory → queryDataSource → notionCall callback).\n const queryDataSource = (\n client: NotionClientLike,\n dataSourceId: string,\n cursor?: string\n ): Promise<NotionList<NotionPage>> =>\n notionCall(() =>\n client.dataSources.query({\n data_source_id: dataSourceId,\n start_cursor: cursor,\n })\n );\n\n const load = async (\n refresh = ctx?.refresh ?? true\n ): Promise<SourceLoadResult> => {\n const assetDiagnostics: Diagnostic[] = [];\n const result = await loadWithCache(\n options.name,\n cache,\n async () => {\n const client = resolveClient();\n const dataSourceId = await resolveDataSource(client);\n const pages = await collectAll((cursor) =>\n queryDataSource(client, dataSourceId, cursor)\n );\n const built = await Promise.all(\n pages.map((page) => toEntry(client, page))\n );\n for (const item of built) {\n assetDiagnostics.push(...item.diagnostics);\n }\n return built.map((item) => item.entry);\n },\n refresh\n );\n snapshot = new Map(result.entries.map((entry) => [entry.ref, entry]));\n return {\n diagnostics: [...result.diagnostics, ...assetDiagnostics],\n entries: result.entries,\n };\n };\n\n const read = async (ref: string): Promise<string> => {\n const cached = snapshot.get(ref);\n if (cached) {\n return cached.raw ?? cached.body.text;\n }\n const all = await cache.read();\n return all.find((e) => e.ref === ref)?.raw ?? \"\";\n };\n\n return {\n load,\n name: options.name,\n prefix: options.prefix,\n read,\n staged: true,\n watch: options.pollInterval\n ? pollingWatch(\n () => load(true),\n options.pollInterval,\n () => load()\n )\n : undefined,\n };\n};\n",
23
- "import { randomUUID } from \"node:crypto\";\nimport {\n access,\n mkdir,\n readdir,\n rename,\n rm,\n writeFile,\n} from \"node:fs/promises\";\n\nimport { extname, join } from \"pathe\";\n\nimport type { Diagnostic } from \"../types.ts\";\nimport { hashText } from \"./cache.ts\";\n\nconst MD_IMAGE = /!\\[(?<alt>[^\\]]*)\\]\\((?<url>[^)\\s]+)\\)/gu;\n// A `<video>` tag's `src`, split so the rewrite can swap the URL and keep the\n// surrounding attributes untouched. Notion's uploaded videos arrive as signed,\n// expiring URLs exactly like its images, so they rot the same way. `[^>]`\n// bounds the attribute run to a single tag.\nconst HTML_VIDEO_SRC =\n /(?<open><video\\b[^>]*?\\ssrc=\")(?<url>[^\"]+)(?<close>\")/gu;\nconst REMOTE = /^https?:\\/\\//u;\nconst SAFE_EXT = /^\\.[a-z0-9]+$/iu;\nconst CODE_FENCE_BLOCK =\n /^(?<fence>`{3,}|~{3,})[^\\n]*\\n[\\s\\S]*?^\\k<fence>[^\\n]*(?=\\n|$)/gmu;\n// NUL delimiters cannot appear in authored markdown, so tokens never collide.\n// oxlint-disable-next-line no-control-regex -- the NUL is the collision guard.\nconst FENCE_TOKEN = /\\u0000blume-fence-(?<index>\\d+)\\u0000/gu;\n\n// The extension for a URL whose path carries none, keyed by the media type the\n// server reports. A static host serves by extension, so a `.png` holding JPEG\n// bytes is mislabeled and a `.png` holding a video is refused by strict\n// players — the response is the source of truth, not the reference kind.\nconst EXT_BY_MIME = new Map([\n [\"image/avif\", \".avif\"],\n [\"image/gif\", \".gif\"],\n [\"image/jpeg\", \".jpg\"],\n [\"image/png\", \".png\"],\n [\"image/svg+xml\", \".svg\"],\n [\"image/webp\", \".webp\"],\n [\"video/mp4\", \".mp4\"],\n [\"video/ogg\", \".ogv\"],\n [\"video/quicktime\", \".mov\"],\n [\"video/webm\", \".webm\"],\n]);\nconst UNKNOWN_EXT = \".bin\";\n// Response types that are never a media file. A pasted Vimeo/Loom/Wistia link\n// is a video block in Notion whose URL is a watch page (200 text/html), and an\n// API endpoint answers JSON or XML; `image/svg+xml` is media and stays.\nconst NON_MEDIA_TYPE =\n /^(?:text\\/|application\\/(?:[\\w.-]+\\+)?(?:json|xml|javascript))/u;\nconst PART_SUFFIX = \".part\";\n// Generous enough for a multi-hundred-megabyte recording on an ordinary\n// connection; its job is to fail a stalled download rather than hang the build.\nconst DEFAULT_TIMEOUT_MS = 120_000;\n\n/** Where to write downloaded assets and how to reference them publicly. */\nexport interface AssetContext {\n assetsDir: string;\n assetsBaseUrl: string;\n /** Injected for tests; defaults to the global `fetch`. */\n fetchImpl?: typeof fetch;\n /**\n * Gate for concurrent downloads. A source shares one gate across every page\n * it materializes, so a database of video-heavy pages doesn't open every\n * download at once. Defaults to no gate.\n */\n limit?: <T>(task: () => Promise<T>) => Promise<T>;\n /**\n * Downloads in progress, keyed by asset stem. A source shares one table\n * (alongside `limit`) across every page it materializes, so two pages that\n * reference the same asset share one download instead of racing to publish\n * the same file. Defaults to a table private to this call.\n */\n inFlight?: Map<string, Promise<string>>;\n /** Abort a download that hasn't completed within this many milliseconds. */\n timeoutMs?: number;\n}\n\n/** The extension in a URL's path, or null when it carries none we'd trust. */\nconst extFromUrl = (url: string): string | null => {\n const clean = url.split(\"?\")[0] ?? url;\n const ext = extname(clean);\n return SAFE_EXT.test(ext) ? ext.toLowerCase() : null;\n};\n\n/** The response's media type, lowercased and stripped of parameters. */\nconst mediaType = (res: Response): string =>\n res.headers.get(\"content-type\")?.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n\nconst exists = async (path: string): Promise<boolean> => {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n};\n\n/**\n * The completed file for a stem whose extension came from an earlier response\n * rather than the URL, so an extension-less asset is not fetched on every\n * poll. Only a lone candidate counts: query-less URLs can collide, and picking\n * between two files would be a guess.\n */\nconst completedFor = async (\n dir: string,\n stem: string\n): Promise<string | null> => {\n let names: string[];\n try {\n names = await readdir(dir);\n } catch {\n return null;\n }\n const candidates = names.filter(\n (name) => name.startsWith(`${stem}.`) && !name.endsWith(PART_SUFFIX)\n );\n return candidates.length === 1 ? (candidates[0] ?? null) : null;\n};\n\n/**\n * Download remote media referenced in a Markdown body into the asset dir and\n * rewrite the reference to the local public path. Markdown images and the\n * `src` of a `<video>` tag are both covered. Remote CMS URLs (notably Notion's\n * signed, expiring links) would otherwise rot a static build. Assets are\n * content-addressed by URL hash, so repeated builds are stable and deduped —\n * and a file already on disk is not fetched again, which keeps a dev poll\n * from re-downloading every video on every tick.\n */\nexport const materializeAssets = async (\n markdown: string,\n ctx: AssetContext\n): Promise<{ markdown: string; diagnostics: Diagnostic[] }> => {\n const doFetch = ctx.fetchImpl ?? globalThis.fetch;\n const limit = ctx.limit ?? ((task) => task());\n const inFlight = ctx.inFlight ?? new Map<string, Promise<string>>();\n const timeoutMs = ctx.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const diagnostics: Diagnostic[] = [];\n\n // Mask fenced code blocks so an image URL inside a code sample is neither\n // downloaded nor rewritten — the sample must keep showing what the author\n // wrote.\n const fences: string[] = [];\n const masked = markdown.replace(CODE_FENCE_BLOCK, (block) => {\n fences.push(block);\n return `\\u0000blume-fence-${fences.length - 1}\\u0000`;\n });\n\n const urls = new Set<string>();\n for (const pattern of [MD_IMAGE, HTML_VIDEO_SRC]) {\n for (const match of masked.matchAll(pattern)) {\n const url = match.groups?.url;\n if (url && REMOTE.test(url)) {\n urls.add(url);\n }\n }\n }\n\n /** Fetch one asset into the asset dir and return its file name. */\n const download = async (url: string, stem: string): Promise<string> => {\n const urlExt = extFromUrl(url);\n // The name is known up front whenever the path has an extension (every\n // Notion upload does), so a file from an earlier run is reused as is;\n // otherwise the extension came from the last response, so look for it.\n if (urlExt && (await exists(join(ctx.assetsDir, `${stem}${urlExt}`)))) {\n return `${stem}${urlExt}`;\n }\n const completed = urlExt ? null : await completedFor(ctx.assetsDir, stem);\n if (completed) {\n return completed;\n }\n const res = await doFetch(url, { signal: AbortSignal.timeout(timeoutMs) });\n if (!res.ok) {\n throw new Error(`${res.status}`);\n }\n // Writing a watch page or an API response out as `.mp4` gives a player\n // that can't play and a green build, so refuse what is never media.\n const type = mediaType(res);\n if (NON_MEDIA_TYPE.test(type)) {\n throw new Error(`responded with ${type}, not a media file`);\n }\n if (!res.body) {\n throw new Error(\"empty response body\");\n }\n const file = `${stem}${urlExt ?? EXT_BY_MIME.get(type) ?? UNKNOWN_EXT}`;\n const target = join(ctx.assetsDir, file);\n await mkdir(ctx.assetsDir, { recursive: true });\n // Stream the body to disk rather than buffering it: a video is hundreds of\n // megabytes where an image was a hundred kilobytes. Write to a temporary\n // name unique to this attempt and rename on completion, so a download that\n // dies midway never leaves a truncated file the next run would trust as\n // complete. Two pages fetching the same asset at once share one download\n // through `inFlight` (below), so no two attempts ever publish one file.\n const part = `${target}.${randomUUID()}${PART_SUFFIX}`;\n try {\n await writeFile(part, res.body);\n } catch (error) {\n await rm(part, { force: true });\n throw error;\n }\n await rename(part, target);\n return file;\n };\n\n /**\n * Publish one asset, joining a download another page already has in\n * flight. The gate sits inside the shared promise, so a page waiting on\n * another page's download holds no slot of its own. A waiter whose\n * publisher failed makes its own attempt, exactly as it would have without\n * sharing — one transient error must not fail every page naming the asset.\n */\n const publish = async (url: string): Promise<string> => {\n // Hash the query-less URL: CMS asset URLs are pre-signed, so the query\n // changes on every fetch of the same file — hashing it would mint a new\n // file each refresh and re-dirty the content digest. Two real assets\n // sharing scheme+host+path and differing only in query are rare enough to\n // accept colliding.\n const stem = hashText(url.split(\"?\")[0] ?? url);\n const pending = inFlight.get(stem);\n if (pending) {\n try {\n return await pending;\n } catch {\n // The failed download has left the table by now: join whichever\n // waiter retried first, or go it alone.\n return await publish(url);\n }\n }\n const own = (async () => {\n try {\n return await limit(() => download(url, stem));\n } finally {\n inFlight.delete(stem);\n }\n })();\n inFlight.set(stem, own);\n return await own;\n };\n\n const rewrites = new Map<string, string>();\n await Promise.all(\n [...urls].map(async (url) => {\n try {\n const file = await publish(url);\n rewrites.set(url, `${ctx.assetsBaseUrl}/${file}`);\n } catch (error) {\n // SAFETY: everything thrown in this block is an Error — the manual\n // throws in `download`, and fetch/fs failures.\n diagnostics.push({\n code: \"BLUME_ASSET_FETCH_FAILED\",\n message: `Failed to download asset ${url}: ${(error as Error).message}`,\n severity: \"warning\",\n });\n }\n })\n );\n\n const rewritten = masked\n .replaceAll(MD_IMAGE, (match, alt, url) => {\n const local = rewrites.get(url);\n return local ? `![${alt}](${local})` : match;\n })\n .replaceAll(HTML_VIDEO_SRC, (match, open, url, close) => {\n const local = rewrites.get(url);\n return local ? `${open}${local}${close}` : match;\n })\n .replaceAll(FENCE_TOKEN, (token, index) => fences[Number(index)] ?? token);\n\n return { diagnostics, markdown: rewritten };\n};\n",
24
- "import { existsSync, watch as fsWatch, statSync } from \"node:fs\";\nimport type { Dirent } from \"node:fs\";\nimport { readdir, readFile, stat } from \"node:fs/promises\";\n\nimport { basename, isAbsolute, join, relative, resolve } from \"pathe\";\n\nimport { nextFenceState } from \"../code-fences.ts\";\nimport type { FenceState } from \"../code-fences.ts\";\nimport { BlumeError } from \"../diagnostics.ts\";\nimport matter from \"../frontmatter.ts\";\nimport { pageMetaSchema } from \"../schema.ts\";\nimport type { ResolvedI18nConfig, ResolvedVersionsConfig } from \"../schema.ts\";\nimport type { Diagnostic } from \"../types.ts\";\nimport { hashText } from \"./cache.ts\";\nimport type { EntryPlacement } from \"./normalize.ts\";\nimport {\n extractHeadings,\n isStringValue,\n localizedRoute,\n placeEntryRef,\n resolveEntryRoute,\n slugifyPath,\n} from \"./normalize.ts\";\nimport type {\n ContentSource,\n SourceContext,\n SourceEntry,\n SourceLoadResult,\n} from \"./types.ts\";\nimport { BLUME_IGNORE_DIRS, ignoringWatchListener } from \"./watch.ts\";\n\n/** Options for the built-in Obsidian vault source. */\nexport interface ObsidianSourceOptions {\n /**\n * The project's default content type (`content.defaultType`), which a note\n * without a `type` resolves to when {@link typeFrontmatterKeys} are picked.\n */\n defaultType?: string;\n /** Vault folder names to skip at any depth, in addition to dot-folders. */\n exclude?: string[];\n /**\n * Frontmatter keys the project declares site-wide beyond Blume's page meta\n * (`frontmatter.extend`). Any other Obsidian property is dropped when a note\n * is lowered, since the strict meta schema would reject it and fail the\n * build.\n */\n frontmatterKeys?: readonly string[];\n /** The project's i18n config, when locale directories place vault notes. */\n i18n?: ResolvedI18nConfig;\n /** Stable source name; namespaces ids and diagnostics. */\n name: string;\n /** Namespaces the source's routes under `/<prefix>/`; e.g. `vault`. */\n prefix?: string;\n /**\n * Frontmatter keys each content type declares (`content.types.<type>.frontmatter`),\n * keyed by type. A note keeps only the keys of its own type — the meta parse\n * merges only that type's schema, so a key another type declares would still\n * reach the strict page schema and fail.\n */\n typeFrontmatterKeys?: Readonly<Record<string, readonly string[]>>;\n /** Vault directory, absolute or relative to `projectRoot`. */\n vault: string;\n /** The project's versions config, when snapshot directories hold notes. */\n versions?: ResolvedVersionsConfig;\n}\n\nconst MARKDOWN_FILE = /\\.md$/iu;\n/** `%%comment%%` on a single line; multi-line comments are not stripped yet. */\nconst OBSIDIAN_COMMENT = /%%.*?%%/gu;\n/**\n * `[[target]]`, `[[target|alias]]`, `[[target#heading]]`, `![[embed]]`. The\n * target and heading are lazy so the `\\|` Obsidian writes for an alias inside\n * a table cell (a bare `|` would end the cell) is read as the alias separator\n * rather than as a backslash ending the target. A target cannot open with `[`:\n * Obsidian reads `[[[Note]]]` as a literal `[`, the link, and a literal `]`,\n * and so does the match once the first bracket is left out of it.\n */\nconst WIKILINK =\n /(?<embed>!)?\\[\\[(?<target>(?:[^\\][|#\\n][^\\]|#\\n]*?)?)(?:#(?<heading>[^\\]|\\n]+?))?(?:\\\\?\\|(?<alias>[^\\]\\n]+))?\\]\\]/gu;\n\n/** A vault note, read and split into frontmatter and body. */\ninterface ParsedNote {\n absPath: string;\n /** The note body, frontmatter stripped and otherwise untouched. */\n content: string;\n data: SourceEntry[\"data\"];\n placement: EntryPlacement;\n /** Vault-relative path, e.g. `guides/Getting Started.md`. */\n rel: string;\n}\n\n/**\n * The key a note name or heading is indexed and looked up under. macOS writes\n * filenames as NFD and editors type NFC, so both sides normalize before\n * casefolding.\n */\nconst indexKey = (value: string): string =>\n value.normalize(\"NFC\").toLowerCase();\n\n/** A Markdown link or image, reduced to its text by {@link headingKey}. */\nconst INLINE_LINK = /!?\\[(?<text>[^\\]]*)\\]\\([^)]*\\)/gu;\n/**\n * Inline formatting Obsidian drops when it autocompletes a heading link:\n * emphasis and strikethrough marks, code-span backticks, and an `_` that opens\n * or closes a word (one inside `snake_case` is text).\n */\nconst INLINE_MARKS = /[*~`]+|(?<![\\p{L}\\p{N}])_+|_+(?![\\p{L}\\p{N}])/gu;\n\n/**\n * The key a heading is indexed and looked up under: its text with inline\n * Markdown stripped, because Obsidian writes `[[Note#Bold heading]]` for a\n * `## **Bold** heading` — and because that is the text the rendered id is\n * slugged from.\n */\nconst headingKey = (text: string): string =>\n indexKey(\n text.replaceAll(INLINE_LINK, \"$<text>\").replaceAll(INLINE_MARKS, \"\")\n );\n\n/**\n * Obsidian's own default properties (the Properties UI writes the plural\n * spellings; older vaults carry the singular ones). They are not Blume\n * frontmatter, so they are dropped even when a project happens to declare a\n * key of the same name. `aliases` is dropped rather than resolved; alias link\n * targets are not supported yet.\n */\nconst OBSIDIAN_NATIVE_KEYS = new Set([\n \"alias\",\n \"aliases\",\n \"cssclass\",\n \"cssclasses\",\n \"tag\",\n \"tags\",\n]);\n\n/** Every key Blume's page meta schema accepts. */\nconst PAGE_META_KEYS = new Set<string>(pageMetaSchema.keyof().options);\n\n/**\n * A note's route input: its locale- and version-stripped path, slugged. Vault\n * filenames are prose (`Getting Started.md`) and the route mapper does not\n * slug, so this does — through {@link slugifyPath}, which keeps a non-Latin\n * name routable.\n */\nconst entrySlugFor = (navPath: string): string =>\n slugifyPath(navPath.replace(MARKDOWN_FILE, \"\"));\n\n/** One note as the wikilink index knows it: where it routes, and its anchors. */\ninterface IndexedNote {\n /** Anchor id per heading, keyed by {@link headingKey}. */\n anchors: Map<string, string>;\n /** The locales the note publishes in — every locale for a shared `$` note. */\n locales: string[];\n /** The note's version-prefixed, locale-agnostic route, prefix included. */\n logicalRoute: string;\n}\n\n/** The wikilink lookup table. */\ninterface LinkIndex {\n /**\n * Bare note names claimed by more than one file, keyed by {@link indexKey},\n * with the diagnostic text naming the claimants. A name some note owns as\n * its exact vault path is not here — Obsidian resolves a path before a name.\n */\n ambiguous: Map<string, string>;\n i18n?: ResolvedI18nConfig;\n notes: Map<string, IndexedNote>;\n}\n\n/** Dead or ambiguous wikilink targets, accumulated across one load. */\ninterface UnresolvedTargets {\n /** Bare names a wikilink resolved through a collision, with the claimants. */\n ambiguous: string[];\n /** `Note#Heading` targets whose note exists but whose heading does not. */\n anchors: string[];\n /** Targets that matched no note in the vault. */\n notes: string[];\n}\n\n/** A note paired with its own index entry, so a rewrite can address itself. */\ninterface IndexedPair {\n note: ParsedNote;\n self: IndexedNote;\n}\n\n/** The wikilink lookup table, plus each note's own entry in it. */\ninterface NoteIndex {\n index: LinkIndex;\n pairs: IndexedPair[];\n}\n\n/** A fresh accumulator. */\nconst noTargets = (): UnresolvedTargets => ({\n ambiguous: [],\n anchors: [],\n notes: [],\n});\n\n/**\n * The href a link from one note to another takes. A shared `Note.$.md`\n * publishes in every locale, so a link to it stays in the linking note's\n * locale rather than jumping to whichever locale is configured first; a target\n * that does not publish in that locale links to the first locale it does. The\n * Markdown pipeline prefixes every root-absolute link with `deployment.base`\n * at render time, so the base is left off here.\n */\nconst hrefBetween = (\n target: IndexedNote,\n from: IndexedNote,\n i18n: ResolvedI18nConfig | undefined\n): string => {\n const own = from.locales[0] ?? \"\";\n const locale = target.locales.includes(own) ? own : (target.locales[0] ?? \"\");\n return localizedRoute(target.logicalRoute, locale, i18n);\n};\n\n/**\n * Every path suffix a wikilink can address a note by: `docs/guides/Setup.md`\n * yields `docs/guides/setup`, `guides/setup`, and `setup`. Obsidian's default\n * \"shortest path when possible\" setting writes any of them into a link, so all\n * of them must resolve.\n */\nconst suffixKeysOf = (rel: string): string[] => {\n const segments = rel.replace(MARKDOWN_FILE, \"\").split(\"/\");\n return segments.map((_, from) => indexKey(segments.slice(from).join(\"/\")));\n};\n\n/** Every run of backticks — the only delimiter a code span has. */\nconst BACKTICK_RUN = /`+/gu;\n\n/** A run of backticks: where it starts and how many. */\ninterface BacktickRun {\n at: number;\n length: number;\n}\n\n/** Whether the character at `at` sits behind an odd number of backslashes. */\nconst isEscaped = (text: string, at: number): boolean => {\n let backslashes = 0;\n for (let i = at - 1; i >= 0 && text[i] === \"\\\\\"; i -= 1) {\n backslashes += 1;\n }\n return backslashes % 2 === 1;\n};\n\n/**\n * The backtick runs that can delimit a code span. A backslash escapes the one\n * backtick after it (CommonMark 2.4), so an escaped run loses its first tick\n * — and drops out entirely when that was its only one.\n */\nconst backtickRuns = (text: string): BacktickRun[] => {\n const runs: BacktickRun[] = [];\n for (const match of text.matchAll(BACKTICK_RUN)) {\n const escaped = isEscaped(text, match.index);\n const at = escaped ? match.index + 1 : match.index;\n const length = escaped ? match[0].length - 1 : match[0].length;\n if (length > 0) {\n runs.push({ at, length });\n }\n }\n return runs;\n};\n\n/** One piece of a line: literal text the rewrite must not touch, or prose. */\ninterface LineChunk {\n literal: boolean;\n text: string;\n}\n\n/** A span of text that is literal: a code span or an HTML comment. */\ninterface LiteralSpan {\n end: number;\n start: number;\n}\n\n/** The index of the next backtick run of exactly `length`, or -1. */\nconst closerAfter = (\n runs: BacktickRun[],\n from: number,\n length: number\n): number => {\n for (let i = from; i < runs.length; i += 1) {\n if (runs[i]?.length === length) {\n return i;\n }\n }\n return -1;\n};\n\n/**\n * The first code span opening at or after `from`. A run of N backticks opens\n * a span only if a run of exactly N follows — one regex expresses neither the\n * length match nor that condition — and a run with no closer is literal text\n * that the scan steps over.\n */\nconst nextCodeSpan = (\n runs: BacktickRun[],\n from: number\n): LiteralSpan | null => {\n for (let i = 0; i < runs.length; i += 1) {\n const run = runs[i];\n if (run === undefined || run.at < from) {\n continue;\n }\n const close = closerAfter(runs, i + 1, run.length);\n if (close !== -1) {\n return { end: (runs[close]?.at ?? 0) + run.length, start: run.at };\n }\n }\n return null;\n};\n\nconst COMMENT_OPEN = \"<!--\";\nconst COMMENT_CLOSE = \"-->\";\n\n/**\n * The first HTML comment opening at or after `from`. Obsidian hides one in\n * reading view, so a wikilink inside it is never a link the reader sees; an\n * unclosed `<!--` is literal text (CommonMark 6.6), not a comment to the end.\n */\nconst nextComment = (text: string, from: number): LiteralSpan | null => {\n const start = text.indexOf(COMMENT_OPEN, from);\n if (start === -1) {\n return null;\n }\n const close = text.indexOf(COMMENT_CLOSE, start + COMMENT_OPEN.length);\n return close === -1 ? null : { end: close + COMMENT_CLOSE.length, start };\n};\n\n/**\n * Split prose into literal and rewritable chunks. Code spans and HTML comments\n * have equal precedence and the leftmost wins (CommonMark 6.6): a `<!--`\n * inside a code span is code, and a backtick inside a comment is comment. The\n * scan runs over a whole run of prose rather than a line, because either may\n * hold newlines while an unclosed opener is literal text.\n */\nconst splitLiterals = (text: string): LineChunk[] => {\n const runs = backtickRuns(text);\n const chunks: LineChunk[] = [];\n let cursor = 0;\n for (;;) {\n const code = nextCodeSpan(runs, cursor);\n const comment = nextComment(text, cursor);\n const span =\n code === null || (comment !== null && comment.start < code.start)\n ? comment\n : code;\n if (span === null) {\n break;\n }\n chunks.push(\n { literal: false, text: text.slice(cursor, span.start) },\n { literal: true, text: text.slice(span.start, span.end) }\n );\n cursor = span.end;\n }\n chunks.push({ literal: false, text: text.slice(cursor) });\n return chunks;\n};\n\n/** Rewrite one chunk's wikilinks and strip single-line comments. */\nconst transformChunk = (\n chunk: string,\n index: LinkIndex,\n self: IndexedNote,\n unresolved: UnresolvedTargets\n): string =>\n chunk.replaceAll(OBSIDIAN_COMMENT, \"\").replaceAll(WIKILINK, (...args) => {\n // SAFETY: `String.replaceAll` passes the groups object last whenever the\n // pattern has named groups, and WIKILINK has four.\n const groups = args.at(-1) as Record<string, string | undefined>;\n const target = (groups.target ?? \"\").trim();\n const heading = groups.heading?.trim();\n const label = groups.alias?.trim() || heading || target;\n // Rewriting an embed means serving the attachment, which this source\n // does not do yet.\n if (groups.embed) {\n // SAFETY: the replacer's first argument is always the matched substring.\n return args[0] as string;\n }\n // `[[#Heading]]` addresses the note it sits in; an empty target with no\n // heading is not a link at all.\n if (target === \"\") {\n if (heading === undefined) {\n // SAFETY: the replacer's first argument is always the matched substring.\n return args[0] as string;\n }\n const ownHref = hrefBetween(self, self, index.i18n);\n // `#^block-id` names a block, not a heading. Blocks render with no\n // anchor to land on, so the link goes to the page itself rather than\n // warning about a heading that never existed. The caret never reaches\n // the label — `[^id]` would read as a GFM footnote reference.\n if (heading.startsWith(\"^\")) {\n return `[${groups.alias?.trim() || heading.slice(1)}](${ownHref})`;\n }\n const own = self.anchors.get(headingKey(heading));\n if (own === undefined) {\n // Same rule as a missing heading in another note: keep the page link,\n // drop only the anchor.\n unresolved.anchors.push(`#${heading}`);\n return `[${label}](${ownHref})`;\n }\n return `[${label}](${ownHref}#${own})`;\n }\n // `[[Note.md]]` is the path form Obsidian also accepts; the index is keyed\n // without the extension.\n const key = indexKey(target.replace(MARKDOWN_FILE, \"\"));\n const note = index.notes.get(key);\n if (note === undefined) {\n unresolved.notes.push(target);\n return label;\n }\n const clash = index.ambiguous.get(key);\n if (clash !== undefined) {\n unresolved.ambiguous.push(clash);\n }\n const href = hrefBetween(note, self, index.i18n);\n if (heading === undefined) {\n return `[${label}](${href})`;\n }\n // A block reference links to its note without an anchor; block ids are\n // generated noise (`^a1b2c3`), so an unaliased one reads as the note name.\n if (heading.startsWith(\"^\")) {\n return `[${groups.alias?.trim() || target}](${href})`;\n }\n const anchor = note.anchors.get(headingKey(heading));\n if (anchor === undefined) {\n // The note is real, so keep the link and drop only the anchor — landing\n // on the page beats degrading the whole link to plain text.\n unresolved.anchors.push(`${target}#${heading}`);\n return `[${label}](${href})`;\n }\n return `[${label}](${href}#${anchor})`;\n });\n\n/**\n * Rewrite a run of prose, leaving inline code spans (`` `[[x]]` ``) and HTML\n * comments (`<!-- [[x]] -->`) verbatim.\n */\nconst transformProse = (\n text: string,\n index: LinkIndex,\n self: IndexedNote,\n unresolved: UnresolvedTargets\n): string =>\n splitLiterals(text)\n .map((chunk) =>\n chunk.literal\n ? chunk.text\n : transformChunk(chunk.text, index, self, unresolved)\n )\n .join(\"\");\n\n/** An indented code block's marker: four spaces or a tab (CommonMark 4.4). */\nconst INDENTED_CODE = /^(?: {4}|\\t)/u;\n/** A list item opener (CommonMark 5.2), which makes later indentation prose. */\nconst LIST_ITEM = /^ {0,3}(?:[-+*]|\\d{1,9}[.)])(?: |$)/u;\n\n/** How many leading whitespace characters a line carries. */\nconst indentOf = (line: string): number =>\n line.length - line.trimStart().length;\n\n/**\n * Whether a list is open after `line`: an item opens one, and it stays open\n * until a non-blank line that is neither an item nor indented.\n */\nconst listAfter = (line: string, inList: boolean): boolean => {\n if (line.trim() === \"\") {\n return inList;\n }\n if (LIST_ITEM.test(line)) {\n return true;\n }\n return line.startsWith(\" \") || line.startsWith(\"\\t\") ? inList : false;\n};\n\n/**\n * The fence state after `line`. Outside a list, a line indented four or more\n * spaces is never a fence delimiter: it is indented code or a continuation\n * line. Inside a list item the content indent is the item's, so a fence\n * there is written four spaces deep (`1. step` then ` ```js`) and must\n * still open. Once a fence is open only a run at most three spaces deeper\n * than it (CommonMark 4.5) closes it; a deeper run is content.\n */\nconst fenceAfter = (\n line: string,\n fence: FenceState,\n fenceIndent: number,\n inList: boolean\n): FenceState => {\n const canDelimit =\n fence === null\n ? inList || !INDENTED_CODE.test(line)\n : indentOf(line) <= fenceIndent + 3;\n return canDelimit ? nextFenceState(line, fence) : fence;\n};\n\n/**\n * Transform an Obsidian body to Blume-ready Markdown: wikilinks become route\n * links and `%%comments%%` are stripped, while fenced, indented, and inline\n * code pass through so a note documenting the syntax survives. Callouts stay\n * blockquotes.\n */\nconst transformBody = (\n body: string,\n index: LinkIndex,\n self: IndexedNote,\n unresolved: UnresolvedTargets\n): string => {\n let fence: FenceState = null;\n // The indent the open fence was written at: a closing fence may sit up to\n // three spaces deeper (CommonMark 4.5), and a deeper run is content.\n let fenceIndent = 0;\n // An indented code block opens only after a blank line (CommonMark: it\n // cannot interrupt a paragraph) and outside a list (a loose item's indented\n // continuation paragraph is prose), then runs while lines stay indented or\n // blank. A list stays open until a non-indented line that is not an item.\n let afterBlank = true;\n let indentedCode = false;\n let inList = false;\n const out: string[] = [];\n let prose: string[] = [];\n const flush = (): void => {\n if (prose.length > 0) {\n out.push(transformProse(prose.join(\"\\n\"), index, self, unresolved));\n prose = [];\n }\n };\n for (const line of body.split(\"\\n\")) {\n const blank = line.trim() === \"\";\n if (fence === null && indentedCode) {\n if (blank || INDENTED_CODE.test(line)) {\n out.push(line);\n afterBlank = blank;\n continue;\n }\n indentedCode = false;\n }\n inList = listAfter(line, inList);\n if (\n fence === null &&\n afterBlank &&\n !(blank || inList) &&\n INDENTED_CODE.test(line)\n ) {\n flush();\n indentedCode = true;\n out.push(line);\n afterBlank = false;\n continue;\n }\n const next: FenceState = fenceAfter(line, fence, fenceIndent, inList);\n if (fence !== null || next !== null) {\n if (fence === null) {\n fenceIndent = indentOf(line);\n }\n flush();\n fence = next;\n out.push(line);\n afterBlank = blank;\n continue;\n }\n if (blank) {\n // A code span cannot cross a blank line (CommonMark 6.1), so each prose\n // run flushes at one — a stray backtick stays confined to its paragraph\n // instead of pairing with another paragraph's and swallowing the links\n // between them.\n flush();\n out.push(line);\n afterBlank = true;\n continue;\n }\n prose.push(line);\n afterBlank = false;\n }\n flush();\n return out.join(\"\\n\");\n};\n\n/**\n * Fill a note's anchors: the id the renderer emits for each heading, keyed by\n * {@link headingKey}. The ids are whatever {@link extractHeadings} assigns —\n * the same pass fills the page manifest from the staged body, so a\n * `[#custom-id]` pin and the `setup-1` a later collision gets are honored\n * rather than re-slugged. When no heading holds anything the rewrite changes,\n * the raw body's headings are the staged body's; otherwise the body is lowered\n * once more so the headings are scanned exactly as they ship. A link inside a\n * heading is rewritten here before the other notes' anchors are known, so its\n * own anchor is left off; that only moves the manifest id of a heading that\n * itself holds a heading link, which the docs already flag as unaddressable.\n */\nconst fillAnchors = (pair: IndexedPair, index: LinkIndex): void => {\n const raw = extractHeadings(pair.note.content);\n const rewritten = raw.some(\n (heading) =>\n transformProse(heading.text, index, pair.self, noTargets()) !==\n heading.text\n );\n const headings = rewritten\n ? extractHeadings(\n transformBody(pair.note.content, index, pair.self, noTargets())\n )\n : raw;\n for (const heading of headings) {\n const key = headingKey(heading.text);\n // Obsidian points a repeated-heading link at the first match; the manifest\n // scan has already disambiguated the later ones (`setup-1`).\n if (!pair.self.anchors.has(key)) {\n pair.self.anchors.set(key, heading.slug);\n }\n }\n};\n\n/**\n * Obsidian addresses `[[Name]]` by note name, not only by path; index each note\n * under every suffix of its vault-relative path, bare basename included. A key\n * two notes share resolves to the first in vault order — Obsidian disambiguates\n * by the linking note's location, which a rewrite cannot know — except that a\n * note's exact full path always wins for its own key, the way Obsidian resolves\n * a link as a path before a name. Only a bare-name collision is recorded, and\n * only so a link that actually resolves through it can warn; a longer shared\n * suffix is already the author's disambiguation.\n */\nconst buildLinkIndex = (\n notes: ParsedNote[],\n options: Pick<ObsidianSourceOptions, \"i18n\" | \"prefix\" | \"versions\">\n): NoteIndex => {\n const entries = new Map<string, IndexedNote>();\n const indexed = (note: ParsedNote): IndexedNote => {\n const cached = entries.get(note.rel);\n if (cached) {\n return cached;\n }\n // The route the pipeline will assign, from the same resolver\n // `normalizeEntry` uses — keyed by the same ref, slug, and frontmatter\n // `slug` the staged entry carries, so the two cannot disagree.\n const route = resolveEntryRoute(\n { ref: note.rel, slug: entrySlugFor(note.placement.navPath) },\n \".md\",\n isStringValue(note.data.slug) ? note.data.slug : undefined,\n options\n );\n const built: IndexedNote = {\n anchors: new Map(),\n locales: route.locales,\n logicalRoute: route.logicalRoute,\n };\n entries.set(note.rel, built);\n return built;\n };\n const claims = new Map<string, [ParsedNote, ...ParsedNote[]]>();\n for (const note of notes) {\n for (const key of suffixKeysOf(note.rel)) {\n const claimed = claims.get(key);\n if (claimed) {\n claimed.push(note);\n } else {\n claims.set(key, [note]);\n }\n }\n }\n const exactKeys = new Set(\n notes.map((note) => indexKey(note.rel.replace(MARKDOWN_FILE, \"\")))\n );\n const index: LinkIndex = {\n ambiguous: new Map(),\n i18n: options.i18n,\n notes: new Map(),\n };\n for (const [key, claimants] of claims) {\n const [first, ...rest] = claimants;\n if (rest.length > 0 && !key.includes(\"/\") && !exactKeys.has(key)) {\n index.ambiguous.set(\n key,\n `${key} (${claimants.map((note) => note.rel).join(\", \")})`\n );\n }\n index.notes.set(key, indexed(first));\n }\n const pairs = notes.map((note) => {\n const self = indexed(note);\n // Set last, over any name or suffix claim another note holds on this key:\n // an exact vault-relative path is never ambiguous.\n index.notes.set(indexKey(note.rel.replace(MARKDOWN_FILE, \"\")), self);\n return { note, self };\n });\n // Anchors need every href in place (a heading may hold a wikilink), so they\n // fill in after the routes.\n for (const pair of pairs) {\n fillAnchors(pair, index);\n }\n return { index, pairs };\n};\n\n/**\n * An explicit frontmatter title wins, then the filename — how Obsidian titles\n * notes. `index` names a route rather than a note, so an untitled one falls\n * through to Blume's own derivation instead of publishing as \"index\".\n */\nconst titleFor = (\n rel: string,\n frontmatterTitle: SourceEntry[\"data\"][string]\n): string | undefined => {\n if (isStringValue(frontmatterTitle)) {\n return frontmatterTitle;\n }\n const noteName = basename(rel).replace(MARKDOWN_FILE, \"\");\n return noteName.toLowerCase() === \"index\" ? undefined : noteName;\n};\n\n/**\n * The declared keys a note keeps: the site-wide ones plus those of its own\n * content type, resolved the way the meta parse resolves it (`type` falling\n * back to the project default). A non-string `type` fails the strict parse\n * later regardless, so which per-type list it picks never matters.\n */\nconst keptKeysFor = (\n data: SourceEntry[\"data\"],\n options: Pick<\n ObsidianSourceOptions,\n \"defaultType\" | \"frontmatterKeys\" | \"typeFrontmatterKeys\"\n >\n): Set<string> => {\n const entryType = isStringValue(data.type) ? data.type : options.defaultType;\n const typeKeys =\n entryType === undefined\n ? []\n : (options.typeFrontmatterKeys?.[entryType] ?? []);\n return new Set([...(options.frontmatterKeys ?? []), ...typeKeys]);\n};\n\n/**\n * Lower one vault note to a staged Markdown entry, keyed by the same route\n * input the link index used when rewriting links to it. Frontmatter keeps\n * what Blume's page meta accepts plus what the project declares for the note's\n * type; every other Obsidian property (Dataview fields, Templater dates,\n * `publish`, …) is dropped rather than failing the strict schema.\n */\nconst noteToEntry = (\n pair: IndexedPair,\n index: LinkIndex,\n options: Pick<\n ObsidianSourceOptions,\n \"defaultType\" | \"frontmatterKeys\" | \"typeFrontmatterKeys\"\n >,\n unresolved: UnresolvedTargets\n): SourceEntry => {\n const { note } = pair;\n const title = titleFor(note.rel, note.data.title);\n const keep = keptKeysFor(note.data, options);\n const data = Object.fromEntries(\n Object.entries(note.data).filter(\n ([key]) =>\n !OBSIDIAN_NATIVE_KEYS.has(key) &&\n (PAGE_META_KEYS.has(key) || keep.has(key))\n )\n );\n const merged = title === undefined ? data : { ...data, title };\n const text = transformBody(note.content.trim(), index, pair.self, unresolved);\n const raw = matter.stringify(`${text}\\n`, merged);\n return {\n body: { format: \"md\", text },\n data: merged,\n hash: hashText(raw),\n raw,\n ref: note.rel,\n slug: entrySlugFor(note.placement.navPath),\n sourcePath: note.absPath,\n };\n};\n\n/**\n * Read and split one note, or null when it vanished between the walk and the\n * read. Obsidian renames and deletes notes while a dev server watches the\n * vault, and one file disappearing mid-load must not fail the whole reload.\n * Any other read failure still throws.\n */\nconst readNote = async (\n vaultDir: string,\n rel: string,\n options: Pick<ObsidianSourceOptions, \"i18n\" | \"versions\">\n): Promise<ParsedNote | null> => {\n const absPath = join(vaultDir, rel);\n try {\n const { content, data } = matter(await readFile(absPath, \"utf-8\"));\n return {\n absPath,\n content,\n data,\n // Version outermost, then locale, the way `normalizeEntry` reads the\n // ref — the slug is built from what remains, so the pipeline's own\n // re-prefixing does not stack a second `fr/` or `v1.0/` onto the route.\n placement: placeEntryRef(rel, \".md\", options),\n rel,\n };\n } catch (error) {\n // SAFETY: a rejected `readFile` always yields a Node system error, whose\n // `code` is the only field read here.\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n};\n\n/** A directory entry with symlinks resolved to what they point at. */\ninterface VaultEntry {\n directory: boolean;\n file: boolean;\n name: string;\n}\n\n/**\n * A dot-name is never content: Obsidian's own `.obsidian/` and `.trash/`, and\n * the caches plugins keep in dot-folders. The walk and the watcher apply the\n * same rule, so a write into one of them neither publishes nor rescans.\n */\nconst isHidden = (name: string): boolean => name.startsWith(\".\");\n\n/**\n * Classify one directory entry, following a symlink to what it points at the\n * way the filesystem source's glob does — a vault that symlinks a shared\n * folder in must publish it, not report every link into it as a missing\n * note. A link that cannot be followed (dangling, or a loop) is left to the\n * read when it names a note: a missing target is then the same vanished file\n * a mid-load delete produces, and anything else is the real failure it is.\n */\nconst classify = async (dir: string, entry: Dirent): Promise<VaultEntry> => {\n if (!entry.isSymbolicLink()) {\n return {\n directory: entry.isDirectory(),\n file: entry.isFile(),\n name: entry.name,\n };\n }\n try {\n const target = await stat(join(dir, entry.name));\n return {\n directory: target.isDirectory(),\n file: target.isFile(),\n name: entry.name,\n };\n } catch {\n return {\n directory: false,\n file: MARKDOWN_FILE.test(entry.name),\n name: entry.name,\n };\n }\n};\n\n/**\n * Vault order, the way Obsidian's file explorer lists a folder: subfolders\n * first, then notes, each case-insensitively and numeric-aware (`Note 2`\n * before `Note 10`), with a code-point tiebreak so the order is total.\n */\nconst byVaultOrder = (a: VaultEntry, b: VaultEntry): number =>\n Number(b.directory) - Number(a.directory) ||\n a.name.localeCompare(b.name, \"en\", { numeric: true, sensitivity: \"base\" }) ||\n (a.name < b.name ? -1 : 1);\n\n/** Recursively list vault-relative `.md` paths, skipping dot/excluded dirs. */\nconst walkVault = async (\n dir: string,\n root: string,\n exclude: ReadonlySet<string>\n): Promise<string[]> => {\n const found: string[] = [];\n const listed = await readdir(dir, { withFileTypes: true });\n const entries = await Promise.all(\n listed\n .filter((entry) => !(isHidden(entry.name) || exclude.has(entry.name)))\n .map((entry) => classify(dir, entry))\n );\n for (const entry of entries.toSorted(byVaultOrder)) {\n const full = join(dir, entry.name);\n if (entry.directory) {\n // oxlint-disable-next-line no-await-in-loop -- vault trees are shallow; parallelizing complicates ordering for no measurable win.\n found.push(...(await walkVault(full, root, exclude)));\n } else if (entry.file && MARKDOWN_FILE.test(entry.name)) {\n found.push(relative(root, full));\n }\n }\n return found;\n};\n\n/** The first few dead targets, deduplicated, for a diagnostic message. */\nconst sample = (targets: string[]): string =>\n [...new Set(targets)].slice(0, 5).join(\", \");\n\n/** The warnings one load raises: dead notes, then dead headings. */\nconst unresolvedDiagnostics = (\n name: string,\n unresolved: UnresolvedTargets\n): Diagnostic[] => {\n const diagnostics: Diagnostic[] = [];\n if (unresolved.notes.length > 0) {\n diagnostics.push({\n code: \"BLUME_WIKILINK_UNRESOLVED\",\n message: `Source \"${name}\" found ${unresolved.notes.length} wikilink(s) to a missing note (${sample(unresolved.notes)}); rendered as plain text.`,\n severity: \"warning\",\n suggestion:\n \"Create the missing note, or fix the link target in Obsidian — note names are matched case-insensitively across the whole vault.\",\n });\n }\n if (unresolved.ambiguous.length > 0) {\n const names = new Set(unresolved.ambiguous).size;\n diagnostics.push({\n code: \"BLUME_WIKILINK_AMBIGUOUS\",\n message: `Source \"${name}\" found ${unresolved.ambiguous.length} wikilink(s) to ${names} note name(s) claimed by more than one file (${sample(unresolved.ambiguous)}); each resolves to the first note in vault order.`,\n severity: \"warning\",\n suggestion:\n \"Rename one of the notes, or link to the full vault-relative path (`[[folder/Note]]`) so the target is unambiguous.\",\n });\n }\n if (unresolved.anchors.length > 0) {\n diagnostics.push({\n code: \"BLUME_WIKILINK_UNRESOLVED\",\n message: `Source \"${name}\" found ${unresolved.anchors.length} wikilink(s) to a missing heading (${sample(unresolved.anchors)}); linked to the page without an anchor.`,\n severity: \"warning\",\n suggestion:\n \"Fix the heading text in the link, or add the heading to the target note.\",\n });\n }\n return diagnostics;\n};\n\n/**\n * The built-in Obsidian vault source: read a vault directly — no export step,\n * no generated files in the user's repo — lowering Obsidian's dialect to\n * Blume-ready Markdown at load time.\n *\n * Staged, since the body is rewritten before Blume sees it; `sourcePath` still\n * points at the note, so diagnostics and relative image checks name the real\n * file. A wikilink Blume cannot resolve degrades rather than failing the build.\n */\nexport const obsidianSource = (\n options: ObsidianSourceOptions,\n ctx: SourceContext\n): ContentSource => {\n const vaultDir = resolve(ctx.projectRoot, options.vault);\n // The never-content directories every filesystem scan skips, so a vault\n // rooted at the project (`vault: \".\"`) doesn't publish dependency READMEs\n // or build output — and so the scan and the watcher agree on what is\n // content.\n const exclude = new Set([...BLUME_IGNORE_DIRS, ...(options.exclude ?? [])]);\n\n const load = async (): Promise<SourceLoadResult> => {\n const files = await walkVault(vaultDir, vaultDir, exclude);\n const read = await Promise.all(\n files.map((rel) => readNote(vaultDir, rel, options))\n );\n const notes = read.filter((note): note is ParsedNote => note !== null);\n // Resolving `[[Note#H]]` needs the target's route and headings, so every\n // note is parsed and indexed before any body is rewritten.\n const { index, pairs } = buildLinkIndex(notes, options);\n const unresolved = noTargets();\n const entries = pairs.map((pair) =>\n noteToEntry(pair, index, options, unresolved)\n );\n return {\n diagnostics: unresolvedDiagnostics(options.name, unresolved),\n entries,\n };\n };\n\n // The note as written, for the SPI's lazy read. The lowered body is what\n // `load` stages, and the pipeline reads that copy; this serves the vault\n // file itself, the way the filesystem source does, without pinning a second\n // copy of every note for the life of a dev server.\n const read = async (ref: string): Promise<string> => {\n const absPath = resolve(vaultDir, ref);\n // Lexical containment only — `..` and sibling paths are refused, but a\n // symlink inside the vault is followed wherever it points, the way\n // `walkVault` and the filesystem source follow theirs. Vault symlinks are\n // the author's own and are trusted; the Obsidian source docs say so.\n const rel = relative(vaultDir, absPath);\n if (rel.startsWith(\"..\") || isAbsolute(rel)) {\n throw new BlumeError({\n code: \"BLUME_SOURCE_MISCONFIGURED\",\n file: absPath,\n message: `Source \"${options.name}\" cannot read \"${ref}\": it resolves outside the vault.`,\n severity: \"error\",\n suggestion: \"Reference notes by their vault-relative path.\",\n });\n }\n return await readFile(absPath, \"utf-8\");\n };\n\n const validate = (): void => {\n // `existsSync` alone also accepts a regular file, which `validate` would\n // wave through and `load` would then fail on with a raw ENOTDIR.\n const stats = statSync(vaultDir, { throwIfNoEntry: false });\n if (stats?.isDirectory()) {\n return;\n }\n const problem = stats ? \"is not a directory\" : \"does not exist\";\n throw new BlumeError({\n code: \"BLUME_SOURCE_MISCONFIGURED\",\n file: vaultDir,\n message: `Source \"${options.name}\" points at \"${options.vault}\", which ${problem}.`,\n severity: \"error\",\n suggestion:\n \"Set `vault` to your Obsidian vault directory, relative to the project root.\",\n });\n };\n\n // Obsidian rewrites `.obsidian/workspace.json` as you move a pane and moves\n // a deleted note into `.trash/`; plugins keep caches in dot-folders of their\n // own. The walk publishes none of them, so a write there must not trigger a\n // rescan either. See {@link ignoringWatchListener}.\n const watch = (onChange: () => void): (() => void) => {\n if (!existsSync(vaultDir)) {\n return () => {\n // Nothing to dispose when the vault doesn't exist yet.\n };\n }\n const watcher = fsWatch(\n vaultDir,\n { recursive: true },\n ignoringWatchListener(onChange, exclude, isHidden)\n );\n return () => watcher.close();\n };\n\n return {\n // The vault is a real on-disk tree, so exposing it lets git last-modified\n // bound its log pathspec to the notes. Folder-meta discovery still skips\n // it — that scan is guarded on `staged`.\n contentRoot: vaultDir,\n load,\n name: options.name,\n prefix: options.prefix,\n read,\n staged: true,\n validate,\n watch,\n };\n};\n",
25
- "/**\n * Lexical (Payload's rich text editor) → Markdown. Covers the nodes Payload's\n * default features emit — paragraphs, headings, lists (bullet, numbered,\n * check), quotes, links, uploads, horizontal rules — and hands `block` /\n * `inlineBlock` nodes to a serializer keyed by their `blockType`, or notes\n * them in a comment.\n */\nimport type { JsonObject } from \"./json.ts\";\nimport { asNumber, asObject, asString, getPath, objectsIn } from \"./json.ts\";\nimport type { InlineMarks } from \"./lower.ts\";\nimport {\n absoluteUrl,\n blockquote,\n headingPrefix,\n image,\n indent,\n listItem,\n markdownDocument,\n renderInline,\n renderLink,\n unsupported,\n writesMdx,\n} from \"./lower.ts\";\n\nexport interface LexicalOptions {\n /** The CMS origin a relative upload URL (`/media/x.png`) resolves against. */\n baseUrl?: string;\n /** Serializers for `block`/`inlineBlock` nodes, keyed by `fields.blockType`. */\n serializers?: Record<string, (fields: JsonObject) => string>;\n}\n\n// Lexical's text `format` bitmask.\nconst IS_BOLD = 1;\nconst IS_ITALIC = 2;\nconst IS_STRIKETHROUGH = 4;\nconst IS_CODE = 16;\n\n/** Whether a power-of-two flag is set in the format bitmask. */\nconst hasFlag = (format: number, flag: number): boolean =>\n Math.floor(format / flag) % 2 === 1;\n\nconst marksOf = (node: JsonObject): InlineMarks => {\n const format = asNumber(node.format) ?? 0;\n return {\n bold: hasFlag(format, IS_BOLD),\n code: hasFlag(format, IS_CODE),\n italic: hasFlag(format, IS_ITALIC),\n strike: hasFlag(format, IS_STRIKETHROUGH),\n };\n};\n\nconst children = (node: JsonObject): JsonObject[] => objectsIn(node.children);\n\nconst typeOf = (node: JsonObject): string => asString(node.type) ?? \"\";\n\nconst customBlock = (node: JsonObject, options: LexicalOptions): string => {\n const fields = asObject(node.fields);\n const blockType = fields ? asString(fields.blockType) : undefined;\n const serializer = blockType ? options.serializers?.[blockType] : undefined;\n if (fields && serializer) {\n return serializer(fields);\n }\n return unsupported(\n `Lexical block${blockType ? `: ${blockType}` : \"\"}`,\n writesMdx(options.serializers)\n );\n};\n\nconst renderInlines = (nodes: JsonObject[], options: LexicalOptions): string =>\n nodes\n // oxlint-disable-next-line no-use-before-define -- mutual recursion: a link's label is itself inline content\n .map((node) => renderInlineNode(node, options))\n .join(\"\");\n\nconst renderInlineNode = (\n node: JsonObject,\n options: LexicalOptions\n): string => {\n switch (typeOf(node)) {\n case \"text\": {\n return renderInline(asString(node.text) ?? \"\", marksOf(node));\n }\n case \"linebreak\": {\n return \"\\n\";\n }\n case \"tab\": {\n return \"\\t\";\n }\n case \"link\":\n case \"autolink\": {\n // `fields.url` on Payload 3; `url` on older Lexical payloads. An\n // internal link (`linkType: \"internal\"`) carries a document, not a\n // URL, so its label stays.\n return renderLink(\n renderInlines(children(node), options),\n asString(getPath(node, \"fields.url\")) ?? asString(node.url)\n );\n }\n case \"inlineBlock\": {\n return customBlock(node, options);\n }\n default: {\n return renderInlines(children(node), options);\n }\n }\n};\n\nconst renderUpload = (node: JsonObject, options: LexicalOptions): string => {\n const value = asObject(node.value);\n const url = value ? asString(value.url) : undefined;\n if (!(value && url)) {\n return unsupported(\n \"Lexical upload (fetch with depth 1 to populate it)\",\n writesMdx(options.serializers)\n );\n }\n const alt = asString(value.alt) ?? asString(value.filename) ?? \"\";\n return image(alt, absoluteUrl(url, options.baseUrl));\n};\n\nconst renderList = (node: JsonObject, options: LexicalOptions): string => {\n const listType = asString(node.listType) ?? \"bullet\";\n const start = asNumber(node.start) ?? 1;\n const items: string[] = [];\n let lastMarker = \"-\";\n let index = 0;\n for (const item of children(node)) {\n const kids = children(item);\n const nested = kids.filter((kid) => typeOf(kid) === \"list\");\n const inline = kids.filter((kid) => typeOf(kid) !== \"list\");\n const sub = nested.map((list) => renderList(list, options)).join(\"\\n\");\n if (inline.length === 0 && nested.length > 0) {\n // Lexical nests a sub-list as its own item holding only the list; it\n // hangs under the item before it, or stands alone when there is none.\n items.push(items.length > 0 ? indent(sub, lastMarker.length + 1) : sub);\n continue;\n }\n lastMarker = listType === \"number\" ? `${start + index}.` : \"-\";\n let check = \"\";\n if (listType === \"check\") {\n check = item.checked === true ? \"[x] \" : \"[ ] \";\n }\n const line = `${check}${renderInlines(inline, options)}`;\n items.push(listItem(lastMarker, sub ? `${line}\\n${sub}` : line));\n index += 1;\n }\n return items.join(\"\\n\");\n};\n\nconst renderBlock = (node: JsonObject, options: LexicalOptions): string => {\n switch (typeOf(node)) {\n case \"paragraph\": {\n return renderInlines(children(node), options);\n }\n case \"heading\": {\n const level = Number((asString(node.tag) ?? \"h1\").slice(1));\n return `${headingPrefix(level)}${renderInlines(children(node), options)}`;\n }\n case \"quote\": {\n return blockquote(renderInlines(children(node), options));\n }\n case \"list\": {\n return renderList(node, options);\n }\n case \"horizontalrule\": {\n return \"---\";\n }\n case \"upload\": {\n return renderUpload(node, options);\n }\n case \"block\": {\n return customBlock(node, options);\n }\n default: {\n return unsupported(\n `Lexical node: ${typeOf(node)}`,\n writesMdx(options.serializers)\n );\n }\n }\n};\n\n/**\n * Serialize a Lexical editor state (`{ root: { children } }`, or the root\n * node itself) to Markdown.\n */\nexport const lexicalToMarkdown = (\n state: JsonObject,\n options: LexicalOptions = {}\n): string => {\n const root = asObject(state.root) ?? state;\n return markdownDocument(\n children(root).map((node) => renderBlock(node, options))\n );\n};\n",
26
- "import type { JsonObject } from \"./json.ts\";\nimport { asObject, asString, isJsonObject, objectsIn } from \"./json.ts\";\nimport { lexicalToMarkdown } from \"./lexical.ts\";\nimport { writesMdx } from \"./lower.ts\";\nimport type { RemoteFieldMap, RestClient } from \"./remote.ts\";\nimport {\n documentEntry,\n fetchJson,\n queryString,\n remoteSource,\n} from \"./remote.ts\";\nimport type { ContentSource, SourceContext, SourceEntry } from \"./types.ts\";\n\nexport interface PayloadSourceOptions {\n name: string;\n prefix?: string;\n /** The Payload app's origin (`https://cms.acme.dev`); its REST API is at `/api`. */\n url: string;\n /** The collection slug whose documents become pages. */\n collection: string;\n /**\n * The auth-enabled collection the API key belongs to; default `users`. It\n * names the scheme in the `Authorization` header (`users API-Key <key>`).\n */\n authCollection?: string;\n /** Relationship depth to populate; default `1`, enough for upload URLs. */\n depth?: number;\n /**\n * Field paths mapping a document onto Blume meta + body. Defaults:\n * `title`, `description`, `slug`, `content`, `updatedAt`.\n */\n fields?: RemoteFieldMap;\n /** Extra query parameters for the collection request (`where[...]`, `sort`). */\n params?: Record<string, string>;\n /** Serializers for `block`/`inlineBlock` nodes, keyed by `blockType`. */\n serializers?: Record<string, (fields: JsonObject) => string>;\n /** API key; defaults to `PAYLOAD_API_KEY`. */\n token?: string;\n /** Opt-in dev polling interval (seconds); omit to freeze for the session. */\n pollInterval?: number;\n /** Injected for tests; defaults to the global `fetch`. */\n fetchImpl?: typeof fetch;\n}\n\nconst PAGE_SIZE = 100;\n\nconst DEFAULT_FIELDS: Required<RemoteFieldMap> = {\n body: \"content\",\n description: \"description\",\n lastModified: \"updatedAt\",\n slug: \"slug\",\n title: \"title\",\n};\n\n/**\n * Payload content source. Pages through a collection's REST endpoint, maps\n * each document's fields to frontmatter, and lowers its Lexical body to\n * Markdown. Published documents only, unless `--preview` asks for drafts.\n */\nexport const payloadSource = (\n options: PayloadSourceOptions,\n ctx?: SourceContext\n): ContentSource => {\n const fields = { ...DEFAULT_FIELDS, ...options.fields };\n const origin = options.url.replace(/\\/+$/u, \"\");\n\n const lower = (body: JsonObject): string =>\n lexicalToMarkdown(body, {\n baseUrl: origin,\n serializers: options.serializers,\n });\n\n const fetchEntries = async (): Promise<SourceEntry[]> => {\n const preview = ctx?.preview ?? false;\n const token = options.token ?? process.env.PAYLOAD_API_KEY;\n const client: RestClient = {\n fetchImpl: options.fetchImpl,\n headers: token\n ? {\n authorization: `${options.authCollection ?? \"users\"} API-Key ${token}`,\n }\n : {},\n };\n const base = `${origin}/api/${options.collection}`;\n const entries: SourceEntry[] = [];\n let page = 1;\n let more = true;\n while (more) {\n // The user's params go first so the paging controls always win — a\n // `params` key that shadowed them would refetch the same page forever.\n const query = queryString({\n ...options.params,\n depth: String(options.depth ?? 1),\n draft: preview ? \"true\" : undefined,\n limit: String(PAGE_SIZE),\n page: String(page),\n });\n // oxlint-disable-next-line no-await-in-loop -- pages are sequential: each response says whether another exists.\n const result = asObject(await fetchJson(`${base}?${query}`, client));\n if (!result) {\n throw new Error(\"Payload returned a non-object response\");\n }\n for (const doc of objectsIn(result.docs)) {\n const draft = asString(doc._status) === \"draft\";\n if (draft && !preview) {\n continue;\n }\n const id = asString(doc.id) ?? String(doc.id ?? \"\");\n entries.push(\n documentEntry(\n doc,\n fields,\n id,\n (body) => (isJsonObject(body) ? lower(body) : \"\"),\n draft,\n writesMdx(options.serializers)\n )\n );\n }\n more = result.hasNextPage === true;\n page += 1;\n }\n return entries;\n };\n\n return remoteSource(\n {\n fetchEntries,\n name: options.name,\n pollInterval: options.pollInterval,\n prefix: options.prefix,\n },\n ctx\n );\n};\n",
27
- "import { join } from \"pathe\";\n\nimport { BlumeError } from \"../diagnostics.ts\";\nimport matter from \"../frontmatter.ts\";\nimport { nodeRequire } from \"../node-require.ts\";\nimport {\n hashText,\n loadWithCache,\n pollingWatch,\n snapshotCache,\n} from \"./cache.ts\";\nimport type { JsonObject } from \"./json.ts\";\nimport { asString, getPath } from \"./json.ts\";\nimport { writesMdx } from \"./lower.ts\";\nimport { slugify, slugifyPath } from \"./normalize.ts\";\nimport { portableTextToMarkdown } from \"./portable-text.ts\";\nimport type { PortableTextBlock } from \"./portable-text.ts\";\nimport type {\n ContentSource,\n SourceContext,\n SourceEntry,\n SourceLoadResult,\n} from \"./types.ts\";\n\n/** The slice of `@sanity/client` this adapter relies on (so it's mockable). */\nexport interface SanityClientLike {\n fetch: <T = unknown>(query: string) => Promise<T>;\n}\n\n/** Field paths mapping a Sanity document onto Blume meta + body. */\nexport interface SanityFieldMap {\n /** Frontmatter title; default `title`. */\n title?: string;\n /** Frontmatter description; default `description`. */\n description?: string;\n /** Route slug (dot path); default `slug.current`. */\n slug?: string;\n /** Portable Text body field; default `body`. */\n body?: string;\n /** Last-modified ISO date; default `_updatedAt`. */\n lastModified?: string;\n}\n\nexport interface SanitySourceOptions {\n name: string;\n prefix?: string;\n projectId: string;\n dataset: string;\n /** Sanity API version (a date); default `2024-01-01`. */\n apiVersion?: string;\n /** GROQ query selecting the documents to import. */\n query: string;\n fields?: SanityFieldMap;\n /** Custom Portable Text block serializers, keyed by `_type`. */\n serializers?: Record<string, (block: PortableTextBlock) => string>;\n /** Read token for private datasets; defaults to `SANITY_TOKEN`. */\n token?: string;\n /** Opt-in dev polling interval (seconds); omit to freeze for the session. */\n pollInterval?: number;\n /** Injected for tests; otherwise built from `@sanity/client`. */\n client?: SanityClientLike;\n}\n\nconst IMAGE_REF = /^image-(?<id>[a-f0-9]+)-(?<dims>\\d+x\\d+)-(?<ext>\\w+)$/u;\n\n/** A document as the GROQ query returns it. */\ntype SanityDocument = JsonObject;\n\n/** The frontmatter fields this adapter maps from a document. */\ninterface SanityFrontmatter {\n description?: string;\n title?: string;\n}\n\n/** Build a Sanity CDN URL from an image asset `_ref`. */\nconst imageUrlFromRef = (\n ref: string,\n projectId: string,\n dataset: string\n): string | null => {\n const match = ref.match(IMAGE_REF);\n if (!match?.groups) {\n return null;\n }\n const { id, dims, ext } = match.groups;\n return `https://cdn.sanity.io/images/${projectId}/${dataset}/${id}-${dims}.${ext}`;\n};\n\n/** The `createClient` config slice this adapter passes. */\ninterface SanityClientConfig {\n apiVersion: string;\n dataset: string;\n perspective: \"previewDrafts\" | \"published\";\n projectId: string;\n token: string | undefined;\n useCdn: boolean;\n}\n\nconst resolveClient = (\n options: SanitySourceOptions,\n preview: boolean\n): SanityClientLike => {\n if (options.client) {\n return options.client;\n }\n let createClient: (config: SanityClientConfig) => SanityClientLike;\n try {\n // `require`, not `import()`: an ejected app scans in `astro:build:done`\n // (see `core/node-require.ts`).\n // SAFETY: `@sanity/client` is an optional dependency; its `createClient`\n // accepts a superset of this config slice and returns a client exposing\n // the `fetch` method this adapter uses.\n ({ createClient } = nodeRequire(\"@sanity/client\") as {\n createClient: (config: SanityClientConfig) => SanityClientLike;\n });\n } catch {\n throw new BlumeError({\n code: \"BLUME_SOURCE_SDK_MISSING\",\n message: `Source \"${options.name}\" needs \"@sanity/client\". Install it (e.g. \\`npm install @sanity/client\\`).`,\n severity: \"error\",\n });\n }\n return createClient({\n apiVersion: options.apiVersion ?? \"2024-01-01\",\n dataset: options.dataset,\n // Preview reads draft documents through the API; published builds use the CDN.\n perspective: preview ? \"previewDrafts\" : \"published\",\n projectId: options.projectId,\n token: options.token ?? process.env.SANITY_TOKEN,\n useCdn: !preview,\n });\n};\n\n/**\n * Sanity content source. Runs a GROQ query, maps each document's fields to Blume\n * frontmatter and its Portable Text body to Markdown, and stages the result.\n */\nexport const sanitySource = (\n options: SanitySourceOptions,\n ctx?: SourceContext\n): ContentSource => {\n const fields = options.fields ?? {};\n // When constructed directly (custom-source SPI) without a context, cache under\n // a name-derived dir relative to the project; the built-in type passes a ctx.\n const cache = snapshotCache(\n ctx?.cacheDir ?? join(\".blume\", \"cache\", options.name)\n );\n let snapshot = new Map<string, SourceEntry>();\n\n const toEntry = (doc: SanityDocument): SourceEntry => {\n const slugValue =\n asString(getPath(doc, fields.slug ?? \"slug.current\")) ??\n asString(doc._id) ??\n \"untitled\";\n // Fall back to the unique `_id` when a slug (e.g. a non-ASCII `slug.current`)\n // slugifies to empty, so distinct documents don't all collapse to the same\n // `untitled.md` ref and silently overwrite each other. Path-aware: a\n // `guides/setup` slug keeps its `/` (per-segment slugging) instead of\n // mashing into `guidessetup`.\n const slug =\n slugifyPath(slugValue) || slugify(asString(doc._id) ?? \"\") || \"untitled\";\n\n const data: SanityFrontmatter = {};\n const title = asString(getPath(doc, fields.title ?? \"title\"));\n const description = asString(\n getPath(doc, fields.description ?? \"description\")\n );\n if (title) {\n data.title = title;\n }\n if (description) {\n data.description = description;\n }\n\n // SAFETY: the configured body field holds Portable Text blocks; a value of\n // any other shape fails the `Array.isArray` check below and yields an\n // empty body, and the serializer tolerates malformed blocks.\n const blocks = (getPath(doc, fields.body ?? \"body\") ??\n []) as PortableTextBlock[];\n const markdown = Array.isArray(blocks)\n ? portableTextToMarkdown(blocks, {\n imageUrl: (block) => {\n // SAFETY: `asset` on an image block is Sanity's asset reference\n // object; any other shape yields no `_ref` and the image is\n // skipped.\n const ref = (block.asset as { _ref?: string } | undefined)?._ref;\n return ref\n ? imageUrlFromRef(ref, options.projectId, options.dataset)\n : null;\n },\n serializers: options.serializers,\n })\n : \"\";\n\n // Serializer output is MDX (components, directives), so a source with\n // serializers writes its entries as `.mdx`.\n const format = writesMdx(options.serializers) ? \"mdx\" : \"md\";\n const raw = matter.stringify(markdown, data);\n return {\n body: { format, text: markdown },\n // Spread into a fresh literal: `SourceEntry.data` wants an\n // index-signature type, which the named interface lacks.\n data: { ...data },\n hash: hashText(raw),\n lastModified: asString(getPath(doc, fields.lastModified ?? \"_updatedAt\")),\n raw,\n ref: `${slug}.${format}`,\n };\n };\n\n const load = async (\n refresh = ctx?.refresh ?? true\n ): Promise<SourceLoadResult> => {\n const result = await loadWithCache(\n options.name,\n cache,\n async () => {\n const client = resolveClient(options, ctx?.preview ?? false);\n const docs = await client.fetch<SanityDocument[]>(options.query);\n return docs.map(toEntry);\n },\n refresh\n );\n snapshot = new Map(result.entries.map((entry) => [entry.ref, entry]));\n return result;\n };\n\n const read = async (ref: string): Promise<string> => {\n const cached = snapshot.get(ref);\n if (cached) {\n return cached.raw ?? cached.body.text;\n }\n const all = await cache.read();\n return all.find((e) => e.ref === ref)?.raw ?? \"\";\n };\n\n return {\n load,\n name: options.name,\n prefix: options.prefix,\n read,\n staged: true,\n watch: options.pollInterval\n ? pollingWatch(\n () => load(true),\n options.pollInterval,\n () => load()\n )\n : undefined,\n };\n};\n",
28
- "/**\n * A minimal Portable Text → Markdown serializer. Covers the standard block,\n * list, and mark types Sanity emits; custom block/mark types fall through to a\n * user-supplied serializer or are skipped with a noted comment. Output is\n * Markdown text that flows through Blume's normal pipeline.\n */\nimport { escapeMarkdownText, image, unsupported, writesMdx } from \"./lower.ts\";\n\n/**\n * A field value on a Portable Text node: the arbitrary JSON the CMS query\n * returned (custom blocks carry whatever fields the studio schema defines).\n * Spans and mark defs appear as members so the block's typed fields conform\n * to its index signature.\n */\nexport type PortableTextValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | PortableTextSpan\n | PortableTextMarkDef\n | PortableTextValue[]\n | { [key: string]: PortableTextValue };\n\n/** A single Portable Text node (block, image, or a custom type). */\nexport interface PortableTextBlock {\n _type: string;\n _key?: string;\n style?: string;\n listItem?: string;\n level?: number;\n children?: PortableTextSpan[];\n markDefs?: PortableTextMarkDef[];\n [key: string]: PortableTextValue;\n}\n\ninterface PortableTextSpan {\n _type: string;\n text?: string;\n marks?: string[];\n}\n\ninterface PortableTextMarkDef {\n _key: string;\n _type: string;\n href?: string;\n}\n\nexport interface PortableTextOptions {\n /** Resolve an image block to a URL (the adapter knows project/dataset). */\n imageUrl?: (block: PortableTextBlock) => string | null;\n /**\n * Custom block-type serializers, keyed by `_type`; return Markdown or MDX.\n * Setting any writes the source's entries as MDX.\n */\n serializers?: Record<string, (block: PortableTextBlock) => string>;\n}\n\nconst HEADING_STYLES = new Map([\n [\"h1\", \"# \"],\n [\"h2\", \"## \"],\n [\"h3\", \"### \"],\n [\"h4\", \"#### \"],\n [\"h5\", \"##### \"],\n [\"h6\", \"###### \"],\n]);\n\n/** Wrap a span's text in Markdown for its marks (decorators + link defs). */\nconst renderSpan = (\n span: PortableTextSpan,\n defs: Map<string, PortableTextMarkDef>\n): string => {\n // Code spans stay verbatim: their text is literal inside the backticks,\n // and backslash escapes would render as backslashes.\n const isCode = span.marks?.includes(\"code\") ?? false;\n let text = isCode ? (span.text ?? \"\") : escapeMarkdownText(span.text ?? \"\");\n if (!span.marks || span.marks.length === 0) {\n return text;\n }\n // Decorators wrap inline; a link def wraps last so its label keeps emphasis.\n let link: PortableTextMarkDef | undefined;\n for (const mark of span.marks) {\n switch (mark) {\n case \"strong\": {\n text = `**${text}**`;\n break;\n }\n case \"em\": {\n text = `*${text}*`;\n break;\n }\n case \"code\": {\n text = `\\`${text}\\``;\n break;\n }\n case \"strike-through\": {\n text = `~~${text}~~`;\n break;\n }\n default: {\n const def = defs.get(mark);\n if (def?._type === \"link\") {\n link = def;\n }\n }\n }\n }\n return link?.href ? `[${text}](${link.href})` : text;\n};\n\n/** Render the inline children of a block to a single Markdown string. */\nconst renderChildren = (block: PortableTextBlock): string => {\n const defs = new Map(\n (block.markDefs ?? []).map((def) => [def._key, def] as const)\n );\n return (block.children ?? []).map((span) => renderSpan(span, defs)).join(\"\");\n};\n\n/** Whether an image block's `alt` field is usable alt text (CMS JSON may hold anything). */\nconst isAltText = (value: PortableTextValue): value is string =>\n typeof value === \"string\";\n\nconst renderBlock = (\n block: PortableTextBlock,\n options: PortableTextOptions\n): string => {\n const custom = options.serializers?.[block._type];\n if (custom) {\n return custom(block);\n }\n if (block._type === \"image\") {\n const url = options.imageUrl?.(block);\n const alt = isAltText(block.alt) ? block.alt : \"\";\n return url ? image(alt, url) : \"\";\n }\n if (block._type !== \"block\") {\n return unsupported(\n `Portable Text block: ${block._type}`,\n writesMdx(options.serializers)\n );\n }\n\n const inline = renderChildren(block);\n if (block.listItem) {\n const indent = \" \".repeat(Math.max(0, (block.level ?? 1) - 1));\n const marker = block.listItem === \"number\" ? \"1.\" : \"-\";\n return `${indent}${marker} ${inline}`;\n }\n if (block.style === \"blockquote\") {\n return `> ${inline}`;\n }\n return `${HEADING_STYLES.get(block.style ?? \"normal\") ?? \"\"}${inline}`;\n};\n\n/** Serialize a Portable Text array into a Markdown string. */\nexport const portableTextToMarkdown = (\n blocks: PortableTextBlock[],\n options: PortableTextOptions = {}\n): string => {\n const lines = blocks.map((block) => renderBlock(block, options));\n // List items are single-newline separated; everything else gets a blank line.\n const out: string[] = [];\n for (let i = 0; i < lines.length; i += 1) {\n const line = lines[i] ?? \"\";\n const prevList = Boolean(blocks[i - 1]?.listItem);\n const thisList = Boolean(blocks[i]?.listItem);\n if (i > 0) {\n out.push(prevList && thisList ? \"\\n\" : \"\\n\\n\");\n }\n out.push(line);\n }\n return `${out.join(\"\")}\\n`;\n};\n",
29
- "/**\n * Strapi's Rich text (Blocks) field → Markdown. Covers every block the\n * editor emits: paragraphs, headings, lists (nested), quotes, code, images,\n * and links with the text modifiers.\n */\nimport type { JsonObject, JsonValue } from \"./json.ts\";\nimport { asNumber, asObject, asString, objectsIn } from \"./json.ts\";\nimport {\n absoluteUrl,\n blockquote,\n codeFence,\n headingPrefix,\n image,\n listItem,\n markdownDocument,\n renderInline,\n renderLink,\n unsupported,\n} from \"./lower.ts\";\n\nexport interface StrapiBlocksOptions {\n /** The Strapi origin a relative upload URL (`/uploads/x.png`) resolves against. */\n baseUrl?: string;\n}\n\nconst children = (node: JsonObject): JsonObject[] => objectsIn(node.children);\n\nconst typeOf = (node: JsonObject): string => asString(node.type) ?? \"\";\n\nconst renderInlines = (nodes: JsonObject[]): string =>\n nodes\n // oxlint-disable-next-line no-use-before-define -- mutual recursion: a link's label is itself inline content\n .map((node) => renderInlineNode(node))\n .join(\"\");\n\nconst renderInlineNode = (node: JsonObject): string => {\n switch (typeOf(node)) {\n case \"text\": {\n return renderInline(asString(node.text) ?? \"\", {\n bold: node.bold === true,\n code: node.code === true,\n italic: node.italic === true,\n strike: node.strikethrough === true,\n });\n }\n case \"link\": {\n return renderLink(renderInlines(children(node)), asString(node.url));\n }\n default: {\n return renderInlines(children(node));\n }\n }\n};\n\nconst renderList = (node: JsonObject): string => {\n const ordered = asString(node.format) === \"ordered\";\n return children(node)\n .map((item, index) => {\n const kids = children(item);\n const line = renderInlines(kids.filter((kid) => typeOf(kid) !== \"list\"));\n const sub = kids\n .filter((kid) => typeOf(kid) === \"list\")\n .map((list) => renderList(list))\n .join(\"\\n\");\n const body = sub ? `${line}\\n${sub}` : line;\n return listItem(ordered ? `${index + 1}.` : \"-\", body);\n })\n .join(\"\\n\");\n};\n\nconst renderImage = (\n node: JsonObject,\n options: StrapiBlocksOptions\n): string => {\n const file = asObject(node.image);\n const url = file ? asString(file.url) : undefined;\n if (!(file && url)) {\n return \"\";\n }\n return image(\n asString(file.alternativeText) ?? asString(file.name) ?? \"\",\n absoluteUrl(url, options.baseUrl)\n );\n};\n\nconst renderBlock = (\n node: JsonObject,\n options: StrapiBlocksOptions\n): string => {\n switch (typeOf(node)) {\n case \"paragraph\": {\n return renderInlines(children(node));\n }\n case \"heading\": {\n return `${headingPrefix(asNumber(node.level) ?? 1)}${renderInlines(children(node))}`;\n }\n case \"quote\": {\n return blockquote(renderInlines(children(node)));\n }\n case \"list\": {\n return renderList(node);\n }\n case \"code\": {\n // Code children are plain text nodes; their text is literal.\n const code = children(node)\n .map((child) => asString(child.text) ?? \"\")\n .join(\"\");\n return codeFence(code, asString(node.language) ?? \"\");\n }\n case \"image\": {\n return renderImage(node, options);\n }\n default: {\n return unsupported(`Strapi block: ${typeOf(node)}`);\n }\n }\n};\n\n/** Serialize a Blocks field value (an array of block nodes) to Markdown. */\nexport const strapiBlocksToMarkdown = (\n blocks: JsonValue,\n options: StrapiBlocksOptions = {}\n): string =>\n markdownDocument(objectsIn(blocks).map((node) => renderBlock(node, options)));\n",
30
- "import type { JsonObject } from \"./json.ts\";\nimport { asNumber, asObject, asString, getPath, objectsIn } from \"./json.ts\";\nimport type { RemoteFieldMap, RestClient } from \"./remote.ts\";\nimport {\n documentEntry,\n fetchJson,\n queryString,\n remoteSource,\n} from \"./remote.ts\";\nimport { strapiBlocksToMarkdown } from \"./strapi-blocks.ts\";\nimport type { ContentSource, SourceContext, SourceEntry } from \"./types.ts\";\n\nexport interface StrapiSourceOptions {\n name: string;\n prefix?: string;\n /** The Strapi origin (`https://cms.acme.dev`); its REST API is at `/api`. */\n url: string;\n /** The content type's plural API id (`articles`). */\n contentType: string;\n /** Locale code to fetch, for a localized content type. */\n locale?: string;\n /** The `populate` parameter; default `*`, which fills media and relations. */\n populate?: string;\n /**\n * Field paths mapping an entry onto Blume meta + body. Defaults:\n * `title`, `description`, `slug`, `content`, `updatedAt`.\n */\n fields?: RemoteFieldMap;\n /** Extra query parameters for the request (`filters[...]`, `sort`). */\n params?: Record<string, string>;\n /** API token; defaults to `STRAPI_API_TOKEN`. */\n token?: string;\n /** Opt-in dev polling interval (seconds); omit to freeze for the session. */\n pollInterval?: number;\n /** Injected for tests; defaults to the global `fetch`. */\n fetchImpl?: typeof fetch;\n}\n\nconst PAGE_SIZE = 100;\n\nconst DEFAULT_FIELDS: Required<RemoteFieldMap> = {\n body: \"content\",\n description: \"description\",\n lastModified: \"updatedAt\",\n slug: \"slug\",\n title: \"title\",\n};\n\n/**\n * The entry as a flat document. Strapi 5 returns fields at the top level\n * beside `documentId`; Strapi 4 wraps them in `attributes` under a numeric\n * `id`, and that envelope is flattened so the same field paths apply.\n */\nconst flatten = (item: JsonObject): JsonObject => {\n const attributes = asObject(item.attributes);\n return attributes ? { ...attributes, id: item.id ?? null } : item;\n};\n\nconst idOf = (doc: JsonObject): string => {\n const raw = doc.documentId ?? doc.id;\n return asString(raw) ?? String(asNumber(raw) ?? \"\");\n};\n\n/** Every entry one query returns, across its pages, flattened. */\ninterface StrapiListing {\n docs: JsonObject[];\n /** Whether any entry came in Strapi 4's `attributes` envelope. */\n v4: boolean;\n}\n\n/** Strapi 4 marks an unpublished entry with a null `publishedAt`. */\nconst unpublished = (doc: JsonObject): boolean => doc.publishedAt === null;\n\n/**\n * Strapi content source. Pages through a content type's REST endpoint, maps\n * each entry's fields to frontmatter, and lowers its Blocks body to\n * Markdown. Published entries only, unless `--preview` asks for drafts.\n */\nexport const strapiSource = (\n options: StrapiSourceOptions,\n ctx?: SourceContext\n): ContentSource => {\n const fields = { ...DEFAULT_FIELDS, ...options.fields };\n const origin = options.url.replace(/\\/+$/u, \"\");\n\n const fetchEntries = async (): Promise<SourceEntry[]> => {\n const token = options.token ?? process.env.STRAPI_API_TOKEN;\n const client: RestClient = {\n fetchImpl: options.fetchImpl,\n headers: token ? { authorization: `Bearer ${token}` } : {},\n };\n const base = `${origin}/api/${options.contentType}`;\n\n const list = async (\n publication: Record<string, string>\n ): Promise<StrapiListing> => {\n const listing: StrapiListing = { docs: [], v4: false };\n let page = 1;\n let more = true;\n while (more) {\n // The user's params go first so the paging controls always win — a\n // `params` key that shadowed them would refetch the same page forever.\n const query = queryString({\n ...options.params,\n locale: options.locale,\n \"pagination[pageSize]\": String(PAGE_SIZE),\n \"pagination[page]\": String(page),\n populate: options.populate ?? \"*\",\n ...publication,\n });\n // oxlint-disable-next-line no-await-in-loop -- pages are sequential: each response says whether another exists.\n const result = asObject(await fetchJson(`${base}?${query}`, client));\n if (!result) {\n throw new Error(\"Strapi returned a non-object response\");\n }\n const items = objectsIn(result.data);\n for (const item of items) {\n listing.v4 ||= asObject(item.attributes) !== undefined;\n listing.docs.push(flatten(item));\n }\n const pageCount =\n asNumber(getPath(result, \"meta.pagination.pageCount\")) ?? 1;\n more = items.length > 0 && page < pageCount;\n page += 1;\n }\n return listing;\n };\n\n const toEntries = (\n docs: JsonObject[],\n isDraft: (doc: JsonObject) => boolean\n ): SourceEntry[] =>\n docs.map((doc) =>\n documentEntry(\n doc,\n fields,\n idOf(doc),\n (body) => strapiBlocksToMarkdown(body, { baseUrl: origin }),\n isDraft(doc)\n )\n );\n\n // The default publication state is the published one in both Strapi 4\n // and 5, and its response shape says which version is answering.\n const published = await list({});\n if (!ctx?.preview) {\n return toEntries(published.docs, () => false);\n }\n // Strapi 4 previews with `publicationState=preview`, which returns drafts\n // and published entries together, a draft's `publishedAt` being null.\n if (published.v4) {\n const previewed = await list({ publicationState: \"preview\" });\n return toEntries(previewed.docs, unpublished);\n }\n // Strapi 5 answers `status=draft` with the draft version of every\n // document, `publishedAt` null even when a published version exists, so a\n // document is a draft only when it has no published version.\n const drafts = await list({ status: \"draft\" });\n if (drafts.docs.length === 0 && published.docs.length === 0) {\n // Strapi 4 ignores `status`, so a Strapi 4 content type holding only\n // drafts reads as empty on both requests. Ask with its own parameter;\n // Strapi 5 either ignores it or rejects it (`strictParams`), and in\n // both cases has nothing more to return.\n const previewed = await list({ publicationState: \"preview\" }).catch(\n () => null\n );\n return previewed ? toEntries(previewed.docs, unpublished) : [];\n }\n const publishedIds = new Set(published.docs.map(idOf));\n const draftIds = new Set(drafts.docs.map(idOf));\n // A published document with no draft version (a content type without\n // Draft & Publish) still belongs in the preview.\n return [\n ...toEntries(drafts.docs, (doc) => !publishedIds.has(idOf(doc))),\n ...toEntries(\n published.docs.filter((doc) => !draftIds.has(idOf(doc))),\n () => false\n ),\n ];\n };\n\n return remoteSource(\n {\n fetchEntries,\n name: options.name,\n pollInterval: options.pollInterval,\n prefix: options.prefix,\n },\n ctx\n );\n};\n"
31
- ],
32
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,IAAM,sBAAsB,CAAC,YAAoB,WAC/C,GAAG,iBAAmB;AAQxB,IAAM,uBAAuB,CAC3B,OACA,YACA,WACuB;AAAA,EACvB,MAAM,MAAM,oBAAoB,YAAY,MAAM;AAAA,EAClD,MAAM,WAAW,MAAM,IAAI,GAAG;AAAA,EAC9B,IAAI,UAAU;AAAA,IACZ,OAAO;AAAA,EACT;AAAA,EACA,MAAM,OAA2B,CAAC;AAAA,EAClC,MAAM,IAAI,KAAK,IAAI;AAAA,EACnB,OAAO;AAAA;AAIF,IAAM,mBAAmB;AAQzB,IAAM,mBAAmB,CAC9B,MACA,WAEA,CAAC,KAAK,KAAK,OAAO,YACjB,CAAC,KAAK,KAAK,QAAQ,UAAU,OAAO,OAAO,SAAS;AAavD,IAAM,mBAAmB,CAAC,SAC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