kawapress 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +17 -5
  2. package/README.zh-CN.md +17 -5
  3. package/package.json +7 -3
  4. package/src/api/config.ts +12 -16
  5. package/src/api/plugin.ts +20 -3
  6. package/src/cli.ts +28 -2
  7. package/src/client/app.ts +36 -6
  8. package/src/client/components/KawaOutlet.vue +36 -0
  9. package/src/client/components/Root.vue +7 -0
  10. package/src/client/composables.ts +11 -10
  11. package/src/client/entries/entry-client.ts +8 -3
  12. package/src/client/entries/entry-server.ts +36 -6
  13. package/src/client/index.ts +8 -2
  14. package/src/client/outlet.ts +85 -0
  15. package/src/client/page-data.ts +23 -16
  16. package/src/client/page-table.ts +138 -0
  17. package/src/client/router/RouterLink.ts +34 -0
  18. package/src/client/router/RouterView.ts +25 -0
  19. package/src/client/router/app-router.ts +84 -0
  20. package/src/client/router/history.ts +53 -0
  21. package/src/client/router/injection.ts +29 -0
  22. package/src/client/router/link-interceptor.ts +67 -0
  23. package/src/client/router/reload.ts +34 -0
  24. package/src/client/router/route.ts +82 -0
  25. package/src/client/router/router.ts +160 -0
  26. package/src/client/testing/virtual-modules.ts +19 -0
  27. package/src/client/types/global-components.d.ts +1 -0
  28. package/src/client/types/virtual-modules.d.ts +3 -5
  29. package/src/compiler/frontmatter-compat.ts +12 -0
  30. package/src/compiler/link-registry.ts +29 -0
  31. package/src/compiler/markdown.ts +223 -21
  32. package/src/compiler/page-components.ts +144 -0
  33. package/src/compiler/page-loader.ts +15 -2
  34. package/src/compiler/page-summary.ts +96 -0
  35. package/src/core/dead-links.ts +234 -0
  36. package/src/core/extension-points.ts +64 -0
  37. package/src/core/head.ts +207 -0
  38. package/src/core/heading-title.ts +78 -0
  39. package/src/core/hydration-plan.ts +79 -0
  40. package/src/core/locale.ts +28 -18
  41. package/src/core/not-found.ts +22 -0
  42. package/src/core/outlet.ts +110 -0
  43. package/src/core/page-chunk.ts +50 -0
  44. package/src/core/page-manifest.ts +53 -0
  45. package/src/core/router.ts +46 -0
  46. package/src/core/site.ts +19 -19
  47. package/src/core/tokens.ts +59 -0
  48. package/src/generator/config.ts +93 -13
  49. package/src/generator/data/context.ts +1 -0
  50. package/src/generator/git.ts +79 -0
  51. package/src/generator/pages.ts +126 -0
  52. package/src/generator/runtime-dependencies.ts +280 -0
  53. package/src/generator/vite/app-chunk.ts +65 -0
  54. package/src/generator/vite/config.ts +98 -10
  55. package/src/generator/vite/page-inputs.ts +22 -0
  56. package/src/generator/vite/plugins/dev-dead-links.ts +72 -0
  57. package/src/generator/vite/plugins/pages.ts +162 -114
  58. package/src/generator.ts +13 -0
  59. package/src/index.ts +30 -2
  60. package/src/plugin/execution.ts +17 -13
  61. package/src/plugin/generator-runner.ts +8 -3
  62. package/src/plugin/outlet-collector.ts +69 -0
  63. package/src/plugin/runtime-runner.ts +7 -1
  64. package/src/server/build-node-env.ts +48 -0
  65. package/src/server/build.ts +50 -4
  66. package/src/server/check-dead-links.ts +88 -0
  67. package/src/server/page-assets.ts +138 -0
  68. package/src/server/prerender.ts +134 -27
  69. package/src/server/preview-routing.ts +64 -0
  70. package/src/server/preview.ts +78 -11
  71. package/src/server/request-handler.ts +36 -12
  72. package/src/server/template.ts +31 -0
  73. package/src/client/router.ts +0 -81
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Components that one Markdown page declared while it was rendered.
3
+ *
4
+ * A Markdown plugin says "this page uses this component" from inside a
5
+ * markdown-it rule, fence renderer or highlight callback, which all receive the
6
+ * Markdown `env`. KawaPress merges the import into that page's own Vue SFC, so
7
+ * Vue resolves the tag in the page template, Markdown authors declare nothing,
8
+ * and pages that never produce the tag never download the component module.
9
+ */
10
+
11
+ /** One component that the template of a page uses. */
12
+ export interface PageComponent {
13
+ /**
14
+ * Name of the tag in the page template, for example `AcmeChart` in
15
+ * `<AcmeChart />`. It becomes the import binding of the page SFC, so it must
16
+ * be a valid JavaScript identifier.
17
+ */
18
+ name: string
19
+ /**
20
+ * Module whose default export is the component: a bare package specifier or
21
+ * an absolute file path. Vite resolves it from the page that imports it.
22
+ */
23
+ from: string
24
+ }
25
+
26
+ /** Part of the Markdown `env` that carries the page components. */
27
+ export interface PageComponentEnv {
28
+ /** Public route of the page being rendered. Only used in error messages. */
29
+ path?: string
30
+ pageComponents?: PageComponent[]
31
+ /**
32
+ * The Markdown env of markdown-it and markdown-exit carries every value a
33
+ * plugin writes. Accepting that shape here lets a plugin pass the env it
34
+ * receives straight to `addPageComponent()`.
35
+ */
36
+ [key: string]: unknown
37
+ }
38
+
39
+ const COMPONENT_NAME_RE = /^[A-Z_$][\w$]*$/i
40
+ const SCRIPT_SETUP_RE = /<\s*script[^>]*\ssetup\b/
41
+ const SCRIPT_LANG_RE = /\slang\s*=\s*["']([^"']+)["']/
42
+ const SCRIPT_OPEN_RE = /<\s*script[^>]*>/
43
+
44
+ /**
45
+ * Declares that the page being rendered uses `component`.
46
+ *
47
+ * Call it with the `env` of the rule that produced the tag. Declaring the same
48
+ * name and module twice is harmless, because a page can render a component many
49
+ * times; declaring the same name from two modules is an error.
50
+ */
51
+ export function addPageComponent(
52
+ env: PageComponentEnv,
53
+ component: PageComponent,
54
+ ): void {
55
+ if (typeof env !== 'object' || env === null) {
56
+ throw new Error(
57
+ `KawaPress: addPageComponent() expects the Markdown env of the page being rendered, but received a value of type ${env === null ? 'null' : typeof env}. Call it from a markdown-it rule, fence renderer or highlight callback and pass the env that callback receives.`,
58
+ )
59
+ }
60
+
61
+ const page = describePage(env)
62
+ const name: unknown = component?.name
63
+ const from: unknown = component?.from
64
+
65
+ if (typeof name !== 'string' || !COMPONENT_NAME_RE.test(name)) {
66
+ throw new Error(
67
+ `KawaPress: the component name ${JSON.stringify(name)} declared on ${page} is not a valid identifier. The name becomes the import binding of the page component, so use the PascalCase form of the tag, for example "AcmeChart" for <AcmeChart />.`,
68
+ )
69
+ }
70
+ if (typeof from !== 'string' || from.length === 0) {
71
+ throw new Error(
72
+ `KawaPress: the component "${name}" declared on ${page} has no module to import from. Pass a bare package specifier such as "@acme/chart" or an absolute file path.`,
73
+ )
74
+ }
75
+
76
+ const declared = (env.pageComponents ??= []).find(entry => entry.name === name)
77
+ if (!declared) {
78
+ env.pageComponents.push({ name, from })
79
+ return
80
+ }
81
+ if (declared.from === from) {
82
+ return
83
+ }
84
+
85
+ throw new Error(
86
+ `KawaPress: ${page} declares the component "${name}" from two modules: ${JSON.stringify(declared.from)} and ${JSON.stringify(from)}. One component name can come from one module per page; rename one of them, or declare it only where that page needs it.`,
87
+ )
88
+ }
89
+
90
+ function describePage(env: PageComponentEnv): string {
91
+ return typeof env.path === 'string'
92
+ ? `route ${JSON.stringify(env.path)}`
93
+ : 'a page without a route'
94
+ }
95
+
96
+ /**
97
+ * Merges the declared components into the scripts of the page SFC.
98
+ *
99
+ * Imports always land in a `<script setup>` block, so the page template resolves
100
+ * them as local bindings: an existing setup block is reused, a page with only a
101
+ * plain `<script>` gets a setup block with the same `lang`, and a page without
102
+ * any script gets one too. The returned array is new; the input is untouched.
103
+ */
104
+ export function injectPageComponentImports(
105
+ scripts: string[],
106
+ components: readonly PageComponent[],
107
+ ): string[] {
108
+ if (components.length === 0) {
109
+ return scripts
110
+ }
111
+
112
+ const imports = components
113
+ .map(component => `import ${component.name} from ${JSON.stringify(component.from)}`)
114
+ .join('\n')
115
+ const setupIndex = scripts.findIndex(isScriptSetupBlock)
116
+ if (setupIndex >= 0) {
117
+ return scripts.map((script, index) => (
118
+ index === setupIndex ? insertAfterScriptTag(script, imports) : script
119
+ ))
120
+ }
121
+
122
+ const lang = scripts.map(readScriptLang).find(value => value !== undefined)
123
+ const langAttribute = lang ? ` lang=${JSON.stringify(lang)}` : ''
124
+ return [`<script setup${langAttribute}>\n${imports}\n</script>`, ...scripts]
125
+ }
126
+
127
+ /** Whether a script block is `<script setup>`, whatever its `lang` is. */
128
+ export function isScriptSetupBlock(script: string): boolean {
129
+ return SCRIPT_SETUP_RE.test(script)
130
+ }
131
+
132
+ /** `lang` attribute of a script block, for example `ts`. */
133
+ export function readScriptLang(script: string): string | undefined {
134
+ return SCRIPT_LANG_RE.exec(script)?.[1]
135
+ }
136
+
137
+ function insertAfterScriptTag(script: string, code: string): string {
138
+ const match = SCRIPT_OPEN_RE.exec(script)
139
+ if (!match) {
140
+ return script
141
+ }
142
+ const index = match.index + match[0].length
143
+ return `${script.slice(0, index)}\n${code}${script.slice(index)}`
144
+ }
@@ -1,8 +1,10 @@
1
1
  import type { GeneratorPluginRunner } from '../plugin/generator-runner'
