Skip to content
Source
Sign inSign up

nativeRunHook.js

65 lines2.2 KB

1import * as NodeFSP from "node:fs/promises";
2import * as NodeOS from "node:os";
3import * as NodePath from "node:path";
4import * as NodeURL from "node:url";
5​
6async function readJson(file) {
7 try {
8 return JSON.parse(await NodeFSP.readFile(file, "utf8"));
9 } catch (error) {
10 if (error.code !== "ENOENT") throw error;
11 }
13​
14// Optional repository integration; never changes the task runner's exit status.
15export async function startRunHook(command, cwd = process.cwd(), resolveWorkspaceRoot) {
16 if (command !== "run") return;
17 try {
18 const configured = await readJson(
19 NodePath.join(NodeOS.homedir(), ".config/vite-plus/run-hook.json"),
20 );
21 let root = cwd;
22 while (true) {
23 let hook;
24 if (configured?.rootMarker && configured?.module) {
25 try {
26 await NodeFSP.access(NodePath.join(root, configured.rootMarker));
27 hook = configured.module;
28 } catch (error) {
29 if (error.code !== "ENOENT") throw error;
30 }
31 }
32 if (typeof hook === "string") {
33 // Use Vite's own workspace resolver so nested standalone projects stay independent.
34 if (resolveWorkspaceRoot) {
35 const workspace = await resolveWorkspaceRoot();
36 if (!workspace || (await NodeFSP.realpath(workspace)) !== (await NodeFSP.realpath(root)))
37 break;
38 }
39 const integration = await import(NodeURL.pathToFileURL(NodePath.resolve(root, hook)).href);
40 const finish = await integration.default({ root });
41 return Object.assign(
42 async () => {
43 try {
44 await finish?.();
45 } catch {
46 console.warn("[Vite+] Run hook failed to finish.");
47 }
48 },
49 { remoteCache: finish?.remoteCache },
50 );
51 }
52 const parent = NodePath.dirname(root);
53 if (parent === root) break;
54 root = parent;
55 }
56 // Vite forwards our CLI mode to tasks, including agents working in other projects.
57 if (
58 process.env.VP_T3_TASK_CACHE_MODE &&
59 process.env.VP_REMOTE_CACHE === process.env.VP_T3_TASK_CACHE_MODE
60 )
61 delete process.env.VP_REMOTE_CACHE;
62 } catch {
63 console.warn("[Vite+] Run hook failed to start.");
64 }