@matra/site-generation 0.1.0 → 0.2.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/README.ja.md ADDED
@@ -0,0 +1,122 @@
1
+ # @matra/site-generation
2
+
3
+ `@matra/site-generation`はMarkdownコンテンツとMatraのページ・レイアウトから
4
+ 静的サイトを生成します。`matra.site.yaml`、`matra.site.json`、
5
+ `matra.site.matra`で設定するファイル方式のAPIと、JavaScriptからページを
6
+ 直接登録するAPIを提供します。
7
+
8
+ ## 要件
9
+
10
+ Node.js 22以降を推奨します。projectにinstallします。
11
+
12
+ ```sh
13
+ npm install @matra/site-generation
14
+ ```
15
+
16
+ ## ファイル方式での生成
17
+
18
+ project rootにsite設定を作成します。
19
+
20
+ ```yaml
21
+ version: 1
22
+ site:
23
+ pages: pages
24
+ layouts: layouts
25
+ defaultLayout: default
26
+ output: dist
27
+ ```
28
+
29
+ `pages/`以下にMarkdownページを配置します。通常の`.md`はcontentとして
30
+ 公開されます。実行するMatraページとlayoutは`.matra.md`を使い、
31
+ FrontMatterの`matra.entry`でentry pointを指定します。次のようにbuildします。
32
+
33
+ ```js
34
+ import { buildSite } from "@matra/site-generation"
35
+
36
+ const outputs = await buildSite(process.cwd())
37
+ console.log(`Generated ${outputs.length} files`)
38
+ ```
39
+
40
+ `buildSite()`はsite設定を読み込み、ページ・layout・文書を収集してサイトを
41
+ 生成し、生成fileのpathを返します。`matra.site.yaml`、`matra.site.json`、
42
+ `matra.site.matra`は同じversioned schemaを使用します。
43
+
44
+ `buildSitePreview(directory)`は同じビルドを実行し、ローカル配信用に`files`、
45
+ `outputDirectory`、`routes`(ルートから出力相対パスへのmap)、`basePath`、`notFound`を返します。
46
+
47
+ ## JavaScriptからの直接登録
48
+
49
+ ページdataがすでにJavaScriptにあり、中間fileを作らずMatraに直接渡す場合は
50
+ `generateSite()`を使います。
51
+
52
+ ```js
53
+ import { generateSite } from "@matra/site-generation"
54
+
55
+ const products = [
56
+ { slug: "first", title: "First product", description: "Product details" },
57
+ { slug: "second", title: "Second product", description: "More details" },
58
+ ]
59
+
60
+ const outputs = await generateSite({
61
+ root: process.cwd(),
62
+ defaultLayout: "default",
63
+ layouts: {
64
+ default: { source: "html { head {}; body { ...page.content } }" },
65
+ },
66
+ templates: { product: { source: "main { h1 { page.data.title }; p { page.data.description } }" } },
67
+ pages: products.map(product => ({
68
+ kind: "matra",
69
+ route: `/products/${product.slug}/`,
70
+ template: "product",
71
+ data: product,
72
+ })),
73
+ })
74
+ console.log(`Generated ${outputs.length} files`)
75
+ ```
76
+
77
+ 各ページは`kind`(`"matra"`または`"markdown"`)、`route`、`source`文字列を
78
+ 指定します。Matraページでは`source`の代わりに名前付き`template`を指定できます。
79
+ テンプレートは一度だけコンパイルし、その`document`と記事側の`document`・`route`を区別して診断します。
80
+ `data`、`layout`、`document`は任意で、ページdata、使用layout
81
+ (`layout: false`で無効化可能)、diagnosticと相対link解決に使う論理文書pathを
82
+ 指定します。`layouts`と`components`は名前から`{ source, document? }`へのmapです。
83
+
84
+ テンプレートとlayoutが`site.documents`を使わない場合、
85
+ `includeDocumentsInTemplates: false`を指定すると空配列を渡し、描画時の全文書一覧のコピーを避けます。
86
+ 既定値は`true`です。Markdown変換、リンク検証、ページのdataとcontent、route、出力管理は変わりません。
87
+
88
+ 両APIはlayout、asset、base path、再利用可能なMatra部品に対応します。
89
+ Matra部品は`fn Name(props, children) { ... }`で定義し、単一の文書nodeを返します。
90
+ 子要素なしの呼び出しは`Name(props, [])`と書きます。第2引数の省略には、公開済みの
91
+ Core `0.3.1`より新しいruntimeが必要です。
92
+ 設定schema、入力規則、部品の動作、出力保証の詳細は
93
+ [サイト生成の契約](../../spec/site-generation.ja.md)を参照してください。
94
+
95
+ ## Markdownとブログの出力
96
+
97
+ 既定のMarkdown変換はそのままです。site-generation `0.2.x`で、サイトに`npm install @matra/markdown-unified@^0.1.0`し、
98
+ `markdown: "unified"`(ファイル設定では`site.markdown`)を指定すると、
99
+ YAML frontmatter・GFM・数式(MathML)・見出しID・目次・抜粋を利用できます。
100
+ 目次は`page.data.toc`、抜粋は`page.data.excerpt`から参照できます。
101
+ 独自構文が必要な場合だけ[公式プリセット](../markdown-unified/README.md)にプラグインを渡してください。
102
+
103
+ `generateSite()`の`markdown`には`async ({ body, document, metadata }) => ...`も指定できます。
104
+ 戻り値は文書ノード列、または`{ content: ノード列, data: 派生フィールド }`です。
105
+ リンク・画像に本文先頭を1とする`position.start.line`を付けると、Matraが変換後のURLを検証し、
106
+ frontmatterを含めた元記事の行番号を報告します。HTML文字列をそのまま挿入することはありません。
107
+
108
+ `publicDir: "public"`は、従来の`assets`とは別に`public/favicon.ico`を`/favicon.ico`のように
109
+ 元のパスで公開します。`notFound: "/404/"`は、指定ページの通常のルートを残しながら
110
+ 同じHTMLを`/404.html`にも出力します。どちらも既存の衝突・symlink検証、ステージング、
111
+ manifestによる不要ファイルの削除の対象です。
112
+
113
+ ## 出力の安全性
114
+
115
+ 入力を検証し、公開前にページを生成します。生成fileはstageを経てまとめて公開され、
116
+ 生成・検証に失敗した場合は既存出力を維持します。manifestで生成fileを追跡し、
117
+ 次回の成功buildで不要になった生成fileを削除しますが、追跡されていないfileは
118
+ 削除しません。入力symlinkとproject root外のpathは拒否されます。
119
+
120
+ ## ライセンス
121
+
122
+ MIT
package/README.md ADDED
@@ -0,0 +1,126 @@
1
+ # @matra/site-generation
2
+
3
+ `@matra/site-generation` generates static websites from Markdown content and
4
+ Matra pages and layouts. It provides a file-based API for projects configured
5
+ with `matra.site.yaml`, `matra.site.json`, or `matra.site.matra`, as well as a
6
+ JavaScript API for registering pages directly.
7
+
8
+ ## Requirements
9
+
10
+ Node.js 22 or later is recommended. Install the package in a project:
11
+
12
+ ```sh
13
+ npm install @matra/site-generation
14
+ ```
15
+
16
+ ## File-based generation
17
+
18
+ Create a site configuration in the project root:
19
+
20
+ ```yaml
21
+ version: 1
22
+ site:
23
+ pages: pages
24
+ layouts: layouts
25
+ defaultLayout: default
26
+ output: dist
27
+ ```
28
+
29
+ Add Markdown pages under `pages/`. Ordinary `.md` files are published as
30
+ content. Executable Matra pages and layouts use the `.matra.md` extension and
31
+ declare their entry point with `matra.entry` front matter. Then build the site:
32
+
33
+ ```js
34
+ import { buildSite } from "@matra/site-generation"
35
+
36
+ const outputs = await buildSite(process.cwd())
37
+ console.log(`Generated ${outputs.length} files`)
38
+ ```
39
+
40
+ `buildSite()` reads the site configuration, collects pages, layouts, and
41
+ documents, renders the site, and returns the generated file paths. The
42
+ `matra.site.yaml`, `matra.site.json`, and `matra.site.matra` formats use the
43
+ same versioned schema.
44
+
45
+ `buildSitePreview(directory)` performs the same build and additionally returns its `files`,
46
+ `outputDirectory`, `routes` (route to relative output path), `basePath`, and `notFound` for local serving.
47
+
48
+ ## Direct JavaScript API
49
+
50
+ Use `generateSite()` when page data is already available in JavaScript and
51
+ should be passed directly to Matra without writing intermediate files:
52
+
53
+ ```js
54
+ import { generateSite } from "@matra/site-generation"
55
+
56
+ const products = [
57
+ { slug: "first", title: "First product", description: "Product details" },
58
+ { slug: "second", title: "Second product", description: "More details" },
59
+ ]
60
+
61
+ const outputs = await generateSite({
62
+ root: process.cwd(),
63
+ defaultLayout: "default",
64
+ layouts: {
65
+ default: { source: "html { head {}; body { ...page.content } }" },
66
+ },
67
+ templates: { product: { source: "main { h1 { page.data.title }; p { page.data.description } }" } },
68
+ pages: products.map(product => ({
69
+ kind: "matra",
70
+ route: `/products/${product.slug}/`,
71
+ template: "product",
72
+ data: product,
73
+ })),
74
+ })
75
+ console.log(`Generated ${outputs.length} files`)
76
+ ```
77
+
78
+ Each page specifies `kind` (`"matra"` or `"markdown"`), a `route`, and a
79
+ `source` string (or a named `template` instead of `source` for a Matra page).
80
+ Templates compile once; `templates.product.document` identifies the template, while the
81
+ page's `document` and `route` identify the article in runtime errors. Optional `data`, `layout`, and `document` fields provide page
82
+ data, select a layout (or disable it with `layout: false`), and set the
83
+ logical document path used for diagnostics and relative links. `layouts` and
84
+ `components` map names to `{ source, document? }` objects.
85
+
86
+ When templates and layouts do not use `site.documents`, set
87
+ `includeDocumentsInTemplates: false` to pass them an empty array and avoid copying
88
+ the full document list during rendering. The default is `true`. Markdown conversion,
89
+ link validation, page data and content, routes, and output management are unaffected.
90
+
91
+ Both APIs support layouts, assets, a base path, and reusable Matra components.
92
+ Matra components are defined as `fn Name(props, children) { ... }` and return
93
+ one document node. Use `Name(props, [])` when there are no children; omitting the
94
+ second argument requires a newer Core runtime than the published `0.3.1`. See the
95
+ [site-generation contract](../../spec/site-generation.md)
96
+ for the complete configuration schema, input rules, component behavior, and
97
+ output guarantees.
98
+
99
+ ## Markdown and blog outputs
100
+
101
+ The default Markdown behavior is unchanged. For frontmatter, GFM, math, heading IDs, TOC and
102
+ excerpts, use site-generation `0.2.x` and install the [optional unified preset](../markdown-unified/README.md) (`@matra/markdown-unified@^0.1.0`) in the site
103
+ and set `markdown: "unified"` (under `site` in file configuration).
104
+ `generateSite({ markdown: async ({ body, document, metadata }) => ..., ... })` also accepts a
105
+ custom hook returning a node sequence or `{ content: nodes, data: derivedFields }`.
106
+ Supply `position.start.line` on link/image nodes relative to the body (first line is 1).
107
+ Matra resolves and validates URLs after conversion and adds the frontmatter line offset.
108
+ Raw HTML strings are never injected into the page.
109
+
110
+ Set `publicDir: "public"` to copy files such as `public/favicon.ico` to `/favicon.ico`,
111
+ alongside the existing `assets` mount. Set `notFound: "/404/"` to also publish that page's
112
+ HTML at `/404.html` without breaking its regular route. Both outputs use the ordinary
113
+ collision checks, symlink rejection, staging and stale-file manifest.
114
+
115
+ ## Output safety
116
+
117
+ The generator validates inputs and renders pages before publishing. Generated
118
+ files are staged and published together; generation or validation failures
119
+ preserve the previous output. A manifest tracks generated files so obsolete
120
+ generated files can be removed on a later successful build without deleting
121
+ untracked files. Input symlinks and paths outside the project root are
122
+ rejected.
123
+
124
+ ## License
125
+
126
+ MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@matra/site-generation",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Declarative static site generation for Matra",
5
5
  "type": "module",
