@lvl99dotcom/edaha.md 0.0.0-stage → 0.2.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 (52) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +13 -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 +71 -0
  6. package/dist/cli/index.js +149 -0
  7. package/dist/embeds/blocks/index.d.ts +59 -0
  8. package/dist/embeds/blocks/index.js +103 -0
  9. package/dist/embeds/index.d.ts +143 -0
  10. package/dist/embeds/index.js +411 -0
  11. package/dist/embeds/types/index.d.ts +117 -0
  12. package/dist/embeds/types/index.js +1 -0
  13. package/dist/generator/article/index.d.ts +151 -0
  14. package/dist/generator/article/index.js +325 -0
  15. package/dist/generator/build/index.d.ts +109 -0
  16. package/dist/generator/build/index.js +363 -0
  17. package/dist/generator/config/index.d.ts +96 -0
  18. package/dist/generator/config/index.js +298 -0
  19. package/dist/generator/configFile/index.d.ts +58 -0
  20. package/dist/generator/configFile/index.js +122 -0
  21. package/dist/generator/fields/index.d.ts +93 -0
  22. package/dist/generator/fields/index.js +186 -0
  23. package/dist/generator/format/index.d.ts +92 -0
  24. package/dist/generator/format/index.js +177 -0
  25. package/dist/generator/lists/index.d.ts +63 -0
  26. package/dist/generator/lists/index.js +133 -0
  27. package/dist/generator/markdown/index.d.ts +25 -0
  28. package/dist/generator/markdown/index.js +62 -0
  29. package/dist/generator/metadata/index.d.ts +150 -0
  30. package/dist/generator/metadata/index.js +361 -0
  31. package/dist/generator/metadataGroups/index.d.ts +45 -0
  32. package/dist/generator/metadataGroups/index.js +169 -0
  33. package/dist/generator/slug/index.d.ts +26 -0
  34. package/dist/generator/slug/index.js +57 -0
  35. package/dist/generator/templates/index.d.ts +88 -0
  36. package/dist/generator/templates/index.js +175 -0
  37. package/dist/generator/types/index.d.ts +186 -0
  38. package/dist/generator/types/index.js +1 -0
  39. package/dist/generator/urls/index.d.ts +50 -0
  40. package/dist/generator/urls/index.js +77 -0
  41. package/dist/index.d.ts +8 -0
  42. package/dist/index.js +9 -0
  43. package/dist/theme/index.d.ts +8 -0
  44. package/dist/theme/index.js +9 -0
  45. package/package.json +64 -3
  46. package/theme/static/base.css +328 -0
  47. package/theme/templates/article/list.njk +69 -0
  48. package/theme/templates/article/single.njk +64 -0
  49. package/theme/templates/layouts/html.njk +72 -0
  50. package/theme/templates/layouts/rssfeed.njk +28 -0
  51. package/theme/templates/page/home.njk +16 -0
  52. package/theme/templates/page/single.njk +18 -0
