-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbuild.ts
77 lines (69 loc) · 2.05 KB
/
build.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
/**
* This module builds lessons into the app.
*
* @module
*/
import type { FileSystemTree } from '@webcontainer/api';
import {
copyFile,
mkdir,
readdir,
readFile,
writeFile,
} from 'node:fs/promises';
/** Computes a path relative to this file. */
const relative = (path: string) => new URL(path, import.meta.url);
const dest = '../app/src/lessons/';
/** Main build function, builds all directories in `lessons`. */
const build = async () => {
const entries = await readdir(relative('.'), { withFileTypes: true });
const dirs = entries.filter((entry) => entry.isDirectory());
await copyFile(relative('authors.json'), `${dest}authors.json`);
return Promise.all(
dirs.map((dir) => buildLesson(dir.name, relative(`${dir.name}/`))),
);
};
/** Build a single lesson. */
const buildLesson = async (name: string, dir: URL) => {
console.log(`Building lesson ${name}...`);
try {
const files = await buildLessonFiles(dir);
await mkdir(relative(`${dest}${name}`), { recursive: true });
await copyFile(new URL('README.md', dir), `${dest}${name}/README.md`);
await writeFile(`${dest}${name}/files.json`, JSON.stringify(files));
} catch (error) {
console.error(`Error building lesson ${name}: ${error}`);
}
};
/**
* Serialize all files in a format compatible with
* [WebContainers](https://webcontainers.io).
*/
const buildLessonFiles = async (dir: URL): Promise<FileSystemTree> => {
const entries = await readdir(dir, { withFileTypes: true });
return Object.fromEntries(
await Promise.all(
entries.map(async (entry) => {
if (entry.isDirectory()) {
return [
entry.name,
{
directory: await buildLessonFiles(new URL(`${entry.name}/`, dir)),
},
];
}
return [
entry.name,
{
file: {
contents: await readFile(new URL(entry.name, dir), 'utf8'),
},
},
];
}),
),
);
};
console.time('Built lessons in');
await build();
console.timeEnd('Built lessons in');