@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.
- package/LICENSE +201 -0
- package/README.md +13 -2
- package/dist/cli/bin.d.ts +2 -0
- package/dist/cli/bin.js +9 -0
- package/dist/cli/index.d.ts +71 -0
- package/dist/cli/index.js +149 -0
- package/dist/embeds/blocks/index.d.ts +59 -0
- package/dist/embeds/blocks/index.js +103 -0
- package/dist/embeds/index.d.ts +143 -0
- package/dist/embeds/index.js +411 -0
- package/dist/embeds/types/index.d.ts +117 -0
- package/dist/embeds/types/index.js +1 -0
- package/dist/generator/article/index.d.ts +151 -0
- package/dist/generator/article/index.js +325 -0
- package/dist/generator/build/index.d.ts +109 -0
- package/dist/generator/build/index.js +363 -0
- package/dist/generator/config/index.d.ts +96 -0
- package/dist/generator/config/index.js +298 -0
- 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 +92 -0
- package/dist/generator/format/index.js +177 -0
- package/dist/generator/lists/index.d.ts +63 -0
- package/dist/generator/lists/index.js +133 -0
- package/dist/generator/markdown/index.d.ts +25 -0
- package/dist/generator/markdown/index.js +62 -0
- 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/slug/index.d.ts +26 -0
- package/dist/generator/slug/index.js +57 -0
- package/dist/generator/templates/index.d.ts +88 -0
- package/dist/generator/templates/index.js +175 -0
- package/dist/generator/types/index.d.ts +186 -0
- package/dist/generator/types/index.js +1 -0
- package/dist/generator/urls/index.d.ts +50 -0
- package/dist/generator/urls/index.js +77 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +9 -0
- package/dist/theme/index.d.ts +8 -0
- package/dist/theme/index.js +9 -0
- package/package.json +64 -3
- package/theme/static/base.css +328 -0
- package/theme/templates/article/list.njk +69 -0
- package/theme/templates/article/single.njk +64 -0
- package/theme/templates/layouts/html.njk +72 -0
- package/theme/templates/layouts/rssfeed.njk +28 -0
- package/theme/templates/page/home.njk +16 -0
- package/theme/templates/page/single.njk +18 -0
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { isAbsolute, normalize, sep } from "node:path";
|
|
2
|
+
import { checkEmbedPlugins } from "../../embeds/index.js";
|
|
3
|
+
import { isSlug, slugify } from "../slug/index.js";
|
|
4
|
+
import { parseMetadata, parseTypeMetadata, } from "../metadata/index.js";
|
|
5
|
+
import { metadataLayout, parseMetadataGroups, } from "../metadataGroups/index.js";
|
|
6
|
+
/** Settings under `generate` */
|
|
7
|
+
const GENERATE_KEYS = [
|
|
8
|
+
"article",
|
|
9
|
+
"list",
|
|
10
|
+
"feed",
|
|
11
|
+
"author",
|
|
12
|
+
"tag",
|
|
13
|
+
];
|
|
14
|
+
/** Settings of an article type */
|
|
15
|
+
const TYPE_KEYS = [
|
|
16
|
+
"labelSingle",
|
|
17
|
+
"labelPlural",
|
|
18
|
+
"path",
|
|
19
|
+
"generate",
|
|
20
|
+
"metadata",
|
|
21
|
+
"author",
|
|
22
|
+
];
|
|
23
|
+
/** The site's settings */
|
|
24
|
+
const CONFIG_KEYS = [
|
|
25
|
+
"name",
|
|
26
|
+
"description",
|
|
27
|
+
"path",
|
|
28
|
+
"outputDir",
|
|
29
|
+
"articlesDir",
|
|
30
|
+
"templatesDir",
|
|
31
|
+
"staticDir",
|
|
32
|
+
"publishDir",
|
|
33
|
+
"siteUrl",
|
|
34
|
+
"reservedPaths",
|
|
35
|
+
"types",
|
|
36
|
+
"plugins",
|
|
37
|
+
"metadata",
|
|
38
|
+
"metadataGroups",
|
|
39
|
+
"author",
|
|
40
|
+
];
|
|
41
|
+
/** List folders that can't be used as article types */
|
|
42
|
+
export const RESERVED_TYPES = ["tags", "authors"];
|
|
43
|
+
/**
|
|
44
|
+
* Settings for an article type that isn't configured: everything generated, labelled from its name.
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* defaultTypeConfig("video"); // { path: "video", labelSingle: "Video", labelPlural: "Videos", generate: { article: true, ... } }
|
|
48
|
+
*/
|
|
49
|
+
export const defaultTypeConfig = (type) => {
|
|
50
|
+
const labelSingle = type.charAt(0).toUpperCase() + type.slice(1);
|
|
51
|
+
return {
|
|
52
|
+
path: type,
|
|
53
|
+
labelSingle,
|
|
54
|
+
labelPlural: `${labelSingle}s`,
|
|
55
|
+
generate: {
|
|
56
|
+
article: true,
|
|
57
|
+
list: true,
|
|
58
|
+
feed: true,
|
|
59
|
+
author: true,
|
|
60
|
+
tag: true,
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
/** Check a value is a map, throwing a config error if not */
|
|
65
|
+
const asMap = (value, what) => {
|
|
66
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
67
|
+
throw new Error(`${what} must be a map of settings`);
|
|
68
|
+
return value;
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* Read an optional URL path: lowercase kebab-case, or "" for the root.
|
|
72
|
+
*/
|
|
73
|
+
const parsePath = (value, what) => {
|
|
74
|
+
if (value === undefined || value === null)
|
|
75
|
+
return undefined;
|
|
76
|
+
if (typeof value !== "string" || (value !== "" && !isSlug(value)))
|
|
77
|
+
throw new Error(`${what} must be lowercase kebab-case, or "" for the root`);
|
|
78
|
+
return value;
|
|
79
|
+
};
|
|
80
|
+
/** Throw a config error for keys that aren't allowed */
|
|
81
|
+
const checkKeys = (map, allowed, what) => {
|
|
82
|
+
const unknown = Object.keys(map).filter((key) => !allowed.includes(key));
|
|
83
|
+
if (unknown.length)
|
|
84
|
+
throw new Error(`unknown ${what} setting${unknown.length > 1 ? "s" : ""} ${unknown.map((key) => `"${key}"`).join(", ")}`);
|
|
85
|
+
};
|
|
86
|
+
/**
|
|
87
|
+
* Parse one article type's settings, filling in defaults.
|
|
88
|
+
*/
|
|
89
|
+
const parseTypeConfig = (type, value) => {
|
|
90
|
+
if (!isSlug(type) || RESERVED_TYPES.includes(type))
|
|
91
|
+
throw new Error(`type "${type}" must be lowercase kebab-case and not ${RESERVED_TYPES.join(" or ")}`);
|
|
92
|
+
const config = defaultTypeConfig(type);
|
|
93
|
+
if (value === null || value === undefined)
|
|
94
|
+
return config;
|
|
95
|
+
const fields = asMap(value, `"types.${type}"`);
|
|
96
|
+
checkKeys(fields, TYPE_KEYS, `"types.${type}"`);
|
|
97
|
+
for (const label of ["labelSingle", "labelPlural"]) {
|
|
98
|
+
const text = fields[label];
|
|
99
|
+
if (text === undefined)
|
|
100
|
+
continue;
|
|
101
|
+
if (typeof text !== "string" || !text.trim())
|
|
102
|
+
throw new Error(`"types.${type}.${label}" must be a non-empty string`);
|
|
103
|
+
config[label] = text.trim();
|
|
104
|
+
}
|
|
105
|
+
config.path = parsePath(fields.path, `"types.${type}.path"`) ?? type;
|
|
106
|
+
config.author = parseAuthor(fields.author, `"types.${type}.author"`);
|
|
107
|
+
config.metadata = parseTypeMetadata(fields.metadata, `"types.${type}.metadata"`);
|
|
108
|
+
const generate = fields.generate;
|
|
109
|
+
if (generate === false)
|
|
110
|
+
for (const key of GENERATE_KEYS)
|
|
111
|
+
config.generate[key] = false;
|
|
112
|
+
else if (generate !== undefined && generate !== true) {
|
|
113
|
+
const flags = asMap(generate, `"types.${type}.generate"`);
|
|
114
|
+
checkKeys(flags, GENERATE_KEYS, `"types.${type}.generate"`);
|
|
115
|
+
for (const key of GENERATE_KEYS) {
|
|
116
|
+
const flag = flags[key];
|
|
117
|
+
if (flag === undefined)
|
|
118
|
+
continue;
|
|
119
|
+
if (typeof flag !== "boolean")
|
|
120
|
+
throw new Error(`"types.${type}.generate.${key}" must be true or false`);
|
|
121
|
+
config.generate[key] = flag;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
// Without articles, nothing else can be built
|
|
125
|
+
if (!config.generate.article)
|
|
126
|
+
for (const key of GENERATE_KEYS)
|
|
127
|
+
config.generate[key] = false;
|
|
128
|
+
return config;
|
|
129
|
+
};
|
|
130
|
+
/**
|
|
131
|
+
* Read a default author: a name, a map with a `name` and optionally an `email` and `url` (like an article's), or `false`
|
|
132
|
+
* for none.
|
|
133
|
+
*
|
|
134
|
+
* @param what - the setting, for errors, e.g. '"author"'
|
|
135
|
+
*
|
|
136
|
+
* @example
|
|
137
|
+
* parseAuthor("Matt", '"author"'); // { name: "Matt" }
|
|
138
|
+
* parseAuthor(false, '"author"'); // false
|
|
139
|
+
*/
|
|
140
|
+
const parseAuthor = (value, what) => {
|
|
141
|
+
if (value === undefined || value === null)
|
|
142
|
+
return undefined;
|
|
143
|
+
if (value === false)
|
|
144
|
+
return false;
|
|
145
|
+
const nameNeeded = `${what} needs a name with letters or numbers, or false for no author`;
|
|
146
|
+
if (typeof value === "string") {
|
|
147
|
+
if (!slugify(value))
|
|
148
|
+
throw new Error(nameNeeded);
|
|
149
|
+
return { name: value.trim() };
|
|
150
|
+
}
|
|
151
|
+
const fields = asMap(value, what);
|
|
152
|
+
checkKeys(fields, ["name", "email", "url"], what);
|
|
153
|
+
const name = optionalString(fields, "name");
|
|
154
|
+
if (!name || !slugify(name))
|
|
155
|
+
throw new Error(nameNeeded);
|
|
156
|
+
return {
|
|
157
|
+
name,
|
|
158
|
+
email: optionalString(fields, "email"),
|
|
159
|
+
url: optionalString(fields, "url"),
|
|
160
|
+
};
|
|
161
|
+
};
|
|
162
|
+
/**
|
|
163
|
+
* Read a required, non-empty string field from parsed YAML.
|
|
164
|
+
*/
|
|
165
|
+
const requireString = (data, field) => {
|
|
166
|
+
const value = data[field];
|
|
167
|
+
if (typeof value !== "string" || value.trim() === "")
|
|
168
|
+
throw new Error(`"${field}" must be a non-empty string`);
|
|
169
|
+
return value.trim();
|
|
170
|
+
};
|
|
171
|
+
/**
|
|
172
|
+
* Read an optional, non-empty string field from parsed YAML.
|
|
173
|
+
*/
|
|
174
|
+
const optionalString = (data, field) => data[field] === undefined || data[field] === null
|
|
175
|
+
? undefined
|
|
176
|
+
: requireString(data, field);
|
|
177
|
+
/**
|
|
178
|
+
* Read the optional site URL: an absolute http(s) URL.
|
|
179
|
+
*/
|
|
180
|
+
const parseSiteUrl = (data) => {
|
|
181
|
+
const value = optionalString(data, "siteUrl");
|
|
182
|
+
if (value !== undefined && !/^https?:\/\/[^/]/.test(value))
|
|
183
|
+
throw new Error('"siteUrl" must be an absolute http(s) URL, e.g. "https://example.com"');
|
|
184
|
+
return value;
|
|
185
|
+
};
|
|
186
|
+
/**
|
|
187
|
+
* Read the optional list of reserved paths: URL path segments or file names, e.g. "app" or "jwks.json".
|
|
188
|
+
*/
|
|
189
|
+
/** The site's source folders' settings, with their defaults */
|
|
190
|
+
export const SOURCE_FOLDERS = {
|
|
191
|
+
articlesDir: "articles",
|
|
192
|
+
templatesDir: "templates",
|
|
193
|
+
staticDir: "static",
|
|
194
|
+
};
|
|
195
|
+
/**
|
|
196
|
+
* Read an optional source folder setting: a folder inside the site folder (not the site folder itself). Gives the folder
|
|
197
|
+
* with "/" separators.
|
|
198
|
+
*/
|
|
199
|
+
const parseFolder = (data, field) => {
|
|
200
|
+
const value = optionalString(data, field) ?? SOURCE_FOLDERS[field];
|
|
201
|
+
const folder = normalize(value).split(sep).join("/").replace(/\/$/, "");
|
|
202
|
+
if (isAbsolute(value) || folder === "." || folder.split("/")[0] === "..")
|
|
203
|
+
throw new Error(`"${field}" must be a folder inside the site folder, got "${value}"`);
|
|
204
|
+
return folder;
|
|
205
|
+
};
|
|
206
|
+
/** Whether one folder (with "/" separators) is the other or inside it */
|
|
207
|
+
const overlaps = (a, b) => a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
|
|
208
|
+
/**
|
|
209
|
+
* Read the source folders (articles, templates and static files), which must be apart from each other.
|
|
210
|
+
*/
|
|
211
|
+
const parseSourceFolders = (data) => {
|
|
212
|
+
const fields = Object.keys(SOURCE_FOLDERS);
|
|
213
|
+
const folders = Object.fromEntries(fields.map((field) => [field, parseFolder(data, field)]));
|
|
214
|
+
fields.forEach((a, i) => {
|
|
215
|
+
for (const b of fields.slice(i + 1))
|
|
216
|
+
if (overlaps(folders[a], folders[b]))
|
|
217
|
+
throw new Error(`"${a}" and "${b}" must be apart from each other, got "${folders[a]}" and "${folders[b]}"`);
|
|
218
|
+
});
|
|
219
|
+
return folders;
|
|
220
|
+
};
|
|
221
|
+
/**
|
|
222
|
+
* Read the optional embed plugins. Package names in the config file are loaded by loadSiteConfig before this, so only
|
|
223
|
+
* plugin objects are left.
|
|
224
|
+
*/
|
|
225
|
+
const parsePlugins = (data) => {
|
|
226
|
+
const value = data.plugins;
|
|
227
|
+
if (value === undefined || value === null)
|
|
228
|
+
return [];
|
|
229
|
+
if (!Array.isArray(value))
|
|
230
|
+
throw new Error('"plugins" must be a list of embed plugin package names (or, in a JavaScript config file, embed plugins)');
|
|
231
|
+
if (value.some((plugin) => typeof plugin === "string"))
|
|
232
|
+
throw new Error('"plugins" package names are loaded by loadSiteConfig; pass embed plugins to parseConfig');
|
|
233
|
+
return checkEmbedPlugins(value);
|
|
234
|
+
};
|
|
235
|
+
const parseReservedPaths = (data) => {
|
|
236
|
+
const value = data.reservedPaths;
|
|
237
|
+
if (value === undefined || value === null)
|
|
238
|
+
return [];
|
|
239
|
+
if (!Array.isArray(value) ||
|
|
240
|
+
value.some((path) => typeof path !== "string" || !/^[a-z0-9][a-z0-9._-]*$/.test(path)))
|
|
241
|
+
throw new Error('"reservedPaths" must be a list of lowercase paths at the website\'s root, e.g. ["app", "api"]');
|
|
242
|
+
return value;
|
|
243
|
+
};
|
|
244
|
+
/**
|
|
245
|
+
* Validate the settings read from the site's config file and fill in defaults.
|
|
246
|
+
*/
|
|
247
|
+
const validateConfig = (data) => {
|
|
248
|
+
const fields = asMap(data, "the config file");
|
|
249
|
+
checkKeys(fields, CONFIG_KEYS, "site");
|
|
250
|
+
const types = fields.types === undefined || fields.types === null
|
|
251
|
+
? {}
|
|
252
|
+
: asMap(fields.types, '"types"');
|
|
253
|
+
const metadata = parseMetadata(fields.metadata);
|
|
254
|
+
const metadataGroups = parseMetadataGroups(fields.metadataGroups);
|
|
255
|
+
// Every field's group, and what each field and group follows, must exist
|
|
256
|
+
metadataLayout(metadata, metadataGroups);
|
|
257
|
+
const typeConfigs = Object.fromEntries(Object.entries(types).map(([type, value]) => [
|
|
258
|
+
type,
|
|
259
|
+
parseTypeConfig(type, value),
|
|
260
|
+
]));
|
|
261
|
+
// Types can only use custom metadata that is defined
|
|
262
|
+
for (const [type, { metadata: keys }] of Object.entries(typeConfigs))
|
|
263
|
+
for (const key of keys || [])
|
|
264
|
+
if (!(key in metadata))
|
|
265
|
+
throw new Error(`"types.${type}.metadata" lists "${key}", which isn't defined in "metadata"`);
|
|
266
|
+
return {
|
|
267
|
+
name: requireString(fields, "name"),
|
|
268
|
+
description: requireString(fields, "description"),
|
|
269
|
+
path: parsePath(fields.path, '"path"') ?? "",
|
|
270
|
+
outputDir: optionalString(fields, "outputDir") ?? "build",
|
|
271
|
+
...parseSourceFolders(fields),
|
|
272
|
+
publishDir: optionalString(fields, "publishDir"),
|
|
273
|
+
siteUrl: parseSiteUrl(fields),
|
|
274
|
+
reservedPaths: parseReservedPaths(fields),
|
|
275
|
+
plugins: parsePlugins(fields),
|
|
276
|
+
metadata,
|
|
277
|
+
metadataGroups,
|
|
278
|
+
author: parseAuthor(fields.author, '"author"'),
|
|
279
|
+
types: typeConfigs,
|
|
280
|
+
};
|
|
281
|
+
};
|
|
282
|
+
/**
|
|
283
|
+
* Validate the settings read from the site's config file (YAML, JSON or JavaScript) and fill in defaults. Errors start
|
|
284
|
+
* with the config file's name.
|
|
285
|
+
*
|
|
286
|
+
* @param source - the config file's name, for errors
|
|
287
|
+
*
|
|
288
|
+
* @example
|
|
289
|
+
* parseConfig({ name: "News", description: "Updates" }, "edaha.config.json");
|
|
290
|
+
*/
|
|
291
|
+
export const parseConfig = (data, source = "config") => {
|
|
292
|
+
try {
|
|
293
|
+
return validateConfig(data);
|
|
294
|
+
}
|
|
295
|
+
catch (error) {
|
|
296
|
+
throw new Error(`${source}: ${error.message}`, { cause: error });
|
|
297
|
+
}
|
|
298
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { type EdahaConfig } from "../config/index.ts";
|
|
2
|
+
import type { Logger } from "../types/index.ts";
|
|
3
|
+
/** Config file names (without extension), in the order they are looked for */
|
|
4
|
+
export declare const CONFIG_NAMES: string[];
|
|
5
|
+
/** Config file extensions, in the order they are looked for */
|
|
6
|
+
export declare const CONFIG_EXTENSIONS: string[];
|
|
7
|
+
/** Every config file name, in the order they are looked for */
|
|
8
|
+
export declare const CONFIG_FILES: string[];
|
|
9
|
+
/** A site's config file, its folder and its validated settings */
|
|
10
|
+
export interface SiteConfig {
|
|
11
|
+
/** The config file's absolute path */
|
|
12
|
+
configFile: string;
|
|
13
|
+
/** The site folder: the config file's folder, which the paths in its settings are relative to */
|
|
14
|
+
siteDir: string;
|
|
15
|
+
/** The validated settings */
|
|
16
|
+
config: EdahaConfig;
|
|
17
|
+
}
|
|
18
|
+
/** Options for finding and reading a site's config file */
|
|
19
|
+
export interface SiteConfigOptions {
|
|
20
|
+
/** The folder to look for a config file in, before the nearest package.json's folder. Default: the current folder */
|
|
21
|
+
siteDir?: string | undefined;
|
|
22
|
+
/** The config file to use instead of looking for one */
|
|
23
|
+
configFile?: string | undefined;
|
|
24
|
+
/** Where warnings go */
|
|
25
|
+
logger?: Logger | undefined;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The folder of the nearest package.json, from a folder up to the file system's root, or undefined if there is none.
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* await packageDir("/projects/my-site/site"); // "/projects/my-site"
|
|
32
|
+
*/
|
|
33
|
+
export declare const packageDir: (dir: string) => Promise<string | undefined>;
|
|
34
|
+
/**
|
|
35
|
+
* Find a site's config file: the first of CONFIG_FILES in a folder, then in the nearest package.json's folder. Warns
|
|
36
|
+
* when a folder has more than one. Throws if there is none.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* await findConfigFile("my-site"); // "/projects/my-site/edahaconfig.yml"
|
|
40
|
+
*/
|
|
41
|
+
export declare const findConfigFile: (dir: string, logger?: Logger) => Promise<string>;
|
|
42
|
+
/**
|
|
43
|
+
* Read a config file's settings, by its extension: YAML (`.yml`, `.yaml`), JSON (`.json`), or JavaScript (`.js`, `.cjs`,
|
|
44
|
+
* `.mjs`) whose default export is the settings object. A changed JavaScript file is imported again. Throws, naming the
|
|
45
|
+
* file, if it can't be read.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* await readConfigFile("my-site/edaha.config.mjs"); // { name: "My site", ... }
|
|
49
|
+
*/
|
|
50
|
+
export declare const readConfigFile: (file: string) => Promise<unknown>;
|
|
51
|
+
/**
|
|
52
|
+
* Find (or use the given) config file, read it and validate its settings. The site folder is the config file's folder.
|
|
53
|
+
* Embed plugin packages named in `plugins` are loaded from it.
|
|
54
|
+
*
|
|
55
|
+
* @example
|
|
56
|
+
* const { siteDir, config } = await loadSiteConfig({ siteDir: "my-site" });
|
|
57
|
+
*/
|
|
58
|
+
export declare const loadSiteConfig: (options?: SiteConfigOptions) => Promise<SiteConfig>;
|
|
@@ -0,0 +1,122 @@
|
|
|
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 { readFile, stat } from "node:fs/promises";
|
|
10
|
+
import { basename, dirname, extname, join, resolve } from "node:path";
|
|
11
|
+
import { pathToFileURL } from "node:url";
|
|
12
|
+
import { parse } from "yaml";
|
|
13
|
+
import { loadPlugins } from "../../embeds/index.js";
|
|
14
|
+
import { parseConfig } from "../config/index.js";
|
|
15
|
+
/** Config file names (without extension), in the order they are looked for */
|
|
16
|
+
export const CONFIG_NAMES = [
|
|
17
|
+
".edahaconfigrc",
|
|
18
|
+
".edahaconfig",
|
|
19
|
+
"edahaconfigrc",
|
|
20
|
+
"edahaconfig",
|
|
21
|
+
"edaha.config",
|
|
22
|
+
];
|
|
23
|
+
/** Config file extensions, in the order they are looked for */
|
|
24
|
+
export const CONFIG_EXTENSIONS = ["yml", "yaml", "json", "js", "cjs", "mjs"];
|
|
25
|
+
/** Every config file name, in the order they are looked for */
|
|
26
|
+
export const CONFIG_FILES = CONFIG_NAMES.flatMap((name) => CONFIG_EXTENSIONS.map((extension) => `${name}.${extension}`));
|
|
27
|
+
/** A file's modification time, or undefined if it isn't a file */
|
|
28
|
+
const fileTime = (path) => stat(path).then((stats) => (stats.isFile() ? stats.mtimeMs : undefined), () => undefined);
|
|
29
|
+
/**
|
|
30
|
+
* The folder of the nearest package.json, from a folder up to the file system's root, or undefined if there is none.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* await packageDir("/projects/my-site/site"); // "/projects/my-site"
|
|
34
|
+
*/
|
|
35
|
+
export const packageDir = async (dir) => {
|
|
36
|
+
for (let folder = resolve(dir);; folder = dirname(folder)) {
|
|
37
|
+
if ((await fileTime(join(folder, "package.json"))) !== undefined)
|
|
38
|
+
return folder;
|
|
39
|
+
if (dirname(folder) === folder)
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Find a site's config file: the first of CONFIG_FILES in a folder, then in the nearest package.json's folder. Warns
|
|
45
|
+
* when a folder has more than one. Throws if there is none.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* await findConfigFile("my-site"); // "/projects/my-site/edahaconfig.yml"
|
|
49
|
+
*/
|
|
50
|
+
export const findConfigFile = async (dir, logger) => {
|
|
51
|
+
const folders = [resolve(dir), await packageDir(dir)].filter((folder, index, all) => folder !== undefined && all.indexOf(folder) === index);
|
|
52
|
+
for (const folder of folders) {
|
|
53
|
+
const times = await Promise.all(CONFIG_FILES.map((name) => fileTime(join(folder, name))));
|
|
54
|
+
const found = CONFIG_FILES.filter((_, i) => times[i] !== undefined);
|
|
55
|
+
if (!found.length)
|
|
56
|
+
continue;
|
|
57
|
+
if (found.length > 1)
|
|
58
|
+
logger?.warn(`${folder} has several config files (${found.join(", ")}); using ${found[0]}`);
|
|
59
|
+
return join(folder, found[0]);
|
|
60
|
+
}
|
|
61
|
+
throw new Error(`No config file found in ${folders.join(" or ")}. Add one named ${CONFIG_NAMES.join(", ")} ending in .${CONFIG_EXTENSIONS.join(", .")}, or name it with --config.`);
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Read a config file's settings, by its extension: YAML (`.yml`, `.yaml`), JSON (`.json`), or JavaScript (`.js`, `.cjs`,
|
|
65
|
+
* `.mjs`) whose default export is the settings object. A changed JavaScript file is imported again. Throws, naming the
|
|
66
|
+
* file, if it can't be read.
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* await readConfigFile("my-site/edaha.config.mjs"); // { name: "My site", ... }
|
|
70
|
+
*/
|
|
71
|
+
export const readConfigFile = async (file) => {
|
|
72
|
+
const path = resolve(file);
|
|
73
|
+
const extension = extname(path).slice(1);
|
|
74
|
+
try {
|
|
75
|
+
const time = await fileTime(path);
|
|
76
|
+
if (time === undefined)
|
|
77
|
+
throw new Error("file not found");
|
|
78
|
+
if (extension === "yml" || extension === "yaml")
|
|
79
|
+
return parse(await readFile(path, "utf8"));
|
|
80
|
+
if (extension === "json")
|
|
81
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
82
|
+
if (CONFIG_EXTENSIONS.includes(extension)) {
|
|
83
|
+
// The modification time makes a changed file a new module, rather than the one imported before
|
|
84
|
+
const url = `${pathToFileURL(path).href}?mtime=${time}`;
|
|
85
|
+
return (await import(__rewriteRelativeImportExtension(url))).default;
|
|
86
|
+
}
|
|
87
|
+
throw new Error(`config files must end in .${CONFIG_EXTENSIONS.join(", .")}`);
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
throw new Error(`${basename(path)}: ${error.message}`, {
|
|
91
|
+
cause: error,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
/**
|
|
96
|
+
* Find (or use the given) config file, read it and validate its settings. The site folder is the config file's folder.
|
|
97
|
+
* Embed plugin packages named in `plugins` are loaded from it.
|
|
98
|
+
*
|
|
99
|
+
* @example
|
|
100
|
+
* const { siteDir, config } = await loadSiteConfig({ siteDir: "my-site" });
|
|
101
|
+
*/
|
|
102
|
+
export const loadSiteConfig = async (options = {}) => {
|
|
103
|
+
const configFile = options.configFile
|
|
104
|
+
? resolve(options.configFile)
|
|
105
|
+
: await findConfigFile(options.siteDir ?? ".", options.logger);
|
|
106
|
+
const siteDir = dirname(configFile);
|
|
107
|
+
const data = await readConfigFile(configFile);
|
|
108
|
+
if (data && typeof data === "object" && "plugins" in data)
|
|
109
|
+
try {
|
|
110
|
+
data.plugins = await loadPlugins(data.plugins, siteDir);
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
throw new Error(`${basename(configFile)}: ${error.message}`, {
|
|
114
|
+
cause: error,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
configFile,
|
|
119
|
+
siteDir,
|
|
120
|
+
config: parseConfig(data, basename(configFile)),
|
|
121
|
+
};
|
|
122
|
+
};
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import type { MetadataSchema } from "../metadata/index.ts";
|
|
2
|
+
/** A value a condition compares with */
|
|
3
|
+
export type ConditionValue = string | number | boolean | null;
|
|
4
|
+
/** Operators comparing a value with one value */
|
|
5
|
+
export type ConditionOperator = "=" | "!=" | ">" | ">=" | "<" | "<=";
|
|
6
|
+
/** Operators checking whether a value is in a list of values */
|
|
7
|
+
export type ConditionListOperator = "in" | "not-in";
|
|
8
|
+
/**
|
|
9
|
+
* One condition: a value's path (dot notation from the top of the values, e.g. "credit.name" or "images.0"), an
|
|
10
|
+
* operator, and what it is compared with.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ["layout", "=", "large"]
|
|
14
|
+
* ["layout", "in", ["slim", "large"]]
|
|
15
|
+
*/
|
|
16
|
+
export type MatchCondition = readonly [string, ConditionOperator, ConditionValue] | readonly [string, ConditionListOperator, readonly ConditionValue[]];
|
|
17
|
+
/** Conditions that must all match (`and`), or any of which must match (`or`) */
|
|
18
|
+
export type MatchConditionsUnion = {
|
|
19
|
+
readonly and: FieldConditions;
|
|
20
|
+
} | {
|
|
21
|
+
readonly or: FieldConditions;
|
|
22
|
+
};
|
|
23
|
+
/** One group of conditions, or a list of conditions and groups that must all match */
|
|
24
|
+
export type MatchConditions = MatchConditionsUnion | readonly FieldConditions[];
|
|
25
|
+
/** A field's `showWhen` or `hideWhen`: one condition, or groups of them */
|
|
26
|
+
export type FieldConditions = MatchCondition | MatchConditions;
|
|
27
|
+
/** The settings `$edahaField` can have besides the field's kind and labels */
|
|
28
|
+
export interface EdahaFieldExtensions {
|
|
29
|
+
/** The value used when there is none (also saved by the editor) */
|
|
30
|
+
defaultValue?: ConditionValue | undefined;
|
|
31
|
+
/** Show the field (and keep its value) only when these match */
|
|
32
|
+
showWhen?: FieldConditions | undefined;
|
|
33
|
+
/** Hide the field (and leave out its value) when these match */
|
|
34
|
+
hideWhen?: FieldConditions | undefined;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Check a field's `showWhen` or `hideWhen` is made of conditions and `and`/`or` groups. Throws an Error naming where
|
|
38
|
+
* the problem is.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* checkConditions({ or: [["layout", "=", "slim"], ["layout", "=", "large"]] }, '"showWhen"');
|
|
42
|
+
*/
|
|
43
|
+
export declare const checkConditions: (value: unknown, what: string) => void;
|
|
44
|
+
/**
|
|
45
|
+
* Check an `$edahaField`'s `defaultValue`, `showWhen` and `hideWhen`. Throws an Error naming where the problem is.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* checkFieldExtensions({ select: true, defaultValue: "large" }, '"metadata.layout.$edahaField"');
|
|
49
|
+
*/
|
|
50
|
+
export declare const checkFieldExtensions: (field: Record<string, unknown>, what: string) => void;
|
|
51
|
+
/**
|
|
52
|
+
* The value at a dot path inside values, e.g. "credit.name" or "images.0".
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* valueAt({ credit: { name: "Ann" } }, "credit.name"); // "Ann"
|
|
56
|
+
*/
|
|
57
|
+
export declare const valueAt: (values: unknown, path: string) => unknown;
|
|
58
|
+
/**
|
|
59
|
+
* Whether values match conditions: one condition, `and` (all match) or `or` (any match) groups, or a list (all match).
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* matchesConditions({ layout: "slim" }, { or: [["layout", "=", "slim"], ["layout", "=", "large"]] }); // true
|
|
63
|
+
* matchesConditions({ layout: "slim" }, ["layout", "in", ["large"]]); // false
|
|
64
|
+
*/
|
|
65
|
+
export declare const matchesConditions: (values: unknown, conditions: FieldConditions) => boolean;
|
|
66
|
+
/**
|
|
67
|
+
* Whether a field shows: its `showWhen` matches (or it has none), and its `hideWhen` doesn't (or it has none).
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* fieldShown({ checkbox: true, showWhen: ["layout", "=", "large"] }, { layout: "slim" }); // false
|
|
71
|
+
*/
|
|
72
|
+
export declare const fieldShown: (field: EdahaFieldExtensions | undefined, values: unknown) => boolean;
|
|
73
|
+
/** Values with their fields' defaults and hidden fields applied, and which fields are hidden */
|
|
74
|
+
export interface ResolvedFields {
|
|
75
|
+
/** The values: a shown field without a value has its default, and a hidden field's value is left out */
|
|
76
|
+
values: Record<string, unknown>;
|
|
77
|
+
/** The hidden fields' paths, in dot notation, e.g. "credit.name" */
|
|
78
|
+
hidden: Set<string>;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Apply fields' `defaultValue`, `showWhen` and `hideWhen` to values: shown fields without a value get their default,
|
|
82
|
+
* and hidden fields' values (and those of fields in a hidden group) are left out. Conditions are checked again until
|
|
83
|
+
* nothing changes, as hiding or filling in one value can show or hide another. The values are in the fields' order,
|
|
84
|
+
* then any values without a field.
|
|
85
|
+
*
|
|
86
|
+
* @example
|
|
87
|
+
* resolveFields(
|
|
88
|
+
* { layout: { type: "string", $edahaField: { select: true, defaultValue: "large" } },
|
|
89
|
+
* tracklist: { type: "boolean", $edahaField: { checkbox: true, hideWhen: ["layout", "=", "slim"] } } },
|
|
90
|
+
* { tracklist: true },
|
|
91
|
+
* ); // { values: { layout: "large", tracklist: true }, hidden: Set {} }
|
|
92
|
+
*/
|
|
93
|
+
export declare const resolveFields: (schemas: Record<string, MetadataSchema>, values: Record<string, unknown>) => ResolvedFields;
|