@@ -0,0 +1,143 @@
1
+ import type { Logger } from "../generator/types/index.ts";
2
+ import { type EmbedOptionValues } from "./blocks/index.ts";
3
+ import type { EmbedContext, EmbedPageParts, EmbedPlugin, EmbedTarget } from "./types/index.ts";
4
+ export type * from "./types/index.ts";
5
+ export { EMBED_BLOCK, embedBlock, embedContent, embedOptionsOf, embedText, splitEmbed, } from "./blocks/index.ts";
6
+ /**
7
+ * Template data for the `{% embedHead %}` and `{% embedFoot %}` tags while a page is rendered: where `renderPage` puts
8
+ * the HTML the page's embeds need, once it knows which embeds the page shows.
9
+ */
10
+ export declare const EMBED_PAGE_PARTS: EmbedPageParts;
11
+ /** The kinds of web addresses an embed can list in its `sources` */
12
+ export declare const EMBED_SOURCE_KINDS: readonly ["frame", "script", "style", "font", "connect"];
13
+ /**
14
+ * Whether a value is an embed plugin: a kebab-case `key`, a `name`, a `build.render` function, and valid optional
15
+ * `description`, `info`, `sources`, `options` (a map), `validate` and `editor` renderers.
16
+ *
17
+ * @example
18
+ * isEmbedPlugin({ key: "quote", name: "Quote", build: { render: async (text) => text } }); // true
19
+ */
20
+ export declare const isEmbedPlugin: (value: unknown) => value is EmbedPlugin;
21
+ /**
22
+ * Check a list of embed plugins: each must be valid (see isEmbedPlugin), with a key of its own, and its options must be
23
+ * fields like article metadata's (see EmbedPlugin.options). Throws describing the first problem.
24
+ *
25
+ * @example
26
+ * checkEmbedPlugins([youtube, bandcamp]); // [youtube, bandcamp]
27
+ */
28
+ export declare const checkEmbedPlugins: (plugins: unknown[]) => EmbedPlugin[];
29
+ /**
30
+ * Load a config file's `plugins`: package names are imported from the config file's folder (their default export is
31
+ * an embed plugin or a list of them); objects are used as they are. Throws naming a package that can't be loaded.
32
+ *
33
+ * @param fromDir - the folder package names are found from, i.e. the config file's
34
+ * @example
35
+ * await loadPlugins(["@lvl99dotcom/edaha-plugin-youtube"], "my-site"); // [youtube]
36
+ */
37
+ export declare const loadPlugins: (entries: unknown, fromDir: string) => Promise<unknown[]>;
38
+ /** Options for resolving embeds */
39
+ export interface EmbedOptions extends EmbedContext {
40
+ /** The embed plugins */
41
+ plugins: readonly EmbedPlugin[];
42
+ /** Where to report embeds that can't be rendered */
43
+ logger: Logger;
44
+ }
45
+ /**
46
+ * Renders embed blocks to HTML with embed plugins, page by page: each page's blocks share their embed's `state`, and
47
+ * the page gets the HTML its embeds need once (`renderHead` and `renderFoot`).
48
+ *
49
+ * Put blocks in markdown with placeholders (`replaceBlocks`), render the markdown and the page's template (with
50
+ * EMBED_PAGE_PARTS for the `{% embedHead %}` and `{% embedFoot %}` tags), then render the page's embeds
51
+ * (`renderPage`).
52
+ *
53
+ * @example
54
+ * const embeds = new EmbedResolver({ fetch, logger: console, plugins: [youtube] });
55
+ * const body = renderMarkdown(embeds.replaceBlocks(source, "news/hello"));
56
+ * const page = await embeds.renderPage(render("article.njk", { body, embeds: EMBED_PAGE_PARTS }), "/news/hello/");
57
+ */
58
+ export declare class EmbedResolver {
59
+ private readonly options;
60
+ private readonly plugins;
61
+ /** Embed blocks put in pages, by their placeholders' IDs */
62
+ private readonly placed;
63
+ /** Why blocks aren't valid, by their key, options and content (see validate) */
64
+ private readonly checked;
65
+ /** Each embed's options' validator, by its key */
66
+ private readonly optionValidators;
67
+ /** Warnings given, so a block shown on several pages is warned about once */
68
+ private readonly warned;
69
+ constructor(options: EmbedOptions);
70
+ /**
71
+ * Put an embed block in a page by a placeholder, which `renderPage` renders.
72
+ *
73
+ * @param key - the block's key, or undefined for an old `<!-- embed -->` block
74
+ * @param text - what is between its tags: its options and content
75
+ * @param source - where it is, for warnings
76
+ * @example
77
+ * embeds.place("youtube", "https://youtu.be/x", "Embed"); // "<!--edaha-embed:0-->"
78
+ */
79
+ place(key: string | undefined, text: string, source: string): string;
80
+ /**
81
+ * Replace every embed block in markdown with a placeholder (see place), as its own block. Blocks in code blocks and
82
+ * inline code are left as they are. Embed HTML put straight into markdown would end at its first blank line, so the
83
+ * blocks are rendered with the page they are shown on (see renderPage).
84
+ *
85
+ * @param source - where the markdown is from, for warnings
86
+ * @example
87
+ * embeds.replaceBlocks("Hi\n<!-- embed:youtube -->https://youtu.be/x<!-- /embed:youtube -->", "news/hello");
88
+ * // "Hi\n\n\n<!--edaha-embed:0-->\n\n"
89
+ */
90
+ replaceBlocks(markdown: string, source: string): string;
91
+ /**
92
+ * Render a page's embeds: each placeholder of a block (see place) in order, sharing each embed's state on the page,
93
+ * then the HTML the page's embeds need in place of EMBED_PAGE_PARTS' placeholders. A block whose key has no plugin,
94
+ * or whose plugin fails, is shown as it is (a link for a URL, otherwise as text), and one that isn't valid is left
95
+ * out, with a warning (once, however many pages show it). An escaped placeholder (e.g. in a feed) gets escaped HTML.
96
+ *
97
+ * @param source - which page it is, for warnings
98
+ * @param target - render for the website (default) or the editor
99
+ * @example
100
+ * await embeds.renderPage('<head><!--edaha-embeds-head--></head><body><!--edaha-embed:0--></body>', "/news/hello/");
101
+ */
102
+ renderPage(html: string, source: string, target?: EmbedTarget): Promise<string>;
103
+ /**
104
+ * Why a block isn't valid, or nothing when it is: its key has no plugin, its options aren't the embed's (see
105
+ * EmbedPlugin.options), or the embed's `validate` says its content (or options) isn't valid. The options are checked
106
+ * with their defaults and without hidden ones. Used by the editor to check blocks before they are saved.
107
+ *
108
+ * @example
109
+ * await embeds.validate("youtube", "https://example.com/"); // ["https://example.com/ is not a YouTube URL"]
110
+ * await embeds.validate("bandcamp", url, { layout: "huge" }); // ['Layout must be one of "slim", "artwork-only", "large"']
111
+ */
112
+ validate(key: string | undefined, content: string, options?: EmbedOptionValues): Promise<string[]>;
113
+ /** Why a block with its options resolved isn't valid (see validate), checked once */
114
+ private check;
115
+ /** Why a block's options (resolved) aren't the embed's, in plain words, e.g. 'Layout must be one of "slim", "large"' */
116
+ private optionProblems;
117
+ /** Warn about a block or page, unless that warning was given before */
118
+ private warn;
119
+ /** Render a block on a page: its HTML, a fallback, or nothing when it is left out (see renderPage) */
120
+ private renderBlock;
121
+ /**
122
+ * The HTML a page needs for the embeds it shows: each shown embed's `renderHead` and `renderFoot`, once, in the
123
+ * order of the plugins. One that fails is left out with a warning.
124
+ */
125
+ private pageParts;
126
+ }
127
+ /**
128
+ * A fetch that fetches each address once (requests without other settings only), giving each caller a copy of the
129
+ * response, e.g. so pages that show the same embed don't fetch it again.
130
+ *
131
+ * @example
132
+ * const fetchOnce = cachedFetch(fetch);
133
+ * await fetchOnce("https://example.com/"); // fetched
134
+ * await fetchOnce("https://example.com/"); // the same response, not fetched again
135
+ */
136
+ export declare const cachedFetch: (fetcher: typeof fetch) => typeof fetch;
137
+ /**
138
+ * The messages of an error thrown by an embed's `validate`: each of an `AggregateError`'s errors, or the error's own.
139
+ *
140
+ * @example
141
+ * validationErrors(new AggregateError([new Error("No ID"), new Error("Too long")])); // ["No ID", "Too long"]
142
+ */
143
+ export declare const validationErrors: (error: unknown) => string[];
@@ -0,0 +1,411 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { createRequire } from "node:module";
10
+ import { join } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import { resolveFields } from "../generator/fields/index.js";
13
+ import { escapeHtml, replaceOutsideCode } from "../generator/format/index.js";
14
+ import { checkFieldSchema, createAjv, plainMessage, } from "../generator/metadata/index.js";
15
+ import { EMBED_BLOCK, splitEmbed, } from "./blocks/index.js";
16
+ export { EMBED_BLOCK, embedBlock, embedContent, embedOptionsOf, embedText, splitEmbed, } from "./blocks/index.js";
17
+ /**
18
+ * Where `replaceBlocks` (or `place`) put an embed block, for `renderPage`: as written, or escaped by a template (e.g.
19
+ * in a feed's descriptions). Group 1 is "<" or "&lt;", group 2 the block's ID.
20
+ */
21
+ const EMBED_PLACEHOLDER = /(<|&lt;)!--edaha-embed:(\d+)--(?:>|&gt;)/g;
22
+ /**
23
+ * Template data for the `{% embedHead %}` and `{% embedFoot %}` tags while a page is rendered: where `renderPage` puts
24
+ * the HTML the page's embeds need, once it knows which embeds the page shows.
25
+ */
26
+ export const EMBED_PAGE_PARTS = {
27
+ head: "<!--edaha-embeds-head-->",
28
+ foot: "<!--edaha-embeds-foot-->",
29
+ };
30
+ /** Embed keys: lowercase kebab-case */
31
+ const EMBED_KEY = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
32
+ /** The kinds of web addresses an embed can list in its `sources` */
33
+ export const EMBED_SOURCE_KINDS = [
34
+ "frame",
35
+ "script",
36
+ "style",
37
+ "font",
38
+ "connect",
39
+ ];
40
+ /** Whether a value is a list of `https://` origins */
41
+ const isOrigins = (value) => value === undefined ||
42
+ (Array.isArray(value) &&
43
+ value.every((source) => typeof source === "string" && /^https:\/\/[^/\s;,'"]+$/.test(source)));
44
+ /** Whether a value is an object of optional renderer functions (and an optional icon) */
45
+ const isRenderers = (value, renderRequired) => {
46
+ if (!value || typeof value !== "object")
47
+ return false;
48
+ const { render, renderHead, renderFoot, icon } = value;
49
+ return ((typeof render === "function" ||
50
+ (!renderRequired && render === undefined)) &&
51
+ [renderHead, renderFoot].every((fn) => fn === undefined || typeof fn === "function") &&
52
+ (icon === undefined || typeof icon === "string"));
53
+ };
54
+ /**
55
+ * Whether a value is an embed plugin: a kebab-case `key`, a `name`, a `build.render` function, and valid optional
56
+ * `description`, `info`, `sources`, `options` (a map), `validate` and `editor` renderers.
57
+ *
58
+ * @example
59
+ * isEmbedPlugin({ key: "quote", name: "Quote", build: { render: async (text) => text } }); // true
60
+ */
61
+ export const isEmbedPlugin = (value) => {
62
+ if (!value || typeof value !== "object")
63
+ return false;
64
+ const { key, name, description, info, sources, options, validate, build, editor, } = value;
65
+ return (typeof key === "string" &&
66
+ EMBED_KEY.test(key) &&
67
+ typeof name === "string" &&
68
+ name.trim() !== "" &&
69
+ [description, info].every((text) => text === undefined || typeof text === "string") &&
70
+ (options === undefined ||
71
+ (typeof options === "object" &&
72
+ options !== null &&
73
+ !Array.isArray(options))) &&
74
+ (validate === undefined || typeof validate === "function") &&
75
+ (sources === undefined ||
76
+ (typeof sources === "object" &&
77
+ sources !== null &&
78
+ Object.entries(sources).every(([kind, origins]) => EMBED_SOURCE_KINDS.includes(kind) &&
79
+ isOrigins(origins)))) &&
80
+ isRenderers(build, true) &&
81
+ (editor === undefined || isRenderers(editor, false)));
82
+ };
83
+ /**
84
+ * Check a list of embed plugins: each must be valid (see isEmbedPlugin), with a key of its own, and its options must be
85
+ * fields like article metadata's (see EmbedPlugin.options). Throws describing the first problem.
86
+ *
87
+ * @example
88
+ * checkEmbedPlugins([youtube, bandcamp]); // [youtube, bandcamp]
89
+ */
90
+ export const checkEmbedPlugins = (plugins) => {
91
+ const keys = new Set();
92
+ for (const plugin of plugins) {
93
+ if (!isEmbedPlugin(plugin))
94
+ throw new Error(`"plugins" must be embed plugins ({ key, name, description?, info?, sources?, options?, validate?, build: { render, renderHead?, renderFoot? }, editor? }, with a lowercase kebab-case key and https origins), got ${JSON.stringify(plugin) ?? String(plugin)}`);
95
+ if (keys.has(plugin.key))
96
+ throw new Error(`"plugins" has more than one embed with the key "${plugin.key}"`);
97
+ keys.add(plugin.key);
98
+ for (const [name, schema] of Object.entries(plugin.options ?? {}))
99
+ checkFieldSchema(schema, `${plugin.name} embed's options.${name}`);
100
+ try {
101
+ createAjv().compile({ type: "object", properties: plugin.options ?? {} });
102
+ }
103
+ catch (error) {
104
+ throw new Error(`${plugin.name} embed's options aren't valid JSON Schemas: ${error.message}`, { cause: error });
105
+ }
106
+ }
107
+ return plugins;
108
+ };
109
+ /**
110
+ * Load a config file's `plugins`: package names are imported from the config file's folder (their default export is
111
+ * an embed plugin or a list of them); objects are used as they are. Throws naming a package that can't be loaded.
112
+ *
113
+ * @param fromDir - the folder package names are found from, i.e. the config file's
114
+ * @example
115
+ * await loadPlugins(["@lvl99dotcom/edaha-plugin-youtube"], "my-site"); // [youtube]
116
+ */
117
+ export const loadPlugins = async (entries, fromDir) => {
118
+ if (entries === undefined || entries === null)
119
+ return [];
120
+ if (!Array.isArray(entries))
121
+ throw new Error('"plugins" must be a list of embed plugin package names (or, in a JavaScript config file, embed plugins)');
122
+ const require = createRequire(join(fromDir, "package.json"));
123
+ const plugins = [];
124
+ for (const entry of entries) {
125
+ if (typeof entry !== "string") {
126
+ plugins.push(entry);
127
+ continue;
128
+ }
129
+ try {
130
+ const module = (await import(__rewriteRelativeImportExtension(pathToFileURL(require.resolve(entry)).href)));
131
+ plugins.push(...(Array.isArray(module.default) ? module.default : [module.default]));
132
+ }
133
+ catch (error) {
134
+ throw new Error(`plugin "${entry}" couldn't be loaded: ${error.message}`, { cause: error });
135
+ }
136
+ }
137
+ return plugins;
138
+ };
139
+ /** The renderers to use for a target: the editor's fall back to the website's, one by one */
140
+ const renderersFor = (plugin, target) => target === "editor" ? { ...plugin.build, ...plugin.editor } : plugin.build;
141
+ /**
142
+ * Renders embed blocks to HTML with embed plugins, page by page: each page's blocks share their embed's `state`, and
143
+ * the page gets the HTML its embeds need once (`renderHead` and `renderFoot`).
144
+ *
145
+ * Put blocks in markdown with placeholders (`replaceBlocks`), render the markdown and the page's template (with
146
+ * EMBED_PAGE_PARTS for the `{% embedHead %}` and `{% embedFoot %}` tags), then render the page's embeds
147
+ * (`renderPage`).
148
+ *
149
+ * @example
150
+ * const embeds = new EmbedResolver({ fetch, logger: console, plugins: [youtube] });
151
+ * const body = renderMarkdown(embeds.replaceBlocks(source, "news/hello"));
152
+ * const page = await embeds.renderPage(render("article.njk", { body, embeds: EMBED_PAGE_PARTS }), "/news/hello/");
153
+ */
154
+ export class EmbedResolver {
155
+ options;
156
+ plugins;
157
+ /** Embed blocks put in pages, by their placeholders' IDs */
158
+ placed = [];
159
+ /** Why blocks aren't valid, by their key, options and content (see validate) */
160
+ checked = new Map();
161
+ /** Each embed's options' validator, by its key */
162
+ optionValidators = new Map();
163
+ /** Warnings given, so a block shown on several pages is warned about once */
164
+ warned = new Set();
165
+ constructor(options) {
166
+ this.options = options;
167
+ this.plugins = new Map(options.plugins.map((plugin) => [plugin.key, plugin]));
168
+ }
169
+ /**
170
+ * Put an embed block in a page by a placeholder, which `renderPage` renders.
171
+ *
172
+ * @param key - the block's key, or undefined for an old `<!-- embed -->` block
173
+ * @param text - what is between its tags: its options and content
174
+ * @param source - where it is, for warnings
175
+ * @example
176
+ * embeds.place("youtube", "https://youtu.be/x", "Embed"); // "<!--edaha-embed:0-->"
177
+ */
178
+ place(key, text, source) {
179
+ this.placed.push({ key, text, source });
180
+ return `<!--edaha-embed:${this.placed.length - 1}-->`;
181
+ }
182
+ /**
183
+ * Replace every embed block in markdown with a placeholder (see place), as its own block. Blocks in code blocks and
184
+ * inline code are left as they are. Embed HTML put straight into markdown would end at its first blank line, so the
185
+ * blocks are rendered with the page they are shown on (see renderPage).
186
+ *
187
+ * @param source - where the markdown is from, for warnings
188
+ * @example
189
+ * embeds.replaceBlocks("Hi\n<!-- embed:youtube -->https://youtu.be/x<!-- /embed:youtube -->", "news/hello");
190
+ * // "Hi\n\n\n<!--edaha-embed:0-->\n\n"
191
+ */
192
+ replaceBlocks(markdown, source) {
193
+ return replaceOutsideCode(markdown, EMBED_BLOCK, ([, key, text]) => `\n\n${this.place(key, text, source)}\n\n`);
194
+ }
195
+ /**
196
+ * Render a page's embeds: each placeholder of a block (see place) in order, sharing each embed's state on the page,
197
+ * then the HTML the page's embeds need in place of EMBED_PAGE_PARTS' placeholders. A block whose key has no plugin,
198
+ * or whose plugin fails, is shown as it is (a link for a URL, otherwise as text), and one that isn't valid is left
199
+ * out, with a warning (once, however many pages show it). An escaped placeholder (e.g. in a feed) gets escaped HTML.
200
+ *
201
+ * @param source - which page it is, for warnings
202
+ * @param target - render for the website (default) or the editor
203
+ * @example
204
+ * await embeds.renderPage('<head><!--edaha-embeds-head--></head><body><!--edaha-embed:0--></body>', "/news/hello/");
205
+ */
206
+ async renderPage(html, source, target = "build") {
207
+ const page = new Map();
208
+ const rendered = [];
209
+ // One after another, so each embed's state is changed in page order
210
+ for (const [placeholder, open, id] of html.matchAll(EMBED_PLACEHOLDER)) {
211
+ const block = this.placed[Number(id)];
212
+ const embed = block
213
+ ? await this.renderBlock(block, page, target)
214
+ : undefined;
215
+ rendered.push(embed === undefined
216
+ ? placeholder
217
+ : open === "<"
218
+ ? embed
219
+ : escapeHtml(embed));
220
+ }
221
+ let index = 0;
222
+ const withEmbeds = html.replace(EMBED_PLACEHOLDER, () => rendered[index++]);
223
+ if (!withEmbeds.includes(EMBED_PAGE_PARTS.head) &&
224
+ !withEmbeds.includes(EMBED_PAGE_PARTS.foot))
225
+ return withEmbeds;
226
+ const { head, foot } = await this.pageParts(page, source, target);
227
+ return withEmbeds
228
+ .replaceAll(EMBED_PAGE_PARTS.head, () => head)
229
+ .replaceAll(EMBED_PAGE_PARTS.foot, () => foot);
230
+ }
231
+ /**
232
+ * Why a block isn't valid, or nothing when it is: its key has no plugin, its options aren't the embed's (see
233
+ * EmbedPlugin.options), or the embed's `validate` says its content (or options) isn't valid. The options are checked
234
+ * with their defaults and without hidden ones. Used by the editor to check blocks before they are saved.
235
+ *
236
+ * @example
237
+ * await embeds.validate("youtube", "https://example.com/"); // ["https://example.com/ is not a YouTube URL"]
238
+ * await embeds.validate("bandcamp", url, { layout: "huge" }); // ['Layout must be one of "slim", "artwork-only", "large"']
239
+ */
240
+ async validate(key, content, options = {}) {
241
+ const plugin = key ? this.plugins.get(key) : undefined;
242
+ return plugin
243
+ ? this.check(plugin, content, resolveOptions(plugin, options))
244
+ : [capitalise(missingPlugin(key))];
245
+ }
246
+ /** Why a block with its options resolved isn't valid (see validate), checked once */
247
+ check(plugin, content, options) {
248
+ const id = `${plugin.key}\0${JSON.stringify(options)}\0${content}`;
249
+ let checked = this.checked.get(id);
250
+ if (!checked) {
251
+ const problems = this.optionProblems(plugin, options);
252
+ checked = problems.length
253
+ ? Promise.resolve(problems)
254
+ : validateContent(plugin, content, options);
255
+ this.checked.set(id, checked);
256
+ }
257
+ return checked;
258
+ }
259
+ /** Why a block's options (resolved) aren't the embed's, in plain words, e.g. 'Layout must be one of "slim", "large"' */
260
+ optionProblems(plugin, options) {
261
+ let validate = this.optionValidators.get(plugin.key);
262
+ if (!validate) {
263
+ validate = createAjv().compile({
264
+ type: "object",
265
+ properties: plugin.options ?? {},
266
+ additionalProperties: false,
267
+ });
268
+ this.optionValidators.set(plugin.key, validate);
269
+ }
270
+ if (validate(options))
271
+ return [];
272
+ // Options that aren't valid always have errors
273
+ return validate.errors.map((error) => {
274
+ const unknown = error.params
275
+ .additionalProperty;
276
+ if (unknown)
277
+ return `"${unknown}" isn't one of the embed's options`;
278
+ const [name, ...path] = error.instancePath.slice(1).split("/");
279
+ const schema = plugin.options?.[name];
280
+ const label = schema.$edahaField?.title ?? schema.title ?? name;
281
+ return `${[label, ...path].join(" ")} ${plainMessage(error)}`;
282
+ });
283
+ }
284
+ /** Warn about a block or page, unless that warning was given before */
285
+ warn(message) {
286
+ if (this.warned.has(message))
287
+ return;
288
+ this.warned.add(message);
289
+ this.options.logger.warn(message);
290
+ }
291
+ /** Render a block on a page: its HTML, a fallback, or nothing when it is left out (see renderPage) */
292
+ async renderBlock({ key, text, source }, page, target) {
293
+ const { content, options, optionsError } = splitEmbed(text);
294
+ const fallback = () => /^https?:\/\/\S+$/.test(content)
295
+ ? `<p class="embed-link"><a href="${escapeHtml(content)}">${escapeHtml(content)}</a></p>`
296
+ : `<pre class="embed-text">${escapeHtml(content)}</pre>`;
297
+ const plugin = key ? this.plugins.get(key) : undefined;
298
+ if (!plugin) {
299
+ this.warn(`${source}: ${missingPlugin(key)}; shown as it is`);
300
+ return fallback();
301
+ }
302
+ const resolved = resolveOptions(plugin, options);
303
+ const errors = optionsError
304
+ ? [optionsError]
305
+ : await this.check(plugin, content, resolved);
306
+ if (errors.length) {
307
+ // Left out, so the website doesn't show something broken; the rest of the page is still built
308
+ this.warn(`${source}: ${plugin.name} embed isn't valid (${errors.join("; ")}); left out`);
309
+ return "";
310
+ }
311
+ const used = page.get(plugin.key) ?? { state: {}, options: [] };
312
+ try {
313
+ // The build's render is required, so a target always has one
314
+ const render = renderersFor(plugin, target)
315
+ .render;
316
+ const html = await render(content, {
317
+ fetch: this.options.fetch,
318
+ state: used.state,
319
+ options: resolved,
320
+ });
321
+ used.options.push(resolved);
322
+ page.set(plugin.key, used);
323
+ return `<div class="embed embed-${plugin.key}">${html}</div>`;
324
+ }
325
+ catch (error) {
326
+ this.warn(`${source}: ${plugin.name} embed failed (${error.message}); shown as it is`);
327
+ return fallback();
328
+ }
329
+ }
330
+ /**
331
+ * The HTML a page needs for the embeds it shows: each shown embed's `renderHead` and `renderFoot`, once, in the
332
+ * order of the plugins. One that fails is left out with a warning.
333
+ */
334
+ async pageParts(page, source, target) {
335
+ const part = async (name) => {
336
+ const html = [];
337
+ for (const [key, plugin] of this.plugins) {
338
+ const used = page.get(key);
339
+ const fn = renderersFor(plugin, target)[name];
340
+ if (!used || !fn)
341
+ continue;
342
+ try {
343
+ html.push(await fn({ fetch: this.options.fetch, ...used }));
344
+ }
345
+ catch (error) {
346
+ this.warn(`${source}: ${plugin.name} embed's ${name} failed (${error.message}); left out`);
347
+ }
348
+ }
349
+ return html.join("\n");
350
+ };
351
+ return { head: await part("renderHead"), foot: await part("renderFoot") };
352
+ }
353
+ }
354
+ /** A block's options with their defaults, and without hidden ones (see EmbedPlugin.options) */
355
+ const resolveOptions = (plugin, options) => plugin.options ? resolveFields(plugin.options, options).values : options;
356
+ /**
357
+ * A fetch that fetches each address once (requests without other settings only), giving each caller a copy of the
358
+ * response, e.g. so pages that show the same embed don't fetch it again.
359
+ *
360
+ * @example
361
+ * const fetchOnce = cachedFetch(fetch);
362
+ * await fetchOnce("https://example.com/"); // fetched
363
+ * await fetchOnce("https://example.com/"); // the same response, not fetched again
364
+ */
365
+ export const cachedFetch = (fetcher) => {
366
+ const responses = new Map();
367
+ return async (input, init) => {
368
+ const url = typeof input === "string" || input instanceof URL ? String(input) : "";
369
+ if (!url || init)
370
+ return fetcher(input, init);
371
+ let response = responses.get(url);
372
+ if (!response) {
373
+ response = fetcher(url);
374
+ responses.set(url, response);
375
+ // A failed request is tried again next time
376
+ response.catch(() => responses.delete(url));
377
+ }
378
+ return (await response).clone();
379
+ };
380
+ };
381
+ /** Why a block's key has no plugin */
382
+ const missingPlugin = (key) =>
383
+ // An empty key is an old block without one, as the editor sends it
384
+ !key
385
+ ? "embed blocks need a key, e.g. <!-- embed:youtube -->...<!-- /embed:youtube -->"
386
+ : `no embed plugin with the key "${key}"`;
387
+ /** A message with its first letter in capitals */
388
+ const capitalise = (text) => text.charAt(0).toUpperCase() + text.slice(1);
389
+ /**
390
+ * The messages of an error thrown by an embed's `validate`: each of an `AggregateError`'s errors, or the error's own.
391
+ *
392
+ * @example
393
+ * validationErrors(new AggregateError([new Error("No ID"), new Error("Too long")])); // ["No ID", "Too long"]
394
+ */
395
+ export const validationErrors = (error) => {
396
+ const errors = error instanceof AggregateError && error.errors.length
397
+ ? error.errors
398
+ : [error];
399
+ return errors.map((e) => (e instanceof Error ? e.message : String(e)));
400
+ };
401
+ /** Why a block's content isn't valid for its plugin, or nothing when it is */
402
+ const validateContent = async (plugin, content, options) => {
403
+ try {
404
+ return (await plugin.validate?.(content, options)) === false
405
+ ? [`The content isn't a valid ${plugin.name}`]
406
+ : [];
407
+ }
408
+ catch (error) {
409
+ return validationErrors(error);
410
+ }
411
+ };
@@ -0,0 +1,117 @@
1
+ import type { EmbedOptionValues } from "../blocks/index.ts";
2
+ import type { MetadataDefinitions } from "../../generator/metadata/index.ts";
3
+ export type { EmbedOptionValues } from "../blocks/index.ts";
4
+ /** An embed's options' schemas, by the name each is saved under (see EmbedPlugin.options) */
5
+ export type EmbedOptionSchemas = MetadataDefinitions;
6
+ /** What an embed's functions may use */
7
+ export interface EmbedContext {
8
+ /** Fetches extra data, e.g. oEmbed JSON (replaceable for tests) */
9
+ fetch: typeof fetch;
10
+ }
11
+ /**
12
+ * Things an embed keeps for one page while it renders, which every render of it on the page and its `renderHead` and
13
+ * `renderFoot` share, e.g. the IDs of the diagrams to start. Each page starts with an empty one for each embed.
14
+ */
15
+ export type EmbedState = Record<string, unknown>;
16
+ /** What an embed's `render` gets besides the content */
17
+ export interface EmbedRenderContext extends EmbedContext {
18
+ /** What the embed keeps for this page (see EmbedState): change it while rendering */
19
+ state: EmbedState;
20
+ /** The block's options, with their defaults and without hidden ones (see EmbedPlugin.options) */
21
+ options: EmbedOptionValues;
22
+ }
23
+ /** What an embed's `renderHead` and `renderFoot` get */
24
+ export interface EmbedPageContext extends EmbedContext {
25
+ /** What the embed kept for this page (see EmbedState), after every render of it */
26
+ state: EmbedState;
27
+ /** The options of each of the embed's blocks on the page, in page order */
28
+ options: readonly EmbedOptionValues[];
29
+ }
30
+ /** How an embed renders for the website, or for the editor */
31
+ export interface EmbedRenderers {
32
+ /** Render one embed block's content (the text between its tags) to HTML. Throws if it can't be embedded. */
33
+ render?(content: string, context: EmbedRenderContext): Promise<string>;
34
+ /** Optional; HTML for the page's `<head>` (e.g. stylesheets), once per page that has this embed */
35
+ renderHead?(context: EmbedPageContext): Promise<string>;
36
+ /** Optional; HTML for the end of the page's `<body>` (e.g. scripts), once per page that has this embed */
37
+ renderFoot?(context: EmbedPageContext): Promise<string>;
38
+ }
39
+ /** How an embed renders for the website: `render` is required */
40
+ export interface EmbedBuildRenderers extends EmbedRenderers {
41
+ render(content: string, context: EmbedRenderContext): Promise<string>;
42
+ }
43
+ /** How an embed shows in the editor's rich text body, where each of these replaces the website's own */
44
+ export interface EmbedEditorRenderers extends EmbedRenderers {
45
+ /** An SVG icon (markup) for the embed in the editor's lists, sized by the editor */
46
+ icon?: string | undefined;
47
+ }
48
+ /**
49
+ * The web addresses an embed's HTML loads from, by kind (each an `https://` origin, e.g. "https://cdn.example.com"),
50
+ * which the editor's preview pages allow. Its own scripts and styles inside the HTML are always allowed there.
51
+ */
52
+ export interface EmbedSources {
53
+ /** Frames, e.g. a video player */
54
+ frame?: readonly string[] | undefined;
55
+ /** Scripts */
56
+ script?: readonly string[] | undefined;
57
+ /** Stylesheets */
58
+ style?: readonly string[] | undefined;
59
+ /** Fonts */
60
+ font?: readonly string[] | undefined;
61
+ /** Requests made by its scripts */
62
+ connect?: readonly string[] | undefined;
63
+ }
64
+ /**
65
+ * An embed plugin: turns the content of `<!-- embed:<key> -->...<!-- /embed:<key> -->` blocks into HTML.
66
+ *
67
+ * @example
68
+ * const quote: EmbedPlugin = {
69
+ * key: "quote",
70
+ * name: "Quote",
71
+ * build: { render: async (content) => `<blockquote>${content}</blockquote>` },
72
+ * };
73
+ */
74
+ export interface EmbedPlugin {
75
+ /** Which blocks it renders, e.g. "youtube" for `<!-- embed:youtube -->`: lowercase kebab-case */
76
+ key: string;
77
+ /** Its name, shown in the editor and in warnings, e.g. "YouTube video" */
78
+ name: string;
79
+ /** Optional; what it embeds, shown in the editor, e.g. "Paste a YouTube video's URL" */
80
+ description?: string | undefined;
81
+ /**
82
+ * Optional; shown under the content's label in the embed dialog, e.g. "Paste the album's or track's URL". Without
83
+ * it, the dialog says "Provide the embed's content, e.g. a URL or code".
84
+ */
85
+ info?: string | undefined;
86
+ /** Optional; the web addresses its HTML loads from, which the editor's previews allow */
87
+ sources?: EmbedSources | undefined;
88
+ /**
89
+ * Optional; options that change how a block shows, by the name they are saved under: JSON Schemas with
90
+ * `$edahaField`, like article metadata fields (including `defaultValue`, `showWhen` and `hideWhen`). The embed dialog
91
+ * shows them above the content, and blocks save them in YAML before their content:
92
+ * `<!-- embed:bandcamp -->\n<!--yaml\nlayout: large\n-->\nhttps://...\n<!-- /embed:bandcamp -->`. A block's options
93
+ * are checked against them, and one with options that aren't valid is left out, like one with content that isn't.
94
+ */
95
+ options?: EmbedOptionSchemas | undefined;
96
+ /**
97
+ * Optional; check a block's content (and options) before it is rendered, for the website and the editor. Return
98
+ * `true` when it is valid. Throw an error saying what is wrong (or an `AggregateError` with one error for each
99
+ * problem), or return `false` for a general message. A block whose content isn't valid is left out of the website,
100
+ * with a warning (the rest of its page is still built), and the editor shows the errors on it and in its embed
101
+ * dialog.
102
+ */
103
+ validate?: ((content: string, options: EmbedOptionValues) => boolean | undefined | Promise<boolean | undefined>) | undefined;
104
+ /** How it renders for the website */
105
+ build: EmbedBuildRenderers;
106
+ /** Optional; how it shows in the editor's rich text body instead (each one defaults to the website's) */
107
+ editor?: EmbedEditorRenderers | undefined;
108
+ }
109
+ /** Which of an embed's renderers to use: the website's, or the editor's (which default to the website's) */
110
+ export type EmbedTarget = "build" | "editor";
111
+ /** HTML an embed adds to a page, for the `{% embedHead %}` and `{% embedFoot %}` template tags */
112
+ export interface EmbedPageParts {
113
+ /** For the end of `<head>` */
114
+ head: string;
115
+ /** For the end of `<body>` */
116
+ foot: string;
117
+ }