@lvl99dotcom/edaha.md 0.0.0-stage → 0.1.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 +201 -0
- package/README.md +258 -2
- package/dist/cli/bin.d.ts +2 -0
- package/dist/cli/bin.js +9 -0
- package/dist/cli/index.d.ts +41 -0
- package/dist/cli/index.js +110 -0
- package/dist/client/assets/index-BbKEbPS8.css +1 -0
- package/dist/client/assets/index-DtG7vi1d.js +559 -0
- package/dist/client/index.html +13 -0
- package/dist/editor/index.d.ts +62 -0
- package/dist/editor/index.js +102 -0
- package/dist/embeds/bandcamp/index.d.ts +9 -0
- package/dist/embeds/bandcamp/index.js +28 -0
- package/dist/embeds/index.d.ts +40 -0
- package/dist/embeds/index.js +71 -0
- package/dist/embeds/types/index.d.ts +14 -0
- package/dist/embeds/types/index.js +1 -0
- package/dist/embeds/youtube/index.d.ts +17 -0
- package/dist/embeds/youtube/index.js +48 -0
- package/dist/generator/article/index.d.ts +111 -0
- package/dist/generator/article/index.js +257 -0
- package/dist/generator/build/index.d.ts +77 -0
- package/dist/generator/build/index.js +293 -0
- package/dist/generator/config/index.d.ts +59 -0
- package/dist/generator/config/index.js +176 -0
- package/dist/generator/format/index.d.ts +52 -0
- package/dist/generator/format/index.js +102 -0
- package/dist/generator/lists/index.d.ts +63 -0
- package/dist/generator/lists/index.js +132 -0
- package/dist/generator/markdown/index.d.ts +20 -0
- package/dist/generator/markdown/index.js +55 -0
- package/dist/generator/slug/index.d.ts +26 -0
- package/dist/generator/slug/index.js +57 -0
- package/dist/generator/templates/index.d.ts +56 -0
- package/dist/generator/templates/index.js +109 -0
- package/dist/generator/types/index.d.ts +161 -0
- package/dist/generator/types/index.js +1 -0
- package/dist/generator/urls/index.d.ts +40 -0
- package/dist/generator/urls/index.js +67 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +10 -0
- package/dist/server/app/index.d.ts +39 -0
- package/dist/server/app/index.js +138 -0
- package/dist/server/convert/index.d.ts +25 -0
- package/dist/server/convert/index.js +125 -0
- package/dist/server/store/index.d.ts +148 -0
- package/dist/server/store/index.js +411 -0
- package/dist/server/types/index.d.ts +76 -0
- package/dist/server/types/index.js +1 -0
- package/dist/theme/index.d.ts +8 -0
- package/dist/theme/index.js +9 -0
- package/package.json +93 -3
- package/theme/static/site.css +220 -0
- package/theme/templates/article/list.njk +69 -0
- package/theme/templates/article/single.njk +58 -0
- package/theme/templates/layouts/html.njk +50 -0
- package/theme/templates/layouts/rssfeed.njk +28 -0
- package/theme/templates/page/home.njk +21 -0
- package/theme/templates/page/single.njk +18 -0
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { stat } from "node:fs/promises";
|
|
2
|
+
import { basename, join } from "node:path";
|
|
3
|
+
import mime from "mime-types";
|
|
4
|
+
import { parse } from "yaml";
|
|
5
|
+
import { formatBytes, isRelativeUrl, stripHtml, cropText, escapeHtml, } from "../format/index.js";
|
|
6
|
+
import { isSlug, slugify } from "../slug/index.js";
|
|
7
|
+
/** The YAML config header at the start of an article: `<!--yaml ... -->` */
|
|
8
|
+
const HEADER = /^\s*<!--yaml\s*?\n([\s\S]*?)-->/;
|
|
9
|
+
/** The `<!-- readmore -->` shortcode */
|
|
10
|
+
export const READMORE = /<!--\s*readmore\s*-->/;
|
|
11
|
+
/** A leading `# Title` line (only blank lines before it) */
|
|
12
|
+
const LEADING_H1 = /^\s*#[ \t]+(.+?)[ \t#]*(?:\r?\n|$)/;
|
|
13
|
+
/** Any `# Title` line */
|
|
14
|
+
const ANY_H1 = /^#[ \t]+(.+?)[ \t#]*$/m;
|
|
15
|
+
/** Excerpts without a readmore shortcode or config are cropped to this many characters */
|
|
16
|
+
export const EXCERPT_LENGTH = 200;
|
|
17
|
+
const STATUSES = ["published", "draft", "unlisted"];
|
|
18
|
+
/**
|
|
19
|
+
* Split an article's source into its parsed YAML config header (empty if there is none) and its markdown content.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* splitArticle("<!--yaml\ndate: 2026-10-19\n-->\n# Hi"); // { header: { date: "2026-10-19" }, content: "\n# Hi" }
|
|
23
|
+
*/
|
|
24
|
+
export const splitArticle = (source) => {
|
|
25
|
+
const match = HEADER.exec(source);
|
|
26
|
+
if (!match)
|
|
27
|
+
return { header: {}, content: source };
|
|
28
|
+
return {
|
|
29
|
+
header: parse(match[1]) ?? {},
|
|
30
|
+
content: source.slice(match[0].length),
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
/** Throw a config error for an article */
|
|
34
|
+
const fail = (source, message) => {
|
|
35
|
+
throw new Error(`${source}: ${message}`);
|
|
36
|
+
};
|
|
37
|
+
/** Read an optional string field */
|
|
38
|
+
const optionalString = (data, field, source) => {
|
|
39
|
+
const value = data[field];
|
|
40
|
+
if (value === undefined || value === null)
|
|
41
|
+
return undefined;
|
|
42
|
+
if (typeof value !== "string" || value.trim() === "")
|
|
43
|
+
return fail(source, `"${field}" must be a non-empty string`);
|
|
44
|
+
return value.trim();
|
|
45
|
+
};
|
|
46
|
+
/** Check a value is a map */
|
|
47
|
+
const asMap = (value, source, what) => value && typeof value === "object" && !Array.isArray(value)
|
|
48
|
+
? value
|
|
49
|
+
: fail(source, `${what} must be a map of fields`);
|
|
50
|
+
/**
|
|
51
|
+
* Validate an article's config header and fill in defaults.
|
|
52
|
+
*
|
|
53
|
+
* @param folderType - the type folder the article is in
|
|
54
|
+
* @param source - where the article is, for errors
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* parseArticleConfig({ date: "2026-10-19T09:54:00Z" }, "article", "article/hello");
|
|
58
|
+
*/
|
|
59
|
+
export const parseArticleConfig = (header, folderType, source) => {
|
|
60
|
+
const data = asMap(header, source, "the config header");
|
|
61
|
+
const type = optionalString(data, "type", source) ?? folderType;
|
|
62
|
+
if (type !== folderType)
|
|
63
|
+
fail(source, `type "${type}" doesn't match its folder "${folderType}"`);
|
|
64
|
+
const template = optionalString(data, "template", source);
|
|
65
|
+
if (template !== undefined && (!isSlug(template) || template === "list"))
|
|
66
|
+
fail(source, `"template" must be a template name like "single" (lowercase kebab-case, not "list")`);
|
|
67
|
+
const status = (optionalString(data, "status", source) ??
|
|
68
|
+
"published");
|
|
69
|
+
if (!STATUSES.includes(status))
|
|
70
|
+
fail(source, `"status" must be one of ${STATUSES.join(", ")}`);
|
|
71
|
+
const rawDate = data.date instanceof Date ? data.date.toISOString() : data.date;
|
|
72
|
+
if (typeof rawDate !== "string" || Number.isNaN(Date.parse(rawDate)))
|
|
73
|
+
fail(source, `"date" must be an ISO 8601 timestamp`);
|
|
74
|
+
const date = new Date(rawDate).toISOString();
|
|
75
|
+
let author;
|
|
76
|
+
if (typeof data.author === "string")
|
|
77
|
+
author = { name: data.author.trim() };
|
|
78
|
+
else if (data.author !== undefined && data.author !== null) {
|
|
79
|
+
const fields = asMap(data.author, source, `"author"`);
|
|
80
|
+
author = {
|
|
81
|
+
name: optionalString(fields, "name", source) ??
|
|
82
|
+
fail(source, `"author.name" is required`),
|
|
83
|
+
email: optionalString(fields, "email", source),
|
|
84
|
+
url: optionalString(fields, "url", source),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
if (author && !slugify(author.name))
|
|
88
|
+
fail(source, `"author" needs a name with letters or numbers`);
|
|
89
|
+
const attachmentList = data.attachments ?? [];
|
|
90
|
+
if (!Array.isArray(attachmentList))
|
|
91
|
+
fail(source, `"attachments" must be a list`);
|
|
92
|
+
const attachments = attachmentList.map((item, i) => {
|
|
93
|
+
const fields = asMap(item, source, `attachment ${i + 1}`);
|
|
94
|
+
return {
|
|
95
|
+
url: optionalString(fields, "url", source) ??
|
|
96
|
+
fail(source, `attachment ${i + 1} needs a "url"`),
|
|
97
|
+
thumbnail: optionalString(fields, "thumbnail", source),
|
|
98
|
+
mimeType: optionalString(fields, "mimeType", source),
|
|
99
|
+
name: optionalString(fields, "name", source),
|
|
100
|
+
};
|
|
101
|
+
});
|
|
102
|
+
const tagList = data.tags ?? [];
|
|
103
|
+
if (!Array.isArray(tagList) ||
|
|
104
|
+
tagList.some((tag) => typeof tag !== "string" || !slugify(tag)))
|
|
105
|
+
fail(source, `"tags" must be a list of names`);
|
|
106
|
+
return {
|
|
107
|
+
type,
|
|
108
|
+
status,
|
|
109
|
+
date,
|
|
110
|
+
author,
|
|
111
|
+
title: optionalString(data, "title", source),
|
|
112
|
+
template,
|
|
113
|
+
excerpt: optionalString(data, "excerpt", source),
|
|
114
|
+
thumbnail: optionalString(data, "thumbnail", source),
|
|
115
|
+
attachments,
|
|
116
|
+
tags: tagList.map((tag) => tag.trim()),
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
/**
|
|
120
|
+
* Split article markdown into its title heading, body and the part before `<!-- readmore -->`.
|
|
121
|
+
*
|
|
122
|
+
* @example
|
|
123
|
+
* splitContent("# Hi\n\nIntro <!-- readmore -->rest"); // { heading: "Hi", body: "\nIntro rest", beforeReadmore: "\nIntro" }
|
|
124
|
+
*/
|
|
125
|
+
export const splitContent = (content) => {
|
|
126
|
+
const heading = ANY_H1.exec(content)?.[1];
|
|
127
|
+
const withoutTitle = content.replace(LEADING_H1, "");
|
|
128
|
+
const readmore = READMORE.exec(withoutTitle);
|
|
129
|
+
return {
|
|
130
|
+
heading,
|
|
131
|
+
body: withoutTitle.replace(READMORE, "").trim(),
|
|
132
|
+
beforeReadmore: readmore
|
|
133
|
+
? withoutTitle.slice(0, readmore.index).trim()
|
|
134
|
+
: undefined,
|
|
135
|
+
};
|
|
136
|
+
};
|
|
137
|
+
/**
|
|
138
|
+
* Build an author's template data. Authors without a config are the website itself (the blog's name).
|
|
139
|
+
*
|
|
140
|
+
* @param typeUrl - the URL of the article type, which its author lists are under
|
|
141
|
+
*
|
|
142
|
+
* @example
|
|
143
|
+
* authorData({ name: "Matt Scheurich" }, "LiveCanvas", "/news/"); // { name: "Matt Scheurich", slug: "matt-scheurich", listUrl: "/news/authors/matt-scheurich/" }
|
|
144
|
+
*/
|
|
145
|
+
export const authorData = (author, blogName, typeUrl) => {
|
|
146
|
+
const name = author?.name ?? blogName;
|
|
147
|
+
const slug = slugify(name);
|
|
148
|
+
return {
|
|
149
|
+
name,
|
|
150
|
+
slug,
|
|
151
|
+
email: author?.email,
|
|
152
|
+
url: author?.url,
|
|
153
|
+
listUrl: `${typeUrl}authors/${slug}/`,
|
|
154
|
+
};
|
|
155
|
+
};
|
|
156
|
+
/**
|
|
157
|
+
* Build a tag's template data.
|
|
158
|
+
*
|
|
159
|
+
* @param typeUrl - the URL of the article type, which its tag lists are under
|
|
160
|
+
*
|
|
161
|
+
* @example
|
|
162
|
+
* tagData("Release Notes", "/news/"); // { name: "Release Notes", slug: "release-notes", url: "/news/tags/release-notes/" }
|
|
163
|
+
*/
|
|
164
|
+
export const tagData = (name, typeUrl) => {
|
|
165
|
+
const slug = slugify(name);
|
|
166
|
+
return { name, slug, url: `${typeUrl}tags/${slug}/` };
|
|
167
|
+
};
|
|
168
|
+
/**
|
|
169
|
+
* Resolve a URL from an article's config: relative URLs must be files in the article's folder and become
|
|
170
|
+
* root-relative URLs. Returns the URL and, for local files, the file size.
|
|
171
|
+
*/
|
|
172
|
+
const resolveFile = async (url, articleUrl, context) => {
|
|
173
|
+
if (!isRelativeUrl(url))
|
|
174
|
+
return { url };
|
|
175
|
+
const file = join(context.dir, decodeURIComponent(url.split(/[?#]/)[0]));
|
|
176
|
+
try {
|
|
177
|
+
const info = await stat(file);
|
|
178
|
+
if (!info.isFile())
|
|
179
|
+
throw new Error();
|
|
180
|
+
return { url: articleUrl + url, size: info.size };
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
return fail(context.source, `"${url}" was not found in the article's folder`);
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
/**
|
|
187
|
+
* Build an attachment's template data, filling in its name and mime type from the file name and its size from the file.
|
|
188
|
+
*/
|
|
189
|
+
const attachmentData = async (attachment, articleUrl, context) => {
|
|
190
|
+
const file = await resolveFile(attachment.url, articleUrl, context);
|
|
191
|
+
const thumbnail = attachment.thumbnail
|
|
192
|
+
? (await resolveFile(attachment.thumbnail, articleUrl, context)).url
|
|
193
|
+
: undefined;
|
|
194
|
+
const fileName = decodeURIComponent(basename(new URL(attachment.url, "file:///").pathname));
|
|
195
|
+
return {
|
|
196
|
+
name: attachment.name ?? fileName,
|
|
197
|
+
thumbnail,
|
|
198
|
+
url: file.url,
|
|
199
|
+
mimeType: attachment.mimeType ||
|
|
200
|
+
mime.lookup(fileName) ||
|
|
201
|
+
"application/octet-stream",
|
|
202
|
+
size: file.size,
|
|
203
|
+
sizeRelative: file.size === undefined ? undefined : formatBytes(file.size),
|
|
204
|
+
};
|
|
205
|
+
};
|
|
206
|
+
/**
|
|
207
|
+
* Build an article's template data from its source. Returns undefined for drafts, which are not built.
|
|
208
|
+
*
|
|
209
|
+
* @example
|
|
210
|
+
* await loadArticle(source, "article", context);
|
|
211
|
+
*/
|
|
212
|
+
export const loadArticle = async (source, type, context) => {
|
|
213
|
+
const { header, content } = splitArticle(source);
|
|
214
|
+
const config = parseArticleConfig(header, type, context.source);
|
|
215
|
+
if (config.status === "draft")
|
|
216
|
+
return undefined;
|
|
217
|
+
const parts = splitContent(content);
|
|
218
|
+
const title = config.title ??
|
|
219
|
+
parts.heading ??
|
|
220
|
+
fail(context.source, `needs a "title" in its config or a "# Title" heading`);
|
|
221
|
+
const url = context.url;
|
|
222
|
+
const body = parts.body;
|
|
223
|
+
const bodyHtml = context.renderMarkdown(await context.replaceEmbeds(body), url);
|
|
224
|
+
const bodyText = stripHtml(bodyHtml);
|
|
225
|
+
const excerptSource = config.excerpt ?? parts.beforeReadmore;
|
|
226
|
+
let excerpt;
|
|
227
|
+
let excerptHtml;
|
|
228
|
+
if (excerptSource === undefined) {
|
|
229
|
+
excerpt = cropText(bodyText, EXCERPT_LENGTH);
|
|
230
|
+
excerptHtml = `<p>${escapeHtml(excerpt)}</p>`;
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
excerpt = excerptSource;
|
|
234
|
+
excerptHtml = context.renderMarkdown(await context.replaceEmbeds(excerptSource), url);
|
|
235
|
+
}
|
|
236
|
+
return {
|
|
237
|
+
type,
|
|
238
|
+
status: config.status,
|
|
239
|
+
date: config.date,
|
|
240
|
+
slug: context.slug,
|
|
241
|
+
template: config.template ?? "single",
|
|
242
|
+
url,
|
|
243
|
+
title,
|
|
244
|
+
author: authorData(config.author, context.blog.name, context.typeUrl),
|
|
245
|
+
thumbnail: config.thumbnail
|
|
246
|
+
? (await resolveFile(config.thumbnail, url, context)).url
|
|
247
|
+
: undefined,
|
|
248
|
+
tags: config.tags.map((tag) => tagData(tag, context.typeUrl)),
|
|
249
|
+
excerpt,
|
|
250
|
+
excerptText: stripHtml(excerptHtml),
|
|
251
|
+
excerptHtml,
|
|
252
|
+
body,
|
|
253
|
+
bodyText,
|
|
254
|
+
bodyHtml,
|
|
255
|
+
attachments: await Promise.all(config.attachments.map((attachment) => attachmentData(attachment, url, context))),
|
|
256
|
+
};
|
|
257
|
+
};
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { type EmbedRenderer } from "../../embeds/index.ts";
|
|
2
|
+
import { type ArticleTypeConfig, type BlogConfig } from "../config/index.ts";
|
|
3
|
+
import type { Logger, TemplateDataArticle, TemplateDataBlog } from "../types/index.ts";
|
|
4
|
+
export { RESERVED_TYPES } from "../config/index.ts";
|
|
5
|
+
/** Used for feeds when neither `SITE_URL` nor `siteUrl` in config.yml is set */
|
|
6
|
+
export declare const DEFAULT_SITE_URL = "http://localhost";
|
|
7
|
+
/** Options for building the blog */
|
|
8
|
+
export interface BuildOptions {
|
|
9
|
+
/** The site folder: holds config.yml and articles/, and optionally templates/ and static/ */
|
|
10
|
+
siteDir: string;
|
|
11
|
+
/** The default theme folder (holds templates/ and static/) that the site's own files override. Default: THEME_DIR */
|
|
12
|
+
themeDir?: string;
|
|
13
|
+
/** The website's absolute URL, for feeds. Defaults to `siteUrl` in config.yml, then DEFAULT_SITE_URL with a warning. */
|
|
14
|
+
siteUrl?: string | undefined;
|
|
15
|
+
/** Where warnings go (defaults to console) */
|
|
16
|
+
logger?: Logger;
|
|
17
|
+
/** Fetches extra data for embeds (defaults to the global fetch) */
|
|
18
|
+
fetch?: typeof fetch;
|
|
19
|
+
/** Embed renderers (defaults to all) */
|
|
20
|
+
embedRenderers?: readonly EmbedRenderer[];
|
|
21
|
+
}
|
|
22
|
+
/** What a build produced */
|
|
23
|
+
export interface BuildResult {
|
|
24
|
+
/** The absolute output directory */
|
|
25
|
+
outputDir: string;
|
|
26
|
+
/** The absolute folder the files were copied to, if config.yml sets `publishDir` */
|
|
27
|
+
publishDir: string | undefined;
|
|
28
|
+
/** Rendered articles (published and unlisted) */
|
|
29
|
+
articles: TemplateDataArticle[];
|
|
30
|
+
/** Files written, relative to the output directory (and the publish directory) */
|
|
31
|
+
files: string[];
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Resolve `outputDir` from config.yml: a folder inside the site folder, apart from its source folders, as it is
|
|
35
|
+
* emptied on every build.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* resolveOutputDir("/site", "dist"); // "/site/dist"
|
|
39
|
+
*/
|
|
40
|
+
export declare const resolveOutputDir: (siteDir: string, folder: string) => string;
|
|
41
|
+
/**
|
|
42
|
+
* Resolve `publishDir` from config.yml, relative to the site folder: any folder apart from the site folder, e.g.
|
|
43
|
+
* another app's build folder.
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* resolvePublishDir("/work/blog", "../app/dist"); // "/work/app/dist"
|
|
47
|
+
*/
|
|
48
|
+
export declare const resolvePublishDir: (siteDir: string, folder: string) => string;
|
|
49
|
+
/**
|
|
50
|
+
* Map each static file's path to its source: the theme's files, overridden by the site's files with the same path.
|
|
51
|
+
*
|
|
52
|
+
* @param dirs - static folders, the overriding one last
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* await staticFiles(["/theme/static", "/site/static"]); // Map { "site.css" => "/site/static/site.css", ... }
|
|
56
|
+
*/
|
|
57
|
+
export declare const staticFiles: (dirs: string[]) => Promise<Map<string, string>>;
|
|
58
|
+
/**
|
|
59
|
+
* The blog's template data: its name, description and URL, and each article type's settings and URL.
|
|
60
|
+
*
|
|
61
|
+
* @param typeConfigs - the article types' settings (configured ones, plus defaults for any others)
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
64
|
+
* blogData(config, config.types).types.news.url; // "/news/"
|
|
65
|
+
*/
|
|
66
|
+
export declare const blogData: (config: BlogConfig, typeConfigs: Record<string, ArticleTypeConfig>) => TemplateDataBlog;
|
|
67
|
+
/**
|
|
68
|
+
* Build the blog: render every published and unlisted article with its assets, then each type's paginated list and
|
|
69
|
+
* RSS feed, and its tag and author lists, and copy the static files (the theme's, overridden by the site's `static/`)
|
|
70
|
+
* as they are. Files are written to `outputDir` (emptied first). If `publishDir` is set, they are then copied into it
|
|
71
|
+
* (the website's root): the files published by the previous build are removed from it first, and the build stops if a
|
|
72
|
+
* file is already there.
|
|
73
|
+
*
|
|
74
|
+
* @example
|
|
75
|
+
* await buildBlog({ siteDir: "my-site", siteUrl: "https://example.com" });
|
|
76
|
+
*/
|
|
77
|
+
export declare const buildBlog: (options: BuildOptions) => Promise<BuildResult>;
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import { cp, mkdir, readdir, readFile, rm, stat, writeFile, } from "node:fs/promises";
|
|
2
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
3
|
+
import { EmbedResolver } from "../../embeds/index.js";
|
|
4
|
+
import { loadArticle } from "../article/index.js";
|
|
5
|
+
import { defaultTypeConfig, parseConfig, RESERVED_TYPES, } from "../config/index.js";
|
|
6
|
+
import { collectLists, PAGE_SIZE, pageFile, paginate } from "../lists/index.js";
|
|
7
|
+
import { createMarkdown, renderMarkdown } from "../markdown/index.js";
|
|
8
|
+
import { isSlug } from "../slug/index.js";
|
|
9
|
+
import { THEME_DIR } from "../../theme/index.js";
|
|
10
|
+
import { Templates } from "../templates/index.js";
|
|
11
|
+
import { checkTypePaths, folderPath, folderUrl, slugProblem, } from "../urls/index.js";
|
|
12
|
+
export { RESERVED_TYPES } from "../config/index.js";
|
|
13
|
+
/** Used for feeds when neither `SITE_URL` nor `siteUrl` in config.yml is set */
|
|
14
|
+
export const DEFAULT_SITE_URL = "http://localhost";
|
|
15
|
+
/** The site's folders that hold its sources, which built files must never be written into */
|
|
16
|
+
const SOURCE_FOLDERS = ["articles", "templates", "static"];
|
|
17
|
+
/** List the names of sub-folders in a folder (none if it doesn't exist) */
|
|
18
|
+
const subfolders = async (dir) => {
|
|
19
|
+
try {
|
|
20
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
21
|
+
return entries
|
|
22
|
+
.filter((entry) => entry.isDirectory())
|
|
23
|
+
.map((entry) => entry.name)
|
|
24
|
+
.sort();
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return [];
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
/** List every file in a folder and its sub-folders, relative to it (none if it doesn't exist) */
|
|
31
|
+
const listFiles = async (dir) => {
|
|
32
|
+
try {
|
|
33
|
+
const entries = await readdir(dir, {
|
|
34
|
+
recursive: true,
|
|
35
|
+
withFileTypes: true,
|
|
36
|
+
});
|
|
37
|
+
return entries
|
|
38
|
+
.filter((entry) => entry.isFile())
|
|
39
|
+
.map((entry) => relative(dir, join(entry.parentPath, entry.name)).split(sep).join("/"))
|
|
40
|
+
.sort();
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return [];
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
/** Whether a path exists */
|
|
47
|
+
const exists = (path) => stat(path).then(() => true, () => false);
|
|
48
|
+
/** Whether one folder is the other or inside it */
|
|
49
|
+
const overlaps = (a, b) => {
|
|
50
|
+
const fromA = relative(a, b);
|
|
51
|
+
const fromB = relative(b, a);
|
|
52
|
+
return !fromA || !fromB || !fromA.startsWith("..") || !fromB.startsWith("..");
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Resolve `outputDir` from config.yml: a folder inside the site folder, apart from its source folders, as it is
|
|
56
|
+
* emptied on every build.
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* resolveOutputDir("/site", "dist"); // "/site/dist"
|
|
60
|
+
*/
|
|
61
|
+
export const resolveOutputDir = (siteDir, folder) => {
|
|
62
|
+
const dir = resolve(siteDir, folder);
|
|
63
|
+
const fromSite = relative(resolve(siteDir), dir);
|
|
64
|
+
if (!fromSite || fromSite.startsWith("..") || isAbsolute(fromSite))
|
|
65
|
+
throw new Error(`config.yml: "outputDir" must be a folder inside the site folder, got "${folder}"`);
|
|
66
|
+
if (SOURCE_FOLDERS.some((source) => overlaps(join(siteDir, source), dir)))
|
|
67
|
+
throw new Error(`config.yml: "outputDir" must be apart from ${SOURCE_FOLDERS.join(", ")}, got "${folder}"`);
|
|
68
|
+
return dir;
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* Resolve `publishDir` from config.yml, relative to the site folder: any folder apart from the site folder, e.g.
|
|
72
|
+
* another app's build folder.
|
|
73
|
+
*
|
|
74
|
+
* @example
|
|
75
|
+
* resolvePublishDir("/work/blog", "../app/dist"); // "/work/app/dist"
|
|
76
|
+
*/
|
|
77
|
+
export const resolvePublishDir = (siteDir, folder) => {
|
|
78
|
+
const dir = resolve(siteDir, folder);
|
|
79
|
+
if (overlaps(resolve(siteDir), dir))
|
|
80
|
+
throw new Error(`config.yml: "publishDir" must be a folder apart from the site folder, got "${folder}"`);
|
|
81
|
+
return dir;
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* Map each static file's path to its source: the theme's files, overridden by the site's files with the same path.
|
|
85
|
+
*
|
|
86
|
+
* @param dirs - static folders, the overriding one last
|
|
87
|
+
*
|
|
88
|
+
* @example
|
|
89
|
+
* await staticFiles(["/theme/static", "/site/static"]); // Map { "site.css" => "/site/static/site.css", ... }
|
|
90
|
+
*/
|
|
91
|
+
export const staticFiles = async (dirs) => {
|
|
92
|
+
const files = new Map();
|
|
93
|
+
for (const dir of dirs)
|
|
94
|
+
for (const file of await listFiles(dir))
|
|
95
|
+
files.set(file, join(dir, file));
|
|
96
|
+
return new Map([...files].sort(([a], [b]) => (a < b ? -1 : 1)));
|
|
97
|
+
};
|
|
98
|
+
/**
|
|
99
|
+
* An article type's template data: its settings and URL.
|
|
100
|
+
*/
|
|
101
|
+
const typeData = (blogPath, config) => ({
|
|
102
|
+
...config,
|
|
103
|
+
url: folderUrl(folderPath(blogPath, config.path)),
|
|
104
|
+
});
|
|
105
|
+
/**
|
|
106
|
+
* The blog's template data: its name, description and URL, and each article type's settings and URL.
|
|
107
|
+
*
|
|
108
|
+
* @param typeConfigs - the article types' settings (configured ones, plus defaults for any others)
|
|
109
|
+
*
|
|
110
|
+
* @example
|
|
111
|
+
* blogData(config, config.types).types.news.url; // "/news/"
|
|
112
|
+
*/
|
|
113
|
+
export const blogData = (config, typeConfigs) => ({
|
|
114
|
+
name: config.name,
|
|
115
|
+
description: config.description,
|
|
116
|
+
path: config.path,
|
|
117
|
+
url: folderUrl(folderPath(config.path)),
|
|
118
|
+
types: Object.fromEntries(Object.entries(typeConfigs).map(([type, typeConfig]) => [
|
|
119
|
+
type,
|
|
120
|
+
typeData(config.path, typeConfig),
|
|
121
|
+
])),
|
|
122
|
+
});
|
|
123
|
+
/**
|
|
124
|
+
* Build the blog: render every published and unlisted article with its assets, then each type's paginated list and
|
|
125
|
+
* RSS feed, and its tag and author lists, and copy the static files (the theme's, overridden by the site's `static/`)
|
|
126
|
+
* as they are. Files are written to `outputDir` (emptied first). If `publishDir` is set, they are then copied into it
|
|
127
|
+
* (the website's root): the files published by the previous build are removed from it first, and the build stops if a
|
|
128
|
+
* file is already there.
|
|
129
|
+
*
|
|
130
|
+
* @example
|
|
131
|
+
* await buildBlog({ siteDir: "my-site", siteUrl: "https://example.com" });
|
|
132
|
+
*/
|
|
133
|
+
export const buildBlog = async (options) => {
|
|
134
|
+
const logger = options.logger ?? console;
|
|
135
|
+
const siteDir = resolve(options.siteDir);
|
|
136
|
+
const themeDir = options.themeDir ?? THEME_DIR;
|
|
137
|
+
const config = parseConfig(await readFile(join(siteDir, "config.yml"), "utf8"));
|
|
138
|
+
const outputDir = resolveOutputDir(siteDir, config.outputDir);
|
|
139
|
+
const publishDir = config.publishDir === undefined
|
|
140
|
+
? undefined
|
|
141
|
+
: resolvePublishDir(siteDir, config.publishDir);
|
|
142
|
+
const templates = new Templates([join(siteDir, "templates"), join(themeDir, "templates")], logger);
|
|
143
|
+
const siteUrl = options.siteUrl || config.siteUrl;
|
|
144
|
+
if (!siteUrl)
|
|
145
|
+
logger.warn(`SITE_URL is not set and config.yml has no "siteUrl"; feeds will link to ${DEFAULT_SITE_URL}`);
|
|
146
|
+
const site = {
|
|
147
|
+
url: (siteUrl || DEFAULT_SITE_URL).replace(/\/+$/, ""),
|
|
148
|
+
};
|
|
149
|
+
// Article types: configured ones, plus any other type folders (with defaults)
|
|
150
|
+
const articlesDir = join(siteDir, "articles");
|
|
151
|
+
const typeFolders = await subfolders(articlesDir);
|
|
152
|
+
const typeConfigs = { ...config.types };
|
|
153
|
+
for (const type of typeFolders) {
|
|
154
|
+
if (!isSlug(type) || RESERVED_TYPES.includes(type))
|
|
155
|
+
throw new Error(`articles/${type}: article types must be lowercase kebab-case and not ${RESERVED_TYPES.join(" or ")}`);
|
|
156
|
+
if (!typeConfigs[type]) {
|
|
157
|
+
logger.warn(`articles/${type}: type "${type}" is not in config.yml; using the default settings`);
|
|
158
|
+
typeConfigs[type] = defaultTypeConfig(type);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
checkTypePaths(config.path, typeConfigs, config.reservedPaths);
|
|
162
|
+
const blog = blogData(config, typeConfigs);
|
|
163
|
+
const markdown = createMarkdown();
|
|
164
|
+
const embeds = new EmbedResolver({
|
|
165
|
+
fetch: options.fetch ?? fetch,
|
|
166
|
+
logger,
|
|
167
|
+
renderers: options.embedRenderers,
|
|
168
|
+
});
|
|
169
|
+
// Remove what the previous build published, then empty the build folder
|
|
170
|
+
if (publishDir)
|
|
171
|
+
for (const file of await listFiles(outputDir))
|
|
172
|
+
await rm(join(publishDir, file), { force: true });
|
|
173
|
+
await rm(outputDir, { recursive: true, force: true });
|
|
174
|
+
const files = [];
|
|
175
|
+
const write = async (file, contents) => {
|
|
176
|
+
const path = join(outputDir, file);
|
|
177
|
+
await mkdir(dirname(path), { recursive: true });
|
|
178
|
+
await writeFile(path, contents);
|
|
179
|
+
files.push(file);
|
|
180
|
+
};
|
|
181
|
+
// Load articles (types that generate nothing are still checked for errors)
|
|
182
|
+
const articles = [];
|
|
183
|
+
for (const type of typeFolders) {
|
|
184
|
+
const typeConfig = blog.types[type];
|
|
185
|
+
const built = typeConfig.generate.article;
|
|
186
|
+
const typeFolder = typeConfig.url.slice(1);
|
|
187
|
+
for (const slug of await subfolders(join(articlesDir, type))) {
|
|
188
|
+
const source = `articles/${type}/${slug}`;
|
|
189
|
+
if (!isSlug(slug))
|
|
190
|
+
throw new Error(`${source}: folder names must be lowercase kebab-case`);
|
|
191
|
+
const problem = slugProblem(slug, type, config.path, typeConfigs, config.reservedPaths);
|
|
192
|
+
if (problem)
|
|
193
|
+
throw new Error(`${source}: ${problem}`);
|
|
194
|
+
const dir = join(articlesDir, type, slug);
|
|
195
|
+
let text;
|
|
196
|
+
try {
|
|
197
|
+
text = await readFile(join(dir, "article.md"), "utf8");
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
logger.warn(`${source}: no article.md; skipped`);
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
// An index article is its type's front page
|
|
204
|
+
const folder = slug === "index" ? typeFolder : `${typeFolder}${slug}/`;
|
|
205
|
+
const article = await loadArticle(text, type, {
|
|
206
|
+
blog,
|
|
207
|
+
dir,
|
|
208
|
+
slug,
|
|
209
|
+
url: folderUrl(folder),
|
|
210
|
+
typeUrl: typeConfig.url,
|
|
211
|
+
source,
|
|
212
|
+
// Embeds aren't fetched for articles that won't be built
|
|
213
|
+
replaceEmbeds: built
|
|
214
|
+
? (md) => embeds.replaceBlocks(md, source)
|
|
215
|
+
: async (md) => md,
|
|
216
|
+
renderMarkdown: (md, baseUrl) => renderMarkdown(markdown, md, baseUrl),
|
|
217
|
+
});
|
|
218
|
+
if (article && built)
|
|
219
|
+
articles.push({ article, dir, folder });
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
// Lists (published articles only, without index articles)
|
|
223
|
+
const withIndex = new Set(articles
|
|
224
|
+
.filter(({ article }) => article.slug === "index")
|
|
225
|
+
.map(({ article }) => article.type));
|
|
226
|
+
const listed = articles
|
|
227
|
+
.map(({ article }) => article)
|
|
228
|
+
.filter((article) => article.status === "published" && article.slug !== "index");
|
|
229
|
+
const lists = collectLists(listed, blog, withIndex);
|
|
230
|
+
const firstPages = new Map();
|
|
231
|
+
for (const list of lists) {
|
|
232
|
+
const pages = paginate(list);
|
|
233
|
+
if (list.kind === "type")
|
|
234
|
+
firstPages.set(list.type, pages[0]);
|
|
235
|
+
if (list.pages) {
|
|
236
|
+
const listTemplate = templates.resolve(list.type, "list");
|
|
237
|
+
for (const page of pages)
|
|
238
|
+
await write(list.dir + pageFile(page.pagination.page.index), templates.render(listTemplate, { site, blog, list: page }));
|
|
239
|
+
}
|
|
240
|
+
if (list.feed)
|
|
241
|
+
await write(`${list.dir}feed.xml`, templates.render("layouts/rssfeed.njk", {
|
|
242
|
+
site,
|
|
243
|
+
blog,
|
|
244
|
+
// The feed has the newest articles that can be in feeds
|
|
245
|
+
list: {
|
|
246
|
+
...pages[0],
|
|
247
|
+
articles: list.feedArticles.slice(0, PAGE_SIZE),
|
|
248
|
+
},
|
|
249
|
+
}));
|
|
250
|
+
}
|
|
251
|
+
// Article pages with their assets; index articles also get their type's list
|
|
252
|
+
for (const { article, dir, folder } of articles) {
|
|
253
|
+
await cp(dir, join(outputDir, folder), {
|
|
254
|
+
recursive: true,
|
|
255
|
+
filter: (path) => path !== join(dir, "article.md"),
|
|
256
|
+
});
|
|
257
|
+
await write(`${folder}index.html`, templates.render(templates.resolve(article.type, article.template), {
|
|
258
|
+
site,
|
|
259
|
+
blog,
|
|
260
|
+
article,
|
|
261
|
+
...(article.slug === "index"
|
|
262
|
+
? { list: firstPages.get(article.type) }
|
|
263
|
+
: {}),
|
|
264
|
+
}));
|
|
265
|
+
}
|
|
266
|
+
// Static files (stylesheet, fonts) at the website's root, beside the articles
|
|
267
|
+
const statics = await staticFiles([
|
|
268
|
+
join(themeDir, "static"),
|
|
269
|
+
join(siteDir, "static"),
|
|
270
|
+
]);
|
|
271
|
+
for (const file of statics.keys())
|
|
272
|
+
if (await exists(join(outputDir, file)))
|
|
273
|
+
throw new Error(`static/${file} has the same path as an article's file; rename one of them`);
|
|
274
|
+
for (const [file, source] of statics) {
|
|
275
|
+
await mkdir(dirname(join(outputDir, file)), { recursive: true });
|
|
276
|
+
await cp(source, join(outputDir, file));
|
|
277
|
+
}
|
|
278
|
+
// Publish into the website's root, without replacing anything already there
|
|
279
|
+
const built = await listFiles(outputDir);
|
|
280
|
+
if (publishDir) {
|
|
281
|
+
for (const file of built)
|
|
282
|
+
if (await exists(join(publishDir, file)))
|
|
283
|
+
throw new Error(`${file} is already in "publishDir" (${config.publishDir}); remove it there or rename the article`);
|
|
284
|
+
if (built.length)
|
|
285
|
+
await cp(outputDir, publishDir, { recursive: true });
|
|
286
|
+
}
|
|
287
|
+
return {
|
|
288
|
+
outputDir,
|
|
289
|
+
publishDir,
|
|
290
|
+
articles: articles.map(({ article }) => article),
|
|
291
|
+
files: built,
|
|
292
|
+
};
|
|
293
|
+
};
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/** What is built for an article type */
|
|
2
|
+
export interface GenerateConfig {
|
|
3
|
+
/** Build the type's articles (when false, nothing else is built for it either) */
|
|
4
|
+
article: boolean;
|
|
5
|
+
/** Build the type's list pages, and include its articles in the all-articles list */
|
|
6
|
+
list: boolean;
|
|
7
|
+
/** Build the type's feed, and include its articles in the all-articles, tag and author feeds */
|
|
8
|
+
feed: boolean;
|
|
9
|
+
/** Include the type's articles in author lists */
|
|
10
|
+
author: boolean;
|
|
11
|
+
/** Include the type's articles in tag lists */
|
|
12
|
+
tag: boolean;
|
|
13
|
+
}
|
|
14
|
+
/** Settings of an article type */
|
|
15
|
+
export interface ArticleTypeConfig {
|
|
16
|
+
/** The type's URL path ("" for the blog's root), e.g. "news" */
|
|
17
|
+
path: string;
|
|
18
|
+
/** Label for one article, e.g. "Article" */
|
|
19
|
+
labelSingle: string;
|
|
20
|
+
/** Label for several articles, e.g. "Articles" */
|
|
21
|
+
labelPlural: string;
|
|
22
|
+
/** What is built for the type */
|
|
23
|
+
generate: GenerateConfig;
|
|
24
|
+
}
|
|
25
|
+
/** Blog-level settings from `config.yml` */
|
|
26
|
+
export interface BlogConfig {
|
|
27
|
+
/** The name of the website */
|
|
28
|
+
name: string;
|
|
29
|
+
/** The description of the website */
|
|
30
|
+
description: string;
|
|
31
|
+
/** The URL path prefix of every article type ("" for the website's root) */
|
|
32
|
+
path: string;
|
|
33
|
+
/** The build folder, relative to the site folder and inside it (emptied on every build). Default: "dist" */
|
|
34
|
+
outputDir: string;
|
|
35
|
+
/** Optional; where built files are copied to, relative to the site folder (e.g. another app's build folder) */
|
|
36
|
+
publishDir?: string | undefined;
|
|
37
|
+
/** Optional; the website's absolute URL for feeds, used when the `SITE_URL` environment variable isn't set */
|
|
38
|
+
siteUrl?: string | undefined;
|
|
39
|
+
/** Paths at the website's root that the blog can't use, e.g. another app's routes. Default: none */
|
|
40
|
+
reservedPaths: string[];
|
|
41
|
+
/** Article type settings, by type */
|
|
42
|
+
types: Record<string, ArticleTypeConfig>;
|
|
43
|
+
}
|
|
44
|
+
/** List folders that can't be used as article types */
|
|
45
|
+
export declare const RESERVED_TYPES: string[];
|
|
46
|
+
/**
|
|
47
|
+
* Settings for an article type that isn't configured: everything generated, labelled from its name.
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* defaultTypeConfig("video"); // { path: "video", labelSingle: "Video", labelPlural: "Videos", generate: { article: true, ... } }
|
|
51
|
+
*/
|
|
52
|
+
export declare const defaultTypeConfig: (type: string) => ArticleTypeConfig;
|
|
53
|
+
/**
|
|
54
|
+
* Parse and validate the contents of the blog's `config.yml`.
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* parseConfig("name: News\ndescription: Updates\noutputDir: dist");
|
|
58
|
+
*/
|
|
59
|
+
export declare const parseConfig: (text: string) => BlogConfig;
|