@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.
Files changed (59) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +258 -2
  3. package/dist/cli/bin.d.ts +2 -0
  4. package/dist/cli/bin.js +9 -0
  5. package/dist/cli/index.d.ts +41 -0
  6. package/dist/cli/index.js +110 -0
  7. package/dist/client/assets/index-BbKEbPS8.css +1 -0
  8. package/dist/client/assets/index-DtG7vi1d.js +559 -0
  9. package/dist/client/index.html +13 -0
  10. package/dist/editor/index.d.ts +62 -0
  11. package/dist/editor/index.js +102 -0
  12. package/dist/embeds/bandcamp/index.d.ts +9 -0
  13. package/dist/embeds/bandcamp/index.js +28 -0
  14. package/dist/embeds/index.d.ts +40 -0
  15. package/dist/embeds/index.js +71 -0
  16. package/dist/embeds/types/index.d.ts +14 -0
  17. package/dist/embeds/types/index.js +1 -0
  18. package/dist/embeds/youtube/index.d.ts +17 -0
  19. package/dist/embeds/youtube/index.js +48 -0
  20. package/dist/generator/article/index.d.ts +111 -0
  21. package/dist/generator/article/index.js +257 -0
  22. package/dist/generator/build/index.d.ts +77 -0
  23. package/dist/generator/build/index.js +293 -0
  24. package/dist/generator/config/index.d.ts +59 -0
  25. package/dist/generator/config/index.js +176 -0
  26. package/dist/generator/format/index.d.ts +52 -0
  27. package/dist/generator/format/index.js +102 -0
  28. package/dist/generator/lists/index.d.ts +63 -0
  29. package/dist/generator/lists/index.js +132 -0
  30. package/dist/generator/markdown/index.d.ts +20 -0
  31. package/dist/generator/markdown/index.js +55 -0
  32. package/dist/generator/slug/index.d.ts +26 -0
  33. package/dist/generator/slug/index.js +57 -0
  34. package/dist/generator/templates/index.d.ts +56 -0
  35. package/dist/generator/templates/index.js +109 -0
  36. package/dist/generator/types/index.d.ts +161 -0
  37. package/dist/generator/types/index.js +1 -0
  38. package/dist/generator/urls/index.d.ts +40 -0
  39. package/dist/generator/urls/index.js +67 -0
  40. package/dist/index.d.ts +10 -0
  41. package/dist/index.js +10 -0
  42. package/dist/server/app/index.d.ts +39 -0
  43. package/dist/server/app/index.js +138 -0
  44. package/dist/server/convert/index.d.ts +25 -0
  45. package/dist/server/convert/index.js +125 -0
  46. package/dist/server/store/index.d.ts +148 -0
  47. package/dist/server/store/index.js +411 -0
  48. package/dist/server/types/index.d.ts +76 -0
  49. package/dist/server/types/index.js +1 -0
  50. package/dist/theme/index.d.ts +8 -0
  51. package/dist/theme/index.js +9 -0
  52. package/package.json +93 -3
  53. package/theme/static/site.css +220 -0
  54. package/theme/templates/article/list.njk +69 -0
  55. package/theme/templates/article/single.njk +58 -0
  56. package/theme/templates/layouts/html.njk +50 -0
  57. package/theme/templates/layouts/rssfeed.njk +28 -0
  58. package/theme/templates/page/home.njk +21 -0
  59. package/theme/templates/page/single.njk +18 -0
