@matra/site-generation 0.0.0-stage → 0.1.0-site.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Matra contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "@matra/site-generation",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-site.0",
4
+ "description": "Declarative static site generation for Matra",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./src/index.mjs"
8
+ },
9
+ "files": [
10
+ "src"
11
+ ],
12
+ "dependencies": {
13
+ "@matra/core": "^0.3.1-site.0",
14
+ "@matra/html": "^0.3.0",
15
+ "js-yaml": "^5.2.2",
16
+ "markdown-it": "^14.3.0"
17
+ },
18
+ "license": "MIT",
19
+ "scripts": {
20
+ "build": "node --check src/index.mjs && node --check src/site.mjs && node --check src/markdown.mjs",
21
+ "check": "pnpm run build",
22
+ "test": "pnpm run build && node --test"
23
+ }
6
24
  }
package/src/index.mjs ADDED
@@ -0,0 +1 @@
1
+ export { buildSite, renderLiterateDocument } from "./site.mjs"
@@ -0,0 +1,96 @@
1
+ import MarkdownIt from "markdown-it"
2
+
3
+ const markdown = new MarkdownIt({ html: false, linkify: false, typographer: false })
4
+ const BLOCK_TAGS = {
5
+ blockquote_open: "blockquote",
6
+ bullet_list_open: "ul",
7
+ heading_open: token => token.tag,
8
+ list_item_open: "li",
9
+ ordered_list_open: "ol",
10
+ paragraph_open: "p",
11
+ table_open: "table",
12
+ thead_open: "thead",
13
+ tbody_open: "tbody",
14
+ tr_open: "tr",
15
+ th_open: "th",
16
+ td_open: "td",
17
+ }
18
+ const INLINE_TAGS = {
19
+ em_open: "em",
20
+ link_open: "a",
21
+ s_open: "del",
22
+ strong_open: "strong",
23
+ }
24
+
25
+ export function markdownToNodes(source, { resolveLink = value => value } = {}) {
26
+ const tokens = markdown.parse(source, {})
27
+ const root = { tag: "$root", props: {}, children: [] }
28
+ const stack = [root]
29
+ for (const token of tokens) {
30
+ if (token.type.endsWith("_open")) {
31
+ if (token.hidden) continue
32
+ const tag = BLOCK_TAGS[token.type]
33
+ if (!tag) continue
34
+ const node = { tag: typeof tag === "function" ? tag(token) : tag, props: {}, children: [] }
35
+ if (token.type === "ordered_list_open" && token.attrGet("start")) {
36
+ node.props.start = Number(token.attrGet("start"))
37
+ }
38
+ stack.at(-1).children.push(node)
39
+ stack.push(node)
40
+ } else if (token.type.endsWith("_close")) {
41
+ if (token.hidden) continue
42
+ if (BLOCK_TAGS[token.type.replace("_close", "_open")]) stack.pop()
43
+ } else if (token.type === "inline") {
44
+ stack.at(-1).children.push(...inlineNodes(token.children ?? [], resolveLink))
45
+ } else if (token.type === "fence" || token.type === "code_block") {
46
+ const codeProps = {}
47
+ const language = token.info.trim().split(/\s+/, 1)[0]
48
+ if (/^[A-Za-z0-9_-]+$/.test(language)) codeProps.class = `language-${language}`
49
+ stack.at(-1).children.push({
50
+ tag: "pre",
51
+ props: {},
52
+ children: [{ tag: "code", props: codeProps, children: [token.content] }],
53
+ })
54
+ } else if (token.type === "hr") {
55
+ stack.at(-1).children.push({ tag: "hr", props: {}, children: [] })
56
+ } else if (token.type === "html_block") {
57
+ if (token.content) stack.at(-1).children.push(token.content)
58
+ }
59
+ }
60
+ return root.children
61
+ }
62
+
63
+ function inlineNodes(tokens, resolveLink) {
64
+ const root = { tag: "$root", props: {}, children: [] }
65
+ const stack = [root]
66
+ for (const token of tokens) {
67
+ if (token.type.endsWith("_open")) {
68
+ const tag = INLINE_TAGS[token.type]
69
+ if (!tag) continue
70
+ const props = Object.fromEntries(token.attrs ?? [])
71
+ if (tag === "a" && props.href) props.href = resolveLink(props.href, "link")
72
+ const node = { tag, props, children: [] }
73
+ stack.at(-1).children.push(node)
74
+ stack.push(node)
75
+ } else if (token.type.endsWith("_close")) {
76
+ if (INLINE_TAGS[token.type.replace("_close", "_open")]) stack.pop()
77
+ } else if (token.type === "image") {
78
+ const props = Object.fromEntries(token.attrs ?? [])
79
+ if (props.src) props.src = resolveLink(props.src, "image")
80
+ props.alt = token.content
81
+ if (token.attrGet("title")) props.title = token.attrGet("title")
82
+ stack.at(-1).children.push({ tag: "img", props, children: [] })
83
+ } else if (token.type === "code_inline") {
84
+ stack.at(-1).children.push({ tag: "code", props: {}, children: [token.content] })
85
+ } else if (token.type === "hardbreak") {
86
+ stack.at(-1).children.push({ tag: "br", props: {}, children: [] })
87
+ } else if (token.type === "softbreak") {
88
+ stack.at(-1).children.push(" ")
89
+ } else if (token.type === "text" || token.type === "html_inline") {
90
+ if (token.content) stack.at(-1).children.push(token.content)
91
+ } else if (token.content) {
92
+ stack.at(-1).children.push(token.content)
93
+ }
94
+ }
95
+ return root.children
96
+ }
package/src/site.mjs ADDED
@@ -0,0 +1,743 @@
1
+ import { randomUUID } from "node:crypto"
2
+ import {
3
+ cp,
4
+ lstat,
5
+ mkdir,
6
+ mkdtemp,
7
+ readdir,
8
+ readFile,
9
+ rename,
10
+ rm,
11
+ writeFile,
12
+ } from "node:fs/promises"
13
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path"
14
+ import { evaluateStatic, parse, staticValueToAST } from "@matra/core"
15
+ import { buildLiterate, runLiterate } from "@matra/core/experimental/literate"
16
+ import { toHTML } from "@matra/html"
17
+ import { load as loadYaml } from "js-yaml"
18
+ import { markdownToNodes } from "./markdown.mjs"
19
+
20
+ const CONFIG_NAMES = ["matra.site.yaml", "matra.site.json", "matra.site.matra"]
21
+ const SITE_KEYS = new Set(["route", "layout", "data"])
22
+
23
+ export async function renderLiterateDocument(markdown, options = {}) {
24
+ const bundle = await buildLiterate(markdown, { document: options.document })
25
+ const value = await runLiterate(bundle, { globals: options.globals })
26
+ return staticValueToAST(value)
27
+ }
28
+
29
+ export async function buildSite(directory) {
30
+ const root = resolve(directory)
31
+ const config = await readConfig(root)
32
+ const settings = normalizeSettings(config, root)
33
+ for (const input of [
34
+ settings.pagesDirectory,
35
+ ...settings.documentDirectories,
36
+ settings.layoutsDirectory,
37
+ ...(settings.assetsDirectory ? [settings.assetsDirectory] : []),
38
+ ]) {
39
+ if (
40
+ input === settings.outputDirectory ||
41
+ input.startsWith(`${settings.outputDirectory}${sep}`) ||
42
+ settings.outputDirectory.startsWith(`${input}${sep}`)
43
+ ) {
44
+ throw new Error("site.output must not overlap a site input directory")
45
+ }
46
+ }
47
+ await Promise.all([
48
+ assertDirectory(root, settings.pagesDirectory),
49
+ ...settings.documentDirectories.map(path => assertDirectory(root, path)),
50
+ assertDirectory(root, settings.layoutsDirectory, { optional: true }),
51
+ ...(settings.assetsDirectory ? [assertDirectory(root, settings.assetsDirectory)] : []),
52
+ ])
53
+ const documents = await collectDocuments(root, settings)
54
+ const layouts = await collectLayouts(root, settings)
55
+ const pages = await collectPages(root, settings, documents, layouts)
56
+ const assets = settings.assetsDirectory ? await collectAssets(settings.assetsDirectory) : []
57
+ const outputPlan = planOutput(pages, assets, settings)
58
+ settings.routes = new Map(pages.map(page => [page.path, page.route]))
59
+ settings.routesByRoute = new Set(pages.map(page => page.route))
60
+ settings.assetFiles = new Set(assets.map(asset => resolve(asset.source)))
61
+ settings.assetOutputs = new Set(assets.map(asset => `/${asset.output.split(sep).join("/")}`))
62
+ await validateOutput(root, settings.outputDirectory, outputPlan)
63
+ settings.documents = documents.map(document => ({
64
+ id: document.id,
65
+ path: document.id,
66
+ metadata: metadataValues(document.metadata),
67
+ content: markdownToNodes(
68
+ document.body,
69
+ settings.routes.has(document.path)
70
+ ? {
71
+ resolveLink: (href, kind) => resolveMarkdownLink(href, kind, document, settings),
72
+ }
73
+ : {},
74
+ ),
75
+ }))
76
+ for (const layout of layouts.values()) {
77
+ layout.bundle = await buildLiterate(layout.source, { document: layout.document })
78
+ }
79
+ for (const page of pages) {
80
+ if (page.kind === "program") {
81
+ page.bundle = await buildLiterate(page.source, { document: page.document })
82
+ }
83
+ }
84
+
85
+ const rendered = []
86
+ for (const page of pages) {
87
+ const content = await renderPage(page, settings)
88
+ const document = page.layout
89
+ ? await renderLayout(layouts.get(page.layout), content, page, settings)
90
+ : content
91
+ assertCompleteDocument(document, page.source)
92
+ rendered.push({
93
+ path: outputPlan.routes.get(page.route),
94
+ content: `<!doctype html>\n${toHTML(document, { basePath: settings.basePath })}\n`,
95
+ })
96
+ }
97
+ for (const asset of assets) rendered.push({ path: asset.output, content: asset.content })
98
+ await publish(root, settings.outputDirectory, rendered)
99
+ return rendered.map(file => join(settings.outputDirectory, file.path))
100
+ }
101
+
102
+ async function readConfig(root) {
103
+ const found = []
104
+ for (const name of CONFIG_NAMES) {
105
+ try {
106
+ const info = await lstat(join(root, name))
107
+ if (!info.isFile()) throw new Error(`Site configuration must be a regular file: ${name}`)
108
+ found.push(name)
109
+ } catch (error) {
110
+ if (error.code !== "ENOENT") throw error
111
+ }
112
+ }
113
+ if (found.length !== 1) {
114
+ throw new Error(
115
+ found.length
116
+ ? `Use exactly one site configuration file: ${found.join(", ")}`
117
+ : `Missing site configuration. Expected one of: ${CONFIG_NAMES.join(", ")}`,
118
+ )
119
+ }
120
+ const name = found[0]
121
+ const source = await readFile(join(root, name), "utf8")
122
+ let config
123
+ try {
124
+ if (name.endsWith(".json")) config = JSON.parse(source)
125
+ else if (name.endsWith(".matra")) config = evaluateStatic(parse(source))
126
+ else config = loadYaml(source)
127
+ } catch (error) {
128
+ throw new SyntaxError(`${name}: ${error.message}`, { cause: error })
129
+ }
130
+ assertPlainData(config, name)
131
+ if (!isRecord(config)) throw new TypeError(`${name}: configuration must be an object`)
132
+ return config
133
+ }
134
+
135
+ function normalizeSettings(config, root) {
136
+ rejectUnknownKeys(config, new Set(["version", "site"]), "configuration")
137
+ if (config.version !== 1) throw new TypeError("Site configuration must set version: 1")
138
+ if (!isRecord(config.site)) throw new TypeError("Configuration must define a site object")
139
+ rejectUnknownKeys(
140
+ config.site,
141
+ new Set([
142
+ "pages",
143
+ "documents",
144
+ "layouts",
145
+ "defaultLayout",
146
+ "output",
147
+ "format",
148
+ "assets",
149
+ "basePath",
150
+ "data",
151
+ ]),
152
+ "site",
153
+ )
154
+ const site = config.site
155
+ const resolveDirectory = (value, label, fallback) => {
156
+ const name = value === undefined ? fallback : value
157
+ if (typeof name !== "string" || !name || isAbsolute(name) || name.includes("\\")) {
158
+ throw new TypeError(`site.${label} must be a non-empty relative path`)
159
+ }
160
+ const path = resolve(root, name)
161
+ if (path !== root && !path.startsWith(`${root}${sep}`)) {
162
+ throw new TypeError(`site.${label} must stay inside the project directory`)
163
+ }
164
+ return path
165
+ }
166
+ const pagesDirectory = resolveDirectory(site.pages, "pages", "pages")
167
+ const documentsValue = site.documents === undefined ? [] : site.documents
168
+ const documentNames = typeof documentsValue === "string" ? [documentsValue] : documentsValue
169
+ if (!Array.isArray(documentNames)) {
170
+ throw new TypeError("site.documents must be a path or a list of paths")
171
+ }
172
+ const documentDirectories = [
173
+ ...new Set([
174
+ pagesDirectory,
175
+ ...documentNames.map((name, index) => resolveDirectory(name, `documents[${index}]`, name)),
176
+ ]),
177
+ ]
178
+ const layoutsDirectory = resolveDirectory(site.layouts, "layouts", "layouts")
179
+ const outputDirectory = resolveDirectory(site.output, "output", "dist")
180
+ const assetsDirectory =
181
+ site.assets === undefined ? undefined : resolveDirectory(site.assets, "assets", site.assets)
182
+ if (site.format !== undefined && !["directory", "flat"].includes(site.format)) {
183
+ throw new TypeError("site.format must be 'directory' or 'flat'")
184
+ }
185
+ const format = site.format ?? "directory"
186
+ const basePath = normalizeBasePath(site.basePath === undefined ? "" : site.basePath)
187
+ if (site.data !== undefined) assertPlainData(site.data, "site.data")
188
+ if (site.data !== undefined && !isRecord(site.data)) {
189
+ throw new TypeError("site.data must be an object")
190
+ }
191
+ if (
192
+ site.defaultLayout !== undefined &&
193
+ site.defaultLayout !== false &&
194
+ (typeof site.defaultLayout !== "string" || !site.defaultLayout)
195
+ ) {
196
+ throw new TypeError("site.defaultLayout must be a layout name or false")
197
+ }
198
+ return {
199
+ root,
200
+ pagesDirectory,
201
+ documentDirectories,
202
+ layoutsDirectory,
203
+ outputDirectory,
204
+ assetsDirectory,
205
+ defaultLayout: site.defaultLayout === undefined ? false : site.defaultLayout,
206
+ format,
207
+ basePath,
208
+ data: site.data ?? {},
209
+ }
210
+ }
211
+
212
+ async function assertDirectory(root, path, { optional = false } = {}) {
213
+ if (path !== root && !path.startsWith(`${root}${sep}`)) {
214
+ throw new Error(`Input directory escapes project root: ${path}`)
215
+ }
216
+ let current = root
217
+ const parts = relative(root, path).split(sep).filter(Boolean)
218
+ for (const part of parts) {
219
+ current = join(current, part)
220
+ try {
221
+ const info = await lstat(current)
222
+ if (!info.isDirectory())
223
+ throw new Error(`Expected a directory, not a symlink or file: ${current}`)
224
+ } catch (error) {
225
+ if (error.code === "ENOENT" && optional) return false
226
+ throw error
227
+ }
228
+ }
229
+ return true
230
+ }
231
+
232
+ async function walkFiles(directory) {
233
+ const results = []
234
+ async function visit(current) {
235
+ const entries = await readdir(current, { withFileTypes: true })
236
+ entries.sort((left, right) => left.name.localeCompare(right.name, "en"))
237
+ for (const entry of entries) {
238
+ const path = join(current, entry.name)
239
+ if (entry.isDirectory()) await visit(path)
240
+ else if (entry.isFile()) results.push(path)
241
+ else throw new Error(`Unsupported input file type: ${path}`)
242
+ }
243
+ }
244
+ await visit(directory)
245
+ return results
246
+ }
247
+
248
+ async function collectDocuments(root, settings) {
249
+ const documents = []
250
+ const ids = new Map()
251
+ for (const directory of settings.documentDirectories) {
252
+ await assertDirectory(root, directory)
253
+ for (const path of await walkFiles(directory)) {
254
+ if (!path.endsWith(".md") || path.endsWith(".matra.md")) continue
255
+ const id = relative(directory, path).split(sep).join("/")
256
+ const key = id.toLocaleLowerCase("en-US")
257
+ if (ids.has(key)) {
258
+ if (ids.get(key) !== path) throw new Error(`Duplicate document ID ignoring case: ${id}`)
259
+ continue
260
+ }
261
+ ids.set(key, path)
262
+ const source = await readFile(path, "utf8")
263
+ const parsed = parseFrontMatter(source, path)
264
+ documents.push({
265
+ id,
266
+ path,
267
+ source,
268
+ body: parsed.body,
269
+ metadata: parsed.metadata,
270
+ })
271
+ }
272
+ }
273
+ documents.sort((left, right) => left.id.localeCompare(right.id, "en"))
274
+ return documents
275
+ }
276
+
277
+ async function collectLayouts(root, settings) {
278
+ const layouts = new Map()
279
+ if (!(await assertDirectory(root, settings.layoutsDirectory, { optional: true }))) return layouts
280
+ for (const path of await walkFiles(settings.layoutsDirectory)) {
281
+ if (!path.endsWith(".matra.md")) continue
282
+ const name = relative(settings.layoutsDirectory, path)
283
+ .split(sep)
284
+ .join("/")
285
+ .slice(0, -".matra.md".length)
286
+ if (!/^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/.test(name)) {
287
+ throw new Error(`Invalid layout name in ${path}: ${name}`)
288
+ }
289
+ if (layouts.has(name)) throw new Error(`Duplicate layout: ${name}`)
290
+ const source = await readFile(path, "utf8")
291
+ const frontMatter = parseFrontMatter(source, path)
292
+ if (!frontMatter.present) throw new Error(`${path}: layout requires Matra front matter`)
293
+ layouts.set(name, {
294
+ name,
295
+ path,
296
+ source,
297
+ document: relative(root, path).split(sep).join("/"),
298
+ })
299
+ }
300
+ return layouts
301
+ }
302
+
303
+ async function collectPages(root, settings, documents, layouts) {
304
+ const pages = []
305
+ for (const path of await walkFiles(settings.pagesDirectory)) {
306
+ if (path.endsWith(".matra.md")) {
307
+ const source = await readFile(path, "utf8")
308
+ const frontMatter = parseFrontMatter(source, path)
309
+ if (!frontMatter.present) throw new Error(`${path}: program page requires Matra front matter`)
310
+ const controls = siteControls(frontMatter.metadata, path)
311
+ const relativePath = relative(settings.pagesDirectory, path).split(sep).join("/")
312
+ const id = relativePath.slice(0, -".matra.md".length) + ".md"
313
+ const route = normalizeRoute(controls.route ?? routeFromId(id), settings.format, path)
314
+ pages.push({
315
+ kind: "program",
316
+ id,
317
+ path,
318
+ source,
319
+ document: relative(root, path).split(sep).join("/"),
320
+ data: controls.data ?? {},
321
+ route,
322
+ layout: selectedLayout(controls.layout, settings.defaultLayout, layouts, path),
323
+ })
324
+ continue
325
+ }
326
+ if (!path.endsWith(".md")) continue
327
+ const document = documents.find(entry => entry.path === path)
328
+ if (!document) throw new Error(`Page document was not collected: ${path}`)
329
+ const parsed = parseFrontMatter(document.source, path)
330
+ const controls = siteControls(parsed.metadata, path)
331
+ const metadata = metadataValues(parsed.metadata)
332
+ if (controls.data && Object.keys(metadata).length) {
333
+ throw new Error(`${path}: use either site.data or ordinary front matter values, not both`)
334
+ }
335
+ const id = relative(settings.pagesDirectory, path).split(sep).join("/")
336
+ pages.push({
337
+ kind: "markdown",
338
+ id,
339
+ path,
340
+ source: document.source,
341
+ body: parsed.body,
342
+ document,
343
+ data: controls.data ?? metadata,
344
+ route: normalizeRoute(controls.route ?? routeFromId(id), settings.format, path),
345
+ layout: selectedLayout(controls.layout, settings.defaultLayout, layouts, path),
346
+ })
347
+ }
348
+ pages.sort((left, right) => left.route.localeCompare(right.route, "en"))
349
+ const routes = new Set()
350
+ for (const page of pages) {
351
+ const key = page.route.toLocaleLowerCase("en-US")
352
+ if (routes.has(key)) throw new Error(`Duplicate route: ${page.route}`)
353
+ routes.add(key)
354
+ }
355
+ return pages
356
+ }
357
+
358
+ function parseFrontMatter(source, path) {
359
+ const opening = /^(?:\uFEFF)?---[ \t]*\r?\n/.exec(source)
360
+ if (!opening) return { present: false, metadata: {}, body: source }
361
+ const rest = source.slice(opening[0].length)
362
+ const closing = /(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/.exec(rest)
363
+ if (!closing) throw new SyntaxError(`${path}: unclosed YAML front matter`)
364
+ const yaml = rest.slice(0, closing.index)
365
+ let metadata
366
+ try {
367
+ metadata = loadYaml(yaml)
368
+ } catch (error) {
369
+ throw new SyntaxError(`${path}: invalid YAML front matter: ${error.message}`, { cause: error })
370
+ }
371
+ assertPlainData(metadata, `${path} front matter`)
372
+ if (metadata === undefined) metadata = {}
373
+ if (!isRecord(metadata)) throw new TypeError(`${path}: front matter must be an object`)
374
+ const end = closing.index + closing[0].length
375
+ return { present: true, metadata, body: rest.slice(end) }
376
+ }
377
+
378
+ function siteControls(metadata, path) {
379
+ const value = Object.hasOwn(metadata, "site") ? metadata.site : {}
380
+ if (!isRecord(value)) throw new TypeError(`${path}: site front matter must be an object`)
381
+ rejectUnknownKeys(value, SITE_KEYS, `${path} site front matter`)
382
+ if (value.route !== undefined && typeof value.route !== "string") {
383
+ throw new TypeError(`${path}: site.route must be a string`)
384
+ }
385
+ if (
386
+ value.layout !== undefined &&
387
+ value.layout !== false &&
388
+ (typeof value.layout !== "string" || !value.layout)
389
+ ) {
390
+ throw new TypeError(`${path}: site.layout must be a layout name or false`)
391
+ }
392
+ if (value.data !== undefined) {
393
+ assertPlainData(value.data, `${path} site.data`)
394
+ if (!isRecord(value.data)) throw new TypeError(`${path}: site.data must be an object`)
395
+ }
396
+ return value
397
+ }
398
+
399
+ function metadataValues(metadata) {
400
+ const values = { ...metadata }
401
+ delete values.site
402
+ return values
403
+ }
404
+
405
+ function selectedLayout(pageLayout, defaultLayout, layouts, path) {
406
+ const name = pageLayout === false ? false : (pageLayout ?? defaultLayout)
407
+ if (name && !layouts.has(name)) throw new Error(`${path}: unknown layout '${name}'`)
408
+ return name || false
409
+ }
410
+
411
+ function routeFromId(id) {
412
+ const noExtension = id.replace(/\.md$/, "")
413
+ if (noExtension === "index") return "/"
414
+ const route = noExtension.endsWith("/index")
415
+ ? noExtension.slice(0, -"/index".length)
416
+ : noExtension
417
+ return `/${route}/`
418
+ }
419
+
420
+ function normalizeRoute(route, format, path) {
421
+ if (
422
+ !route.startsWith("/") ||
423
+ route.includes("\\") ||
424
+ route.includes("?") ||
425
+ route.includes("#") ||
426
+ route.includes("%")
427
+ ) {
428
+ throw new TypeError(`${path}: invalid site route '${route}'`)
429
+ }
430
+ const parts = route.split("/").slice(1)
431
+ if (parts.at(-1) === "") parts.pop()
432
+ if (parts.some(part => !isSafeSegment(part))) {
433
+ throw new TypeError(`${path}: invalid site route '${route}'`)
434
+ }
435
+ if (parts.length === 0) return "/"
436
+ const normalized = `/${parts.join("/")}`
437
+ return format === "directory" ? `${normalized}/` : normalized
438
+ }
439
+
440
+ function normalizeBasePath(value) {
441
+ if (
442
+ typeof value !== "string" ||
443
+ value.includes("?") ||
444
+ value.includes("#") ||
445
+ value.includes("\\")
446
+ ) {
447
+ throw new TypeError("site.basePath must be a URL path")
448
+ }
449
+ const parts = value.split("/").filter(Boolean)
450
+ if (parts.some(part => part.includes("%") || !isSafeSegment(part))) {
451
+ throw new TypeError("site.basePath contains an invalid path segment")
452
+ }
453
+ return parts.length ? `/${parts.join("/")}` : ""
454
+ }
455
+
456
+ async function renderPage(page, settings) {
457
+ if (page.kind === "markdown") {
458
+ return {
459
+ tag: "$root",
460
+ props: {},
461
+ children: markdownToNodes(page.body, {
462
+ resolveLink: (href, kind) => resolveMarkdownLink(href, kind, page, settings),
463
+ }),
464
+ }
465
+ }
466
+ const value = await runLiterate(page.bundle, {
467
+ globals: globalsFor(page, settings, []),
468
+ })
469
+ return staticValueToAST(value)
470
+ }
471
+
472
+ async function renderLayout(layout, content, page, settings) {
473
+ if (content.tag === "html") {
474
+ throw new TypeError(`${page.source}: a complete HTML document cannot be placed inside a layout`)
475
+ }
476
+ const pageContent = content.tag === "$root" ? content.children : [content]
477
+ const globals = globalsFor(page, settings, pageContent)
478
+ const value = await runLiterate(layout.bundle, { globals })
479
+ return staticValueToAST(value)
480
+ }
481
+
482
+ function globalsFor(page, settings, content) {
483
+ return {
484
+ site: {
485
+ data: settings.data,
486
+ documents: settings.documents,
487
+ },
488
+ page: {
489
+ data: page.data,
490
+ route: page.route,
491
+ content,
492
+ },
493
+ }
494
+ }
495
+
496
+ function resolveMarkdownLink(href, kind, page, settings) {
497
+ if (/^(?:[A-Za-z][A-Za-z0-9+.-]*:|\/\/)/.test(href) || href.startsWith("#")) return href
498
+ const [pathname, suffix = ""] = href.split(/(?=[?#])/, 2)
499
+ if (!pathname) return href
500
+ if (pathname.startsWith("/")) {
501
+ const route = normalizeRoute(pathname, settings.format, page.path)
502
+ if (settings.routesByRoute.has(route)) return `${route}${suffix}`
503
+ if (settings.assetOutputs.has(pathname)) return `${pathname}${suffix}`
504
+ throw new Error(`${page.path}: local reference does not resolve: ${href}`)
505
+ }
506
+ let decodedPath
507
+ try {
508
+ decodedPath = decodeURIComponent(pathname)
509
+ } catch (error) {
510
+ throw new Error(`${page.path}: invalid encoded local reference: ${href}`, { cause: error })
511
+ }
512
+ const target = resolve(dirname(page.path), decodedPath)
513
+ const assetRoot = settings.assetsDirectory
514
+ if (assetRoot && (target === assetRoot || target.startsWith(`${assetRoot}${sep}`))) {
515
+ if (!settings.assetFiles.has(target)) {
516
+ throw new Error(`${page.path}: local asset does not exist: ${href}`)
517
+ }
518
+ const assetPath = relative(assetRoot, target).split(sep).join("/")
519
+ return `/assets/${assetPath}${suffix}`
520
+ }
521
+ if (extname(target) === ".md" || pathname.endsWith(".matra.md")) {
522
+ const route = settings.routes.get(target)
523
+ if (!route) throw new Error(`${page.path}: local Markdown link does not resolve: ${href}`)
524
+ return `${route}${suffix}`
525
+ }
526
+ if (kind === "image") throw new Error(`${page.path}: local image is not in site.assets: ${href}`)
527
+ throw new Error(`${page.path}: local reference does not resolve: ${href}`)
528
+ }
529
+
530
+ function assertCompleteDocument(ast, source) {
531
+ if (ast.tag !== "html") throw new TypeError(`${source}: generated page must have one html root`)
532
+ const heads = ast.children.filter(
533
+ child => child && typeof child === "object" && child.tag === "head",
534
+ )
535
+ const bodies = ast.children.filter(
536
+ child => child && typeof child === "object" && child.tag === "body",
537
+ )
538
+ if (heads.length !== 1 || bodies.length !== 1 || ast.children.length !== 2) {
539
+ throw new TypeError(`${source}: generated html must contain exactly one head and one body`)
540
+ }
541
+ }
542
+
543
+ async function collectAssets(directory) {
544
+ const assets = []
545
+ for (const source of await walkFiles(directory)) {
546
+ const name = relative(directory, source).split(sep).join("/")
547
+ if (name.split("/").some(part => !isSafeSegment(part))) {
548
+ throw new Error(`Invalid asset path: ${name}`)
549
+ }
550
+ assets.push({
551
+ source,
552
+ output: join("assets", ...name.split("/")),
553
+ content: await readFile(source),
554
+ })
555
+ }
556
+ return assets.sort((left, right) => left.output.localeCompare(right.output, "en"))
557
+ }
558
+
559
+ function planOutput(pages, assets, settings) {
560
+ const routes = new Map()
561
+ const outputs = []
562
+ for (const page of pages) {
563
+ const route = page.route
564
+ const path =
565
+ route === "/"
566
+ ? "index.html"
567
+ : settings.format === "flat"
568
+ ? `${route.slice(1)}.html`
569
+ : join(...route.slice(1, -1).split("/"), "index.html")
570
+ routes.set(route, path)
571
+ outputs.push(path)
572
+ }
573
+ outputs.push(...assets.map(asset => asset.output))
574
+ const seen = new Map()
575
+ for (const output of outputs) {
576
+ const normalized = output.split(sep).join("/").toLocaleLowerCase("en-US")
577
+ if (seen.has(normalized))
578
+ throw new Error(`Output collision: ${output} and ${seen.get(normalized)}`)
579
+ seen.set(normalized, output)
580
+ }
581
+ for (const output of outputs) {
582
+ const parts = output.split(sep)
583
+ for (let index = 1; index < parts.length; index++) {
584
+ const prefix = parts.slice(0, index).join("/").toLocaleLowerCase("en-US")
585
+ if (seen.has(prefix)) {
586
+ throw new Error(`File and directory output collision: ${seen.get(prefix)} and ${output}`)
587
+ }
588
+ }
589
+ }
590
+ return { routes, files: outputs }
591
+ }
592
+
593
+ async function validateOutput(root, outputDirectory, plan) {
594
+ let current = root
595
+ const parts = relative(root, outputDirectory).split(sep).filter(Boolean)
596
+ for (const part of parts) {
597
+ current = join(current, part)
598
+ try {
599
+ const info = await lstat(current)
600
+ if (!info.isDirectory()) throw new Error(`Unsafe site output path: ${current}`)
601
+ } catch (error) {
602
+ if (error.code !== "ENOENT") throw error
603
+ }
604
+ }
605
+ try {
606
+ await lstat(outputDirectory)
607
+ } catch (error) {
608
+ if (error.code !== "ENOENT") throw error
609
+ return
610
+ }
611
+ for (const file of plan.files) await validateOutputFile(outputDirectory, file)
612
+ }
613
+
614
+ async function validateOutputFile(output, relativePath) {
615
+ let current = output
616
+ const parts = relativePath.split(sep)
617
+ for (let index = 0; index < parts.length; index++) {
618
+ current = join(current, parts[index])
619
+ try {
620
+ const info = await lstat(current)
621
+ if (info.isSymbolicLink() || (index < parts.length - 1 && !info.isDirectory())) {
622
+ throw new Error(`Unsafe site output path: ${current}`)
623
+ }
624
+ if (index === parts.length - 1 && !info.isFile()) {
625
+ throw new Error(`Expected a regular output file: ${current}`)
626
+ }
627
+ } catch (error) {
628
+ if (error.code !== "ENOENT") throw error
629
+ break
630
+ }
631
+ }
632
+ }
633
+
634
+ async function publish(root, outputDirectory, rendered) {
635
+ const parent = dirname(outputDirectory)
636
+ await ensureDirectoryPath(root, parent)
637
+ await validateOutput(root, outputDirectory, { files: rendered.map(file => file.path) })
638
+ const stage = await mkdtemp(join(parent, `.${basename(outputDirectory)}-stage-`))
639
+ const backup = join(parent, `.${basename(outputDirectory)}-backup-${randomUUID()}`)
640
+ try {
641
+ let existingOutput
642
+ try {
643
+ existingOutput = await lstat(outputDirectory)
644
+ } catch (error) {
645
+ if (error.code !== "ENOENT") throw error
646
+ }
647
+ if (existingOutput) {
648
+ if (!existingOutput.isDirectory())
649
+ throw new Error(`Unsafe site output path: ${outputDirectory}`)
650
+ await validateTree(outputDirectory)
651
+ await cp(outputDirectory, stage, { recursive: true, force: true })
652
+ }
653
+ for (const file of rendered) {
654
+ const stagedPath = join(stage, file.path)
655
+ await mkdir(dirname(stagedPath), { recursive: true })
656
+ await writeFile(stagedPath, file.content)
657
+ }
658
+ let hadOutput = false
659
+ try {
660
+ await rename(outputDirectory, backup)
661
+ hadOutput = true
662
+ } catch (error) {
663
+ if (error.code !== "ENOENT") throw error
664
+ }
665
+ try {
666
+ await rename(stage, outputDirectory)
667
+ } catch (error) {
668
+ if (hadOutput) await rename(backup, outputDirectory)
669
+ throw error
670
+ }
671
+ if (hadOutput) await rm(backup, { recursive: true, force: true })
672
+ } finally {
673
+ await rm(stage, { recursive: true, force: true })
674
+ }
675
+ }
676
+
677
+ async function ensureDirectoryPath(root, path) {
678
+ if (path !== root && !path.startsWith(`${root}${sep}`)) {
679
+ throw new Error(`Site output parent escapes project root: ${path}`)
680
+ }
681
+ let current = root
682
+ for (const part of relative(root, path).split(sep).filter(Boolean)) {
683
+ current = join(current, part)
684
+ try {
685
+ const info = await lstat(current)
686
+ if (!info.isDirectory()) throw new Error(`Unsafe site output path: ${current}`)
687
+ } catch (error) {
688
+ if (error.code !== "ENOENT") throw error
689
+ await mkdir(current)
690
+ }
691
+ }
692
+ }
693
+
694
+ async function validateTree(directory) {
695
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
696
+ const path = join(directory, entry.name)
697
+ if (entry.isDirectory()) await validateTree(path)
698
+ else if (!entry.isFile()) throw new Error(`Unsafe site output entry: ${path}`)
699
+ }
700
+ }
701
+
702
+ function rejectUnknownKeys(value, allowed, label) {
703
+ for (const key of Object.keys(value)) {
704
+ if (!allowed.has(key)) throw new TypeError(`Unknown ${label} setting: ${key}`)
705
+ }
706
+ }
707
+
708
+ function assertPlainData(value, label, active = new Set()) {
709
+ if (value === null || typeof value === "string" || typeof value === "boolean") return
710
+ if (typeof value === "number" && Number.isFinite(value)) return
711
+ if (typeof value !== "object" || active.has(value)) {
712
+ throw new TypeError(`${label} must contain only finite plain data`)
713
+ }
714
+ if (!Array.isArray(value) && !isRecord(value)) {
715
+ throw new TypeError(`${label} must contain only plain objects and arrays`)
716
+ }
717
+ active.add(value)
718
+ for (const item of Array.isArray(value) ? value : Object.values(value)) {
719
+ assertPlainData(item, label, active)
720
+ }
721
+ active.delete(value)
722
+ }
723
+
724
+ function isRecord(value) {
725
+ return (
726
+ value !== null &&
727
+ typeof value === "object" &&
728
+ !Array.isArray(value) &&
729
+ (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)
730
+ )
731
+ }
732
+
733
+ function isSafeSegment(value) {
734
+ return (
735
+ value !== "" &&
736
+ value !== "." &&
737
+ value !== ".." &&
738
+ !/[<>:"|?*]/.test(value) &&
739
+ ![...value].some(character => character.charCodeAt(0) < 0x20) &&
740
+ !/[. ]$/.test(value) &&
741
+ !/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i.test(value)
742
+ )
743
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.