6
6
  "exports": {
@@ -15,6 +15,15 @@
15
15
  "js-yaml": "^5.2.2",
16
16
  "markdown-it": "^14.3.0"
17
17
  },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/matralang/matra.git",
21
+ "directory": "packages/site-generation"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public",
25
+ "registry": "https://registry.npmjs.org"
26
+ },
18
27
  "license": "MIT",
19
28
  "scripts": {
20
29
  "build": "node --check src/index.mjs && node --check src/site.mjs && node --check src/markdown.mjs",
package/src/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  export {
2
2
  buildSite,
3
+ buildSitePreview,
3
4
  generateSite,
4
5
  getSiteProgramDocuments,
5
6
  renderLiterateDocument,
package/src/markdown.mjs CHANGED
@@ -1,6 +1,23 @@
1
1
  import MarkdownIt from "markdown-it"
2
2
 
3
3
  const markdown = new MarkdownIt({ html: false, linkify: false, typographer: false })
4
+ // inline token には map がなく、複数行のコード等は token 化後に改行が失われる。
5
+ markdown.inline.State = class extends markdown.inline.State {
6
+ lineOffset = 0
7
+ nextBreak = this.src.indexOf("\n")
8
+
9
+ push(type, tag, nesting) {
10
+ const token = super.push(type, tag, nesting)
11
+ if (type === "link_open" || type === "image") {
12
+ while (this.nextBreak !== -1 && this.nextBreak < this.pos) {
13
+ this.lineOffset++
14
+ this.nextBreak = this.src.indexOf("\n", this.nextBreak + 1)
15
+ }
16
+ token.meta = { lineOffset: this.lineOffset }
17
+ }
18
+ return token
19
+ }
20
+ }
4
21
  const BLOCK_TAGS = {
5
22
  blockquote_open: "blockquote",
6
23
  bullet_list_open: "ul",
@@ -22,11 +39,17 @@ const INLINE_TAGS = {
22
39
  strong_open: "strong",
23
40
  }
24
41
 
25
- export function markdownToNodes(source, { resolveLink = value => value } = {}) {
42
+ export function isSafeMarkdownUrl(url) {
43
+ return markdown.validateLink(url.replace(/[\t\r\n]/g, ""))
44
+ }
45
+
46
+ export function markdownToNodes(source) {
26
47
  const tokens = markdown.parse(source, {})
27
48
  const root = { tag: "$root", props: {}, children: [] }
28
49
  const stack = [root]
50
+ let line = 1
29
51
  for (const token of tokens) {
52
+ if (token.map) line = token.map[0] + 1
30
53
  if (token.type.endsWith("_open")) {
31
54
  if (token.hidden) continue
32
55
  const tag = BLOCK_TAGS[token.type]
@@ -41,7 +64,7 @@ export function markdownToNodes(source, { resolveLink = value => value } = {}) {
41
64
  if (token.hidden) continue
42
65
  if (BLOCK_TAGS[token.type.replace("_close", "_open")]) stack.pop()
43
66
  } else if (token.type === "inline") {
44
- stack.at(-1).children.push(...inlineNodes(token.children ?? [], resolveLink))
67
+ stack.at(-1).children.push(...inlineNodes(token.children ?? [], line))
45
68
  } else if (token.type === "fence" || token.type === "code_block") {
46
69
  const codeProps = {}
47
70
  const language = token.info.trim().split(/\s+/, 1)[0]
@@ -60,7 +83,7 @@ export function markdownToNodes(source, { resolveLink = value => value } = {}) {
60
83
  return root.children
61
84
  }
62
85
 
63
- function inlineNodes(tokens, resolveLink) {
86
+ function inlineNodes(tokens, line) {
64
87
  const root = { tag: "$root", props: {}, children: [] }
65
88
  const stack = [root]
66
89
  for (const token of tokens) {
@@ -68,18 +91,22 @@ function inlineNodes(tokens, resolveLink) {
68
91
  const tag = INLINE_TAGS[token.type]
69
92
  if (!tag) continue
70
93
  const props = Object.fromEntries(token.attrs ?? [])
71
- if (tag === "a" && props.href) props.href = resolveLink(props.href, "link")
72
94
  const node = { tag, props, children: [] }
95
+ if (tag === "a") node.position = { start: { line: line + token.meta.lineOffset } }
73
96
  stack.at(-1).children.push(node)
74
97
  stack.push(node)
75
98
  } else if (token.type.endsWith("_close")) {
76
99
  if (INLINE_TAGS[token.type.replace("_close", "_open")]) stack.pop()
77
100
  } else if (token.type === "image") {
78
101
  const props = Object.fromEntries(token.attrs ?? [])
79
- if (props.src) props.src = resolveLink(props.src, "image")
80
102
  props.alt = token.content
81
103
  if (token.attrGet("title")) props.title = token.attrGet("title")
82
- stack.at(-1).children.push({ tag: "img", props, children: [] })
104
+ stack.at(-1).children.push({
105
+ tag: "img",
106
+ props,
107
+ children: [],
108
+ position: { start: { line: line + token.meta.lineOffset } },
109
+ })
83
110
  } else if (token.type === "code_inline") {
84
111
  stack.at(-1).children.push({ tag: "code", props: {}, children: [token.content] })
85
112
  } else if (token.type === "hardbreak") {
package/src/site.mjs CHANGED
@@ -11,9 +11,11 @@ import {
11
11
  rmdir,
12
12
  writeFile,
13
13
  } from "node:fs/promises"
14
+ import { createRequire } from "node:module"
14
15
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path"
16
+ import { pathToFileURL } from "node:url"
15
17
  import { types } from "node:util"
16
- import { evaluateStatic, parse, staticValueToAST } from "@matra/core"
18
+ import { evaluateStatic, isMatraAST, parse, staticValueToAST } from "@matra/core"
17
19
  import {
18
20
  buildLiterate,
19
21
  buildMatraComponent,
@@ -22,7 +24,7 @@ import {
22
24
  } from "@matra/core/experimental/literate"
23
25
  import { toHTML } from "@matra/html"
24
26
  import { load as loadYaml } from "js-yaml"
25
- import { markdownToNodes } from "./markdown.mjs"
27
+ import { isSafeMarkdownUrl, markdownToNodes } from "./markdown.mjs"
26
28
 
27
29
  const CONFIG_NAMES = ["matra.site.yaml", "matra.site.json", "matra.site.matra"]
28
30
  const SITE_KEYS = new Set(["route", "layout", "data"])
@@ -42,11 +44,15 @@ export async function renderLiterateDocument(markdown, options = {}) {
42
44
  }
43
45
 
44
46
  export async function buildSite(directory) {
45
- const site = await loadSite(resolve(directory))
47
+ return (await buildSitePreview(directory)).files
48
+ }
49
+
50
+ export async function buildSitePreview(directory, onInputs) {
51
+ const site = await loadSite(resolve(directory), onInputs)
46
52
  const { root, settings } = site
47
53
  const components = []
48
54
  if (settings.componentsDirectory) {
49
- for (const path of await walkFiles(settings.componentsDirectory)) {
55
+ for (const path of await walkFiles(settings.componentsDirectory, settings.observeDirectory)) {
50
56
  if (!path.endsWith(".matra")) continue
51
57
  components.push({
52
58
  source: await readFile(path, "utf8"),
@@ -54,14 +60,29 @@ export async function buildSite(directory) {
54
60
  })
55
61
  }
56
62
  }
57
- return generateLoadedSite({ ...site, components })
63
+ const result = await generateLoadedSite({ ...site, components })
64
+ return {
65
+ ...result,
66
+ outputDirectory: settings.outputDirectory,
67
+ basePath: settings.basePath,
68
+ notFound: settings.notFound,
69
+ }
58
70
  }
59
71
 
60
- async function generateLoadedSite({ root, settings, documents, layouts, pages, components }) {
72
+ async function generateLoadedSite({
73
+ root,
74
+ settings,
75
+ documents,
76
+ layouts,
77
+ pages,
78
+ components,
79
+ templates = new Map(),
80
+ }) {
61
81
  settings.components = []
62
82
  const names = new Set()
63
83
  for (const source of components) {
64
84
  const component = await buildMatraComponent(source.source, { document: source.document })
85
+ warnDiscardedNodes(component.entry)
65
86
  if (source.name !== undefined && source.name !== component.name) {
66
87
  throw new Error(`${source.document}: component name must match '${source.name}'`)
67
88
  }
@@ -72,56 +93,189 @@ async function generateLoadedSite({ root, settings, documents, layouts, pages, c
72
93
  names.add(key)
73
94
  settings.components.push(component)
74
95
  }
75
- const assets = settings.assetsDirectory ? await collectAssets(settings.assetsDirectory) : []
96
+ const assets = [
97
+ ...(settings.assetsDirectory
98
+ ? await collectAssets(settings.assetsDirectory, "assets", settings.observeDirectory)
99
+ : []),
100
+ ...(settings.publicDirectory
101
+ ? await collectAssets(settings.publicDirectory, "", settings.observeDirectory)
102
+ : []),
103
+ ]
76
104
  const outputPlan = planOutput(pages, assets, settings)
77
105
  settings.routes = new Map(pages.map(page => [page.path, page.route]))
78
106
  settings.routesByRoute = new Set(pages.map(page => page.route))
79
- settings.assetFiles = new Set(assets.map(asset => resolve(asset.source)))
80
- settings.assetOutputs = new Set(assets.map(asset => `/${asset.output.split(sep).join("/")}`))
107
+ settings.assetFiles = new Map(
108
+ assets.map(asset => [asset.source, `/${asset.output.split(sep).join("/")}`]),
109
+ )
110
+ settings.assetOutputs = new Set(settings.assetFiles.values())
81
111
  await validateOutput(root, settings.outputDirectory, { files: [] })
82
- settings.documents = documents.map(document => ({
83
- id: document.id,
84
- path: document.id,
85
- metadata: document.metadataIsData ? document.metadata : metadataValues(document.metadata),
86
- content: markdownToNodes(
87
- document.body,
88
- settings.routes.has(document.path)
89
- ? {
90
- resolveLink: (href, kind) => resolveMarkdownLink(href, kind, document, settings),
91
- }
92
- : {},
93
- ),
94
- }))
95
- for (const layout of layouts.values()) {
96
- layout.bundle = await buildTemplate(layout, root)
112
+ const transform =
113
+ settings.markdown === "unified" ? await loadUnifiedPreset(root) : settings.markdown
114
+ const pagesByPath = new Map(pages.map(page => [page.path, page]))
115
+ settings.documents = []
116
+ for (const document of documents) {
117
+ const page = pagesByPath.get(document.path)
118
+ const metadata =
119
+ page && (transform || document.metadataIsData) ? page.data : metadataValues(document.metadata)
120
+ const { content, data } = await convertMarkdown(document, page, settings, transform, metadata)
121
+ if (page) {
122
+ page.content = content
123
+ page.data = { ...data, ...page.data }
124
+ }
125
+ if (settings.includeDocumentsInTemplates !== false) {
126
+ settings.documents.push({
127
+ id: document.id,
128
+ path: document.id,
129
+ route: page?.route ?? null,
130
+ metadata: { ...data, ...metadata },
131
+ content,
132
+ })
133
+ }
134
+ }
135
+ for (const template of [...layouts.values(), ...templates.values()]) {
136
+ template.bundle = await buildTemplate(template, root)
97
137
  }
98
138
  for (const page of pages) {
99
139
  if (page.kind === "program") {
100
- page.bundle = await buildTemplate(page, root)
140
+ page.bundle = page.template
141
+ ? templates.get(page.template).bundle
142
+ : await buildTemplate(page, root)
101
143
  }
102
144
  }
103
145
 
104
146
  const rendered = []
105
147
  for (const page of pages) {
106
- const content = await renderPage(page, settings)
107
- const document = page.layout
108
- ? await renderLayout(layouts.get(page.layout), content, page, settings)
109
- : content
110
- assertCompleteDocument(document, page.path)
111
- rendered.push({
112
- path: outputPlan.routes.get(page.route),
113
- content: `<!doctype html>\n${toHTML(document, { basePath: settings.basePath })}\n`,
114
- })
148
+ try {
149
+ const content = await renderPage(page, settings)
150
+ const document = page.layout
151
+ ? await renderLayout(layouts.get(page.layout), content, page, settings)
152
+ : content
153
+ assertCompleteDocument(document, page.path)
154
+ const html = `<!doctype html>\n${toHTML(document, { basePath: settings.basePath })}\n`
155
+ rendered.push({ path: outputPlan.routes.get(page.route), content: html })
156
+ if (page.route === settings.notFound && outputPlan.routes.get(page.route) !== "404.html") {
157
+ rendered.push({ path: "404.html", content: html })
158
+ }
159
+ } catch (error) {
160
+ error.message = `${page.document} (route ${page.route}): ${error.message}`
161
+ throw error
162
+ }
115
163
  }
116
164
  for (const asset of assets) rendered.push({ path: asset.output, content: asset.content })
117
165
  await publish(root, settings.outputDirectory, rendered)
118
- return rendered.map(file => join(settings.outputDirectory, file.path))
166
+ return {
167
+ files: rendered.map(file => join(settings.outputDirectory, file.path)),
168
+ routes: outputPlan.routes,
169
+ }
170
+ }
171
+
172
+ async function buildTemplate(template, root) {
173
+ const bundle =
174
+ template.sourceKind === "matra"
175
+ ? await buildMatraProgram(template.source, { document: template.document })
176
+ : await buildLiterate(template.source, { document: template.document, moduleRoot: root })
177
+ warnDiscardedNodes(bundle.entry)
178
+ return bundle
119
179
  }
120
180
 
121
- function buildTemplate(template, root) {
122
- return template.sourceKind === "matra"
123
- ? buildMatraProgram(template.source, { document: template.document })
124
- : buildLiterate(template.source, { document: template.document, moduleRoot: root })
181
+ function warnDiscardedNodes(entry) {
182
+ if (!entry.source.includes("if")) return
183
+ let syntax
184
+ try {
185
+ syntax = parse(entry.source)
186
+ } catch (error) {
187
+ if (!(error instanceof SyntaxError)) throw error
188
+ console.warn(`${entry.document}: template warning check unavailable: ${error.message}`)
189
+ return
190
+ }
191
+ function visit(value) {
192
+ if (!value || typeof value !== "object") return
193
+ if (value.kind === "if") {
194
+ for (const branch of [value.thenBody, value.elseBody]) {
195
+ for (const statement of branch.slice(0, -1)) {
196
+ if (statement.kind === "expression" && statement.expression.kind === "node") {
197
+ console.warn(
198
+ `${entry.document}: if branch discards <${statement.expression.tag}>. Use ...if with an array to emit multiple nodes.`,
199
+ )
200
+ }
201
+ }
202
+ }
203
+ }
204
+ Object.values(value).forEach(visit)
205
+ }
206
+ visit(syntax)
207
+ }
208
+
209
+ async function loadUnifiedPreset(root) {
210
+ let path
211
+ try {
212
+ path = createRequire(join(root, "package.json")).resolve("@matra/markdown-unified")
213
+ } catch (error) {
214
+ if (error.code !== "MODULE_NOT_FOUND") throw error
215
+ throw new Error(
216
+ "markdown: unified requires @matra/markdown-unified installed in the site project",
217
+ { cause: error },
218
+ )
219
+ }
220
+ const { createUnifiedMarkdown } = await import(pathToFileURL(path).href)
221
+ return createUnifiedMarkdown()
222
+ }
223
+
224
+ async function convertMarkdown(document, page, settings, transform, metadata) {
225
+ const path = relative(settings.root, document.path).split(sep).join("/")
226
+ const firstLine = document.bodyLine
227
+ const location = line => `${path}:${firstLine + line - 1}${page ? ` (route ${page.route})` : ""}`
228
+ let result
229
+ if (transform) {
230
+ try {
231
+ result = await transform({
232
+ body: document.body,
233
+ document: path,
234
+ metadata: structuredClone(metadata),
235
+ })
236
+ } catch (error) {
237
+ throw new Error(`${location(error?.line ?? 1)}: ${error?.message ?? String(error)}`, {
238
+ cause: error,
239
+ })
240
+ }
241
+ assertPlainData(result, `${location(1)}: Markdown transform result`)
242
+ result = structuredClone(result)
243
+ } else {
244
+ result = markdownToNodes(document.body)
245
+ }
246
+ const { content, data = {} } = Array.isArray(result) ? { content: result } : (result ?? {})
247
+ if (!Array.isArray(content) || !isRecord(data)) {
248
+ throw new TypeError(
249
+ `${location(1)}: expected Markdown nodes or { content: nodes, data?: object }`,
250
+ )
251
+ }
252
+ function resolveNode(node, parentLine) {
253
+ if (node === null || ["string", "number", "boolean"].includes(typeof node)) return node
254
+ if (!isMatraAST(node))
255
+ throw new TypeError(`${location(parentLine)}: invalid Markdown document node`)
256
+ const line = node.position?.start?.line ?? parentLine
257
+ if (!Number.isSafeInteger(line) || line < 1)
258
+ throw new TypeError(`${location(parentLine)}: invalid Markdown node line`)
259
+ const props = { ...node.props }
260
+ for (const name of ["href", "src"]) {
261
+ if (!Object.hasOwn(props, name)) continue
262
+ const href = props[name]
263
+ if (typeof href !== "string" || !isSafeMarkdownUrl(href)) {
264
+ throw new TypeError(`${location(line)}: invalid Markdown ${name}: ${href}`)
265
+ }
266
+ if (page || transform) {
267
+ props[name] = resolveMarkdownLink(
268
+ href,
269
+ name === "src" ? "image" : "link",
270
+ document,
271
+ settings,
272
+ location(line),
273
+ )
274
+ }
275
+ }
276
+ return { tag: node.tag, props, children: node.children.map(child => resolveNode(child, line)) }
277
+ }
278
+ return { content: content.map(node => resolveNode(node, 1)), data }
125
279
  }
126
280
 
127
281
  export async function generateSite(options) {
@@ -132,6 +286,7 @@ export async function generateSite(options) {
132
286
  for (const directory of [
133
287
  ...settings.documentDirectories,
134
288
  ...(settings.assetsDirectory ? [settings.assetsDirectory] : []),
289
+ ...(settings.publicDirectory ? [settings.publicDirectory] : []),
135
290
  ]) {
136
291
  assertInputOutputSeparation(directory, settings.outputDirectory)
137
292
  await assertDirectory(root, directory)
@@ -140,6 +295,7 @@ export async function generateSite(options) {
140
295
  const logicalPaths = new Set([
141
296
  ...site.pages.map(page => page.path.toLowerCase()),
142
297
  ...[...site.layouts.values()].map(layout => layout.path.toLowerCase()),
298
+ ...[...site.templates.values()].map(template => template.path.toLowerCase()),
143
299
  ...site.components.map(component => component.path.toLowerCase()),
144
300
  ])
145
301
  for (const document of documents) {
@@ -152,22 +308,35 @@ export async function generateSite(options) {
152
308
  const id = page.document
153
309
  if (ids.has(id.toLowerCase())) throw new Error(`Duplicate document ID ignoring case: ${id}`)
154
310
  ids.add(id.toLowerCase())
311
+ const parsed = settings.markdown
312
+ ? parseFrontMatter(page.body, id, page.route)
313
+ : { body: page.body, bodyLine: 1, metadata: {} }
314
+ page.data = { ...parsed.metadata, ...page.data }
155
315
  documents.push({
156
316
  id,
157
317
  path: page.path,
158
- body: page.body,
318
+ body: parsed.body,
319
+ bodyLine: parsed.bodyLine,
159
320
  metadata: page.data,
160
321
  metadataIsData: true,
161
322
  })
162
323
  }
163
324
  documents.sort((left, right) => left.id.localeCompare(right.id, "en"))
164
- return generateLoadedSite({ ...site, documents })
325
+ return (await generateLoadedSite({ ...site, documents })).files
165
326
  }
166
327
 
167
328
  function normalizeDirectSite(input) {
168
- if (!isRecord(input)) throw new TypeError("generateSite options must be an object")
169
- assertPlainData(input, "generateSite options")
170
- const options = structuredClone(input)
329
+ if (types.isProxy(input) || !isRecord(input))
330
+ throw new TypeError("generateSite options must be an object")
331
+ const descriptors = Object.getOwnPropertyDescriptors(input)
332
+ const transform =
333
+ descriptors.markdown?.enumerable && typeof descriptors.markdown.value === "function"
334
+ ? descriptors.markdown.value
335
+ : undefined
336
+ if (transform) delete descriptors.markdown
337
+ const data = Object.defineProperties({}, descriptors)
338
+ assertPlainData(data, "generateSite options")
339
+ const options = structuredClone(data)
171
340
  rejectUnknownKeys(
172
341
  options,
173
342
  new Set([
@@ -175,26 +344,50 @@ function normalizeDirectSite(input) {
175
344
  "output",
176
345
  "format",
177
346
  "assets",
347
+ "publicDir",
348
+ "notFound",
349
+ "markdown",
178
350
  "basePath",
179
351
  "data",
180
352
  "defaultLayout",
181
353
  "pages",
182
354
  "layouts",
355
+ "templates",
183
356
  "components",
184
357
  "documents",
358
+ "includeDocumentsInTemplates",
185
359
  ]),
186
360
  "generateSite",
187
361
  )
362
+ if (
363
+ Object.hasOwn(options, "includeDocumentsInTemplates") &&
364
+ typeof options.includeDocumentsInTemplates !== "boolean"
365
+ ) {
366
+ throw new TypeError("includeDocumentsInTemplates must be a boolean")
367
+ }
188
368
  if (options.root !== undefined && (typeof options.root !== "string" || !options.root)) {
189
369
  throw new TypeError("root must be a non-empty path")
190
370
  }
191
371
  const root = resolve(options.root ?? process.cwd())
192
372
  const siteOptions = Object.fromEntries(
193
- ["output", "format", "assets", "basePath", "data", "defaultLayout", "documents"]
373
+ [
374
+ "output",
375
+ "format",
376
+ "assets",
377
+ "publicDir",
378
+ "notFound",
379
+ "markdown",
380
+ "basePath",
381
+ "data",
382
+ "defaultLayout",
383
+ "documents",
384
+ ]
194
385
  .filter(key => Object.hasOwn(options, key))
195
386
  .map(key => [key, options[key]]),
196
387
  )
197
388
  const settings = normalizeSettings({ version: 1, site: siteOptions }, root)
389
+ settings.includeDocumentsInTemplates = options.includeDocumentsInTemplates ?? true
390
+ if (transform) settings.markdown = transform
198
391
  if (settings.outputDirectory === root) throw new Error("site.output must not be the project root")
199
392
  const documentDirectories =
200
393
  typeof options.documents === "string" ? [options.documents] : (options.documents ?? [])
@@ -202,7 +395,8 @@ function normalizeDirectSite(input) {
202
395
  const documents = new Set()
203
396
  const sourceEntry = (entry, fallback, label) => {
204
397
  if (!isRecord(entry)) throw new TypeError(`${label} must be an object`)
205
- if (typeof entry.source !== "string") throw new TypeError(`${label}.source must be a string`)
398
+ if (!Object.hasOwn(entry, "template") && typeof entry.source !== "string")
399
+ throw new TypeError(`${label}.source must be a string`)
206
400
  const document = entry.document === undefined ? fallback : entry.document
207
401
  if (
208
402
  typeof document !== "string" ||
@@ -240,6 +434,7 @@ function normalizeDirectSite(input) {
240
434
  )
241
435
  }
242
436
  const layouts = namedSources(options.layouts, "layouts")
437
+ const templates = namedSources(options.templates, "templates")
243
438
  selectedLayout(undefined, settings.defaultLayout, layouts, "defaultLayout")
244
439
  const components = [...namedSources(options.components, "components").values()]
245
440
  if (!Array.isArray(options.pages)) throw new TypeError("pages must be an array")
@@ -248,12 +443,26 @@ function normalizeDirectSite(input) {
248
443
  if (!isRecord(entry)) throw new TypeError(`${label} must be an object`)
249
444
  rejectUnknownKeys(
250
445
  entry,
251
- new Set(["kind", "route", "source", "layout", "data", "document"]),
446
+ new Set(["kind", "route", "source", "template", "layout", "data", "document"]),
252
447
  label,
253
448
  )
254
449
  if (!["matra", "markdown"].includes(entry.kind))
255
450
  throw new TypeError(`${label}.kind must be 'matra' or 'markdown'`)
256
451
  if (typeof entry.route !== "string") throw new TypeError(`${label}.route must be a string`)
452
+ if (Object.hasOwn(entry, "template")) {
453
+ if (entry.kind !== "matra" || Object.hasOwn(entry, "source")) {
454
+ throw new TypeError(`${label}: template replaces source on a matra page only`)
455
+ }
456
+ if (!templates.has(entry.template))
457
+ throw new TypeError(`${label}: unknown template '${entry.template}'`)
458
+ }
459
+ const route = normalizeRoute(entry.route, settings.format, label)
460
+ const stem = route === "/" ? "index" : route.slice(1).replace(/\/$/, "")
461
+ const source = sourceEntry(
462
+ entry,
463
+ `pages/${stem}.${entry.kind === "matra" ? "matra" : "md"}`,
464
+ label,
465
+ )
257
466
  const controls = siteControls(
258
467
  {
259
468
  site: {
@@ -261,27 +470,21 @@ function normalizeDirectSite(input) {
261
470
  ...(Object.hasOwn(entry, "data") ? { data: entry.data } : {}),
262
471
  },
263
472
  },
264
- label,
265
- )
266
- const route = normalizeRoute(entry.route, settings.format, label)
267
- const stem = route === "/" ? "index" : route.slice(1).replace(/\/$/, "")
268
- const source = sourceEntry(
269
- entry,
270
- `pages/${stem}.${entry.kind === "matra" ? "matra" : "md"}`,
271
- label,
473
+ `${source.document} (route ${route})`,
272
474
  )
273
475
  return {
274
476
  ...source,
275
477
  kind: entry.kind === "matra" ? "program" : "markdown",
276
478
  id: source.document,
277
479
  body: entry.source,
480
+ template: entry.template,
278
481
  route,
279
482
  data: controls.data ?? {},
280
483
  layout: selectedLayout(controls.layout, settings.defaultLayout, layouts, source.document),
281
484
  }
282
485
  })
283
486
  sortAndValidateRoutes(pages)
284
- return { root, settings, layouts, pages, components }
487
+ return { root, settings, layouts, templates, pages, components }
285
488
  }
286
489
 
287
490
  function assertInputOutputSeparation(input, output) {
@@ -302,24 +505,30 @@ export async function getSiteProgramDocuments(directory) {
302
505
  ].sort((left, right) => left.localeCompare(right, "en"))
303
506
  }
304
507
 
305
- async function loadSite(root) {
508
+ async function loadSite(root, onInputs) {
509
+ for (const name of CONFIG_NAMES) onInputs?.(join(root, name))
306
510
  const config = await readConfig(root)
307
511
  const settings = normalizeSettings(config, root)
308
- for (const input of [
512
+ const inputs = [
309
513
  settings.pagesDirectory,
310
514
  ...settings.documentDirectories,
311
515
  settings.layoutsDirectory,
312
516
  ...(settings.componentsDirectory ? [settings.componentsDirectory] : []),
313
517
  ...(settings.assetsDirectory ? [settings.assetsDirectory] : []),
314
- ]) {
518
+ ...(settings.publicDirectory ? [settings.publicDirectory] : []),
519
+ ]
520
+ for (const input of inputs) {
315
521
  assertInputOutputSeparation(input, settings.outputDirectory)
522
+ onInputs?.(input)
316
523
  }
524
+ if (onInputs) settings.observeDirectory = path => onInputs(path, true)
317
525
  await Promise.all([
318
526
  assertDirectory(root, settings.pagesDirectory),
319
527
  ...settings.documentDirectories.map(path => assertDirectory(root, path)),
320
528
  assertDirectory(root, settings.layoutsDirectory, { optional: true }),
321
529
  ...(settings.componentsDirectory ? [assertDirectory(root, settings.componentsDirectory)] : []),
322
530
  ...(settings.assetsDirectory ? [assertDirectory(root, settings.assetsDirectory)] : []),
531
+ ...(settings.publicDirectory ? [assertDirectory(root, settings.publicDirectory)] : []),
323
532
  ])
324
533
  const documents = await collectDocuments(root, settings)
325
534
  const layouts = await collectLayouts(root, settings)
@@ -375,6 +584,9 @@ function normalizeSettings(config, root) {
375
584
  "output",
376
585
  "format",
377
586
  "assets",
587
+ "publicDir",
588
+ "notFound",
589
+ "markdown",
378
590
  "basePath",
379
591
  "data",
380
592
  ]),
@@ -412,6 +624,25 @@ function normalizeSettings(config, root) {
412
624
  const outputDirectory = resolveDirectory(site.output, "output", "dist")
413
625
  const assetsDirectory =
414
626
  site.assets === undefined ? undefined : resolveDirectory(site.assets, "assets", site.assets)
627
+ const publicDirectory =
628
+ site.publicDir === undefined
629
+ ? undefined
630
+ : resolveDirectory(site.publicDir, "publicDir", site.publicDir)
631
+ if (
632
+ assetsDirectory &&
633
+ publicDirectory &&
634
+ (assetsDirectory === publicDirectory ||
635
+ assetsDirectory.startsWith(`${publicDirectory}${sep}`) ||
636
+ publicDirectory.startsWith(`${assetsDirectory}${sep}`))
637
+ ) {
638
+ throw new TypeError("site.publicDir and site.assets must not overlap")
639
+ }
640
+ if (site.markdown !== undefined && site.markdown !== "unified") {
641
+ throw new TypeError("site.markdown must be 'unified'")
642
+ }
643
+ if (site.notFound !== undefined && typeof site.notFound !== "string") {
644
+ throw new TypeError("site.notFound must be a page route")
645
+ }
415
646
  if (site.format !== undefined && !["directory", "flat"].includes(site.format)) {
416
647
  throw new TypeError("site.format must be 'directory' or 'flat'")
417
648
  }
@@ -436,6 +667,12 @@ function normalizeSettings(config, root) {
436
667
  componentsDirectory,
437
668
  outputDirectory,
438
669
  assetsDirectory,
670
+ publicDirectory,
671
+ notFound:
672
+ site.notFound === undefined
673
+ ? undefined
674
+ : normalizeRoute(site.notFound, format, "site.notFound"),
675
+ markdown: site.markdown,
439
676
  defaultLayout: site.defaultLayout === undefined ? false : site.defaultLayout,
440
677
  format,
441
678
  basePath,
@@ -463,9 +700,10 @@ async function assertDirectory(root, path, { optional = false } = {}) {
463
700
  return true
464
701
  }
465
702
 
466
- async function walkFiles(directory) {
703
+ async function walkFiles(directory, observeDirectory) {
467
704
  const results = []
468
705
  async function visit(current) {
706
+ observeDirectory?.(current)
469
707
  const entries = await readdir(current, { withFileTypes: true })
470
708
  entries.sort((left, right) => left.name.localeCompare(right.name, "en"))
471
709
  for (const entry of entries) {
@@ -484,7 +722,7 @@ async function collectDocuments(root, settings) {
484
722
  const ids = new Map()
485
723
  for (const directory of settings.documentDirectories) {
486
724
  await assertDirectory(root, directory)
487
- for (const path of await walkFiles(directory)) {
725
+ for (const path of await walkFiles(directory, settings.observeDirectory)) {
488
726
  if (!path.endsWith(".md") || path.endsWith(".matra.md")) continue
489
727
  const id = relative(directory, path).split(sep).join("/")
490
728
  const key = id.toLocaleLowerCase("en-US")
@@ -500,6 +738,7 @@ async function collectDocuments(root, settings) {
500
738
  path,
501
739
  source,
502
740
  body: parsed.body,
741
+ bodyLine: parsed.bodyLine,
503
742
  metadata: parsed.metadata,
504
743
  })
505
744
  }
@@ -511,7 +750,7 @@ async function collectDocuments(root, settings) {
511
750
  async function collectLayouts(root, settings) {
512
751
  const layouts = new Map()
513
752
  if (!(await assertDirectory(root, settings.layoutsDirectory, { optional: true }))) return layouts
514
- for (const path of await walkFiles(settings.layoutsDirectory)) {
753
+ for (const path of await walkFiles(settings.layoutsDirectory, settings.observeDirectory)) {
515
754
  if (!path.endsWith(".matra.md")) continue
516
755
  const name = relative(settings.layoutsDirectory, path)
517
756
  .split(sep)
@@ -536,7 +775,7 @@ async function collectLayouts(root, settings) {
536
775
 
537
776
  async function collectPages(root, settings, documents, layouts) {
538
777
  const pages = []
539
- for (const path of await walkFiles(settings.pagesDirectory)) {
778
+ for (const path of await walkFiles(settings.pagesDirectory, settings.observeDirectory)) {
540
779
  if (path.endsWith(".matra.md")) {
541
780
  const source = await readFile(path, "utf8")
542
781
  const frontMatter = parseFrontMatter(source, path)
@@ -560,9 +799,8 @@ async function collectPages(root, settings, documents, layouts) {
560
799
  if (!path.endsWith(".md")) continue
561
800
  const document = documents.find(entry => entry.path === path)
562
801
  if (!document) throw new Error(`Page document was not collected: ${path}`)
563
- const parsed = parseFrontMatter(document.source, path)
564
- const controls = siteControls(parsed.metadata, path)
565
- const metadata = metadataValues(parsed.metadata)
802
+ const controls = siteControls(document.metadata, path)
803
+ const metadata = metadataValues(document.metadata)
566
804
  if (controls.data && Object.keys(metadata).length) {
567
805
  throw new Error(`${path}: use either site.data or ordinary front matter values, not both`)
568
806
  }
@@ -572,8 +810,7 @@ async function collectPages(root, settings, documents, layouts) {
572
810
  id,
573
811
  path,
574
812
  source: document.source,
575
- body: parsed.body,
576
- document,
813
+ document: relative(root, path).split(sep).join("/"),
577
814
  data: controls.data ?? metadata,
578
815
  route: normalizeRoute(controls.route ?? routeFromId(id), settings.format, path),
579
816
  layout: selectedLayout(controls.layout, settings.defaultLayout, layouts, path),
@@ -593,24 +830,29 @@ function sortAndValidateRoutes(pages) {
593
830
  }
594
831
  }
595
832
 
596
- function parseFrontMatter(source, path) {
833
+ function parseFrontMatter(source, path, route) {
597
834
  const opening = /^(?:\uFEFF)?---[ \t]*\r?\n/.exec(source)
598
- if (!opening) return { present: false, metadata: {}, body: source }
835
+ if (!opening) return { present: false, metadata: {}, body: source, bodyLine: 1 }
599
836
  const rest = source.slice(opening[0].length)
600
837
  const closing = /(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/.exec(rest)
601
- if (!closing) throw new SyntaxError(`${path}: unclosed YAML front matter`)
838
+ const at = line => `${path}:${line}${route ? ` (route ${route})` : ""}`
839
+ if (!closing) throw new SyntaxError(`${at(1)}: unclosed YAML front matter`)
602
840
  const yaml = rest.slice(0, closing.index)
603
841
  let metadata
604
842
  try {
605
843
  metadata = loadYaml(yaml)
606
844
  } catch (error) {
607
- throw new SyntaxError(`${path}: invalid YAML front matter: ${error.message}`, { cause: error })
845
+ throw new SyntaxError(
846
+ `${at((error.mark?.line ?? 0) + 2)}: invalid YAML front matter: ${error.message}`,
847
+ { cause: error },
848
+ )
608
849
  }
609
- assertPlainData(metadata, `${path} front matter`)
610
850
  if (metadata === undefined) metadata = {}
611
- if (!isRecord(metadata)) throw new TypeError(`${path}: front matter must be an object`)
851
+ assertPlainData(metadata, `${at(2)} front matter`)
852
+ if (!isRecord(metadata)) throw new TypeError(`${at(2)}: front matter must be an object`)
612
853
  const end = closing.index + closing[0].length
613
- return { present: true, metadata, body: rest.slice(end) }
854
+ const bodyLine = 2 + (rest.slice(0, end).match(/\n/g)?.length ?? 0)
855
+ return { present: true, metadata, body: rest.slice(end), bodyLine }
614
856
  }
615
857
 
616
858
  function siteControls(metadata, path) {
@@ -693,13 +935,7 @@ function normalizeBasePath(value) {
693
935
 
694
936
  async function renderPage(page, settings) {
695
937
  if (page.kind === "markdown") {
696
- return {
697
- tag: "$root",
698
- props: {},
699
- children: markdownToNodes(page.body, {
700
- resolveLink: (href, kind) => resolveMarkdownLink(href, kind, page, settings),
701
- }),
702
- }
938
+ return { tag: "$root", props: {}, children: page.content }
703
939
  }
704
940
  const value = await runLiterate(page.bundle, {
705
941
  globals: globalsFor(page, settings, []),
@@ -737,40 +973,43 @@ function globalsFor(page, settings, content) {
737
973
  }
738
974
  }
739
975
 
740
- function resolveMarkdownLink(href, kind, page, settings) {
976
+ function resolveMarkdownLink(href, kind, document, settings, location) {
741
977
  if (/^(?:[A-Za-z][A-Za-z0-9+.-]*:|\/\/)/.test(href) || href.startsWith("#")) return href
742
978
  const suffixStart = href.search(/[?#]/)
743
979
  const pathname = suffixStart === -1 ? href : href.slice(0, suffixStart)
744
980
  const suffix = suffixStart === -1 ? "" : href.slice(suffixStart)
745
981
  if (!pathname) return href
746
- if (pathname.startsWith("/")) {
747
- const route = normalizeRoute(pathname, settings.format, page.path)
748
- if (settings.routesByRoute.has(route)) return `${route}${suffix}`
749
- if (settings.assetOutputs.has(pathname)) return `${pathname}${suffix}`
750
- throw new Error(`${page.path}: local reference does not resolve: ${href}`)
751
- }
752
982
  let decodedPath
753
983
  try {
754
984
  decodedPath = decodeURIComponent(pathname)
755
985
  } catch (error) {
756
- throw new Error(`${page.path}: invalid encoded local reference: ${href}`, { cause: error })
986
+ throw new Error(`${location}: invalid encoded local reference: ${href}`, { cause: error })
757
987
  }
758
- const target = resolve(dirname(page.path), decodedPath)
759
- const assetRoot = settings.assetsDirectory
760
- if (assetRoot && (target === assetRoot || target.startsWith(`${assetRoot}${sep}`))) {
761
- if (!settings.assetFiles.has(target)) {
762
- throw new Error(`${page.path}: local asset does not exist: ${href}`)
988
+ if (pathname.startsWith("/")) {
989
+ if (settings.assetOutputs.has(decodedPath)) return `${pathname}${suffix}`
990
+ if (kind === "link") {
991
+ if (settings.notFound && pathname === "/404.html") return href
992
+ const route = normalizeRoute(decodedPath, settings.format, location)
993
+ if (settings.routesByRoute.has(route)) return `${route}${suffix}`
994
+ }
995
+ throw new Error(`${location}: local reference does not resolve: ${href}`)
996
+ }
997
+ const target = resolve(dirname(document.path), decodedPath)
998
+ const asset = settings.assetFiles.get(target)
999
+ if (asset !== undefined) return `${asset.split("/").map(encodeURIComponent).join("/")}${suffix}`
1000
+ for (const directory of [settings.assetsDirectory, settings.publicDirectory]) {
1001
+ if (directory && (target === directory || target.startsWith(`${directory}${sep}`))) {
1002
+ throw new Error(`${location}: local asset does not exist: ${href}`)
763
1003
  }
764
- const assetPath = relative(assetRoot, target).split(sep).join("/")
765
- return `/assets/${assetPath}${suffix}`
766
1004
  }
767
- if (settings.routes.has(target) || extname(target) === ".md" || pathname.endsWith(".matra.md")) {
1005
+ if (kind === "image")
1006
+ throw new Error(`${location}: local image is not in site.assets or site.publicDir: ${href}`)
1007
+ if (settings.routes.has(target) || extname(target) === ".md") {
768
1008
  const route = settings.routes.get(target)
769
- if (!route) throw new Error(`${page.path}: local Markdown link does not resolve: ${href}`)
1009
+ if (!route) throw new Error(`${location}: local Markdown link does not resolve: ${href}`)
770
1010
  return `${route}${suffix}`
771
1011
  }
772
- if (kind === "image") throw new Error(`${page.path}: local image is not in site.assets: ${href}`)
773
- throw new Error(`${page.path}: local reference does not resolve: ${href}`)
1012
+ throw new Error(`${location}: local reference does not resolve: ${href}`)
774
1013
  }
775
1014
 
776
1015
  function assertCompleteDocument(ast, source) {
@@ -786,16 +1025,16 @@ function assertCompleteDocument(ast, source) {
786
1025
  }
787
1026
  }
788
1027
 
789
- async function collectAssets(directory) {
1028
+ async function collectAssets(directory, prefix, observeDirectory) {
790
1029
  const assets = []
791
- for (const source of await walkFiles(directory)) {
1030
+ for (const source of await walkFiles(directory, observeDirectory)) {
792
1031
  const name = relative(directory, source).split(sep).join("/")
793
- if (name.split("/").some(part => !isSafeSegment(part))) {
1032
+ if (name.includes("\\") || name.split("/").some(part => !isSafeSegment(part))) {
794
1033
  throw new Error(`Invalid asset path: ${name}`)
795
1034
  }
796
1035
  assets.push({
797
1036
  source,
798
- output: join("assets", ...name.split("/")),
1037
+ output: join(prefix, ...name.split("/")),
799
1038
  content: await readFile(source),
800
1039
  })
801
1040
  }
@@ -816,6 +1055,11 @@ function planOutput(pages, assets, settings) {
816
1055
  routes.set(route, path)
817
1056
  outputs.push(path)
818
1057
  }
1058
+ if (settings.notFound !== undefined) {
1059
+ if (!routes.has(settings.notFound))
1060
+ throw new Error(`site.notFound: unknown page route '${settings.notFound}'`)
1061
+ if (routes.get(settings.notFound) !== "404.html") outputs.push("404.html")
1062
+ }
819
1063
  outputs.push(...assets.map(asset => asset.output))
820
1064
  const seen = new Map()
821
1065
  for (const output of outputs) {