/
processors.ts
56 lines (50 loc) 路 1.45 KB
/
processors.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { concurrent } from "./utils.ts";
import { Exception } from "./errors.ts";
import type { Page } from "../core.ts";
/**
* Class to store and run the (pre)processors
*/
export default class Processors {
/** Processors and the assigned extensions */
processors = new Map<Processor, string[] | "*">();
/** Assign a processor to some extensions */
set(extensions: string[] | "*", processor: Processor) {
if (Array.isArray(extensions)) {
extensions.forEach((extension) => {
if (extension.charAt(0) !== ".") {
throw new Exception(
"Invalid extension. It must start with '.'",
{ extension },
);
}
});
}
this.processors.set(processor, extensions);
}
/** Apply the processors to the provided pages */
async run(pages: Page[]): Promise<void> {
for (const [process, exts] of this.processors) {
await concurrent(
pages,
async (page) => {
try {
if (
(exts === "*" || (page.src.ext && exts.includes(page.src.ext)) ||
exts.includes(page.dest.ext))
) {
await process(page);
}
} catch (cause) {
throw new Exception("Error processing page", {
cause,
page,
processor: process.name,
});
}
},
);
}
}
}
/** A (pre)processor */
export type Processor = (page: Page) => void;