Debian Codegraph @

cli/tools-cli/src/scripts/compile.ts

raw symbols SCIP
1 import { build } from "esbuild";
2 import { NodeModulesPolyfillPlugin } from "@esbuild-plugins/node-modules-polyfill";
3 import chokidar from "chokidar";
4 import { Command } from "commander";
5 import glob from "fast-glob";
6 import fs from "node:fs/promises";
7 import path from "node:path";
8 import SpecLogger, { Level } from "./log";
9 import { setSetting } from "./settings";
10
11 // Folder names
12 const SOURCE_FOLDER_NAME = "src";
13 const DEFAULT_DESTINATION_FOLDER_NAME = "build";
14
15 function invalidateCache() {
16 setSetting("autocomplete.developerModeNPMInvalidateCache", true);
17 }
18
19 /**
20 * Generate index files for spec build
21 */
22 async function generateIndex(outdir: string, files: string[]) {
23 const parsedFiles = files.map(path.parse);
24
25 const diffVersionedSpecNames = parsedFiles
26 .filter(({ base }) => base === "index.ts")
27 .map(({ dir }) => dir.replace(/^src\//, ""));
28 diffVersionedSpecNames.sort();
29
30 const specNames = parsedFiles
31 .filter(({ base, ext }) => base !== "index.ts" && ext === ".ts")
32 .map((p) => `${p.dir}/${p.name}`.replace(/^src\//, ""))
33 .concat(diffVersionedSpecNames);
34 specNames.sort();
35
36 await fs.mkdir(outdir, { recursive: true });
37
38 Promise.all([
39 // index.js
40 await fs.writeFile(
41 path.join(outdir, "index.js"),
42 `var e=${JSON.stringify(specNames)},diffVersionedCompletions=${JSON.stringify(
43 diffVersionedSpecNames
44 )};export{e as default,diffVersionedCompletions};`
45 ),
46 // index.json
47 fs.writeFile(
48 path.join(outdir, "index.json"),
49 JSON.stringify({
50 completions: specNames,
51 diffVersionedCompletions: diffVersionedSpecNames,
52 })
53 ),
54 // index.d.ts
55 fs.writeFile(
56 path.join(outdir, "index.d.ts"),
57 `declare const completions: string[]
58 declare const diffVersionedCompletions: string[]
59 export { completions as default, diffVersionedCompletions }
60 `
61 ),
62 ]);
63 }
64
65 /**
66 * Transpiles all passed files and prints the progress
67 * @param specs Array of filepaths
68 */
69 async function processFiles(files: string[], isDev?: boolean, outdir?: string) {
70 const fileName = files.length === 1 ? files[0] : `${files.length} specs`;
71
72 await Promise.all([
73 build({
74 entryPoints: files,
75 outdir: outdir ?? DEFAULT_DESTINATION_FOLDER_NAME,
76 bundle: true,
77 outbase: "src",
78 format: "esm",
79 minify: true,
80 plugins: [NodeModulesPolyfillPlugin()],
81 ...(isDev && { sourcemap: "inline" }),
82 }).catch((e) => SpecLogger.log(`Error building ${fileName}: ${e.message}`, Level.ERROR)),
83 generateIndex(outdir ?? DEFAULT_DESTINATION_FOLDER_NAME, files),
84 ]);
85
86 SpecLogger.log(`Built ${fileName}`);
87 invalidateCache();
88 }
89
90 export async function runCompiler({ watch, outdir }: { watch: boolean; outdir?: string }) {
91 const SOURCE_FILE_GLOB = `${SOURCE_FOLDER_NAME}/**/*.ts`;
92 const files = await glob(SOURCE_FILE_GLOB);
93
94 await processFiles(files, undefined, outdir);
95
96 if (watch) {
97 const watcher = chokidar.watch(SOURCE_FILE_GLOB, { ignoreInitial: true });
98
99 // Process the changed file
100 watcher.on("change", (file) => processFiles([file], true, outdir));
101 watcher.on("add", (file) => processFiles([file], true, outdir));
102 }
103 }
104
105 const program = new Command("compile")
106 .description("compile specs in the current directory")
107 .option("-w, --watch", "Watch files and re-compile on change")
108 .option("-o, --outdir <dir>", "Output directory")
109 .action(runCompiler);
110
111 export default program;