@lvl99dotcom/edaha.md 0.1.0 → 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.
- package/LICENSE +183 -183
- package/README.md +7 -252
- package/dist/cli/index.d.ts +36 -6
- package/dist/cli/index.js +48 -9
- package/dist/embeds/blocks/index.d.ts +59 -0
- package/dist/embeds/blocks/index.js +103 -0
- package/dist/embeds/index.d.ts +122 -19
- package/dist/embeds/index.js +381 -41
- package/dist/embeds/types/index.d.ts +111 -8
- package/dist/generator/article/index.d.ts +52 -12
- package/dist/generator/article/index.js +94 -26
- package/dist/generator/build/index.d.ts +55 -23
- package/dist/generator/build/index.js +151 -81
- package/dist/generator/config/index.d.ts +45 -8
- package/dist/generator/config/index.js +152 -30
- package/dist/generator/configFile/index.d.ts +58 -0
- package/dist/generator/configFile/index.js +122 -0
- package/dist/generator/fields/index.d.ts +93 -0
- package/dist/generator/fields/index.js +186 -0
- package/dist/generator/format/index.d.ts +40 -0
- package/dist/generator/format/index.js +75 -0
- package/dist/generator/lists/index.d.ts +3 -3
- package/dist/generator/lists/index.js +9 -8
- package/dist/generator/markdown/index.d.ts +8 -3
- package/dist/generator/markdown/index.js +11 -4
- package/dist/generator/metadata/index.d.ts +150 -0
- package/dist/generator/metadata/index.js +361 -0
- package/dist/generator/metadataGroups/index.d.ts +45 -0
- package/dist/generator/metadataGroups/index.js +169 -0
- package/dist/generator/templates/index.d.ts +35 -3
- package/dist/generator/templates/index.js +72 -6
- package/dist/generator/types/index.d.ts +43 -18
- package/dist/generator/urls/index.d.ts +18 -8
- package/dist/generator/urls/index.js +22 -12
- package/dist/index.d.ts +5 -7
- package/dist/index.js +6 -7
- package/package.json +18 -47
- package/theme/static/{site.css → base.css} +132 -24
- package/theme/templates/article/list.njk +6 -6
- package/theme/templates/article/single.njk +13 -7
- package/theme/templates/layouts/html.njk +54 -32
- package/theme/templates/layouts/rssfeed.njk +7 -7
- package/theme/templates/page/home.njk +2 -7
- package/theme/templates/page/single.njk +2 -2
- package/dist/client/assets/index-BbKEbPS8.css +0 -1
- package/dist/client/assets/index-DtG7vi1d.js +0 -559
- package/dist/client/index.html +0 -13
- package/dist/editor/index.d.ts +0 -62
- package/dist/editor/index.js +0 -102
- package/dist/embeds/bandcamp/index.d.ts +0 -9
- package/dist/embeds/bandcamp/index.js +0 -28
- package/dist/embeds/youtube/index.d.ts +0 -17
- package/dist/embeds/youtube/index.js +0 -48
- package/dist/server/app/index.d.ts +0 -39
- package/dist/server/app/index.js +0 -138
- package/dist/server/convert/index.d.ts +0 -25
- package/dist/server/convert/index.js +0 -125
- package/dist/server/store/index.d.ts +0 -148
- package/dist/server/store/index.js +0 -411
- package/dist/server/types/index.d.ts +0 -76
- package/dist/server/types/index.js +0 -1
package/dist/embeds/index.js
CHANGED
|
@@ -1,71 +1,411 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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 "<", group 2 the block's ID.
|
|
20
|
+
*/
|
|
21
|
+
const EMBED_PLACEHOLDER = /(<|<)!--edaha-embed:(\d+)--(?:>|>)/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
|
+
};
|
|
8
54
|
/**
|
|
9
|
-
*
|
|
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`).
|
|
10
148
|
*
|
|
11
149
|
* @example
|
|
12
|
-
* const embeds = new EmbedResolver({ fetch, logger: console });
|
|
13
|
-
* const
|
|
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/");
|
|
14
153
|
*/
|
|
15
154
|
export class EmbedResolver {
|
|
16
155
|
options;
|
|
17
|
-
|
|
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();
|
|
18
165
|
constructor(options) {
|
|
19
166
|
this.options = options;
|
|
167
|
+
this.plugins = new Map(options.plugins.map((plugin) => [plugin.key, plugin]));
|
|
20
168
|
}
|
|
21
169
|
/**
|
|
22
|
-
*
|
|
23
|
-
* warn and render a plain link instead.
|
|
170
|
+
* Put an embed block in a page by a placeholder, which `renderPage` renders.
|
|
24
171
|
*
|
|
25
|
-
* @param
|
|
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-->"
|
|
26
177
|
*/
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
return cached;
|
|
31
|
-
const result = this.renderUncached(rawUrl, source);
|
|
32
|
-
this.cache.set(rawUrl, result);
|
|
33
|
-
return result;
|
|
178
|
+
place(key, text, source) {
|
|
179
|
+
this.placed.push({ key, text, source });
|
|
180
|
+
return `<!--edaha-embed:${this.placed.length - 1}-->`;
|
|
34
181
|
}
|
|
35
182
|
/**
|
|
36
|
-
* Replace every
|
|
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).
|
|
37
186
|
*
|
|
38
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"
|
|
39
191
|
*/
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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
|
+
}
|
|
43
221
|
let index = 0;
|
|
44
|
-
|
|
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);
|
|
45
230
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
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);
|
|
52
256
|
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
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);
|
|
56
269
|
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
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`);
|
|
60
300
|
return fallback();
|
|
61
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: [] };
|
|
62
312
|
try {
|
|
63
|
-
|
|
64
|
-
|
|
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>`;
|
|
65
324
|
}
|
|
66
325
|
catch (error) {
|
|
67
|
-
|
|
326
|
+
this.warn(`${source}: ${plugin.name} embed failed (${error.message}); shown as it is`);
|
|
68
327
|
return fallback();
|
|
69
328
|
}
|
|
70
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
|
+
}
|
|
71
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
|
+
};
|
|
@@ -1,14 +1,117 @@
|
|
|
1
|
-
|
|
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 */
|
|
2
7
|
export interface EmbedContext {
|
|
3
8
|
/** Fetches extra data, e.g. oEmbed JSON (replaceable for tests) */
|
|
4
9
|
fetch: typeof fetch;
|
|
5
10
|
}
|
|
6
|
-
/**
|
|
7
|
-
|
|
8
|
-
|
|
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" */
|
|
9
78
|
name: string;
|
|
10
|
-
/**
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
|
|
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;
|
|
14
117
|
}
|