-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathe4.ts
109 lines (91 loc) · 2.78 KB
/
e4.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import {
call,
type Operation,
race,
resource,
run,
sleep,
} from "npm:[email protected]";
import {
close,
createIndex,
PagefindIndex,
PagefindServiceConfig,
SiteDirectory,
WriteOptions,
} from "npm:[email protected]";
import { staticalize } from "jsr:@frontside/[email protected]";
import * as fs from "jsr:@std/fs@1";
function exists(path: string | URL, options?: fs.ExistsOptions) {
return call(() => fs.exists(path, options));
}
type GenerateOptions = {
host: URL;
publicDir: string;
pagefindDir: string;
} & PagefindServiceConfig;
const log = (first: unknown, ...args: unknown[]) =>
console.log(`💪: ${first}`, ...args);
export function generate(
{ host, publicDir, pagefindDir, ...indexOptions }: GenerateOptions,
) {
return async function () {
return await run(function* () {
const built = new URL(publicDir, import.meta.url);
if (yield* exists(built, { isDirectory: true })) {
log(`Reusing existing staticalized ${built.pathname} directory`);
} else {
log(`Staticalizing: ${host} to ${built.pathname}`);
yield* race([
staticalize({
host,
base: host,
dir: built.pathname,
}),
sleep(60000),
]);
}
log("Adding index");
const index = yield* createPagefindIndex(indexOptions);
log(`Adding directory: ${built.pathname}`);
const added = yield* index.addDirectory({ path: built.pathname });
log(`Addedd ${added} pages from ${built.pathname}`);
log(`Writing files ${pagefindDir}`);
return yield* index.writeFiles({ outputPath: pagefindDir });
});
};
}
export class EPagefindIndex {
constructor(private readonly index: PagefindIndex) {}
*addDirectory(path: SiteDirectory): Operation<number> {
const response = yield* call(() => this.index.addDirectory(path));
if (response.errors.length > 0) {
console.error(
`Encountered errors while adding ${path.path}: ${response.errors.join()}`,
);
}
return response.page_count;
}
*writeFiles(options?: WriteOptions): Operation<string> {
const response = yield* call(() => this.index.writeFiles(options));
if (response.errors.length > 0) {
console.error(
`Encountered errors while writing to ${options?.outputPath}: ${response.errors.join()}`,
);
}
return response.outputPath;
}
}
export function createPagefindIndex(config?: PagefindServiceConfig) {
return resource<EPagefindIndex>(function* (provide) {
const { errors, index } = yield* call(() => createIndex(config));
if (!index) {
throw new Error(`Failed to create an index: ${errors.join()}`);
}
try {
yield* provide(new EPagefindIndex(index));
} finally {
yield* call(() => close());
}
});
}