kawapress 0.2.2 → 0.4.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.
- package/package.json +4 -2
- package/src/api/config.ts +11 -1
- package/src/api/plugin.ts +11 -2
- package/src/client/components/KawaOutlet.vue +17 -12
- 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 +25 -12
- 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/outlet.ts +33 -11
- 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/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/plugin/outlet-collector.ts +37 -22
- package/src/plugin/runtime-runner.ts +1 -1
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.0",
|
|
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.0"
|
|
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
|
}
|
|
@@ -68,8 +75,10 @@ export function definePlugin(plugin: KawaPressPlugin): KawaPressPlugin {
|
|
|
68
75
|
export type RuntimePluginHandler<T> = (value: T) => MaybePromise<void>
|
|
69
76
|
|
|
70
77
|
export interface RuntimePluginAPI {
|
|
71
|
-
/** Places a component
|
|
72
|
-
|
|
78
|
+
/** Places a component before the theme's own content of an outlet. */
|
|
79
|
+
prependToOutlet: (outlet: OutletName, item: OutletItemInput) => void
|
|
80
|
+
/** Places a component after the theme's own content of an outlet. */
|
|
81
|
+
appendToOutlet: (outlet: OutletName, item: OutletItemInput) => void
|
|
73
82
|
vueApp: (handler: RuntimePluginHandler<App>) => void
|
|
74
83
|
router: (handler: RuntimePluginHandler<Router>) => void
|
|
75
84
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
<script setup lang="ts">
|
|
2
|
-
import type {
|
|
2
|
+
import type { OutletName } from '../../core/outlet'
|
|
3
3
|
import { computed, onUnmounted } from 'vue'
|
|
4
|
-
import { assertOutletName,
|
|
4
|
+
import { assertOutletName, getOutletSlots } from '../../core/outlet'
|
|
5
5
|
import { recordRenderedOutlet, useOutletRegistry, useOutletRenderStore } from '../outlet'
|
|
6
6
|
|
|
7
7
|
const props = defineProps<{
|
|
@@ -9,14 +9,15 @@ const props = defineProps<{
|
|
|
9
9
|
}>()
|
|
10
10
|
|
|
11
11
|
defineSlots<{
|
|
12
|
-
/**
|
|
13
|
-
default?: (
|
|
12
|
+
/** The theme's own content. Plugin items render before and after it. */
|
|
13
|
+
default?: () => unknown
|
|
14
14
|
}>()
|
|
15
15
|
|
|
16
16
|
assertOutletName(props.name, '<KawaOutlet>')
|
|
17
17
|
|
|
18
18
|
const registry = useOutletRegistry('<KawaOutlet>')
|
|
19
|
-
|
|
19
|
+
// `slots` stays unset when the name check above throws; Vue still renders once after that.
|
|
20
|
+
const slots = computed(() => getOutletSlots(registry, props.name))
|
|
20
21
|
|
|
21
22
|
const renderStore = useOutletRenderStore()
|
|
22
23
|
renderStore?.mount(props.name)
|
|
@@ -26,11 +27,15 @@ recordRenderedOutlet(props.name)
|
|
|
26
27
|
</script>
|
|
27
28
|
|
|
28
29
|
<template>
|
|
29
|
-
<
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
30
|
+
<component
|
|
31
|
+
:is="item.component"
|
|
32
|
+
v-for="item in slots?.prepend"
|
|
33
|
+
:key="item.id"
|
|
34
|
+
/>
|
|
35
|
+
<slot />
|
|
36
|
+
<component
|
|
37
|
+
:is="item.component"
|
|
38
|
+
v-for="item in slots?.append"
|
|
39
|
+
:key="item.id"
|
|
40
|
+
/>
|
|
36
41
|
</template>
|
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
|
@@ -37,8 +37,8 @@ interface MarkdownEnv extends PageComponentEnv {
|
|
|
37
37
|
sfcBlocks?: MarkdownSfcBlocks
|
|
38
38
|
/** Set by the LLMS plugin when it compiles Markdown for plain-text output. */
|
|
39
39
|
ssgMarkdown?: boolean
|
|
40
|
-
/** Set once the `doc.
|
|
41
|
-
|
|
40
|
+
/** Set once the `doc.under-title` outlet has been placed after the first H1. */
|
|
41
|
+
docUnderTitleOutletPlaced?: boolean
|
|
42
42
|
/** Page body after frontmatter removal, set by the frontmatter plugin. */
|
|
43
43
|
content?: string
|
|
44
44
|
/** Internal links of the page, with line numbers relative to the source file. */
|
|
@@ -86,7 +86,7 @@ export async function createMarkdownCompiler(options: MarkdownCompilerOptions =
|
|
|
86
86
|
installHeadingTitles(md)
|
|
87
87
|
installPageLinkCollector(md)
|
|
88
88
|
installLinkRenderer(md, options.base ?? '/')
|
|
89
|
-
|
|
89
|
+
installDocUnderTitleOutlet(md)
|
|
90
90
|
|
|
91
91
|
await options.pluginRunner?.runMarkdown(md)
|
|
92
92
|
return md
|
|
@@ -169,14 +169,14 @@ function installAsyncSfcRenderCompatibility(md: MarkdownExit): void {
|
|
|
169
169
|
}
|
|
170
170
|
}
|
|
171
171
|
|
|
172
|
-
const
|
|
172
|
+
const DOC_UNDER_TITLE_OUTLET = '<KawaOutlet name="doc.under-title" />'
|
|
173
173
|
|
|
174
174
|
/**
|
|
175
|
-
* Renders the `doc.
|
|
175
|
+
* Renders the `doc.under-title` outlet right after the first H1 of every page, so
|
|
176
176
|
* plugins can place interface pieces inside the Markdown body without the
|
|
177
177
|
* theme reaching into compiled content. Pages without an H1 get no outlet.
|
|
178
178
|
*/
|
|
179
|
-
function
|
|
179
|
+
function installDocUnderTitleOutlet(md: MarkdownExit): void {
|
|
180
180
|
const original = md.renderer.rules.heading_close
|
|
181
181
|
|
|
182
182
|
md.renderer.rules.heading_close = (tokens, index, options, env, renderer) => {
|
|
@@ -190,13 +190,13 @@ function installDocHeaderOutlet(md: MarkdownExit): void {
|
|
|
190
190
|
|| typeof env !== 'object'
|
|
191
191
|
|| env === null
|
|
192
192
|
|| renderEnv.ssgMarkdown
|
|
193
|
-
|| renderEnv.
|
|
193
|
+
|| renderEnv.docUnderTitleOutletPlaced
|
|
194
194
|
) {
|
|
195
195
|
return rendered
|
|
196
196
|
}
|
|
197
197
|
|
|
198
|
-
renderEnv.
|
|
199
|
-
return `${rendered}\n${
|
|
198
|
+
renderEnv.docUnderTitleOutletPlaced = true
|
|
199
|
+
return `${rendered}\n${DOC_UNDER_TITLE_OUTLET}\n`
|
|
200
200
|
}
|
|
201
201
|
}
|
|
202
202
|
|
|
@@ -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 {
|