| 1 | # | ||
| 2 | # This file is part of Markdown::Publish. | ||
| 3 | # | ||
| 4 | # This software is copyright (c) 2026 by Andrew Speer <andrew.speer@isolutions.com.au>. | ||
| 5 | # | ||
| 6 | # This is free software; you can redistribute it and/or modify it under | ||
| 7 | # the same terms as the Perl 5 programming language system itself. | ||
| 8 | # | ||
| 9 | # Full license text is available at: | ||
| 10 | # | ||
| 11 | # <http://dev.perl.org/licenses/> | ||
| 12 | # | ||
| 13 | package Markdown::Publish::Starlight; | ||
| 14 | |||
| 15 | |||
| 16 | # Compiler pragma and package variables | ||
| 17 | # | ||
| 18 | use strict qw(vars); | ||
| 19 | use vars qw($VERSION @ISA); | ||
| 20 | use warnings; | ||
| 21 | |||
| 22 | |||
| 23 | # Parent and supporting packages | ||
| 24 | # | ||
| 25 | use Markdown::Publish (); | ||
| 26 | use Markdown::Publish::Constant; | ||
| 27 | use Cwd qw(abs_path); | ||
| 28 | use File::Path qw(make_path); | ||
| 29 | use File::Spec; | ||
| 30 | use JSON::PP qw(encode_json); | ||
| 31 | |||
| 32 | |||
| 33 | # Inheritance and version information | ||
| 34 | # | ||
| 35 | @ISA=qw(Markdown::Publish); | ||
| 36 | $VERSION='1.004'; | ||
| 37 | |||
| 38 | |||
| 39 | # Done | ||
| 40 | # | ||
| 41 | 1; | ||
| 42 | |||
| 43 | |||
| 44 | #====================================================================================================================== | ||
| 45 | |||
| 46 | |||
| 47 | sub prepare { | ||
| 48 | |||
| 49 | my ($self)=@_; | ||
| 50 | my ($temporary_dn, $docs_dn, $pages_ar)=$self->prepare_docs(); | ||
| 51 | $self->promote_home($docs_dn, $pages_ar); | ||
| 52 | my $navigation_ar=$self->navigation($docs_dn, $pages_ar); | ||
| 53 | my $site_dn=File::Spec->catdir($temporary_dn, 'starlight'); | ||
| 54 | my $site_docs_dn=File::Spec->catdir($site_dn, 'src', 'content', 'docs'); | ||
| 55 | make_path($site_docs_dn); | ||
| 56 | $self->copy_tree($docs_dn, $site_docs_dn); | ||
| 57 | $self->normalize_node_markdown($site_docs_dn); | ||
| 58 | my $astro_version=$self->option('astro_version', 'latest'); | ||
| 59 | my $starlight_version=$self->option('starlight_version', 'latest'); | ||
| 60 | my $package_hr={ | ||
| 61 | type => 'module', | ||
| 62 | scripts => {build => 'astro build', start => 'astro dev'}, | ||
| 63 | dependencies => { | ||
| 64 | astro => $astro_version, | ||
| 65 | '@astrojs/starlight' => $starlight_version, | ||
| 66 | '@astrojs/markdown-remark' => 'latest', | ||
| 67 | 'github-slugger' => 'latest' | ||
| 68 | } | ||
| 69 | }; | ||
| 70 | $self->write_file(File::Spec->catfile($site_dn, 'package.json'), encode_json($package_hr)); | ||
| 71 | $self->write_file(File::Spec->catfile($site_dn, 'local-links.mjs'), $self->local_links_plugin()); | ||
| 72 | my ($config_fn, $extend_fn)=$self->configuration_files(); | ||
| 73 | my $prepared_config_fn; | ||
| 74 | if (defined($config_fn) && length($config_fn)) { | ||
| 75 | die "Starlight configuration not found: $config_fn\n" unless -f $config_fn; | ||
| 76 | my $authored_fn=abs_path($config_fn); | ||
| 77 | my $config="import { defineConfig, mergeConfig } from 'astro/config';\n". | ||
| 78 | "import { pathToFileURL } from 'node:url';\n". | ||
| 79 | "import { unified } from '\@astrojs/markdown-remark';\n". | ||
| 80 | "import localLinks from './local-links.mjs';\n\n". | ||
| 81 | "const authored = (await import(pathToFileURL(".encode_json($authored_fn). | ||
| 82 | ").href)).default;\n". | ||
| 83 | "const markdown = authored.markdown || {};\n". | ||
| 84 | "const processor = markdown.processor;\n". | ||
| 85 | "if (processor && processor.name !== 'unified') throw new Error('Starlight link resolution requires unified Markdown processing');\n". | ||
| 86 | "const options = processor ? processor.options : {};\n". | ||
| 87 | "const configured = unified({ ...options, remarkPlugins: [...(options.remarkPlugins || []), ...(markdown.remarkPlugins || []), localLinks] });\n". | ||
| 88 | "export default defineConfig(mergeConfig(authored, { markdown: { processor: configured } }));\n"; | ||
| 89 | $prepared_config_fn=File::Spec->catfile($site_dn, 'astro.config.mjs'); | ||
| 90 | $self->write_file($prepared_config_fn, $config); | ||
| 91 | } | ||
| 92 | else { | ||
| 93 | my @items=map { | ||
| 94 | # Astro normalizes content collection slugs to lower case. | ||
| 95 | my $slug=lc($_->{'id'}); | ||
| 96 | " { label: ".encode_json($_->{'title'}). | ||
| 97 | ", slug: ".encode_json($slug)." }" | ||
| 98 | } @{$navigation_ar}; | ||
| 99 | my $imports="import { defineConfig } from 'astro/config';\n". | ||
| 100 | "import { unified } from '\@astrojs/markdown-remark';\n". | ||
| 101 | "import starlight from '\@astrojs/starlight';\n\n". | ||
| 102 | "import localLinks from './local-links.mjs';\n"; | ||
| 103 | my $astro="{\n base: ".encode_json($self->site_base('/')).",\n". | ||
| 104 | " markdown: { processor: unified({ remarkPlugins: [localLinks] }) }\n}"; | ||
| 105 | my $starlight="{\n title: ". | ||
| 106 | encode_json($self->option('name', 'Documentation')). | ||
| 107 | ",\n sidebar: [{ label: 'Docs', items: [\n". | ||
| 108 | join(",\n", @items)."\n ] }]\n }"; | ||
| 109 | my $config; | ||
| 110 | if (defined($extend_fn)) { | ||
| 111 | die "Starlight configuration extension not found: $extend_fn\n" | ||
| 112 | unless -f $extend_fn; | ||
| 113 | my $context_hr=$self->configuration_context($pages_ar, $navigation_ar); | ||
| 114 | my $authored_fn=abs_path($extend_fn); | ||
| 115 | $config=$imports."import { pathToFileURL } from 'node:url';\n\n". | ||
| 116 | "const generated = { astro: $astro, starlight: $starlight };\n". | ||
| 117 | "const context = ".encode_json($context_hr).";\n". | ||
| 118 | "const extend = (await import(pathToFileURL(". | ||
| 119 | encode_json($authored_fn).").href)).default;\n". | ||
| 120 | "if (typeof extend !== 'function') throw new Error('Starlight config_extend must export a default function');\n". | ||
| 121 | "const configured = await extend(generated, context);\n". | ||
| 122 | "if (!configured || typeof configured !== 'object' || !configured.astro || !configured.starlight) throw new Error('Starlight config_extend must return astro and starlight configuration objects');\n". | ||
| 123 | "const integrations = configured.astro.integrations || [];\n". | ||
| 124 | "if (!Array.isArray(integrations)) throw new Error('Starlight config_extend astro.integrations must be an array');\n". | ||
| 125 | "const { integrations: unused, ...astro } = configured.astro;\n". | ||
| 126 | "export default defineConfig({ ...astro, integrations: [starlight(configured.starlight), ...integrations] });\n"; | ||
| 127 | } | ||
| 128 | else { | ||
| 129 | $config=$imports."\nexport default defineConfig({ ...$astro, integrations: [starlight($starlight)] });\n"; | ||
| 130 | } | ||
| 131 | $prepared_config_fn=File::Spec->catfile($site_dn, 'astro.config.mjs'); | ||
| 132 | $self->write_file($prepared_config_fn, $config); | ||
| 133 | } | ||
| 134 | $self->write_file(File::Spec->catfile($site_dn, 'src', 'content.config.ts'), | ||
| 135 | "import { defineCollection } from 'astro:content';\n". | ||
| 136 | "import { glob } from 'astro/loaders';\n". | ||
| 137 | "import { docsSchema } from '\@astrojs/starlight/schema';\n\n". | ||
| 138 | "export const collections = { docs: defineCollection({ loader: glob({ pattern: '**/*.{md,mdx}', base: './src/content/docs' }), schema: docsSchema() }) };\n"); | ||
| 139 | return ($temporary_dn, $site_dn, $prepared_config_fn); | ||
| 140 | |||
| 141 | } | ||
| 142 | |||
| 143 | |||
| 144 | sub local_links_plugin { | ||
| 145 | |||
| 146 | # Astro routes Markdown through slugged page IDs; resolve authored file | ||
| 147 | # links while their source paths are still available to remark. | ||
| 148 | # | ||
| 149 | return <<'JAVASCRIPT'; | ||
| 150 | import { existsSync } from 'node:fs'; | ||
| 151 | import path from 'node:path'; | ||
| 152 | import { slug } from 'github-slugger'; | ||
| 153 | |||
| 154 | const root = path.resolve('src/content/docs'); | ||
| 155 | |||
| 156 | function route(filename) { | ||
| 157 | const parts = path.relative(root, filename).replace(/\\/g, '/').replace(/\.mdx?$/i, '').split('/'); | ||
| 158 | const id = parts.map((part) => slug(part)).join('/'); | ||
| 159 | if (id === 'index') return '/'; | ||
| 160 | if (parts[parts.length - 1].toLowerCase() === 'index') return '/' + parts.slice(0, -1).map((part) => slug(part)).join('/') + '/'; | ||
| 161 | return '/' + id + '/'; | ||
| 162 | } | ||
| 163 | |||
| 164 | export default function localLinks() { | ||
| 165 | return (tree, file) => { | ||
| 166 | function visit(node) { | ||
| 167 | if ((node.type === 'link' || node.type === 'definition') && typeof node.url === 'string') { | ||
| 168 | const match = /^([^?#]+\.mdx?)(\?[^#]*)?(#.*)?$/i.exec(node.url); | ||
| 169 | if (match && !match[1].startsWith('/') && !match[1].includes('://')) { | ||
| 170 | const target = path.resolve(path.dirname(file.path), decodeURI(match[1])); | ||
| 171 | if (target.startsWith(root + path.sep) && existsSync(target)) { | ||
| 172 | const from = route(file.path); | ||
| 173 | const to = route(target); | ||
| 174 | node.url = (path.posix.relative(from, to) || '.') + '/' + (match[2] || '') + (match[3] || ''); | ||
| 175 | } | ||
| 176 | } | ||
| 177 | } | ||
| 178 | for (const child of node.children || []) visit(child); | ||
| 179 | } | ||
| 180 | visit(tree); | ||
| 181 | }; | ||
| 182 | } | ||
| 183 | JAVASCRIPT | ||
| 184 | |||
| 185 | } | ||
| 186 | |||
| 187 | |||
| 188 | sub normalize_backend_markdown { | ||
| 189 | |||
| 190 | my ($self, $fn, $markdown)=@_; | ||
| 191 | $markdown=$self->title_frontmatter($fn, $markdown); | ||
| 192 | return $self->starlight_title_heading($markdown); | ||
| 193 | |||
| 194 | } | ||
| 195 | |||
| 196 | |||
| 197 | sub heading_anchor_required { | ||
| 198 | |||
| 199 | return 1; | ||
| 200 | |||
| 201 | } | ||
| 202 | |||
| 203 | |||
| 204 | sub admonition_type { | ||
| 205 | |||
| 206 | my ($self, $kind)=@_; | ||
| 207 | my %map=(note => 'note', tip => 'tip', warning => 'caution', | ||
| 208 | important => 'caution', caution => 'caution'); | ||
| 209 | return $map{$kind} || $kind; | ||
| 210 | |||
| 211 | } | ||
| 212 | |||
| 213 | |||
| 214 | sub starlight_title_heading { | ||
| 215 | |||
| 216 | my ($self, $markdown)=@_; | ||
| 217 | my @output; | ||
| 218 | my ($fence, $length, $frontmatter, $removed)=('', 0, 0, 0); | ||
| 219 | my $index=0; | ||
| 220 | foreach my $line (split(/(?<=\n)/, $markdown)) { | ||
| 221 | if (!$index && $line=~/^---[ \t]*\r?\n?$/) { | ||
| 222 | $frontmatter=1; | ||
| 223 | push(@output, $line); | ||
| 224 | $index++; | ||
| 225 | next; | ||
| 226 | } | ||
| 227 | if ($frontmatter) { | ||
| 228 | $frontmatter=0 if $line=~/^---[ \t]*\r?\n?$/; | ||
| 229 | push(@output, $line); | ||
| 230 | $index++; | ||
| 231 | next; | ||
| 232 | } | ||
| 233 | if (!$fence && $line=~/^ {0,3}(`{3,}|~{3,})/) { | ||
| 234 | $fence=substr($1, 0, 1); | ||
| 235 | $length=length($1); | ||
| 236 | } | ||
| 237 | elsif ($fence && $line=~/^ {0,3}\Q$fence\E{$length,}\s*$/) { | ||
| 238 | $fence=''; | ||
| 239 | } | ||
| 240 | elsif (!$fence && !$removed && $line=~/^#\s+(.+?)[ \t]*(\r?\n)?$/) { | ||
| 241 | my ($title, $newline)=($1, $2 || ''); | ||
| 242 | my ($id)=$title=~/\s+\{#([\w.-]+)(?:\s+[^}]*)?\}\s*$/; | ||
| 243 | unless (defined($id)) { | ||
| 244 | $id=lc($title); | ||
| 245 | $id=~s/[^a-z0-9]+/-/g; | ||
| 246 | $id=~s/^-|-$//g; | ||
| 247 | } | ||
| 248 | push(@output, "<a id=\"$id\"></a>$newline") if length($id); | ||
| 249 | $removed=1; | ||
| 250 | $index++; | ||
| 251 | next; | ||
| 252 | } | ||
| 253 | push(@output, $line); | ||
| 254 | $index++; | ||
| 255 | } | ||
| 256 | return join('', @output); | ||
| 257 | |||
| 258 | } | ||
| 259 | |||
| 260 | |||
| 261 | sub build { | ||
| 262 | |||
| 263 | my ($self)=@_; | ||
| 264 | my $output_dn=File::Spec->rel2abs($self->option('output', $MARKDOWN_PUBLISH_OUTPUT_DN)); | ||
| 265 | my (undef, $site_dn, $config_fn)=$self->prepare(); | ||
| 266 | my $config_arg=File::Spec->abs2rel($config_fn, $site_dn); | ||
| 267 | $config_arg=$config_fn if $config_arg=~m{^\.\.[/\\]}; | ||
| 268 | $self->npm_install($site_dn); | ||
| 269 | $self->system_in_dir($site_dn, $self->option('npm', 'npm'), | ||
| 270 | 'run', 'build', '--', '--config', $config_arg, '--outDir', $output_dn); | ||
| 271 | return $output_dn; | ||
| 272 | |||
| 273 | } | ||
| 274 | |||
| 275 | |||
| 276 | sub serve { | ||
| 277 | |||
| 278 | my ($self)=@_; | ||
| 279 | my (undef, $site_dn, $config_fn)=$self->prepare(); | ||
| 280 | my $config_arg=File::Spec->abs2rel($config_fn, $site_dn); | ||
| 281 | $config_arg=$config_fn if $config_arg=~m{^\.\.[/\\]}; | ||
| 282 | $self->npm_install($site_dn); | ||
| 283 | local $ENV{'ASTRO_DEV_BACKGROUND'}=0; | ||
| 284 | my $host=$self->option('host', $MARKDOWN_PUBLISH_HOST); | ||
| 285 | my $port=$self->option('port', $MARKDOWN_PUBLISH_PORT); | ||
| 286 | $host='127.0.0.1' unless defined($host); | ||
| 287 | $port=4321 unless defined($port); | ||
| 288 | return $self->system_in_dir($site_dn, $self->option('npm', 'npm'), | ||
| 289 | 'run', 'start', '--', '--config', $config_arg, | ||
| 290 | '--host', $host, '--port', $port); | ||
| 291 | |||
| 292 | } | ||
| 293 | __END__ |