kawapress 0.3.0 → 0.4.1
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.
- package/package.json +4 -2
- package/src/api/config.ts +11 -1
- package/src/api/plugin.ts +7 -0
- package/src/client/index.ts +2 -1
- package/src/client/platform.ts +30 -0
- package/src/compiler/code-snippet.ts +111 -0
- package/src/compiler/content-loader.ts +7 -3
- package/src/compiler/markdown-source.ts +240 -0
- package/src/compiler/markdown.ts +16 -3
- package/src/compiler/page-loader.ts +40 -12
- package/src/compiler/page-path.ts +93 -0
- package/src/compiler/source-region.ts +78 -0
- package/src/core/extension-points.ts +1 -1
- package/src/core/head.ts +1 -1
- package/src/core/heading-title.ts +9 -5
- package/src/core/site.ts +12 -0
- package/src/generator/config.ts +50 -2
- package/src/generator/data/context.ts +4 -1
- package/src/generator/pages.ts +49 -10
- package/src/generator/vite/config.ts +2 -0
- package/src/generator/vite/entries.ts +8 -0
- package/src/generator/vite/plugins/dev-dead-links.ts +5 -4
- package/src/generator/vite/plugins/markdown.ts +5 -1
- package/src/generator/vite/plugins/pages.ts +2 -0
- package/src/generator.ts +4 -1
- package/src/index.ts +1 -0
- package/src/server/build.ts +6 -3
- package/src/server/prerender.ts +4 -2
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "kawapress",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.4.1",
|
|
5
5
|
"description": "A Vue-centric static site generator",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"homepage": "https://kawapress.dev/",
|
|
@@ -78,10 +78,12 @@
|
|
|
78
78
|
"jiti": "^2.7.0",
|
|
79
79
|
"markdown-exit": "^1.3.0",
|
|
80
80
|
"markdown-it-anchor": "^9.2.0",
|
|
81
|
+
"path-to-regexp": "^6.3.0",
|
|
82
|
+
"picomatch": "^4.0.7",
|
|
81
83
|
"sirv": "^3.0.2",
|
|
82
84
|
"tinyglobby": "^0.2.17",
|
|
83
85
|
"vite": "^8.2.2",
|
|
84
86
|
"vue": "^3.5.41",
|
|
85
|
-
"@kawapress/preset-nagi": "^0.
|
|
87
|
+
"@kawapress/preset-nagi": "^0.4.1"
|
|
86
88
|
}
|
|
87
89
|
}
|
package/src/api/config.ts
CHANGED
|
@@ -1,13 +1,23 @@
|
|
|
1
1
|
import type { DeadLinkConfig } from '../core/dead-links'
|
|
2
2
|
import type { ThemeConfig } from '../core/extension-points'
|
|
3
3
|
import type { HeadConfig } from '../core/head'
|
|
4
|
-
import type { LocaleConfig } from '../core/site'
|
|
4
|
+
import type { LocaleConfig, PageRewrites } from '../core/site'
|
|
5
5
|
import type { KawaPressPlugin } from './plugin'
|
|
6
6
|
|
|
7
7
|
export interface KawapressConfig {
|
|
8
8
|
title?: string
|
|
9
9
|
base?: string
|
|
10
10
|
srcDir?: string
|
|
11
|
+
/**
|
|
12
|
+
* Glob patterns, relative to `srcDir`, of Markdown files that are not pages,
|
|
13
|
+
* for example `snippets/**` for a folder of shared parts.
|
|
14
|
+
*/
|
|
15
|
+
srcExclude?: string[]
|
|
16
|
+
/**
|
|
17
|
+
* Moves pages to other routes without moving their files, for example
|
|
18
|
+
* `{ 'packages/:pkg/src/:page*': ':pkg/:page*' }`.
|
|
19
|
+
*/
|
|
20
|
+
rewrites?: PageRewrites
|
|
11
21
|
publicDir?: string
|
|
12
22
|
head?: HeadConfig[]
|
|
13
23
|
themeConfig?: Partial<ThemeConfig>
|
package/src/api/plugin.ts
CHANGED
|
@@ -11,9 +11,16 @@ export type MaybePromise<T> = T | Promise<T>
|
|
|
11
11
|
export type GeneratorPluginHandler<T> = (value: T) => MaybePromise<void>
|
|
12
12
|
|
|
13
13
|
export interface PageBuildArtifact {
|
|
14
|
+
/** Markdown source of the page, with `<!--@include-->` and `<<<` written out. */
|
|
14
15
|
source: string
|
|
15
16
|
file: string
|
|
17
|
+
/** Path of the file relative to srcDir, for example `/packages/a/src/intro.md`. */
|
|
16
18
|
sourcePath: string
|
|
19
|
+
/**
|
|
20
|
+
* Source path after `rewrites`, for example `/a/intro.md`. Relative links of
|
|
21
|
+
* the page start here; it equals `sourcePath` when no rule moves the page.
|
|
22
|
+
*/
|
|
23
|
+
pagePath: string
|
|
17
24
|
routePath: string
|
|
18
25
|
pageData: Readonly<PageData>
|
|
19
26
|
}
|
package/src/client/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { withBase } from '../core/base'
|
|
1
|
+
export { withBase, withoutBase } from '../core/base'
|
|
2
2
|
export { resolveLocaleIndex } from '../core/locale'
|
|
3
3
|
export { OUTLET_NAMES } from '../core/outlet'
|
|
4
4
|
export type { OutletItem, OutletName, OutletRegistry } from '../core/outlet'
|
|
@@ -6,6 +6,7 @@ export type { Route, RouteGuard, RouteHook, Router } from '../core/router'
|
|
|
6
6
|
export { default as KawaOutlet } from './components/KawaOutlet.vue'
|
|
7
7
|
export { useLocale, usePageData, useSite, useThemeConfig } from './composables'
|
|
8
8
|
export type { LocaleContext } from './composables'
|
|
9
|
+
export { PLATFORM_DETECTION_SCRIPT, usePlatformAttribute } from './platform'
|
|
9
10
|
export { useRoute, useRouter } from './router/injection'
|
|
10
11
|
export { default as RouterLink } from './router/RouterLink'
|
|
11
12
|
export { default as RouterView } from './router/RouterView'
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { useHead } from '@unhead/vue'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Inline script that marks `<html data-kawa-platform>` as `apple` or `control`
|
|
5
|
+
* before the first paint. Its content never changes, so every page can carry
|
|
6
|
+
* the same tag.
|
|
7
|
+
*/
|
|
8
|
+
export const PLATFORM_DETECTION_SCRIPT = `(() => {
|
|
9
|
+
const platform = navigator.userAgentData?.platform || navigator.platform || navigator.userAgent
|
|
10
|
+
document.documentElement.dataset.kawaPlatform = /Mac|iPhone|iPad|iPod/i.test(platform) ? 'apple' : 'control'
|
|
11
|
+
})()`
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Puts the platform detection script into the page head, so CSS can show `⌘`
|
|
15
|
+
* or `Ctrl` from the first frame: static HTML cannot know the visitor's
|
|
16
|
+
* platform, and swapping the text after hydration makes the layout jump.
|
|
17
|
+
*
|
|
18
|
+
* Components render both labels and hide one with
|
|
19
|
+
* `:root[data-kawa-platform='apple']`. Calling this from several components
|
|
20
|
+
* still emits a single tag.
|
|
21
|
+
*/
|
|
22
|
+
export function usePlatformAttribute(): void {
|
|
23
|
+
useHead({
|
|
24
|
+
script: [{
|
|
25
|
+
key: 'kawa-platform',
|
|
26
|
+
id: 'kawa-platform',
|
|
27
|
+
textContent: PLATFORM_DETECTION_SCRIPT,
|
|
28
|
+
}],
|
|
29
|
+
})
|
|
30
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { extname } from 'node:path'
|
|
3
|
+
import { dedent, findSourceRegion, isAnyRegionMarker } from './source-region'
|
|
4
|
+
|
|
5
|
+
/** `{1,3-5}` line numbers to highlight, the first part inside the braces. */
|
|
6
|
+
const HIGHLIGHT_RE = /^\d+(?:[,-]\d+)*$/
|
|
7
|
+
/** `#region` at the end of the path. */
|
|
8
|
+
const REGION_RE = /#([\w-]+)$/
|
|
9
|
+
|
|
10
|
+
export interface CodeSnippetRequest {
|
|
11
|
+
path: string
|
|
12
|
+
region?: string
|
|
13
|
+
highlight?: string
|
|
14
|
+
lang?: string
|
|
15
|
+
attrs?: string
|
|
16
|
+
title?: string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Splits the text after `<<<`, written as `path#region{lines lang attrs} [title]`:
|
|
21
|
+
*
|
|
22
|
+
* - `path`: the file to show, relative to the page or `@/` for srcDir.
|
|
23
|
+
* - `#region`: only the lines between the region markers.
|
|
24
|
+
* - `{1,3-5 ts:line-numbers}`: lines to highlight, then optionally a language
|
|
25
|
+
* and extra fence attributes.
|
|
26
|
+
* - `[title]`: the tab label inside a code group, the file name by default.
|
|
27
|
+
*/
|
|
28
|
+
export function parseCodeSnippet(rawPath: string): CodeSnippetRequest | undefined {
|
|
29
|
+
let rest = rawPath.trim()
|
|
30
|
+
const request: Omit<CodeSnippetRequest, 'path'> = {}
|
|
31
|
+
|
|
32
|
+
if (rest.endsWith(']') && rest.includes('[')) {
|
|
33
|
+
const open = rest.lastIndexOf('[')
|
|
34
|
+
const title = rest.slice(open + 1, -1).trim()
|
|
35
|
+
if (title) {
|
|
36
|
+
request.title = title
|
|
37
|
+
}
|
|
38
|
+
rest = rest.slice(0, open).trimEnd()
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (rest.endsWith('}') && rest.includes('{')) {
|
|
42
|
+
const open = rest.lastIndexOf('{')
|
|
43
|
+
const parts = rest.slice(open + 1, -1).trim().split(/\s+/).filter(Boolean)
|
|
44
|
+
if (parts[0] && HIGHLIGHT_RE.test(parts[0])) {
|
|
45
|
+
request.highlight = parts.shift()
|
|
46
|
+
}
|
|
47
|
+
if (parts.length > 2) {
|
|
48
|
+
return
|
|
49
|
+
}
|
|
50
|
+
const [lang, attrs] = parts
|
|
51
|
+
if (lang) {
|
|
52
|
+
request.lang = lang
|
|
53
|
+
}
|
|
54
|
+
if (attrs) {
|
|
55
|
+
request.attrs = attrs
|
|
56
|
+
}
|
|
57
|
+
rest = rest.slice(0, open).trimEnd()
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const region = REGION_RE.exec(rest)
|
|
61
|
+
if (region) {
|
|
62
|
+
request.region = region[1]
|
|
63
|
+
rest = rest.slice(0, region.index)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const path = rest.trim()
|
|
67
|
+
return path ? { path, ...request } : undefined
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Reads the snippet file and writes it as a fenced code block, so every later
|
|
72
|
+
* step, from highlighting to the search index, sees an ordinary code block.
|
|
73
|
+
*/
|
|
74
|
+
export function renderCodeSnippet(
|
|
75
|
+
request: CodeSnippetRequest,
|
|
76
|
+
file: string,
|
|
77
|
+
): string[] {
|
|
78
|
+
const code = readSnippetCode(file, request.region)
|
|
79
|
+
const lang = request.lang ?? extname(file).slice(1)
|
|
80
|
+
const title = request.title ?? file.split(/[/\\]/).pop() ?? ''
|
|
81
|
+
const info = [
|
|
82
|
+
lang,
|
|
83
|
+
request.highlight ? `{${request.highlight}}` : '',
|
|
84
|
+
request.attrs ?? '',
|
|
85
|
+
title ? `[${title}]` : '',
|
|
86
|
+
].filter(Boolean).join(' ')
|
|
87
|
+
const fence = '`'.repeat(Math.max(3, longestBacktickRun(code) + 1))
|
|
88
|
+
|
|
89
|
+
return [`${fence}${info}`, ...code.split('\n'), fence]
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function readSnippetCode(file: string, regionName: string | undefined): string {
|
|
93
|
+
const content = readFileSync(file, 'utf8').replace(/\r\n?/g, '\n').replace(/\n$/, '')
|
|
94
|
+
if (!regionName) {
|
|
95
|
+
return content
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const lines = content.split('\n')
|
|
99
|
+
const region = findSourceRegion(lines, regionName)
|
|
100
|
+
if (!region) {
|
|
101
|
+
throw new Error(`region ${JSON.stringify(regionName)} does not exist in ${JSON.stringify(file)}`)
|
|
102
|
+
}
|
|
103
|
+
return dedent(lines
|
|
104
|
+
.slice(region.start, region.end)
|
|
105
|
+
.filter(line => !isAnyRegionMarker(line, region.marker))
|
|
106
|
+
.join('\n'))
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function longestBacktickRun(code: string): number {
|
|
110
|
+
return Math.max(0, ...(code.match(/`+/g) ?? []).map(run => run.length))
|
|
111
|
+
}
|
|
@@ -8,7 +8,7 @@ import type {
|
|
|
8
8
|
ContentLoaderSpecification,
|
|
9
9
|
} from '../api/data'
|
|
10
10
|
import type { InternalDataLoaderContext } from '../generator/data/context'
|
|
11
|
-
import {
|
|
11
|
+
import { stat } from 'node:fs/promises'
|
|
12
12
|
import { isAbsolute, relative, sep } from 'node:path'
|
|
13
13
|
import matter from 'gray-matter'
|
|
14
14
|
import { normalizePath } from 'vite'
|
|
@@ -16,6 +16,8 @@ import { normalizeFrontmatterSource } from '../core/frontmatter'
|
|
|
16
16
|
import { markdownPagePathToRoutePath } from '../core/markdown-route'
|
|
17
17
|
import { findDataLoaderFiles, normalizeDataLoaderGlob } from '../generator/data/glob'
|
|
18
18
|
import { createMarkdownCompiler } from './markdown'
|
|
19
|
+
import { readMarkdownSource } from './markdown-source'
|
|
20
|
+
import { resolvePagePathRewriter } from './page-path'
|
|
19
21
|
|
|
20
22
|
interface CachedContent {
|
|
21
23
|
data: ContentData
|
|
@@ -81,9 +83,11 @@ async function loadContentFile(
|
|
|
81
83
|
}
|
|
82
84
|
|
|
83
85
|
try {
|
|
84
|
-
const src =
|
|
86
|
+
const { source: src } = readMarkdownSource({ file, sourceRoot: context.srcDir })
|
|
85
87
|
const parsed = parseContentSource(src, options.excerpt)
|
|
86
|
-
const sourcePath =
|
|
88
|
+
const sourcePath = resolvePagePathRewriter(context.rewrites)(
|
|
89
|
+
contentFileToSourcePath(file, context.srcDir),
|
|
90
|
+
)
|
|
87
91
|
const url = markdownPagePathToRoutePath(sourcePath)
|
|
88
92
|
const data: ContentData = {
|
|
89
93
|
url,
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { dirname, isAbsolute, join, resolve } from 'node:path'
|
|
3
|
+
import matter from 'gray-matter'
|
|
4
|
+
import { normalizeFrontmatterSource } from '../core/frontmatter'
|
|
5
|
+
import { parseCodeSnippet, renderCodeSnippet } from './code-snippet'
|
|
6
|
+
import { findSourceRegion } from './source-region'
|
|
7
|
+
|
|
8
|
+
/** `<!--@include: path-->`, with an optional `#region` and `{start,end}` range. */
|
|
9
|
+
const INCLUDE_RE = /<!--\s*@include:([^>]*)-->/g
|
|
10
|
+
/** `{start,end}` line range and `#region` at the end of an include target. */
|
|
11
|
+
const INCLUDE_RANGE_RE = /\{(\d*),(\d*)\}$/
|
|
12
|
+
const INCLUDE_REGION_RE = /#([\w-]+)$/
|
|
13
|
+
/** `<<< path`, alone on its line. */
|
|
14
|
+
const SNIPPET_LINE_RE = /^(\s*)<<<(.*)$/
|
|
15
|
+
/** Opening or closing line of a fenced code block. */
|
|
16
|
+
const FENCE_RE = /^ {0,3}(`{3,}|~{3,})/
|
|
17
|
+
|
|
18
|
+
/** Where the Markdown being expanded comes from. */
|
|
19
|
+
export interface MarkdownSourceLocation {
|
|
20
|
+
/** Absolute path of the Markdown file. */
|
|
21
|
+
file: string
|
|
22
|
+
/** Absolute source directory, which `@/` paths start from. */
|
|
23
|
+
sourceRoot: string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface ExpandedMarkdownSource {
|
|
27
|
+
/** The page source with every include and snippet written out. */
|
|
28
|
+
source: string
|
|
29
|
+
/** Absolute paths of every file the expanded source was read from, the page excluded. */
|
|
30
|
+
dependencies: string[]
|
|
31
|
+
/**
|
|
32
|
+
* For each line of `source`, the 1-based line of the page file it comes
|
|
33
|
+
* from. Lines written by an include or a snippet point at that directive.
|
|
34
|
+
*/
|
|
35
|
+
lineOrigins: number[]
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Writes out `<!--@include: ...-->` and `<<< ...` in a page source, so every
|
|
40
|
+
* reader of the page, from the compiler to the search index, sees the same
|
|
41
|
+
* Markdown. Directives inside fenced code blocks stay as they are written,
|
|
42
|
+
* which lets a page show the syntax itself.
|
|
43
|
+
*/
|
|
44
|
+
export function expandMarkdownSource(
|
|
45
|
+
source: string,
|
|
46
|
+
location: MarkdownSourceLocation,
|
|
47
|
+
): ExpandedMarkdownSource {
|
|
48
|
+
const dependencies = new Set<string>()
|
|
49
|
+
const lines = expandLines(source, location, dependencies, [location.file])
|
|
50
|
+
return {
|
|
51
|
+
source: lines.map(line => line.text).join('\n'),
|
|
52
|
+
dependencies: [...dependencies],
|
|
53
|
+
lineOrigins: lines.map(line => line.origin),
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Reads a Markdown page and expands its includes and snippets. */
|
|
58
|
+
export function readMarkdownSource(location: MarkdownSourceLocation): ExpandedMarkdownSource {
|
|
59
|
+
return expandMarkdownSource(readFileSync(location.file, 'utf8'), location)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
interface ExpandedLine {
|
|
63
|
+
text: string
|
|
64
|
+
/** 1-based line of the top-level file this line comes from. */
|
|
65
|
+
origin: number
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function expandLines(
|
|
69
|
+
source: string,
|
|
70
|
+
location: MarkdownSourceLocation,
|
|
71
|
+
dependencies: Set<string>,
|
|
72
|
+
stack: readonly string[],
|
|
73
|
+
): ExpandedLine[] {
|
|
74
|
+
const output: ExpandedLine[] = []
|
|
75
|
+
let fence: string | undefined
|
|
76
|
+
|
|
77
|
+
for (const [index, text] of source.split(/\r?\n/).entries()) {
|
|
78
|
+
const origin = index + 1
|
|
79
|
+
const fenceMarker = FENCE_RE.exec(text)?.[1]
|
|
80
|
+
if (fence) {
|
|
81
|
+
if (fenceMarker && fenceMarker[0] === fence[0] && fenceMarker.length >= fence.length && !text.trim().slice(fenceMarker.length).trim()) {
|
|
82
|
+
fence = undefined
|
|
83
|
+
}
|
|
84
|
+
output.push({ text, origin })
|
|
85
|
+
continue
|
|
86
|
+
}
|
|
87
|
+
if (fenceMarker) {
|
|
88
|
+
fence = fenceMarker
|
|
89
|
+
output.push({ text, origin })
|
|
90
|
+
continue
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const at = `${location.file}:${origin}`
|
|
94
|
+
const expanded = expandSnippetLine(text, location, dependencies, at)
|
|
95
|
+
?? expandIncludes(text, location, dependencies, stack, at)
|
|
96
|
+
output.push(...expanded.map(line => ({ text: line, origin })))
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return output
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function expandSnippetLine(
|
|
103
|
+
text: string,
|
|
104
|
+
location: MarkdownSourceLocation,
|
|
105
|
+
dependencies: Set<string>,
|
|
106
|
+
at: string,
|
|
107
|
+
): string[] | undefined {
|
|
108
|
+
const match = SNIPPET_LINE_RE.exec(text)
|
|
109
|
+
const rawPath = match?.[2]?.trim()
|
|
110
|
+
if (!match || !rawPath) {
|
|
111
|
+
return
|
|
112
|
+
}
|
|
113
|
+
const indent = match[1]
|
|
114
|
+
const request = parseCodeSnippet(rawPath)
|
|
115
|
+
if (!request) {
|
|
116
|
+
throw new Error(`KawaPress: cannot read the code snippet "<<< ${rawPath}" at ${at}.`)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const file = resolveDirectivePath(request.path, location)
|
|
120
|
+
dependencies.add(file)
|
|
121
|
+
try {
|
|
122
|
+
return renderCodeSnippet(request, file).map(line => `${indent}${line}`)
|
|
123
|
+
}
|
|
124
|
+
catch (cause) {
|
|
125
|
+
throw new Error(`KawaPress: cannot import the code snippet "<<< ${rawPath}" at ${at}: ${describeError(cause)}.`, { cause })
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function expandIncludes(
|
|
130
|
+
text: string,
|
|
131
|
+
location: MarkdownSourceLocation,
|
|
132
|
+
dependencies: Set<string>,
|
|
133
|
+
stack: readonly string[],
|
|
134
|
+
at: string,
|
|
135
|
+
): string[] {
|
|
136
|
+
if (!text.includes('@include')) {
|
|
137
|
+
return [text]
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const directiveOnly = text.trim().replace(INCLUDE_RE, '') === ''
|
|
141
|
+
const indent = directiveOnly ? /^\s*/.exec(text)![0] : ''
|
|
142
|
+
const replaced = text.replace(INCLUDE_RE, (directive, rawTarget: string) => {
|
|
143
|
+
const target = rawTarget.trim()
|
|
144
|
+
if (!target) {
|
|
145
|
+
return directive
|
|
146
|
+
}
|
|
147
|
+
const included = readInclude(target, location, dependencies, stack, at)
|
|
148
|
+
return indent ? included.split('\n').join(`\n${indent}`) : included
|
|
149
|
+
})
|
|
150
|
+
return replaced.split('\n')
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function readInclude(
|
|
154
|
+
target: string,
|
|
155
|
+
location: MarkdownSourceLocation,
|
|
156
|
+
dependencies: Set<string>,
|
|
157
|
+
stack: readonly string[],
|
|
158
|
+
at: string,
|
|
159
|
+
): string {
|
|
160
|
+
const { path, region, start, end } = parseIncludeTarget(target)
|
|
161
|
+
const file = resolveDirectivePath(path.trim(), location)
|
|
162
|
+
if (stack.includes(file)) {
|
|
163
|
+
throw new Error(`KawaPress: "<!--@include: ${target}-->" at ${at} includes itself through ${stack.map(entry => JSON.stringify(entry)).join(' -> ')}.`)
|
|
164
|
+
}
|
|
165
|
+
dependencies.add(file)
|
|
166
|
+
|
|
167
|
+
let content: string
|
|
168
|
+
try {
|
|
169
|
+
content = readFileSync(file, 'utf8').replace(/\r\n?/g, '\n')
|
|
170
|
+
}
|
|
171
|
+
catch (cause) {
|
|
172
|
+
throw new Error(`KawaPress: "<!--@include: ${target}-->" at ${at} points at a file that cannot be read: ${describeError(cause)}.`, { cause })
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const hasPart = Boolean(region || start || end)
|
|
176
|
+
if (region) {
|
|
177
|
+
content = readRegion(content, region, target, at)
|
|
178
|
+
}
|
|
179
|
+
if (start || end) {
|
|
180
|
+
content = content
|
|
181
|
+
.split('\n')
|
|
182
|
+
.slice(start ? Number(start) - 1 : undefined, end ? Number(end) : undefined)
|
|
183
|
+
.join('\n')
|
|
184
|
+
}
|
|
185
|
+
if (!hasPart && file.endsWith('.md')) {
|
|
186
|
+
content = matter(normalizeFrontmatterSource(content)).content
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const nested = expandLines(
|
|
190
|
+
content.replace(/\n$/, ''),
|
|
191
|
+
{ file, sourceRoot: location.sourceRoot },
|
|
192
|
+
dependencies,
|
|
193
|
+
[...stack, file],
|
|
194
|
+
)
|
|
195
|
+
return nested.map(line => line.text).join('\n')
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function readRegion(content: string, name: string, target: string, at: string): string {
|
|
199
|
+
const lines = content.split('\n')
|
|
200
|
+
const region = findSourceRegion(lines, name)
|
|
201
|
+
if (!region) {
|
|
202
|
+
throw new Error(`KawaPress: "<!--@include: ${target}-->" at ${at} names region ${JSON.stringify(name)}, which the file does not have.`)
|
|
203
|
+
}
|
|
204
|
+
return lines.slice(region.start, region.end).join('\n')
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* A directive path is relative to the file that holds it. `@/` starts at the
|
|
209
|
+
* source directory instead, so shared files can be named the same way from
|
|
210
|
+
* every page.
|
|
211
|
+
*/
|
|
212
|
+
function resolveDirectivePath(path: string, location: MarkdownSourceLocation): string {
|
|
213
|
+
if (path.startsWith('@')) {
|
|
214
|
+
return join(location.sourceRoot, path.replace(/^@\/?/, ''))
|
|
215
|
+
}
|
|
216
|
+
return isAbsolute(path) ? path : resolve(dirname(location.file), path)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function describeError(error: unknown): string {
|
|
220
|
+
return error instanceof Error ? error.message : String(error)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Splits an include target written as `path#region{start,end}`. */
|
|
224
|
+
function parseIncludeTarget(target: string): {
|
|
225
|
+
path: string
|
|
226
|
+
region?: string | undefined
|
|
227
|
+
start?: string | undefined
|
|
228
|
+
end?: string | undefined
|
|
229
|
+
} {
|
|
230
|
+
let path = target
|
|
231
|
+
const range = INCLUDE_RANGE_RE.exec(path)
|
|
232
|
+
if (range) {
|
|
233
|
+
path = path.slice(0, range.index)
|
|
234
|
+
}
|
|
235
|
+
const region = INCLUDE_REGION_RE.exec(path)
|
|
236
|
+
if (region) {
|
|
237
|
+
path = path.slice(0, region.index)
|
|
238
|
+
}
|
|
239
|
+
return { path, region: region?.[1], start: range?.[1], end: range?.[2] }
|
|
240
|
+
}
|
package/src/compiler/markdown.ts
CHANGED
|
@@ -339,16 +339,22 @@ export interface ParsedMarkdown {
|
|
|
339
339
|
pageData: PageData
|
|
340
340
|
}
|
|
341
341
|
|
|
342
|
+
/**
|
|
343
|
+
* Compiles one page. `lineOrigins` maps each line of `src` to the line of the
|
|
344
|
+
* page file it was written on, when includes and snippets were expanded into
|
|
345
|
+
* `src`, so link warnings name the line the author can open.
|
|
346
|
+
*/
|
|
342
347
|
export async function parseMarkdown(
|
|
343
348
|
md: MarkdownExit,
|
|
344
349
|
src: string,
|
|
345
350
|
path: string,
|
|
346
351
|
sourcePath?: string,
|
|
352
|
+
lineOrigins?: readonly number[],
|
|
347
353
|
): Promise<ParsedMarkdown> {
|
|
348
354
|
const env: MarkdownEnv = { path, sourcePath, links: [], headings: [] }
|
|
349
355
|
const html = await md.renderAsync(src, env)
|
|
350
356
|
|
|
351
|
-
env.links = shiftLinksToSourceLines(src, env)
|
|
357
|
+
env.links = shiftLinksToSourceLines(src, env, lineOrigins)
|
|
352
358
|
const frontmatter = env.frontmatter ?? {}
|
|
353
359
|
const headers = env.headers ?? []
|
|
354
360
|
const metadata = resolvePageMetadata(frontmatter, headers)
|
|
@@ -370,9 +376,16 @@ export async function parseMarkdown(
|
|
|
370
376
|
* Token line numbers start at the page body, so frontmatter lines are added back
|
|
371
377
|
* to report the line the author sees in the Markdown file.
|
|
372
378
|
*/
|
|
373
|
-
function shiftLinksToSourceLines(
|
|
379
|
+
function shiftLinksToSourceLines(
|
|
380
|
+
src: string,
|
|
381
|
+
env: MarkdownEnv,
|
|
382
|
+
lineOrigins: readonly number[] | undefined,
|
|
383
|
+
): LinkRecord[] {
|
|
374
384
|
const offset = countRemovedLines(src, env.content)
|
|
375
|
-
return (env.links ?? []).map(link =>
|
|
385
|
+
return (env.links ?? []).map((link) => {
|
|
386
|
+
const line = link.line + offset
|
|
387
|
+
return { ...link, line: lineOrigins?.[line - 1] ?? line }
|
|
388
|
+
})
|
|
376
389
|
}
|
|
377
390
|
|
|
378
391
|
function countRemovedLines(source: string, body: string | undefined): number {
|
|
@@ -1,28 +1,43 @@
|
|
|
1
|
+
import type { PageRewrites } from '../core/site'
|
|
1
2
|
import type { GeneratorPluginRunner } from '../plugin/generator-runner'
|
|
2
3
|
import type { LinkRegistry } from './link-registry'
|
|
3
4
|
import type { ParsedMarkdown } from './markdown'
|
|
4
|
-
import {
|
|
5
|
+
import { resolve } from 'node:path'
|
|
5
6
|
import { markdownPagePathToRoutePath } from '../core/markdown-route'
|
|
6
7
|
import { assertPageDataSerializable } from '../core/site'
|
|
7
8
|
import { createLinkRegistry } from './link-registry'
|
|
8
9
|
import { createMarkdownCompiler, parseMarkdown } from './markdown'
|
|
10
|
+
import { expandMarkdownSource } from './markdown-source'
|
|
11
|
+
import { markdownFileToSourcePath, resolvePagePathRewriter } from './page-path'
|
|
9
12
|
|
|
10
13
|
interface CachedPage {
|
|
11
14
|
source: string
|
|
12
|
-
parsed: Promise<
|
|
15
|
+
parsed: Promise<LoadedMarkdownPage>
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface LoadedMarkdownPage extends ParsedMarkdown {
|
|
19
|
+
/** Files the page reads through `<!--@include-->` and `<<<`, as absolute paths. */
|
|
20
|
+
dependencies: string[]
|
|
13
21
|
}
|
|
14
22
|
|
|
15
23
|
export interface MarkdownPageLoader {
|
|
16
24
|
sourceRoot: string
|
|
25
|
+
/** Glob patterns, relative to `sourceRoot`, of Markdown files that are not pages. */
|
|
26
|
+
srcExclude: readonly string[]
|
|
27
|
+
/** `rewrites` of the site config, which moves pages to other routes. */
|
|
28
|
+
rewrites: PageRewrites | undefined
|
|
17
29
|
/** Links and heading IDs of every page loaded so far. */
|
|
18
30
|
registry: LinkRegistry
|
|
19
|
-
|
|
31
|
+
/** Compiles the page whose file holds `source`, as written on disk. */
|
|
32
|
+
load: (source: string, file: string) => Promise<LoadedMarkdownPage>
|
|
20
33
|
}
|
|
21
34
|
|
|
22
35
|
export interface MarkdownPageLoaderOptions {
|
|
23
36
|
root: string
|
|
24
37
|
base: string
|
|
25
38
|
srcDir: string
|
|
39
|
+
srcExclude?: readonly string[]
|
|
40
|
+
rewrites?: PageRewrites | undefined
|
|
26
41
|
pluginRunner: GeneratorPluginRunner
|
|
27
42
|
}
|
|
28
43
|
|
|
@@ -36,11 +51,24 @@ export function createMarkdownPageLoader(
|
|
|
36
51
|
pluginRunner: options.pluginRunner,
|
|
37
52
|
})
|
|
38
53
|
const cache = new Map<string, CachedPage>()
|
|
54
|
+
const rewrite = resolvePagePathRewriter(options.rewrites)
|
|
39
55
|
|
|
40
56
|
return {
|
|
41
57
|
sourceRoot,
|
|
58
|
+
srcExclude: options.srcExclude ?? [],
|
|
59
|
+
rewrites: options.rewrites,
|
|
42
60
|
registry,
|
|
43
|
-
load(
|
|
61
|
+
load(rawSource, file) {
|
|
62
|
+
// Expanding first makes an edit to an included file a new page source,
|
|
63
|
+
// so the cache can never return a page built from an older include.
|
|
64
|
+
let expanded: ReturnType<typeof expandMarkdownSource>
|
|
65
|
+
try {
|
|
66
|
+
expanded = expandMarkdownSource(rawSource, { file, sourceRoot })
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
return Promise.reject(error)
|
|
70
|
+
}
|
|
71
|
+
const { source, dependencies, lineOrigins } = expanded
|
|
44
72
|
const cached = cache.get(file)
|
|
45
73
|
if (cached?.source === source) {
|
|
46
74
|
return cached.parsed
|
|
@@ -48,12 +76,16 @@ export function createMarkdownPageLoader(
|
|
|
48
76
|
|
|
49
77
|
const parsed = mdPromise.then(async (md) => {
|
|
50
78
|
const sourcePath = markdownFileToSourcePath(file, sourceRoot)
|
|
51
|
-
const
|
|
79
|
+
const pagePath = rewrite(sourcePath)
|
|
80
|
+
const routePath = markdownPagePathToRoutePath(pagePath)
|
|
81
|
+
// Relative links start from where the page is served, so a page moved
|
|
82
|
+
// by rewrites links as if its file were at the new path.
|
|
52
83
|
const result = await parseMarkdown(
|
|
53
84
|
md,
|
|
54
85
|
source,
|
|
55
86
|
routePath,
|
|
56
|
-
|
|
87
|
+
pagePath,
|
|
88
|
+
lineOrigins,
|
|
57
89
|
)
|
|
58
90
|
registry.set({
|
|
59
91
|
route: routePath,
|
|
@@ -68,18 +100,14 @@ export function createMarkdownPageLoader(
|
|
|
68
100
|
source,
|
|
69
101
|
file,
|
|
70
102
|
sourcePath,
|
|
103
|
+
pagePath,
|
|
71
104
|
routePath,
|
|
72
105
|
pageData: result.pageData,
|
|
73
106
|
})
|
|
74
|
-
return result
|
|
107
|
+
return { ...result, dependencies }
|
|
75
108
|
})
|
|
76
109
|
cache.set(file, { source, parsed })
|
|
77
110
|
return parsed
|
|
78
111
|
},
|
|
79
112
|
}
|
|
80
113
|
}
|
|
81
|
-
|
|
82
|
-
/** Path of a Markdown file relative to srcDir, for example `/guide/intro.md`. */
|
|
83
|
-
export function markdownFileToSourcePath(file: string, sourceRoot: string): string {
|
|
84
|
-
return `/${relative(sourceRoot, file).split(sep).join('/')}`
|
|
85
|
-
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import type { PageRewrites } from '../core/site'
|
|
2
|
+
import { relative, resolve, sep } from 'node:path'
|
|
3
|
+
import { compile, match } from 'path-to-regexp'
|
|
4
|
+
import { markdownPagePathToRoutePath } from '../core/markdown-route'
|
|
5
|
+
|
|
6
|
+
/** Turns the source path of a page into the page path its route comes from. */
|
|
7
|
+
export type PagePathRewriter = (sourcePath: string) => string
|
|
8
|
+
|
|
9
|
+
const KEEP: PagePathRewriter = sourcePath => sourcePath
|
|
10
|
+
const rewriters = new WeakMap<object, PagePathRewriter>()
|
|
11
|
+
|
|
12
|
+
/** Path of a Markdown file relative to srcDir, for example `/guide/intro.md`. */
|
|
13
|
+
export function markdownFileToSourcePath(file: string, sourceRoot: string): string {
|
|
14
|
+
return `/${relative(sourceRoot, file).split(sep).join('/')}`
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Page path of a Markdown file: its source path after `rewrites`, for example
|
|
19
|
+
* `/a/intro.md` for `packages/a/src/intro.md` and the rule
|
|
20
|
+
* `'packages/:pkg/src/:page*': ':pkg/:page*'`. Without rewrites it is the
|
|
21
|
+
* source path. The route of the page and its relative links both start here.
|
|
22
|
+
*/
|
|
23
|
+
export function markdownFileToPagePath(
|
|
24
|
+
file: string,
|
|
25
|
+
sourceRoot: string,
|
|
26
|
+
rewrites?: PageRewrites,
|
|
27
|
+
): string {
|
|
28
|
+
return resolvePagePathRewriter(rewrites)(markdownFileToSourcePath(file, resolve(sourceRoot)))
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Public route of a Markdown file, after `rewrites`. */
|
|
32
|
+
export function markdownFileToRoutePath(
|
|
33
|
+
file: string,
|
|
34
|
+
sourceRoot: string,
|
|
35
|
+
rewrites?: PageRewrites,
|
|
36
|
+
): string {
|
|
37
|
+
return markdownPagePathToRoutePath(markdownFileToPagePath(file, sourceRoot, rewrites))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The rewriter of a `rewrites` value, compiled once per value.
|
|
42
|
+
*
|
|
43
|
+
* Paths are matched the way `rewrites` is written: relative to srcDir, without
|
|
44
|
+
* the leading slash. A function returns the new path, or nothing to keep the
|
|
45
|
+
* page where it is. Rules of an object are tried in order and the first match
|
|
46
|
+
* wins; a rule starting with `^` is a regular expression. Rules use the
|
|
47
|
+
* `path-to-regexp` 6 syntax, the same as VitePress.
|
|
48
|
+
*/
|
|
49
|
+
export function resolvePagePathRewriter(rewrites: PageRewrites | undefined): PagePathRewriter {
|
|
50
|
+
if (!rewrites) {
|
|
51
|
+
return KEEP
|
|
52
|
+
}
|
|
53
|
+
let rewriter = rewriters.get(rewrites)
|
|
54
|
+
if (!rewriter) {
|
|
55
|
+
rewriter = typeof rewrites === 'function'
|
|
56
|
+
? fromFunction(rewrites)
|
|
57
|
+
: fromRules(rewrites)
|
|
58
|
+
rewriters.set(rewrites, rewriter)
|
|
59
|
+
}
|
|
60
|
+
return rewriter
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function fromFunction(rewrite: (id: string) => string | undefined): PagePathRewriter {
|
|
64
|
+
return (sourcePath) => {
|
|
65
|
+
const destination = rewrite(sourcePath.slice(1))
|
|
66
|
+
return destination ? toPagePath(destination) : sourcePath
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function fromRules(rules: Record<string, string>): PagePathRewriter {
|
|
71
|
+
const compiled = Object.entries(rules).map(([from, to]) => ({
|
|
72
|
+
matches: match(from.startsWith('^') ? new RegExp(from) : from),
|
|
73
|
+
toPath: compile(`/${to}`, { validate: false }),
|
|
74
|
+
}))
|
|
75
|
+
if (compiled.length === 0) {
|
|
76
|
+
return KEEP
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return (sourcePath) => {
|
|
80
|
+
const id = sourcePath.slice(1)
|
|
81
|
+
for (const { matches, toPath } of compiled) {
|
|
82
|
+
const result = matches(id)
|
|
83
|
+
if (result) {
|
|
84
|
+
return toPagePath(toPath(result.params))
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return sourcePath
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function toPagePath(path: string): string {
|
|
92
|
+
return `/${path.replace(/^\/+/, '')}`
|
|
93
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Region markers that mark part of a file for `<<<` and `<!--@include-->`. A
|
|
3
|
+
* region starts with a `region <name>` comment and ends with the matching
|
|
4
|
+
* `endregion <name>` comment, written in the comment syntax of the language.
|
|
5
|
+
*/
|
|
6
|
+
const REGION_MARKERS: readonly RegExp[] = [
|
|
7
|
+
// JavaScript, TypeScript, Java, Go, Rust
|
|
8
|
+
/^\/\/ ?#?((?:end)?region) ([\w*-]+)$/,
|
|
9
|
+
// CSS, Less, SCSS
|
|
10
|
+
/^\/\* ?#((?:end)?region) ([\w*-]+) ?\*\/$/,
|
|
11
|
+
// C, C++
|
|
12
|
+
/^#pragma ((?:end)?region) ([\w*-]+)$/,
|
|
13
|
+
// HTML, Markdown, Vue templates
|
|
14
|
+
/^<!-- #?((?:end)?region) ([\w*-]+) -->$/,
|
|
15
|
+
// Visual Basic
|
|
16
|
+
/^#((?:End )?Region) ([\w*-]+)$/,
|
|
17
|
+
// Batch
|
|
18
|
+
/^::#((?:end)?region) ([\w*-]+)$/,
|
|
19
|
+
// Python, shell, YAML, PHP, C#, PowerShell
|
|
20
|
+
/^# ?((?:end)?region) ([\w*-]+)$/,
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
export interface SourceRegion {
|
|
24
|
+
/** Index of the first line inside the region. */
|
|
25
|
+
start: number
|
|
26
|
+
/** Index of the line holding the end marker. */
|
|
27
|
+
end: number
|
|
28
|
+
/** Marker syntax of this region, used to drop nested markers. */
|
|
29
|
+
marker: RegExp
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The first region called `name`, or `undefined` when the file has none. */
|
|
33
|
+
export function findSourceRegion(
|
|
34
|
+
lines: readonly string[],
|
|
35
|
+
name: string,
|
|
36
|
+
): SourceRegion | undefined {
|
|
37
|
+
let marker: RegExp | undefined
|
|
38
|
+
let start = -1
|
|
39
|
+
|
|
40
|
+
for (const [index, line] of lines.entries()) {
|
|
41
|
+
if (!marker) {
|
|
42
|
+
marker = REGION_MARKERS.find(candidate => isRegionMarker(line, candidate, name, false))
|
|
43
|
+
start = index + 1
|
|
44
|
+
}
|
|
45
|
+
else if (isRegionMarker(line, marker, name, true)) {
|
|
46
|
+
return { start, end: index, marker }
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Whether `line` is any region marker written in the syntax of `marker`. */
|
|
52
|
+
export function isAnyRegionMarker(line: string, marker: RegExp): boolean {
|
|
53
|
+
return marker.test(line.trim())
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function isRegionMarker(
|
|
57
|
+
line: string,
|
|
58
|
+
marker: RegExp,
|
|
59
|
+
name: string,
|
|
60
|
+
end: boolean,
|
|
61
|
+
): boolean {
|
|
62
|
+
const [, tag, markerName] = marker.exec(line.trim()) ?? []
|
|
63
|
+
if (!tag || markerName !== name) {
|
|
64
|
+
return false
|
|
65
|
+
}
|
|
66
|
+
return end ? /^end ?region$/i.test(tag) : /^region$/i.test(tag)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Removes the indentation every non-blank line shares. */
|
|
70
|
+
export function dedent(text: string): string {
|
|
71
|
+
const lines = text.split('\n')
|
|
72
|
+
const indent = Math.min(...lines
|
|
73
|
+
.filter(line => line.trim())
|
|
74
|
+
.map(line => line.length - line.trimStart().length))
|
|
75
|
+
return Number.isFinite(indent) && indent > 0
|
|
76
|
+
? lines.map(line => line.slice(indent)).join('\n')
|
|
77
|
+
: text
|
|
78
|
+
}
|
package/src/core/head.ts
CHANGED
|
@@ -156,7 +156,7 @@ function resolveHeadAttrs(
|
|
|
156
156
|
return attrs
|
|
157
157
|
}
|
|
158
158
|
|
|
159
|
-
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
159
|
+
export function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
160
160
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
161
161
|
return false
|
|
162
162
|
}
|
|
@@ -14,16 +14,20 @@ const FORMATTING_MARKUP_TYPES = new Set([
|
|
|
14
14
|
's_close',
|
|
15
15
|
'link_open',
|
|
16
16
|
'link_close',
|
|
17
|
+
// Inline HTML is markup around text, like `<kbd>Ctrl</kbd>`, or a component
|
|
18
|
+
// such as `<Badge text="beta" />` that only decorates the heading.
|
|
19
|
+
'html_inline',
|
|
17
20
|
])
|
|
18
21
|
|
|
19
22
|
/**
|
|
20
23
|
* The plain-text title of a heading: the text its author wrote on the heading
|
|
21
|
-
* line, without the Markdown formatting markup.
|
|
24
|
+
* line, without the Markdown formatting markup and without HTML tags.
|
|
22
25
|
*
|
|
23
|
-
* Formatting markup
|
|
24
|
-
*
|
|
25
|
-
* keeps
|
|
26
|
-
*
|
|
26
|
+
* Formatting markup and HTML tags disappear while the text between them stays,
|
|
27
|
+
* so `<kbd>Ctrl</kbd>` reads `Ctrl` and `<Badge text="beta" />` reads nothing.
|
|
28
|
+
* Inline code keeps its content without the backticks, and any other syntax
|
|
29
|
+
* keeps the markup it was written with, so inline math stays `$E=mc^2$` and an
|
|
30
|
+
* emoji shortcode stays `:smile:`. A token
|
|
27
31
|
* type this function has never seen keeps its `content` too, so a Markdown
|
|
28
32
|
* plugin can never make heading text disappear, and the title of a page never
|
|
29
33
|
* depends on which plugins a site installed.
|
package/src/core/site.ts
CHANGED
|
@@ -14,10 +14,22 @@ export interface LocaleConfig {
|
|
|
14
14
|
themeConfig?: Partial<ThemeConfig>
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
+
/**
|
|
18
|
+
* Moves pages to other routes: rules from a source path pattern to a page
|
|
19
|
+
* path, or a function from the source path to the page path. Paths are
|
|
20
|
+
* relative to srcDir and keep their `.md` extension.
|
|
21
|
+
*/
|
|
22
|
+
export type PageRewrites
|
|
23
|
+
= | Record<string, string>
|
|
24
|
+
| ((id: string) => string | undefined)
|
|
25
|
+
|
|
17
26
|
export interface SiteConfig {
|
|
18
27
|
title?: string
|
|
19
28
|
base?: string
|
|
20
29
|
srcDir?: string
|
|
30
|
+
/** Glob patterns, relative to `srcDir`, of Markdown files that are not pages. */
|
|
31
|
+
srcExclude?: string[]
|
|
32
|
+
rewrites?: PageRewrites
|
|
21
33
|
publicDir?: string
|
|
22
34
|
head?: HeadConfig[]
|
|
23
35
|
themeConfig?: Partial<ThemeConfig>
|
package/src/generator/config.ts
CHANGED
|
@@ -2,17 +2,21 @@ import type { KawapressConfig } from '../api/config'
|
|
|
2
2
|
import type { KawaPressPlugin } from '../api/plugin'
|
|
3
3
|
import type { DeadLinkIgnore, ResolvedDeadLinkConfig } from '../core/dead-links'
|
|
4
4
|
import type { HeadConfig } from '../core/head'
|
|
5
|
-
import type { LocaleConfig, SiteConfig } from '../core/site'
|
|
5
|
+
import type { LocaleConfig, PageRewrites, SiteConfig } from '../core/site'
|
|
6
6
|
import type { GeneratorPluginRunner } from '../plugin/generator-runner'
|
|
7
7
|
import { isAbsolute } from 'node:path'
|
|
8
8
|
import { normalizeBase } from '../core/base'
|
|
9
|
-
import { resolveHeadConfig } from '../core/head'
|
|
9
|
+
import { isPlainObject, resolveHeadConfig } from '../core/head'
|
|
10
10
|
import { createGeneratorPluginRunner } from '../plugin/generator-runner'
|
|
11
11
|
|
|
12
12
|
export interface ResolvedSiteConfig {
|
|
13
13
|
title: string
|
|
14
14
|
base: string
|
|
15
15
|
srcDir: string
|
|
16
|
+
/** Glob patterns, relative to `srcDir`, of Markdown files that are not pages. */
|
|
17
|
+
srcExclude: string[]
|
|
18
|
+
/** `rewrites` of the site config; leaves every page at its file path when unset. */
|
|
19
|
+
rewrites: PageRewrites | undefined
|
|
16
20
|
publicDir: string
|
|
17
21
|
head: HeadConfig[]
|
|
18
22
|
themeConfig?: object
|
|
@@ -39,6 +43,8 @@ export async function resolveSiteConfig(
|
|
|
39
43
|
title: userConfig.title,
|
|
40
44
|
base: userConfig.base,
|
|
41
45
|
srcDir: userConfig.srcDir,
|
|
46
|
+
srcExclude: userConfig.srcExclude,
|
|
47
|
+
rewrites: userConfig.rewrites,
|
|
42
48
|
publicDir: userConfig.publicDir,
|
|
43
49
|
head: userConfig.head,
|
|
44
50
|
themeConfig: userConfig.themeConfig,
|
|
@@ -51,6 +57,8 @@ export async function resolveSiteConfig(
|
|
|
51
57
|
throw new Error(`KawaPress: srcDir must be relative to the site root, got ${JSON.stringify(srcDir)}`)
|
|
52
58
|
}
|
|
53
59
|
|
|
60
|
+
const srcExclude = resolveSrcExclude(site.srcExclude)
|
|
61
|
+
const rewrites = resolveRewrites(site.rewrites)
|
|
54
62
|
const publicDir = normalizePublicDir(site.publicDir ?? 'public')
|
|
55
63
|
const head = resolveHeadConfig(site.head, {
|
|
56
64
|
owner: 'the site config',
|
|
@@ -63,6 +71,8 @@ export async function resolveSiteConfig(
|
|
|
63
71
|
title: site.title ?? 'KawaPress',
|
|
64
72
|
base: normalizeBase(site.base),
|
|
65
73
|
srcDir,
|
|
74
|
+
srcExclude,
|
|
75
|
+
rewrites,
|
|
66
76
|
publicDir,
|
|
67
77
|
head,
|
|
68
78
|
themeConfig: site.themeConfig,
|
|
@@ -125,6 +135,44 @@ function describeValue(value: unknown): string {
|
|
|
125
135
|
return Array.isArray(value) ? 'an array' : typeof value
|
|
126
136
|
}
|
|
127
137
|
|
|
138
|
+
function resolveRewrites(rewrites: unknown): PageRewrites | undefined {
|
|
139
|
+
if (rewrites === undefined || typeof rewrites === 'function') {
|
|
140
|
+
return rewrites as PageRewrites | undefined
|
|
141
|
+
}
|
|
142
|
+
if (!isPlainObject(rewrites)) {
|
|
143
|
+
throw new TypeError(
|
|
144
|
+
`KawaPress: rewrites must be an object of path rules or a function, got ${describeValue(rewrites)} in kawapress.config.ts.`,
|
|
145
|
+
)
|
|
146
|
+
}
|
|
147
|
+
for (const [from, to] of Object.entries(rewrites)) {
|
|
148
|
+
if (typeof to !== 'string' || !to) {
|
|
149
|
+
throw new TypeError(
|
|
150
|
+
`KawaPress: rewrites[${JSON.stringify(from)}] must be a page path, got ${describeValue(to)} in kawapress.config.ts.`,
|
|
151
|
+
)
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return rewrites as Record<string, string>
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function resolveSrcExclude(srcExclude: unknown): string[] {
|
|
158
|
+
if (srcExclude === undefined) {
|
|
159
|
+
return []
|
|
160
|
+
}
|
|
161
|
+
if (!Array.isArray(srcExclude)) {
|
|
162
|
+
throw new TypeError(
|
|
163
|
+
`KawaPress: srcExclude must be an array of glob patterns, got ${describeValue(srcExclude)} in kawapress.config.ts.`,
|
|
164
|
+
)
|
|
165
|
+
}
|
|
166
|
+
return srcExclude.map((pattern, index) => {
|
|
167
|
+
if (typeof pattern !== 'string' || !pattern.trim() || isAbsolute(pattern)) {
|
|
168
|
+
throw new Error(
|
|
169
|
+
`KawaPress: srcExclude[${index}] must be a glob pattern relative to srcDir, got ${JSON.stringify(pattern)} in kawapress.config.ts.`,
|
|
170
|
+
)
|
|
171
|
+
}
|
|
172
|
+
return pattern
|
|
173
|
+
})
|
|
174
|
+
}
|
|
175
|
+
|
|
128
176
|
function normalizePublicDir(publicDir: string): string {
|
|
129
177
|
if (!publicDir.trim() || isAbsolute(publicDir)) {
|
|
130
178
|
throw new Error(
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { DataLoaderConfig } from '../../api/data'
|
|
2
|
-
import type { SiteData } from '../../core/site'
|
|
2
|
+
import type { PageRewrites, SiteData } from '../../core/site'
|
|
3
3
|
import type { GeneratorPluginRunner } from '../../plugin/generator-runner'
|
|
4
4
|
import type { ResolvedSiteConfig } from '../config'
|
|
5
5
|
import { resolve } from 'node:path'
|
|
@@ -8,6 +8,8 @@ const DATA_LOADER_CONTEXT = Symbol.for('kawapress.data-loader-context')
|
|
|
8
8
|
|
|
9
9
|
export interface InternalDataLoaderContext extends DataLoaderConfig {
|
|
10
10
|
readonly pluginRunner: GeneratorPluginRunner
|
|
11
|
+
/** `rewrites` of the site config, which gives content entries their public URL. */
|
|
12
|
+
readonly rewrites: PageRewrites | undefined
|
|
11
13
|
}
|
|
12
14
|
|
|
13
15
|
export function createDataLoaderContext(
|
|
@@ -32,6 +34,7 @@ export function createDataLoaderContext(
|
|
|
32
34
|
publicDir: resolve(srcDir, config.publicDir),
|
|
33
35
|
site,
|
|
34
36
|
pluginRunner: config.pluginRunner,
|
|
37
|
+
rewrites: config.rewrites,
|
|
35
38
|
}
|
|
36
39
|
}
|
|
37
40
|
|
package/src/generator/pages.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import type { Dirent } from 'node:fs'
|
|
2
|
+
import type { PageRewrites } from '../core/site'
|
|
2
3
|
import { readdir } from 'node:fs/promises'
|
|
3
4
|
import { isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
4
|
-
import
|
|
5
|
+
import picomatch from 'picomatch'
|
|
6
|
+
import { markdownFileToSourcePath, resolvePagePathRewriter } from '../compiler/page-path'
|
|
5
7
|
import { markdownPagePathToRoutePath } from '../core/markdown-route'
|
|
6
8
|
|
|
7
9
|
/** Directories that never hold pages: build output and installed packages. */
|
|
@@ -13,6 +15,11 @@ export interface MarkdownPage {
|
|
|
13
15
|
file: string
|
|
14
16
|
/** Path relative to the source root, for example `/guide/intro.md`. */
|
|
15
17
|
sourcePath: string
|
|
18
|
+
/**
|
|
19
|
+
* Source path after `rewrites`, for example `/intro.md`; the same as
|
|
20
|
+
* `sourcePath` when no rule moves the page.
|
|
21
|
+
*/
|
|
22
|
+
pagePath: string
|
|
16
23
|
/** Public route path of the page, for example `/guide/intro`. */
|
|
17
24
|
routePath: string
|
|
18
25
|
}
|
|
@@ -27,6 +34,13 @@ export interface MarkdownPageScope {
|
|
|
27
34
|
* the site has no public directory.
|
|
28
35
|
*/
|
|
29
36
|
publicDir?: string | undefined
|
|
37
|
+
/**
|
|
38
|
+
* Glob patterns, relative to `sourceRoot`, of Markdown files that are not
|
|
39
|
+
* pages, that is the resolved `srcExclude`. Leave it out to keep every file.
|
|
40
|
+
*/
|
|
41
|
+
exclude?: readonly string[] | undefined
|
|
42
|
+
/** `rewrites` of the site config, which moves pages to other routes. */
|
|
43
|
+
rewrites?: PageRewrites | undefined
|
|
30
44
|
}
|
|
31
45
|
|
|
32
46
|
/**
|
|
@@ -38,27 +52,52 @@ export async function listMarkdownPages(
|
|
|
38
52
|
scope: MarkdownPageScope,
|
|
39
53
|
): Promise<MarkdownPage[]> {
|
|
40
54
|
const sourceRoot = resolve(scope.sourceRoot)
|
|
55
|
+
const isExcluded = createExcludeMatcher(sourceRoot, scope.exclude)
|
|
56
|
+
const rewrite = resolvePagePathRewriter(scope.rewrites)
|
|
41
57
|
const files = await findMarkdownFiles(sourceRoot, resolvePublicDirectory(scope))
|
|
42
|
-
|
|
58
|
+
const pages = files.filter(file => !isExcluded(file)).map((file) => {
|
|
43
59
|
const sourcePath = markdownFileToSourcePath(file, sourceRoot)
|
|
44
|
-
|
|
60
|
+
const pagePath = rewrite(sourcePath)
|
|
61
|
+
return { file, sourcePath, pagePath, routePath: markdownPagePathToRoutePath(pagePath) }
|
|
45
62
|
})
|
|
63
|
+
assertUniqueRoutes(pages)
|
|
64
|
+
return pages
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Two files on one route would make one of them unreachable, so it is an error. */
|
|
68
|
+
function assertUniqueRoutes(pages: readonly MarkdownPage[]): void {
|
|
69
|
+
const owners = new Map<string, string>()
|
|
70
|
+
for (const page of pages) {
|
|
71
|
+
const owner = owners.get(page.routePath)
|
|
72
|
+
if (owner) {
|
|
73
|
+
throw new Error(
|
|
74
|
+
`KawaPress: ${JSON.stringify(owner)} and ${JSON.stringify(page.sourcePath)} both become the route ${JSON.stringify(page.routePath)}. Check rewrites in kawapress.config.ts.`,
|
|
75
|
+
)
|
|
76
|
+
}
|
|
77
|
+
owners.set(page.routePath, page.sourcePath)
|
|
78
|
+
}
|
|
46
79
|
}
|
|
47
80
|
|
|
48
81
|
/** Whether `file` is a page of this scope, without reading any directory. */
|
|
49
82
|
export function isMarkdownPage(file: string, scope: MarkdownPageScope): boolean {
|
|
50
|
-
|
|
83
|
+
const sourceRoot = resolve(scope.sourceRoot)
|
|
84
|
+
return isMarkdownPageFile(file, sourceRoot, resolvePublicDirectory(scope))
|
|
85
|
+
&& !createExcludeMatcher(sourceRoot, scope.exclude)(file)
|
|
51
86
|
}
|
|
52
87
|
|
|
53
88
|
/**
|
|
54
|
-
*
|
|
55
|
-
*
|
|
89
|
+
* Whether a file matches one of the exclude patterns. Patterns use the glob
|
|
90
|
+
* syntax of `picomatch` and are matched against the path below `sourceRoot`.
|
|
56
91
|
*/
|
|
57
|
-
|
|
58
|
-
file: string,
|
|
92
|
+
function createExcludeMatcher(
|
|
59
93
|
sourceRoot: string,
|
|
60
|
-
|
|
61
|
-
|
|
94
|
+
patterns: readonly string[] | undefined,
|
|
95
|
+
): (file: string) => boolean {
|
|
96
|
+
if (!patterns?.length) {
|
|
97
|
+
return () => false
|
|
98
|
+
}
|
|
99
|
+
const matches = picomatch([...patterns], { dot: true })
|
|
100
|
+
return file => matches(relative(sourceRoot, file).split(sep).join('/'))
|
|
62
101
|
}
|
|
63
102
|
|
|
64
103
|
async function findMarkdownFiles(
|
|
@@ -2,3 +2,11 @@ import { fileURLToPath } from 'node:url'
|
|
|
2
2
|
|
|
3
3
|
export const entryServerPath = fileURLToPath(new URL('../../client/entries/entry-server.ts', import.meta.url))
|
|
4
4
|
export const entryClientPath = fileURLToPath(new URL('../../client/entries/entry-client.ts', import.meta.url))
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Output directory and file name of the built server entry. The `.mjs`
|
|
8
|
+
* extension keeps it an ES module whatever the `type` of the site's
|
|
9
|
+
* `package.json` is.
|
|
10
|
+
*/
|
|
11
|
+
export const SERVER_OUT_DIR = 'dist/.server'
|
|
12
|
+
export const SERVER_ENTRY_FILE = 'entry-server.mjs'
|
|
@@ -2,9 +2,8 @@ import type { Plugin, ViteDevServer } from 'vite'
|
|
|
2
2
|
import type { MarkdownPageLoader } from '../../../compiler/page-loader'
|
|
3
3
|
import type { DeadLink, ResolvedDeadLinkConfig } from '../../../core/dead-links'
|
|
4
4
|
import type { PageRouteIndex } from './pages'
|
|
5
|
-
import {
|
|
5
|
+
import { markdownFileToRoutePath } from '../../../compiler/page-path'
|
|
6
6
|
import { findPageDeadLinks, formatDeadLink } from '../../../core/dead-links'
|
|
7
|
-
import { markdownPagePathToRoutePath } from '../../../core/markdown-route'
|
|
8
7
|
|
|
9
8
|
export interface DevDeadLinksOptions {
|
|
10
9
|
pageLoader: MarkdownPageLoader
|
|
@@ -35,8 +34,10 @@ export function devDeadLinksPlugin(options: DevDeadLinksOptions): Plugin {
|
|
|
35
34
|
return
|
|
36
35
|
}
|
|
37
36
|
|
|
38
|
-
const route =
|
|
39
|
-
|
|
37
|
+
const route = markdownFileToRoutePath(
|
|
38
|
+
file,
|
|
39
|
+
options.pageLoader.sourceRoot,
|
|
40
|
+
options.pageLoader.rewrites,
|
|
40
41
|
)
|
|
41
42
|
const page = options.pageLoader.registry.get(route)
|
|
42
43
|
if (!page) {
|
|
@@ -13,7 +13,11 @@ export function markdownPlugin(pageLoader: MarkdownPageLoader): Plugin {
|
|
|
13
13
|
}
|
|
14
14
|
|
|
15
15
|
const source = await readFile(file, 'utf8')
|
|
16
|
-
const { html, env, pageData } = await pageLoader.load(source, file)
|
|
16
|
+
const { html, env, pageData, dependencies } = await pageLoader.load(source, file)
|
|
17
|
+
// An edit to an included file or a code snippet then updates the page.
|
|
18
|
+
for (const dependency of dependencies) {
|
|
19
|
+
this.addWatchFile(dependency)
|
|
20
|
+
}
|
|
17
21
|
return assembleVueSfc(html, env, pageData)
|
|
18
22
|
},
|
|
19
23
|
}
|
package/src/generator.ts
CHANGED
|
@@ -2,12 +2,15 @@
|
|
|
2
2
|
* Node.js helpers for Generator Plugins. They run only on the generator side;
|
|
3
3
|
* never import this entry from a Runtime Plugin.
|
|
4
4
|
*/
|
|
5
|
+
export { expandMarkdownSource, readMarkdownSource } from './compiler/markdown-source'
|
|
6
|
+
export type { ExpandedMarkdownSource, MarkdownSourceLocation } from './compiler/markdown-source'
|
|
7
|
+
export { markdownFileToPagePath, markdownFileToRoutePath } from './compiler/page-path'
|
|
5
8
|
export { createPageSummaryReader } from './compiler/page-summary'
|
|
6
9
|
export type { PageSummaryReader } from './compiler/page-summary'
|
|
7
10
|
export { resolveHeadingTitle } from './core/heading-title'
|
|
8
11
|
export type { PageSummary } from './core/page-manifest'
|
|
9
12
|
export { parseGitLog, readGitLastUpdated } from './generator/git'
|
|
10
13
|
export type { ReadGitLastUpdatedOptions } from './generator/git'
|
|
11
|
-
export { isMarkdownPage, listMarkdownPages
|
|
14
|
+
export { isMarkdownPage, listMarkdownPages } from './generator/pages'
|
|
12
15
|
export type { MarkdownPage, MarkdownPageScope } from './generator/pages'
|
|
13
16
|
export { useRuntimeDependencies } from './generator/runtime-dependencies'
|
package/src/index.ts
CHANGED
package/src/server/build.ts
CHANGED
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
createBaseViteConfig,
|
|
10
10
|
createSitePageLoader,
|
|
11
11
|
} from '../generator/vite/config'
|
|
12
|
-
import { entryClientPath, entryServerPath } from '../generator/vite/entries'
|
|
12
|
+
import { entryClientPath, entryServerPath, SERVER_ENTRY_FILE, SERVER_OUT_DIR } from '../generator/vite/entries'
|
|
13
13
|
import { createPageInputs } from '../generator/vite/page-inputs'
|
|
14
14
|
import {
|
|
15
15
|
createBuildArtifactEmitter,
|
|
@@ -68,8 +68,11 @@ export async function buildSite(root: string) {
|
|
|
68
68
|
ssr: {
|
|
69
69
|
consumer: 'server',
|
|
70
70
|
build: {
|
|
71
|
-
outDir:
|
|
72
|
-
|
|
71
|
+
outDir: SERVER_OUT_DIR,
|
|
72
|
+
rolldownOptions: {
|
|
73
|
+
input: entryServerPath,
|
|
74
|
+
output: { entryFileNames: SERVER_ENTRY_FILE },
|
|
75
|
+
},
|
|
73
76
|
},
|
|
74
77
|
},
|
|
75
78
|
},
|
package/src/server/prerender.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { NOT_FOUND_ROUTE_PATH } from '../core/not-found'
|
|
|
13
13
|
import { findUnconsumedOutletItems, formatUnconsumedOutletWarnings } from '../core/outlet'
|
|
14
14
|
import { pageChunkFileName, pageChunkHash } from '../core/page-chunk'
|
|
15
15
|
import { pageTableFileName } from '../core/page-manifest'
|
|
16
|
+
import { SERVER_ENTRY_FILE, SERVER_OUT_DIR } from '../generator/vite/entries'
|
|
16
17
|
import { collectPageAssets, collectPageChunk } from './page-assets'
|
|
17
18
|
import { renderHtmlTemplate } from './template'
|
|
18
19
|
|
|
@@ -34,7 +35,8 @@ interface ServerBundle {
|
|
|
34
35
|
|
|
35
36
|
export async function prerenderPages(root: string): Promise<void> {
|
|
36
37
|
const distDir = join(root, 'dist')
|
|
37
|
-
const
|
|
38
|
+
const serverDir = join(root, SERVER_OUT_DIR)
|
|
39
|
+
const serverEntry = join(serverDir, SERVER_ENTRY_FILE)
|
|
38
40
|
const { render, getOutletRegistry, pages, pageModules, site } = await import(
|
|
39
41
|
pathToFileURL(serverEntry).href,
|
|
40
42
|
) as ServerBundle
|
|
@@ -83,7 +85,7 @@ export async function prerenderPages(root: string): Promise<void> {
|
|
|
83
85
|
reportUnconsumedOutlets(getOutletRegistry(), renderedOutlets)
|
|
84
86
|
consola.success(`KawaPress: prerendered ${paths.length} pages`)
|
|
85
87
|
|
|
86
|
-
await rm(
|
|
88
|
+
await rm(serverDir, { recursive: true })
|
|
87
89
|
await rm(join(distDir, '.vite'), { recursive: true })
|
|
88
90
|
}
|
|
89
91
|
|