2
+ import type { LinkRegistry } from './link-registry'
2
3
  import type { ParsedMarkdown } from './markdown'
3
4
  import { relative, resolve, sep } from 'node:path'
4
5
  import { markdownPagePathToRoutePath } from '../core/markdown-route'
5
6
  import { assertPageDataSerializable } from '../core/site'
7
+ import { createLinkRegistry } from './link-registry'
6
8
  import { createMarkdownCompiler, parseMarkdown } from './markdown'
7
9
 
8
10
  interface CachedPage {
@@ -12,6 +14,8 @@ interface CachedPage {
12
14
 
13
15
  export interface MarkdownPageLoader {
14
16
  sourceRoot: string
17
+ /** Links and heading IDs of every page loaded so far. */
18
+ registry: LinkRegistry
15
19
  load: (source: string, file: string) => Promise<ParsedMarkdown>
16
20
  }
17
21
 
@@ -26,6 +30,7 @@ export function createMarkdownPageLoader(
26
30
  options: MarkdownPageLoaderOptions,
27
31
  ): MarkdownPageLoader {
28
32
  const sourceRoot = resolve(options.root, options.srcDir)
33
+ const registry = createLinkRegistry()
29
34
  const mdPromise = createMarkdownCompiler({
30
35
  base: options.base,
31
36
  pluginRunner: options.pluginRunner,
@@ -34,6 +39,7 @@ export function createMarkdownPageLoader(
34
39
 
35
40
  return {
36
41
  sourceRoot,
42
+ registry,
37
43
  load(source, file) {
38
44
  const cached = cache.get(file)
39
45
  if (cached?.source === source) {
@@ -49,8 +55,14 @@ export function createMarkdownPageLoader(
49
55
  routePath,
50
56
  sourcePath,
51
57
  )
58
+ registry.set({
59
+ route: routePath,
60
+ source: sourcePath,
61
+ headings: result.env.headings ?? [],
62
+ links: result.env.links ?? [],
63
+ })
52
64
  assertPageDataSerializable(result.pageData)
53
- await options.pluginRunner.runPageData(result.pageData)
65
+ await options.pluginRunner.runPageData(result.pageData, { file, sourcePath })
54
66
  assertPageDataSerializable(result.pageData)
55
67
  await options.pluginRunner.runPageArtifact({
56
68
  source,
@@ -67,6 +79,7 @@ export function createMarkdownPageLoader(
67
79
  }
68
80
  }
69
81
 
70
- function markdownFileToSourcePath(file: string, sourceRoot: string): string {
82
+ /** Path of a Markdown file relative to srcDir, for example `/guide/intro.md`. */
83
+ export function markdownFileToSourcePath(file: string, sourceRoot: string): string {
71
84
  return `/${relative(sourceRoot, file).split(sep).join('/')}`
72
85
  }
@@ -0,0 +1,96 @@
1
+ import type { MarkdownExit, Token } from 'markdown-exit'
2
+ import type { PageSummary } from '../core/page-manifest'
3
+ import { frontmatterPlugin } from '@mdit-vue/plugin-frontmatter'
4
+ import { attrs as attrsPlugin } from '@mdit/plugin-attrs'
5
+ import { createMarkdownExit } from 'markdown-exit'
6
+ import { resolveHeadingTitle } from '../core/heading-title'
7
+ import { resolvePageMetadata } from '../core/page-metadata'
8
+ import { installJsonFrontmatterCompatibility } from './frontmatter-compat'
9
+ import { useMarkdownItPlugin } from './markdown-it-compat'
10
+
11
+ export interface PageSummaryReader {
12
+ /**
13
+ * Reads the summary of `source`. `file` is only the cache key, so a file that
14
+ * keeps its content keeps its summary between dev requests.
15
+ */
16
+ read: (source: string, file: string) => PageSummary
17
+ }
18
+
19
+ interface SummaryEnv {
20
+ frontmatter?: Record<string, unknown>
21
+ }
22
+
23
+ /**
24
+ * Reads route summaries without running the Markdown pipeline, so listing the
25
+ * site never renders pages: no Shiki, no Twoslash, no MathJax and no plugin
26
+ * `pageData()` handler runs here.
27
+ */
28
+ export function createPageSummaryReader(): PageSummaryReader {
29
+ const md = createSummaryMarkdown()
30
+ const cache = new Map<string, { source: string, summary: PageSummary }>()
31
+
32
+ return {
33
+ read(source, file) {
34
+ const cached = cache.get(file)
35
+ if (cached?.source === source) {
36
+ return cached.summary
37
+ }
38
+
39
+ const summary = summarizeMarkdown(md, source)
40
+ cache.set(file, { source, summary })
41
+ return summary
42
+ },
43
+ }
44
+ }
45
+
46
+ /**
47
+ * A parser that only needs to produce tokens. It carries the two rules that
48
+ * decide what an author sees as a heading: frontmatter detection and the
49
+ * heading `{#custom-id}` suffix.
50
+ */
51
+ function createSummaryMarkdown(): MarkdownExit {
52
+ const md = createMarkdownExit({ html: true })
53
+ useMarkdownItPlugin(md, frontmatterPlugin, { renderExcerpt: false })
54
+ installJsonFrontmatterCompatibility(md)
55
+ useMarkdownItPlugin(md, attrsPlugin, {
56
+ allowed: ['id'],
57
+ rule: ['heading'],
58
+ })
59
+ return md
60
+ }
61
+
62
+ function summarizeMarkdown(md: MarkdownExit, source: string): PageSummary {
63
+ const env: SummaryEnv = {}
64
+ const heading = firstLevelOneHeading(md.parse(source, env))
65
+ const frontmatter = env.frontmatter ?? {}
66
+ // Same title rule as the full pipeline, so both can never disagree.
67
+ const { title } = resolvePageMetadata(
68
+ frontmatter,
69
+ heading === undefined ? [] : [{ level: 1, title: heading }],
70
+ )
71
+ const layout = typeof frontmatter.layout === 'string'
72
+ ? frontmatter.layout
73
+ : undefined
74
+
75
+ return {
76
+ title,
77
+ ...(layout === undefined ? {} : { layout }),
78
+ }
79
+ }
80
+
81
+ /**
82
+ * The first top-level h1 of the page, as plain text. Headings nested in a
83
+ * quote or a list are not page titles, which mirrors the heading rule of the
84
+ * full pipeline.
85
+ */
86
+ function firstLevelOneHeading(tokens: Token[]): string | undefined {
87
+ for (const [index, token] of tokens.entries()) {
88
+ if (token.type !== 'heading_open' || token.tag !== 'h1' || token.level !== 0) {
89
+ continue
90
+ }
91
+ const inline = tokens[index + 1]
92
+ return inline?.type === 'inline'
93
+ ? resolveHeadingTitle(inline)
94
+ : undefined
95
+ }
96
+ }
@@ -0,0 +1,234 @@
1
+ import { decodeUrlPathname } from './base'
2
+ import { markdownPagePathToRoutePath } from './markdown-route'
3
+
4
+ /** Why KawaPress treats an internal link as dead. */
5
+ export type DeadLinkReason = 'missing-page' | 'missing-anchor' | 'missing-file'
6
+
7
+ export interface DeadLink {
8
+ /** Original href from the Markdown source, for example `./intro.md#setup`. */
9
+ href: string
10
+ /** Public route or public file path without the site base, including search and hash. */
11
+ target: string
12
+ /** Source path relative to srcDir, for example `/guide/intro.md`. */
13
+ source: string
14
+ /** 1-based line number of the Markdown block that contains the link. */
15
+ line: number
16
+ reason: DeadLinkReason
17
+ }
18
+
19
+ /** A link is skipped when the value matches its `href` or `target`. */
20
+ export type DeadLinkIgnore = string | RegExp | ((link: DeadLink) => boolean)
21
+
22
+ export interface DeadLinkConfig {
23
+ /** `error` fails the build, `warn` only prints the report. Defaults to `error`. */
24
+ level?: 'error' | 'warn'
25
+ /** Links to skip. A function receives the whole {@link DeadLink}. */
26
+ ignore?: DeadLinkIgnore[]
27
+ }
28
+
29
+ export interface ResolvedDeadLinkConfig {
30
+ level: 'error' | 'warn'
31
+ ignore: DeadLinkIgnore[]
32
+ }
33
+
34
+ /** One internal link written in a Markdown page. */
35
+ export interface LinkRecord {
36
+ /** Original href from the Markdown source. */
37
+ href: string
38
+ /** Public route or public file path without the site base, including search and hash. */
39
+ target: string
40
+ /** 1-based line number in the source file. */
41
+ line: number
42
+ }
43
+
44
+ /** Links and heading IDs of one page, as seen by the dead link checker. */
45
+ export interface PageLinks {
46
+ /** Public route of the page, for example `/guide/intro`. */
47
+ route: string
48
+ /** Source path relative to srcDir, for example `/guide/intro.md`. */
49
+ source: string
50
+ /** Anchor IDs of every heading on the page, from h1 to h6. */
51
+ headings: readonly string[]
52
+ /** Internal links written in the page. */
53
+ links: readonly LinkRecord[]
54
+ }
55
+
56
+ export interface DeadLinkSite {
57
+ /** Public routes of every page in the site. */
58
+ routes: Iterable<string>
59
+ /** Heading IDs of each page, keyed by route. */
60
+ headings: ReadonlyMap<string, readonly string[]>
61
+ /** Files in the public directory, as paths relative to it, for example `/logo.png`. */
62
+ publicFiles: Iterable<string>
63
+ }
64
+
65
+ const PAGE_EXTENSION_RE = /\.(?:md|html)$/i
66
+
67
+ export function findDeadLinks(
68
+ pages: Iterable<PageLinks>,
69
+ site: DeadLinkSite,
70
+ ignore: readonly DeadLinkIgnore[] = [],
71
+ ): DeadLink[] {
72
+ const context = createContext(site, ignore)
73
+ const deadLinks = [...pages].flatMap(page => checkPage(page, context))
74
+ return deadLinks.sort(compareDeadLinks)
75
+ }
76
+
77
+ export function findPageDeadLinks(
78
+ page: PageLinks,
79
+ site: DeadLinkSite,
80
+ ignore: readonly DeadLinkIgnore[] = [],
81
+ ): DeadLink[] {
82
+ return checkPage(page, createContext(site, ignore))
83
+ }
84
+
85
+ /** Format a link as `source:line href reason`, the report line used by build and dev. */
86
+ export function formatDeadLink(link: DeadLink): string {
87
+ return `${link.source}:${link.line} ${link.href} ${link.reason}`
88
+ }
89
+
90
+ interface CheckContext {
91
+ routes: Set<string>
92
+ headings: Map<string, Set<string>>
93
+ publicFiles: Set<string>
94
+ ignore: readonly DeadLinkIgnore[]
95
+ }
96
+
97
+ function createContext(site: DeadLinkSite, ignore: readonly DeadLinkIgnore[]): CheckContext {
98
+ return {
99
+ routes: new Set([...site.routes].map(route => normalizeRoute(route))),
100
+ headings: new Map(
101
+ [...site.headings].map(([route, ids]) => [
102
+ normalizeRoute(route),
103
+ new Set(ids.map(decodeAnchor)),
104
+ ]),
105
+ ),
106
+ publicFiles: new Set([...site.publicFiles].map(file => normalizePublicFile(file))),
107
+ ignore,
108
+ }
109
+ }
110
+
111
+ function checkPage(page: PageLinks, context: CheckContext): DeadLink[] {
112
+ const deadLinks: DeadLink[] = []
113
+ for (const link of page.links) {
114
+ const reason = classifyLink(link.target, page.route, context)
115
+ if (!reason) {
116
+ continue
117
+ }
118
+ const deadLink: DeadLink = {
119
+ href: link.href,
120
+ target: link.target,
121
+ source: page.source,
122
+ line: link.line,
123
+ reason,
124
+ }
125
+ if (!isIgnored(deadLink, context.ignore)) {
126
+ deadLinks.push(deadLink)
127
+ }
128
+ }
129
+ return deadLinks
130
+ }
131
+
132
+ function classifyLink(
133
+ target: string,
134
+ pageRoute: string,
135
+ context: CheckContext,
136
+ ): DeadLinkReason | undefined {
137
+ const { pathname, hash } = splitTarget(target)
138
+
139
+ if (!pathname) {
140
+ return hasAnchor(pageRoute, hash, context) ? undefined : 'missing-anchor'
141
+ }
142
+
143
+ const decodedPath = decodeUrlPathname(pathname)
144
+ const route = normalizeRoute(markdownPagePathToRoutePath(decodedPath))
145
+ if (isPagePath(decodedPath) || context.routes.has(route)) {
146
+ if (!context.routes.has(route)) {
147
+ return 'missing-page'
148
+ }
149
+ return hasAnchor(route, hash, context) ? undefined : 'missing-anchor'
150
+ }
151
+
152
+ return context.publicFiles.has(normalizePublicFile(decodedPath))
153
+ ? undefined
154
+ : 'missing-file'
155
+ }
156
+
157
+ /**
158
+ * Page links are extensionless, `.md`, `.html`, or a directory path. Everything
159
+ * else that carries an extension points into the public directory.
160
+ */
161
+ function isPagePath(pathname: string): boolean {
162
+ return pathname.endsWith('/')
163
+ || !hasExtension(pathname)
164
+ || PAGE_EXTENSION_RE.test(pathname)
165
+ }
166
+
167
+ function hasExtension(pathname: string): boolean {
168
+ const lastSegment = pathname.slice(pathname.lastIndexOf('/') + 1)
169
+ return lastSegment.includes('.')
170
+ }
171
+
172
+ function hasAnchor(route: string, hash: string, context: CheckContext): boolean {
173
+ if (!hash) {
174
+ return true
175
+ }
176
+ const anchors = context.headings.get(normalizeRoute(route))
177
+ return anchors?.has(decodeAnchor(hash)) ?? false
178
+ }
179
+
180
+ function splitTarget(target: string): { pathname: string, hash: string } {
181
+ const hashIndex = target.indexOf('#')
182
+ const withoutHash = hashIndex < 0 ? target : target.slice(0, hashIndex)
183
+ const searchIndex = withoutHash.indexOf('?')
184
+ return {
185
+ pathname: searchIndex < 0 ? withoutHash : withoutHash.slice(0, searchIndex),
186
+ hash: hashIndex < 0 ? '' : target.slice(hashIndex + 1),
187
+ }
188
+ }
189
+
190
+ function normalizeRoute(route: string): string {
191
+ if (route.length <= 1 || !route.endsWith('/')) {
192
+ return route
193
+ }
194
+ return route.slice(0, -1)
195
+ }
196
+
197
+ function normalizePublicFile(file: string): string {
198
+ const decoded = decodeUrlPathname(file)
199
+ return decoded.startsWith('/') ? decoded : `/${decoded}`
200
+ }
201
+
202
+ /** Anchors live in the URL, so `#开始` and `#%E5%BC%80%E5%A7%8B` are the same heading. */
203
+ function decodeAnchor(value: string): string {
204
+ try {
205
+ return decodeURIComponent(value)
206
+ }
207
+ catch {
208
+ return value
209
+ }
210
+ }
211
+
212
+ function isIgnored(link: DeadLink, ignore: readonly DeadLinkIgnore[]): boolean {
213
+ return ignore.some((pattern) => {
214
+ if (typeof pattern === 'string') {
215
+ return pattern === link.href || pattern === link.target
216
+ }
217
+ if (pattern instanceof RegExp) {
218
+ return matchesPattern(pattern, link.href) || matchesPattern(pattern, link.target)
219
+ }
220
+ return pattern(link)
221
+ })
222
+ }
223
+
224
+ function matchesPattern(pattern: RegExp, value: string): boolean {
225
+ // `g` and `y` flags keep state between calls, so every test starts from zero.
226
+ pattern.lastIndex = 0
227
+ return pattern.test(value)
228
+ }
229
+
230
+ function compareDeadLinks(a: DeadLink, b: DeadLink): number {
231
+ return a.source.localeCompare(b.source)
232
+ || a.line - b.line
233
+ || a.target.localeCompare(b.target)
234
+ }
@@ -0,0 +1,64 @@
1
+ import type { HeadConfig } from './head'
2
+ import type { PageHeader } from './site'
3
+
4
+ /**
5
+ * The types a plugin or a theme extends with `declare module 'kawapress'`.
6
+ *
7
+ * They are defined here and exported from the main entry with `export *`.
8
+ * Everything inside KawaPress imports them from this file, so the fields that
9
+ * packages add are the fields that every reader sees.
10
+ */
11
+
12
+ /**
13
+ * Theme configuration of a site. The interface is empty on purpose: a theme or
14
+ * a plugin adds the fields it understands from its own package, and every
15
+ * package that is imported contributes to the same type.
16
+ *
17
+ * ```ts
18
+ * declare module 'kawapress' {
19
+ * interface ThemeConfig {
20
+ * githubUrl?: string
21
+ * }
22
+ * }
23
+ * ```
24
+ *
25
+ * A field only exists in the type while the package that declares it is part of
26
+ * the program, so give every field an optional type: the site may not use it.
27
+ */
28
+
29
+ export interface ThemeConfig {}
30
+
31
+ /**
32
+ * Frontmatter of a page. KawaPress keeps the data open, so any key an author
33
+ * writes is allowed and typed `unknown`. A plugin that reads a key declares it
34
+ * from its own package, which gives every reader the exact type:
35
+ *
36
+ * ```ts
37
+ * declare module 'kawapress' {
38
+ * interface PageFrontmatter {
39
+ * comments?: boolean
40
+ * }
41
+ * }
42
+ * ```
43
+ *
44
+ * The keys are optional because the value comes from the author. Check it at
45
+ * runtime before trusting it.
46
+ */
47
+ export interface PageFrontmatter {
48
+ title?: string
49
+ description?: string
50
+ titleTemplate?: string | false
51
+ head?: HeadConfig[]
52
+ [key: string]: unknown
53
+ }
54
+
55
+ export interface PageData {
56
+ path: string
57
+ title: string
58
+ description?: string
59
+ titleTemplate?: string | false
60
+ /** `<head>` tags from frontmatter, rendered after site and locale tags. */
61
+ head?: HeadConfig[]
62
+ frontmatter: PageFrontmatter
63
+ headers: PageHeader[]
64
+ }