-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathbootstrap.ts
More file actions
146 lines (128 loc) · 4.72 KB
/
Copy pathbootstrap.ts
File metadata and controls
146 lines (128 loc) · 4.72 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import { spawn } from "node:child_process"
import { createHash } from "node:crypto"
import { constants as fsConstants } from "node:fs"
import { access, mkdir, writeFile } from "node:fs/promises"
import net from "node:net"
import path from "node:path"
import { fileURLToPath, pathToFileURL } from "node:url"
const dirname = path.dirname(fileURLToPath(import.meta.url))
const repoRoot = path.join(dirname, "..")
const stateDir = path.join(repoRoot, ".wanta-dev")
const userDataDir = path.join(repoRoot, "wanta")
const bootstrapJsonPath = path.join(stateDir, "bootstrap.json")
const envShPath = path.join(stateDir, "env.sh")
const defaultPort = 5273
const portSpan = 1000
export interface BootstrapConfig {
devServerPort: number
env: Record<string, string>
generatedAt: string
repoRoot: string
userDataDir: string
}
export function preferredWorktreePort(seed: string): number {
const digest = createHash("sha256").update(seed).digest()
return defaultPort + (digest.readUInt32BE(0) % portSpan)
}
export function shellQuote(value: string): string {
return `'${value.replaceAll("'", "'\\''")}'`
}
export function renderEnvScript(env: Record<string, string>): string {
return [
"# Generated by corepack pnpm run bootstrap.",
"# Source this file or run `corepack pnpm run dev:worktree`.",
...Object.entries(env).map(([key, value]) => `export ${key}=${shellQuote(value)}`),
"",
].join("\n")
}
export function isMainModule(): boolean {
return Boolean(process.argv[1]) && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href
}
if (isMainModule()) {
void main(process.argv.slice(2))
}
async function main(args: string[]): Promise<void> {
const skipInstall = args.includes("--skip-install")
const config = await createBootstrapConfig()
await writeBootstrapFiles(config)
if (!skipInstall) {
await run(commandName("corepack"), ["pnpm", "install", "--frozen-lockfile"], {})
}
await run(commandName("corepack"), ["pnpm", "run", "predev"], config.env)
await assertBootstrapOutputs()
console.log("[wanta] bootstrap complete")
console.log(`[wanta] dev server port: ${config.devServerPort}`)
console.log(`[wanta] user data dir: ${config.userDataDir}`)
console.log("[wanta] run: corepack pnpm run dev:worktree")
}
export async function createBootstrapConfig(): Promise<BootstrapConfig> {
const devServerPort = await findAvailablePort(preferredWorktreePort(repoRoot))
return {
devServerPort,
env: {
WANTA_DEV_SERVER_PORT: String(devServerPort),
WANTA_SKIP_PROTOCOL_REGISTRATION: "1",
WANTA_USER_DATA_DIR: userDataDir,
},
generatedAt: new Date().toISOString(),
repoRoot,
userDataDir,
}
}
export async function findAvailablePort(startPort: number): Promise<number> {
for (let offset = 0; offset < portSpan; offset += 1) {
const port = defaultPort + ((startPort - defaultPort + offset) % portSpan)
if (await canListenOnPort(port)) {
return port
}
}
throw new Error(`no available dev server port found from ${startPort}`)
}
function canListenOnPort(port: number): Promise<boolean> {
return new Promise((resolve) => {
const server = net.createServer()
server.once("error", () => resolve(false))
server.once("listening", () => {
server.close(() => resolve(true))
})
server.listen(port, "127.0.0.1")
})
}
export async function writeBootstrapFiles(config: BootstrapConfig): Promise<void> {
await mkdir(stateDir, { recursive: true })
await writeFile(bootstrapJsonPath, `${JSON.stringify(config, null, 2)}\n`, "utf-8")
await writeFile(envShPath, renderEnvScript(config.env), { encoding: "utf-8", mode: 0o600 })
}
async function run(command: string, args: string[], env: Record<string, string>): Promise<void> {
await new Promise<void>((resolve, reject) => {
const child = spawn(command, args, {
cwd: repoRoot,
env: { ...process.env, ...env },
stdio: "inherit",
})
child.once("error", reject)
child.once("exit", (code, signal) => {
if (code === 0) {
resolve()
return
}
reject(new Error(`${command} ${args.join(" ")} failed with ${signal ?? `exit code ${code}`}`))
})
})
}
function commandName(command: string): string {
return process.platform === "win32" ? `${command}.cmd` : command
}
async function assertBootstrapOutputs(): Promise<void> {
await Promise.all([
assertPath(path.join(repoRoot, ".oo-bin")),
assertPath(path.join(repoRoot, ".electron-dist")),
assertPath(path.join(repoRoot, "resources", "skills")),
assertPath(path.join(repoRoot, "resources", "agent-tool-runtime", "tool.js")),
assertPath(bootstrapJsonPath),
assertPath(envShPath),
])
}
async function assertPath(target: string): Promise<void> {
await access(target, fsConstants.F_OK)
}