@@ -0,0 +1,176 @@
1
+ import { parse } from "yaml";
2
+ import { isSlug } from "../slug/index.js";
3
+ /** Settings under `generate` */
4
+ const GENERATE_KEYS = [
5
+ "article",
6
+ "list",
7
+ "feed",
8
+ "author",
9
+ "tag",
10
+ ];
11
+ /** Settings of an article type */
12
+ const TYPE_KEYS = ["labelSingle", "labelPlural", "path", "generate"];
13
+ /** Blog settings */
14
+ const CONFIG_KEYS = [
15
+ "name",
16
+ "description",
17
+ "path",
18
+ "outputDir",
19
+ "publishDir",
20
+ "siteUrl",
21
+ "reservedPaths",
22
+ "types",
23
+ ];
24
+ /** List folders that can't be used as article types */
25
+ export const RESERVED_TYPES = ["tags", "authors"];
26
+ /**
27
+ * Settings for an article type that isn't configured: everything generated, labelled from its name.
28
+ *
29
+ * @example
30
+ * defaultTypeConfig("video"); // { path: "video", labelSingle: "Video", labelPlural: "Videos", generate: { article: true, ... } }
31
+ */
32
+ export const defaultTypeConfig = (type) => {
33
+ const labelSingle = type.charAt(0).toUpperCase() + type.slice(1);
34
+ return {
35
+ path: type,
36
+ labelSingle,
37
+ labelPlural: `${labelSingle}s`,
38
+ generate: {
39
+ article: true,
40
+ list: true,
41
+ feed: true,
42
+ author: true,
43
+ tag: true,
44
+ },
45
+ };
46
+ };
47
+ /** Check a value is a map, throwing a config error if not */
48
+ const asMap = (value, what) => {
49
+ if (!value || typeof value !== "object" || Array.isArray(value))
50
+ throw new Error(`config.yml: ${what} must be a map`);
51
+ return value;
52
+ };
53
+ /**
54
+ * Read an optional URL path: lowercase kebab-case, or "" for the root.
55
+ */
56
+ const parsePath = (value, what) => {
57
+ if (value === undefined || value === null)
58
+ return undefined;
59
+ if (typeof value !== "string" || (value !== "" && !isSlug(value)))
60
+ throw new Error(`config.yml: ${what} must be lowercase kebab-case, or "" for the root`);
61
+ return value;
62
+ };
63
+ /** Throw a config error for keys that aren't allowed */
64
+ const checkKeys = (map, allowed, what) => {
65
+ const unknown = Object.keys(map).filter((key) => !allowed.includes(key));
66
+ if (unknown.length)
67
+ throw new Error(`config.yml: unknown ${what} setting${unknown.length > 1 ? "s" : ""} ${unknown.map((key) => `"${key}"`).join(", ")}`);
68
+ };
69
+ /**
70
+ * Parse one article type's settings, filling in defaults.
71
+ */
72
+ const parseTypeConfig = (type, value) => {
73
+ if (!isSlug(type) || RESERVED_TYPES.includes(type))
74
+ throw new Error(`config.yml: type "${type}" must be lowercase kebab-case and not ${RESERVED_TYPES.join(" or ")}`);
75
+ const config = defaultTypeConfig(type);
76
+ if (value === null || value === undefined)
77
+ return config;
78
+ const fields = asMap(value, `"types.${type}"`);
79
+ checkKeys(fields, TYPE_KEYS, `"types.${type}"`);
80
+ for (const label of ["labelSingle", "labelPlural"]) {
81
+ const text = fields[label];
82
+ if (text === undefined)
83
+ continue;
84
+ if (typeof text !== "string" || !text.trim())
85
+ throw new Error(`config.yml: "types.${type}.${label}" must be a non-empty string`);
86
+ config[label] = text.trim();
87
+ }
88
+ config.path = parsePath(fields.path, `"types.${type}.path"`) ?? type;
89
+ const generate = fields.generate;
90
+ if (generate === false)
91
+ for (const key of GENERATE_KEYS)
92
+ config.generate[key] = false;
93
+ else if (generate !== undefined && generate !== true) {
94
+ const flags = asMap(generate, `"types.${type}.generate"`);
95
+ checkKeys(flags, GENERATE_KEYS, `"types.${type}.generate"`);
96
+ for (const key of GENERATE_KEYS) {
97
+ const flag = flags[key];
98
+ if (flag === undefined)
99
+ continue;
100
+ if (typeof flag !== "boolean")
101
+ throw new Error(`config.yml: "types.${type}.generate.${key}" must be true or false`);
102
+ config.generate[key] = flag;
103
+ }
104
+ }
105
+ // Without articles, nothing else can be built
106
+ if (!config.generate.article)
107
+ for (const key of GENERATE_KEYS)
108
+ config.generate[key] = false;
109
+ return config;
110
+ };
111
+ /**
112
+ * Read a required, non-empty string field from parsed YAML.
113
+ */
114
+ const requireString = (data, field) => {
115
+ const value = data[field];
116
+ if (typeof value !== "string" || value.trim() === "")
117
+ throw new Error(`config.yml: "${field}" must be a non-empty string`);
118
+ return value.trim();
119
+ };
120
+ /**
121
+ * Read an optional, non-empty string field from parsed YAML.
122
+ */
123
+ const optionalString = (data, field) => data[field] === undefined || data[field] === null
124
+ ? undefined
125
+ : requireString(data, field);
126
+ /**
127
+ * Read the optional site URL: an absolute http(s) URL.
128
+ */
129
+ const parseSiteUrl = (data) => {
130
+ const value = optionalString(data, "siteUrl");
131
+ if (value !== undefined && !/^https?:\/\/[^/]/.test(value))
132
+ throw new Error('config.yml: "siteUrl" must be an absolute http(s) URL, e.g. "https://example.com"');
133
+ return value;
134
+ };
135
+ /**
136
+ * Read the optional list of reserved paths: URL path segments or file names, e.g. "app" or "jwks.json".
137
+ */
138
+ const parseReservedPaths = (data) => {
139
+ const value = data.reservedPaths;
140
+ if (value === undefined || value === null)
141
+ return [];
142
+ if (!Array.isArray(value) ||
143
+ value.some((path) => typeof path !== "string" || !/^[a-z0-9][a-z0-9._-]*$/.test(path)))
144
+ throw new Error('config.yml: "reservedPaths" must be a list of lowercase paths at the website\'s root, e.g. ["app", "api"]');
145
+ return value;
146
+ };
147
+ /**
148
+ * Parse and validate the contents of the blog's `config.yml`.
149
+ *
150
+ * @example
151
+ * parseConfig("name: News\ndescription: Updates\noutputDir: dist");
152
+ */
153
+ export const parseConfig = (text) => {
154
+ const data = parse(text);
155
+ if (!data || typeof data !== "object" || Array.isArray(data))
156
+ throw new Error("config.yml: expected a map of settings");
157
+ const fields = data;
158
+ checkKeys(fields, CONFIG_KEYS, "blog");
159
+ const types = fields.types === undefined || fields.types === null
160
+ ? {}
161
+ : asMap(fields.types, '"types"');
162
+ const config = {
163
+ name: requireString(fields, "name"),
164
+ description: requireString(fields, "description"),
165
+ path: parsePath(fields.path, '"path"') ?? "",
166
+ outputDir: optionalString(fields, "outputDir") ?? "dist",
167
+ publishDir: optionalString(fields, "publishDir"),
168
+ siteUrl: parseSiteUrl(fields),
169
+ reservedPaths: parseReservedPaths(fields),
170
+ types: Object.fromEntries(Object.entries(types).map(([type, value]) => [
171
+ type,
172
+ parseTypeConfig(type, value),
173
+ ])),
174
+ };
175
+ return config;
176
+ };
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Format a number of bytes as a human-readable size (1 KB = 1024 bytes).
3
+ *
4
+ * @example
5
+ * formatBytes(204800); // "200 KB"
6
+ * formatBytes(2621440); // "2.5 MB"
7
+ */
8
+ export declare const formatBytes: (bytes: number) => string;
9
+ /**
10
+ * Format an ISO 8601 date as a human-readable date (UTC).
11
+ *
12
+ * @example
13
+ * formatDate("2026-10-19T09:54:00.000Z"); // "19 October 2026"
14
+ */
15
+ export declare const formatDate: (iso: string) => string;
16
+ /**
17
+ * Format an ISO 8601 date for RSS feeds (RFC 822).
18
+ *
19
+ * @example
20
+ * formatRfc822("2026-10-19T09:54:00.000Z"); // "Mon, 19 Oct 2026 09:54:00 GMT"
21
+ */
22
+ export declare const formatRfc822: (iso: string) => string;
23
+ /**
24
+ * Escape text for use in HTML content or attribute values.
25
+ *
26
+ * @example
27
+ * escapeHtml('<a href="x">'); // "&lt;a href=&quot;x&quot;&gt;"
28
+ */
29
+ export declare const escapeHtml: (text: string) => string;
30
+ /**
31
+ * Convert HTML to plain text: remove tags, decode common entities and collapse whitespace.
32
+ *
33
+ * @example
34
+ * stripHtml("<p>Fish &amp; <em>chips</em></p>"); // "Fish & chips"
35
+ */
36
+ export declare const stripHtml: (html: string) => string;
37
+ /**
38
+ * Crop text to a maximum length, ending at a word boundary where possible, and add an ellipsis if it was cropped.
39
+ *
40
+ * @example
41
+ * cropText("Hello wonderful world", 15); // "Hello wonderful…"
42
+ */
43
+ export declare const cropText: (text: string, maxLength: number) => string;
44
+ /**
45
+ * Whether a URL is relative to the current folder (not absolute, root-relative or a fragment).
46
+ *
47
+ * @example
48
+ * isRelativeUrl("thumb.jpg"); // true
49
+ * isRelativeUrl("https://example.com/a.jpg"); // false
50
+ * isRelativeUrl("/news/"); // false
51
+ */
52
+ export declare const isRelativeUrl: (url: string) => boolean;
@@ -0,0 +1,102 @@
1
+ /** Units for human-readable file sizes */
2
+ const SIZE_UNITS = ["bytes", "KB", "MB", "GB"];
3
+ /**
4
+ * Format a number of bytes as a human-readable size (1 KB = 1024 bytes).
5
+ *
6
+ * @example
7
+ * formatBytes(204800); // "200 KB"
8
+ * formatBytes(2621440); // "2.5 MB"
9
+ */
10
+ export const formatBytes = (bytes) => {
11
+ let size = bytes;
12
+ let unit = 0;
13
+ while (size >= 1024 && unit < SIZE_UNITS.length - 1) {
14
+ size /= 1024;
15
+ unit++;
16
+ }
17
+ const rounded = unit === 0 ? size : Math.round(size * 10) / 10;
18
+ return `${rounded} ${SIZE_UNITS[unit]}`;
19
+ };
20
+ const DATE_FORMAT = new Intl.DateTimeFormat("en-GB", {
21
+ day: "numeric",
22
+ month: "long",
23
+ year: "numeric",
24
+ timeZone: "UTC",
25
+ });
26
+ /**
27
+ * Format an ISO 8601 date as a human-readable date (UTC).
28
+ *
29
+ * @example
30
+ * formatDate("2026-10-19T09:54:00.000Z"); // "19 October 2026"
31
+ */
32
+ export const formatDate = (iso) => DATE_FORMAT.format(new Date(iso));
33
+ /**
34
+ * Format an ISO 8601 date for RSS feeds (RFC 822).
35
+ *
36
+ * @example
37
+ * formatRfc822("2026-10-19T09:54:00.000Z"); // "Mon, 19 Oct 2026 09:54:00 GMT"
38
+ */
39
+ export const formatRfc822 = (iso) => new Date(iso).toUTCString();
40
+ /**
41
+ * Escape text for use in HTML content or attribute values.
42
+ *
43
+ * @example
44
+ * escapeHtml('<a href="x">'); // "&lt;a href=&quot;x&quot;&gt;"
45
+ */
46
+ export const escapeHtml = (text) => text
47
+ .replace(/&/g, "&amp;")
48
+ .replace(/</g, "&lt;")
49
+ .replace(/>/g, "&gt;")
50
+ .replace(/"/g, "&quot;")
51
+ .replace(/'/g, "&#39;");
52
+ /** Named HTML entities decoded by `stripHtml` */
53
+ const ENTITIES = {
54
+ amp: "&",
55
+ lt: "<",
56
+ gt: ">",
57
+ quot: '"',
58
+ apos: "'",
59
+ nbsp: " ",
60
+ };
61
+ /**
62
+ * Convert HTML to plain text: remove tags, decode common entities and collapse whitespace.
63
+ *
64
+ * @example
65
+ * stripHtml("<p>Fish &amp; <em>chips</em></p>"); // "Fish & chips"
66
+ */
67
+ export const stripHtml = (html) => html
68
+ .replace(/<[^>]*>/g, " ")
69
+ .replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (entity, code) => {
70
+ if (code[0] === "#") {
71
+ const point = code[1] === "x" || code[1] === "X"
72
+ ? parseInt(code.slice(2), 16)
73
+ : parseInt(code.slice(1), 10);
74
+ return String.fromCodePoint(point);
75
+ }
76
+ return ENTITIES[code.toLowerCase()] ?? entity;
77
+ })
78
+ .replace(/\s+/g, " ")
79
+ .trim();
80
+ /**
81
+ * Crop text to a maximum length, ending at a word boundary where possible, and add an ellipsis if it was cropped.
82
+ *
83
+ * @example
84
+ * cropText("Hello wonderful world", 15); // "Hello wonderful…"
85
+ */
86
+ export const cropText = (text, maxLength) => {
87
+ if (text.length <= maxLength)
88
+ return text;
89
+ // Include the next character, so a word ending exactly at the limit is kept whole
90
+ const lastSpace = text.slice(0, maxLength + 1).lastIndexOf(" ");
91
+ const cropped = lastSpace > 0 ? text.slice(0, lastSpace) : text.slice(0, maxLength);
92
+ return `${cropped.trimEnd()}…`;
93
+ };
94
+ /**
95
+ * Whether a URL is relative to the current folder (not absolute, root-relative or a fragment).
96
+ *
97
+ * @example
98
+ * isRelativeUrl("thumb.jpg"); // true
99
+ * isRelativeUrl("https://example.com/a.jpg"); // false
100
+ * isRelativeUrl("/news/"); // false
101
+ */
102
+ export const isRelativeUrl = (url) => url !== "" && !/^([a-z][a-z0-9+.-]*:|\/|#|\?)/i.test(url);
@@ -0,0 +1,63 @@
1
+ import type { ListKind, TemplateDataArticle, TemplateDataBlog, TemplateDataList } from "../types/index.ts";
2
+ /** Articles per list page */
3
+ export declare const PAGE_SIZE = 20;
4
+ /** A list of articles before pagination */
5
+ export interface ListDefinition {
6
+ kind: ListKind;
7
+ /** The list's name */
8
+ name: string;
9
+ /** The article type/tag/author slug */
10
+ slug: string;
11
+ /** The article type the list belongs to (its list template renders it) */
12
+ type: string;
13
+ /** The list's folder relative to the website's root, e.g. "news/" or "news/tags/art/" */
14
+ dir: string;
15
+ /** The URL of the list's first page */
16
+ url: string;
17
+ /** Whether list pages are built (otherwise only the feed, or nothing) */
18
+ pages: boolean;
19
+ /** The articles on the list's pages, newest first */
20
+ articles: TemplateDataArticle[];
21
+ /** Whether a feed is built */
22
+ feed: boolean;
23
+ /** The articles in the list's feed, newest first */
24
+ feedArticles: TemplateDataArticle[];
25
+ }
26
+ /**
27
+ * Sort articles newest first (by type and slug when dates are equal, so builds are stable).
28
+ *
29
+ * @example
30
+ * sortArticles(articles)[0]; // the newest article
31
+ */
32
+ export declare const sortArticles: (articles: readonly TemplateDataArticle[]) => TemplateDataArticle[];
33
+ /**
34
+ * Group published articles into lists, following each article type's `generate` settings (see config.ts):
35
+ * - one per type (its pages unless the type has an index article, and its feed)
36
+ * - one per tag and per author within a type, with articles of types with `tag` or `author` (and in their feeds,
37
+ * also `feed`)
38
+ *
39
+ * Every type in `withIndex` gets a type list (even without articles or list settings), so its index article can
40
+ * show it; build only the lists with `pages` or `feed`.
41
+ *
42
+ * @param articles - published articles, without index articles
43
+ * @param withIndex - article types that have an index article
44
+ *
45
+ * @example
46
+ * collectLists(published, blog, new Set()).map((list) => list.url); // ["/news/", "/news/tags/art/", ...]
47
+ */
48
+ export declare const collectLists: (articles: readonly TemplateDataArticle[], blog: TemplateDataBlog, withIndex: ReadonlySet<string>) => ListDefinition[];
49
+ /**
50
+ * The output file name of a list page.
51
+ *
52
+ * @example
53
+ * pageFile(1); // "index.html"
54
+ * pageFile(2); // "2.html"
55
+ */
56
+ export declare const pageFile: (index: number) => string;
57
+ /**
58
+ * Split a list into pages of template data (at least one page, even when empty).
59
+ *
60
+ * @example
61
+ * paginate(list).map((page) => page.pagination.page.url); // ["/news/", "/news/2"]
62
+ */
63
+ export declare const paginate: (list: ListDefinition, pageSize?: number) => TemplateDataList[];
@@ -0,0 +1,132 @@
1
+ /** Articles per list page */
2
+ export const PAGE_SIZE = 20;
3
+ /**
4
+ * Sort articles newest first (by type and slug when dates are equal, so builds are stable).
5
+ *
6
+ * @example
7
+ * sortArticles(articles)[0]; // the newest article
8
+ */
9
+ export const sortArticles = (articles) => [...articles].sort((a, b) => b.date.localeCompare(a.date) ||
10
+ a.type.localeCompare(b.type) ||
11
+ a.slug.localeCompare(b.slug));
12
+ /**
13
+ * Group published articles into lists, following each article type's `generate` settings (see config.ts):
14
+ * - one per type (its pages unless the type has an index article, and its feed)
15
+ * - one per tag and per author within a type, with articles of types with `tag` or `author` (and in their feeds,
16
+ * also `feed`)
17
+ *
18
+ * Every type in `withIndex` gets a type list (even without articles or list settings), so its index article can
19
+ * show it; build only the lists with `pages` or `feed`.
20
+ *
21
+ * @param articles - published articles, without index articles
22
+ * @param withIndex - article types that have an index article
23
+ *
24
+ * @example
25
+ * collectLists(published, blog, new Set()).map((list) => list.url); // ["/news/", "/news/tags/art/", ...]
26
+ */
27
+ export const collectLists = (articles, blog, withIndex) => {
28
+ const lists = new Map();
29
+ /** Get or create a list */
30
+ const list = (definition) => {
31
+ const existing = lists.get(definition.dir);
32
+ if (existing)
33
+ return existing;
34
+ const created = {
35
+ ...definition,
36
+ url: `/${definition.dir}`,
37
+ articles: [],
38
+ feedArticles: [],
39
+ };
40
+ lists.set(definition.dir, created);
41
+ return created;
42
+ };
43
+ /** A type's own list */
44
+ const typeList = (type) => {
45
+ const config = blog.types[type];
46
+ return list({
47
+ kind: "type",
48
+ name: config.labelPlural,
49
+ slug: type,
50
+ type,
51
+ dir: config.url.slice(1),
52
+ // An index article takes the place of the list's pages
53
+ pages: config.generate.list && !withIndex.has(type),
54
+ feed: false,
55
+ });
56
+ };
57
+ for (const type of withIndex)
58
+ typeList(type);
59
+ for (const article of sortArticles(articles)) {
60
+ const config = blog.types[article.type];
61
+ const settings = config.generate;
62
+ /** Add the article to a list, and to its feed if the type allows feeds */
63
+ const add = (entry) => {
64
+ entry.articles.push(article);
65
+ if (settings.feed)
66
+ entry.feedArticles.push(article);
67
+ entry.feed ||= settings.feed;
68
+ };
69
+ if (settings.list || settings.feed || withIndex.has(article.type))
70
+ add(typeList(article.type));
71
+ const typeDir = config.url.slice(1);
72
+ if (settings.tag)
73
+ for (const tag of article.tags)
74
+ add(list({
75
+ kind: "tag",
76
+ name: tag.name,
77
+ slug: tag.slug,
78
+ type: article.type,
79
+ dir: `${typeDir}tags/${tag.slug}/`,
80
+ pages: true,
81
+ feed: false,
82
+ }));
83
+ if (settings.author)
84
+ add(list({
85
+ kind: "author",
86
+ name: article.author.name,
87
+ slug: article.author.slug,
88
+ type: article.type,
89
+ dir: `${typeDir}authors/${article.author.slug}/`,
90
+ pages: true,
91
+ feed: false,
92
+ }));
93
+ }
94
+ return [...lists.values()];
95
+ };
96
+ /**
97
+ * The output file name of a list page.
98
+ *
99
+ * @example
100
+ * pageFile(1); // "index.html"
101
+ * pageFile(2); // "2.html"
102
+ */
103
+ export const pageFile = (index) => index === 1 ? "index.html" : `${index}.html`;
104
+ /**
105
+ * Split a list into pages of template data (at least one page, even when empty).
106
+ *
107
+ * @example
108
+ * paginate(list).map((page) => page.pagination.page.url); // ["/news/", "/news/2"]
109
+ */
110
+ export const paginate = (list, pageSize = PAGE_SIZE) => {
111
+ const count = Math.max(1, Math.ceil(list.articles.length / pageSize));
112
+ const pageUrl = (index) => index === 1 ? list.url : `${list.url}${index}`;
113
+ return Array.from({ length: count }, (_, i) => {
114
+ const pages = Array.from({ length: count }, (_, p) => ({ index: p + 1, url: pageUrl(p + 1), isCurrent: p === i }));
115
+ return {
116
+ name: list.name,
117
+ slug: list.slug,
118
+ type: list.type,
119
+ kind: list.kind,
120
+ url: list.url,
121
+ feedUrl: `${list.url}feed.xml`,
122
+ hasFeed: list.feed,
123
+ articles: list.articles.slice(i * pageSize, (i + 1) * pageSize),
124
+ pagination: {
125
+ pages,
126
+ page: pages[i],
127
+ prevPage: pages[i - 1],
128
+ nextPage: pages[i + 1],
129
+ },
130
+ };
131
+ });
132
+ };
@@ -0,0 +1,20 @@
1
+ import MarkdownIt from "markdown-it";
2
+ /** A configured markdown renderer */
3
+ export type Markdown = InstanceType<typeof MarkdownIt>;
4
+ /**
5
+ * Create the markdown renderer. Raw HTML is allowed, as articles are written by trusted authors and embeds are HTML.
6
+ * Relative link and image URLs are resolved against the article's URL, so they work on any page (e.g. lists).
7
+ * Headings get IDs from their text (see `headingIds`), so they can be linked to, e.g. `#this-is-an-example`.
8
+ * Typographer (curly quotes, dashes) is on for the website and off for the editor, so text round-trips unchanged.
9
+ *
10
+ * @example
11
+ * const markdown = createMarkdown();
12
+ * renderMarkdown(markdown, "![A](a.png)", "/news/article/hello/"); // '<p><img src="/news/article/hello/a.png" alt="A"></p>\n'
13
+ */
14
+ export declare const createMarkdown: ({ typographer }?: {
15
+ typographer?: boolean | undefined;
16
+ }) => Markdown;
17
+ /**
18
+ * Render markdown to HTML, resolving relative URLs against a folder URL.
19
+ */
20
+ export declare const renderMarkdown: (markdown: Markdown, source: string, baseUrl: string) => string;
@@ -0,0 +1,55 @@
1
+ import MarkdownIt from "markdown-it";
2
+ import { isRelativeUrl } from "../format/index.js";
3
+ import { headingIds } from "../slug/index.js";
4
+ /**
5
+ * Create the markdown renderer. Raw HTML is allowed, as articles are written by trusted authors and embeds are HTML.
6
+ * Relative link and image URLs are resolved against the article's URL, so they work on any page (e.g. lists).
7
+ * Headings get IDs from their text (see `headingIds`), so they can be linked to, e.g. `#this-is-an-example`.
8
+ * Typographer (curly quotes, dashes) is on for the website and off for the editor, so text round-trips unchanged.
9
+ *
10
+ * @example
11
+ * const markdown = createMarkdown();
12
+ * renderMarkdown(markdown, "![A](a.png)", "/news/article/hello/"); // '<p><img src="/news/article/hello/a.png" alt="A"></p>\n'
13
+ */
14
+ export const createMarkdown = ({ typographer = true } = {}) => {
15
+ const markdown = new MarkdownIt({ html: true, typographer });
16
+ markdown.core.ruler.push("resolve_relative_urls", (state) => {
17
+ const { baseUrl } = state.env;
18
+ for (const block of state.tokens) {
19
+ for (const token of block.children ?? []) {
20
+ const attribute = token.type === "image"
21
+ ? "src"
22
+ : token.type === "link_open"
23
+ ? "href"
24
+ : undefined;
25
+ if (!attribute)
26
+ continue;
27
+ // markdown-it always sets src on images and href on links
28
+ const url = String(token.attrGet(attribute));
29
+ if (isRelativeUrl(url))
30
+ token.attrSet(attribute, baseUrl + url);
31
+ }
32
+ }
33
+ });
34
+ markdown.core.ruler.push("heading_ids", (state) => {
35
+ const headings = state.tokens.flatMap((token, i) => token.type === "heading_open"
36
+ ? [{ token, inline: state.tokens[i + 1] }]
37
+ : []);
38
+ // A heading's text, without its formatting or HTML tags (a heading's inline token always has children)
39
+ const texts = headings.map(({ inline }) => inline.children
40
+ .filter((child) => child.type === "text" || child.type === "code_inline")
41
+ .map((child) => child.content)
42
+ .join(""));
43
+ const ids = headingIds(texts);
44
+ headings.forEach(({ token }, i) => {
45
+ const id = ids[i];
46
+ if (id)
47
+ token.attrSet("id", id);
48
+ });
49
+ });
50
+ return markdown;
51
+ };
52
+ /**
53
+ * Render markdown to HTML, resolving relative URLs against a folder URL.
54
+ */
55
+ export const renderMarkdown = (markdown, source, baseUrl) => markdown.render(source, { baseUrl });
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Convert text to a lowercase, URL-safe `kebab-case` slug. Accented letters become basic Latin, quotes and
3
+ * apostrophes are removed, and any other runs of characters become a single `-`.
4
+ *
5
+ * @example
6
+ * slugify("What?! Who Is This?!? I don't think so..."); // "what-who-is-this-i-dont-think-so"
7
+ * slugify("Café Naïve"); // "cafe-naive"
8
+ */
9
+ export declare const slugify: (text: string) => string;
10
+ /**
11
+ * Whether text is already a valid slug.
12
+ *
13
+ * @example
14
+ * isSlug("hello-world"); // true
15
+ * isSlug("Hello World"); // false
16
+ */
17
+ export declare const isSlug: (text: string) => boolean;
18
+ /**
19
+ * IDs for a document's headings, from their text (as slugs): a repeated heading gets `-2`, `-3`… added, and a heading
20
+ * without letters or numbers gets none (an empty string).
21
+ *
22
+ * @example
23
+ * headingIds(["This?! Is an, example...", "Notes", "Notes", "!!!"]);
24
+ * // ["this-is-an-example", "notes", "notes-2", ""]
25
+ */
26
+ export declare const headingIds: (texts: string[]) => string[];