Elffuss BraidHub

kikocis/continue public

1cfd9a0cd983 · 9.8 KiBRawPermalink
1const esbuild = require("esbuild");
2const fs = require("fs");
3const path = require("path");
4const ncp = require("ncp").ncp;
5const { rimrafSync } = require("rimraf");
6const {
7 validateFilesPresent,
8 execCmdSync,
9 autodetectPlatformAndArch,
10} = require("../scripts/util");
11const { downloadRipgrep } = require("./utils/ripgrep");
12const { ALL_TARGETS, TARGET_TO_LANCEDB } = require("./utils/targets");
13
14const bin = path.join(__dirname, "bin");
15const out = path.join(__dirname, "out");
16const build = path.join(__dirname, "build");
17
18function cleanSlate() {
19 // Clean slate
20 rimrafSync(bin);
21 rimrafSync(out);
22 rimrafSync(build);
23 rimrafSync(path.join(__dirname, "tmp"));
24 fs.mkdirSync(bin);
25 fs.mkdirSync(out);
26 fs.mkdirSync(build);
27}
28
29const esbuildOutputFile = "out/index.js";
30let targets = [...ALL_TARGETS];
31
32const [currentPlatform, currentArch] = autodetectPlatformAndArch();
33
34const assetBackups = [
35 "node_modules/win-ca/lib/crypt32-ia32.node.bak",
36 "node_modules/win-ca/lib/crypt32-x64.node.bak",
37];
38
39let esbuildOnly = false;
40for (let i = 2; i < process.argv.length; i++) {
41 if (process.argv[i] === "--esbuild-only") {
42 esbuildOnly = true;
43 }
44 if (process.argv[i - 1] === "--target") {
45 targets = [process.argv[i]];
46 }
47}
48
49// Bundles the extension into one file
50async function buildWithEsbuild() {
51 console.log("[info] Building with esbuild...");
52 await esbuild.build({
53 entryPoints: ["src/index.ts"],
54 bundle: true,
55 outfile: esbuildOutputFile,
56 external: [
57 "esbuild",
58 "./xhr-sync-worker.js",
59 "llamaTokenizerWorkerPool.mjs",
60 "tiktokenWorkerPool.mjs",
61 "vscode",
62 "./index.node",
63 ],
64 format: "cjs",
65 platform: "node",
66 sourcemap: true,
67 minify: !esbuildOnly,
68 treeShaking: true,
69 loader: {
70 // eslint-disable-next-line @typescript-eslint/naming-convention
71 ".node": "file",
72 },
73
74 // To allow import.meta.path for transformers.js
75 // https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483
76 inject: ["./importMetaUrl.js"],
77 define: { "import.meta.url": "importMetaUrl" },
78 });
79}
80
81async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
82 console.log(`Copying ${packageName} to ${toCopy}`);
83 // This is a way to install only one package without npm trying to install all the dependencies
84 // Create a temporary directory for installing the package
85 const adjustedName = packageName.replace(/@/g, "").replace("/", "-");
86 const tempDir = path.join(
87 __dirname,
88 "tmp",
89 `continue-node_modules-${adjustedName}`,
90 );
91 const currentDir = process.cwd();
92
93 // // Remove the dir we will be copying to
94 // rimrafSync(`node_modules/${toCopy}`);
95
96 // // Ensure the temporary directory exists
97 fs.mkdirSync(tempDir, { recursive: true });
98
99 try {
100 // Move to the temporary directory
101 process.chdir(tempDir);
102
103 // Initialize a new package.json and install the package
104 execCmdSync(`npm init -y && npm i -f ${packageName} --no-save`);
105
106 console.log(
107 `Contents of: ${packageName}`,
108 fs.readdirSync(path.join(tempDir, "node_modules", toCopy)),
109 );
110
111 // Without this it seems the file isn't completely written to disk
112 await new Promise((resolve) => setTimeout(resolve, 2000));
113
114 // Copy the installed package back to the current directory
115 await new Promise((resolve, reject) => {
116 ncp(
117 path.join(tempDir, "node_modules", toCopy),
118 path.join(currentDir, "node_modules", toCopy),
119 { dereference: true },
120 (error) => {
121 if (error) {
122 console.error(
123 `[error] Error copying ${packageName} package`,
124 error,
125 );
126 reject(error);
127 } else {
128 resolve();
129 }
130 },
131 );
132 });
133 } finally {
134 // Clean up the temporary directory
135 // rimrafSync(tempDir);
136
137 // Return to the original directory
138 process.chdir(currentDir);
139 }
140}
141
142/**
143 * Downloads and installs ripgrep binaries for the specified target
144 *
145 * @param {string} target - Target platform-arch (e.g., 'darwin-x64')
146 * @param {string} targetDir - Directory to install ripgrep to
147 * @returns {Promise<void>}
148 */
149async function downloadRipgrepForTarget(target, targetDir) {
150 console.log(`[info] Downloading ripgrep for ${target}...`);
151 try {
152 await downloadRipgrep(target, targetDir);
153 console.log(`[info] Successfully installed ripgrep for ${target}`);
154 } catch (error) {
155 console.error(`[error] Failed to download ripgrep for ${target}:`, error);
156 throw error;
157 }
158}
159
160(async () => {
161 if (esbuildOnly) {
162 await buildWithEsbuild();
163 return;
164 }
165
166 cleanSlate();
167
168 // Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
169 // This is only needed for our `pkg` command at build time
170 fs.writeFileSync(
171 "out/package.json",
172 JSON.stringify(
173 {
174 name: "binary",
175 version: "1.0.0",
176 author: "Continue Dev, Inc",
177 license: "Apache-2.0",
178 },
179 undefined,
180 2,
181 ),
182 );
183
184 console.log("[info] Downloading prebuilt lancedb...");
185 for (const target of targets) {
186 if (TARGET_TO_LANCEDB[target]) {
187 console.log(`[info] Downloading for ${target}...`);
188 await installNodeModuleInTempDirAndCopyToCurrent(
189 TARGET_TO_LANCEDB[target],
190 "@lancedb",
191 );
192 }
193 }
194
195 // tree-sitter-wasm
196 const treeSitterWasmsDir = path.join(out, "tree-sitter-wasms");
197 fs.mkdirSync(treeSitterWasmsDir);
198 await new Promise((resolve, reject) => {
199 ncp(
200 path.join(
201 __dirname,
202 "..",
203 "core",
204 "node_modules",
205 "tree-sitter-wasms",
206 "out",
207 ),
208 treeSitterWasmsDir,
209 { dereference: true },
210 (error) => {
211 if (error) {
212 console.warn("[error] Error copying tree-sitter-wasm files", error);
213 reject(error);
214 } else {
215 resolve();
216 }
217 },
218 );
219 });
220
221 const filesToCopy = [
222 "../core/vendor/tree-sitter.wasm",
223 "../core/llm/llamaTokenizerWorkerPool.mjs",
224 "../core/llm/llamaTokenizer.mjs",
225 "../core/llm/tiktokenWorkerPool.mjs",
226 ];
227 for (const f of filesToCopy) {
228 fs.copyFileSync(
229 path.join(__dirname, f),
230 path.join(__dirname, "out", path.basename(f)),
231 );
232 console.log(`[info] Copied ${path.basename(f)}`);
233 }
234
235 console.log("[info] Cleaning up artifacts from previous builds...");
236
237 // delete asset backups generated by previous pkg invocations, if present
238 for (const assetPath of assetBackups) {
239 fs.rmSync(assetPath, { force: true });
240 }
241
242 await buildWithEsbuild();
243
244 // Copy over any worker files
245 fs.cpSync(
246 "../core/node_modules/jsdom/lib/jsdom/living/xhr/xhr-sync-worker.js",
247 "out/xhr-sync-worker.js",
248 );
249 fs.cpSync("../core/llm/tiktokenWorkerPool.mjs", "out/tiktokenWorkerPool.mjs");
250 fs.cpSync(
251 "../core/llm/llamaTokenizerWorkerPool.mjs",
252 "out/llamaTokenizerWorkerPool.mjs",
253 );
254
255 console.log("[info] Building binaries with pkg...");
256 for (const target of targets) {
257 const targetDir = `bin/${target}`;
258 fs.mkdirSync(targetDir, { recursive: true });
259 console.log(`[info] Building ${target}...`);
260 execCmdSync(
261 `npx pkg --no-bytecode --public-packages "*" --public --compress GZip pkgJson/${target} --out-path ${targetDir}`,
262 );
263
264 // Download and unzip prebuilt sqlite3 binary for the target
265 console.log("[info] Downloading node-sqlite3");
266
267 const downloadUrl =
268 // node-sqlite3 doesn't have a pre-built binary for win32-arm64
269 target === "win32-arm64"
270 ? "https://continue-server-binaries.s3.us-west-1.amazonaws.com/win32-arm64/node_sqlite3.tar.gz"
271 : `https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-${
272 target
273 }.tar.gz`;
274
275 execCmdSync(`curl -L -o ${targetDir}/build.tar.gz ${downloadUrl}`);
276 execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`);
277
278 // Copy to build directory for testing
279 try {
280 const [platform, arch] = target.split("-");
281 if (platform === currentPlatform && arch === currentArch) {
282 fs.copyFileSync(
283 `${targetDir}/build/Release/node_sqlite3.node`,
284 `build/node_sqlite3.node`,
285 );
286 }
287 } catch (error) {
288 console.log("[warn] Could not copy node_sqlite to build");
289 console.log(error);
290 }
291
292 fs.unlinkSync(`${targetDir}/build.tar.gz`);
293
294 // copy @lancedb to bin folders
295 console.log("[info] Copying @lancedb files to bin");
296 fs.copyFileSync(
297 `node_modules/${TARGET_TO_LANCEDB[target]}/index.node`,
298 `${targetDir}/index.node`,
299 );
300
301 // Download and install ripgrep for the target
302 await downloadRipgrepForTarget(target, targetDir);
303
304 // Informs the `continue-binary` of where to look for node_sqlite3.node
305 // https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
306 fs.writeFileSync(`${targetDir}/package.json`, "");
307 }
308
309 // Cleanup - this is needed when running locally
310 fs.rmSync("out/package.json");
311
312 const pathsToVerify = [];
313 for (const target of targets) {
314 const exe = target.startsWith("win") ? ".exe" : "";
315 const targetDir = `bin/${target}`;
316 pathsToVerify.push(
317 `${targetDir}/continue-binary${exe}`,
318 `${targetDir}/index.node`, // @lancedb
319 `${targetDir}/build/Release/node_sqlite3.node`,
320 `${targetDir}/rg${exe}`, // ripgrep binary
321 );
322 }
323
324 // Note that this doesn't verify they actually made it into the binary, just that they were in the expected folder before it was built
325 pathsToVerify.push("out/index.js");
326 pathsToVerify.push("out/llamaTokenizerWorkerPool.mjs");
327 pathsToVerify.push("out/tiktokenWorkerPool.mjs");
328 pathsToVerify.push("out/xhr-sync-worker.js");
329 pathsToVerify.push("out/tree-sitter.wasm");
330
331 validateFilesPresent(pathsToVerify);
332
333 console.log("[info] Done!");
334})();