| 1 | #!/usr/bin/env node |
| 2 | |
| 3 | const fs = require("fs"); |
| 4 | const fsp = require("fs/promises"); |
| 5 | const http = require("http"); |
| 6 | const os = require("os"); |
| 7 | const path = require("path"); |
| 8 | const { spawn } = require("child_process"); |
| 9 | |
| 10 | const repoRoot = path.resolve(__dirname, "..", ".."); |
| 11 | const packageDir = path.join(repoRoot, "npm", "codewhale"); |
| 12 | const prepareAssetsScript = path.join( |
| 13 | repoRoot, |
| 14 | "scripts", |
| 15 | "release", |
| 16 | "prepare-local-release-assets.js", |
| 17 | ); |
| 18 | const CLEANUP_MAX_RETRIES = 8; |
| 19 | const CLEANUP_RETRY_DELAY_MS = 250; |
| 20 | |
| 21 | function shellQuote(value) { |
| 22 | return /\s/.test(value) ? JSON.stringify(value) : value; |
| 23 | } |
| 24 | |
| 25 | function usesWindowsCommandShim(command) { |
| 26 | return process.platform === "win32" && (command === "npm" || command === "npx"); |
| 27 | } |
| 28 | |
| 29 | function runCommand(command, args, options = {}) { |
| 30 | const cwd = options.cwd || repoRoot; |
| 31 | console.log(`$ ${[command, ...args].map(shellQuote).join(" ")}`); |
| 32 | const child = spawn(command, args, { |
| 33 | cwd, |
| 34 | env: { |
| 35 | ...process.env, |
| 36 | ...(options.env || {}), |
| 37 | }, |
| 38 | encoding: "utf8", |
| 39 | shell: usesWindowsCommandShim(command), |
| 40 | stdio: options.capture ? ["ignore", "pipe", "pipe"] : "inherit", |
| 41 | windowsHide: true, |
| 42 | }); |
| 43 | |
| 44 | if (!options.capture) { |
| 45 | return new Promise((resolve, reject) => { |
| 46 | child.once("error", reject); |
| 47 | child.once("close", (status) => { |
| 48 | if (status === 0) { |
| 49 | resolve({ stdout: "", stderr: "" }); |
| 50 | } else { |
| 51 | reject(new Error(`${command} exited with status ${status}`)); |
| 52 | } |
| 53 | }); |
| 54 | }); |
| 55 | } |
| 56 | |
| 57 | let stdout = ""; |
| 58 | let stderr = ""; |
| 59 | child.stdout.setEncoding("utf8"); |
| 60 | child.stderr.setEncoding("utf8"); |
| 61 | child.stdout.on("data", (chunk) => { |
| 62 | stdout += chunk; |
| 63 | }); |
| 64 | child.stderr.on("data", (chunk) => { |
| 65 | stderr += chunk; |
| 66 | }); |
| 67 | return new Promise((resolve, reject) => { |
| 68 | child.once("error", reject); |
| 69 | child.once("close", (status) => { |
| 70 | if (status === 0) { |
| 71 | resolve({ stdout, stderr }); |
| 72 | return; |
| 73 | } |
| 74 | process.stdout.write(stdout); |
| 75 | process.stderr.write(stderr); |
| 76 | reject(new Error(`${command} exited with status ${status}`)); |
| 77 | }); |
| 78 | }); |
| 79 | } |
| 80 | |
| 81 | function serveDirectory(root) { |
| 82 | const server = http.createServer(async (request, response) => { |
| 83 | try { |
| 84 | const requestUrl = new URL(request.url || "/", "http://127.0.0.1"); |
| 85 | const decodedPath = decodeURIComponent(requestUrl.pathname); |
| 86 | const filePath = path.resolve(root, `.${decodedPath}`); |
| 87 | const relative = path.relative(root, filePath); |
| 88 | if (relative.startsWith("..") || path.isAbsolute(relative)) { |
| 89 | response.writeHead(403); |
| 90 | response.end("forbidden"); |
| 91 | return; |
| 92 | } |
| 93 | |
| 94 | const fileStat = await fsp.stat(filePath); |
| 95 | if (!fileStat.isFile()) { |
| 96 | response.writeHead(404); |
| 97 | response.end("not found"); |
| 98 | return; |
| 99 | } |
| 100 | |
| 101 | response.writeHead(200, { |
| 102 | "Content-Length": fileStat.size, |
| 103 | "Content-Type": "application/octet-stream", |
| 104 | }); |
| 105 | fs.createReadStream(filePath).pipe(response); |
| 106 | } catch (error) { |
| 107 | response.writeHead(error && error.code === "ENOENT" ? 404 : 500); |
| 108 | response.end(error && error.message ? error.message : "not found"); |
| 109 | } |
| 110 | }); |
| 111 | |
| 112 | return new Promise((resolve, reject) => { |
| 113 | server.once("error", reject); |
| 114 | server.listen(0, "127.0.0.1", () => { |
| 115 | const address = server.address(); |
| 116 | resolve({ |
| 117 | baseUrl: `http://127.0.0.1:${address.port}/`, |
| 118 | server, |
| 119 | }); |
| 120 | }); |
| 121 | }); |
| 122 | } |
| 123 | |
| 124 | function parsePackJson(stdout) { |
| 125 | const trimmed = stdout.trim(); |
| 126 | if (!trimmed) { |
| 127 | throw new Error("npm pack did not return package metadata"); |
| 128 | } |
| 129 | const parsed = JSON.parse(trimmed); |
| 130 | const first = Array.isArray(parsed) ? parsed[0] : parsed; |
| 131 | if (!first || !first.filename) { |
| 132 | throw new Error(`npm pack metadata did not include a filename: ${trimmed}`); |
| 133 | } |
| 134 | return first.filename; |
| 135 | } |
| 136 | |
| 137 | async function removeSmokeWorkspace(tempRoot, remove = fsp.rm) { |
| 138 | await remove(tempRoot, { |
| 139 | force: true, |
| 140 | recursive: true, |
| 141 | // Windows can report ENOTEMPTY briefly while completed binary downloads |
| 142 | // are still being released by the filesystem. fs.rm retries ENOTEMPTY |
| 143 | // (and the other documented transient removal errors) with linear |
| 144 | // backoff; the finite cap still surfaces a persistent cleanup failure. |
| 145 | maxRetries: CLEANUP_MAX_RETRIES, |
| 146 | retryDelay: CLEANUP_RETRY_DELAY_MS, |
| 147 | }); |
| 148 | } |
| 149 | |
| 150 | async function main() { |
| 151 | const tempRoot = await fsp.mkdtemp(path.join(os.tmpdir(), "codewhale-npm-smoke-")); |
| 152 | const suppliedAssetsDir = String( |
| 153 | process.env.CODEWHALE_SMOKE_ASSETS_DIR || "", |
| 154 | ).trim(); |
| 155 | const releaseAssetsDir = suppliedAssetsDir |
| 156 | ? path.resolve(suppliedAssetsDir) |
| 157 | : path.join(tempRoot, "release-assets"); |
| 158 | const packDir = path.join(tempRoot, "pack"); |
| 159 | const installDir = path.join(tempRoot, "install"); |
| 160 | let keepTemp = |
| 161 | process.env.CODEWHALE_KEEP_SMOKE_DIR === "1" || |
| 162 | process.env.DEEPSEEK_TUI_KEEP_SMOKE_DIR === "1"; |
| 163 | let server; |
| 164 | |
| 165 | try { |
| 166 | await fsp.mkdir(packDir, { recursive: true }); |
| 167 | await fsp.mkdir(installDir, { recursive: true }); |
| 168 | |
| 169 | if (suppliedAssetsDir) { |
| 170 | const assetDirectoryStat = await fsp.stat(releaseAssetsDir); |
| 171 | if (!assetDirectoryStat.isDirectory()) { |
| 172 | throw new Error(`CODEWHALE_SMOKE_ASSETS_DIR is not a directory: ${releaseAssetsDir}`); |
| 173 | } |
| 174 | console.log(`Using preassembled release assets from ${releaseAssetsDir}`); |
| 175 | } else { |
| 176 | const prepareArgs = [prepareAssetsScript, releaseAssetsDir]; |
| 177 | const cargoTargetDir = String(process.env.CARGO_TARGET_DIR || "").trim(); |
| 178 | if (cargoTargetDir) { |
| 179 | prepareArgs.push( |
| 180 | path.join(path.resolve(repoRoot, cargoTargetDir), "release"), |
| 181 | ); |
| 182 | } |
| 183 | await runCommand(process.execPath, prepareArgs); |
| 184 | } |
| 185 | const served = await serveDirectory(releaseAssetsDir); |
| 186 | server = served.server; |
| 187 | |
| 188 | const env = { |
| 189 | CODEWHALE_FORCE_DOWNLOAD: "1", |
| 190 | CODEWHALE_RELEASE_BASE_URL: served.baseUrl, |
| 191 | }; |
| 192 | const pack = await runCommand( |
| 193 | "npm", |
| 194 | ["pack", "--json", "--pack-destination", packDir], |
| 195 | { |
| 196 | capture: true, |
| 197 | cwd: packageDir, |
| 198 | env, |
| 199 | }, |
| 200 | ); |
| 201 | const tarball = path.join(packDir, parsePackJson(pack.stdout)); |
| 202 | |
| 203 | await runCommand("npm", ["init", "-y"], { cwd: installDir }); |
| 204 | await runCommand("npm", ["install", tarball], { cwd: installDir, env }); |
| 205 | await runCommand("npx", ["--no-install", "codewhale", "doctor", "--help"], { |
| 206 | cwd: installDir, |
| 207 | env, |
| 208 | }); |
| 209 | await runCommand("npx", ["--no-install", "codew", "--version"], { |
| 210 | cwd: installDir, |
| 211 | env, |
| 212 | }); |
| 213 | |
| 214 | console.log(`npm wrapper smoke passed with local assets from ${served.baseUrl}`); |
| 215 | } catch (error) { |
| 216 | keepTemp = true; |
| 217 | console.error(`npm wrapper smoke failed: ${error.message}`); |
| 218 | console.error(`Smoke workspace retained at ${tempRoot}`); |
| 219 | process.exitCode = 1; |
| 220 | } finally { |
| 221 | if (server) { |
| 222 | await new Promise((resolve) => server.close(resolve)); |
| 223 | } |
| 224 | if (!keepTemp) { |
| 225 | await removeSmokeWorkspace(tempRoot); |
| 226 | } |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | if (require.main === module) { |
| 231 | main(); |
| 232 | } |
| 233 | |
| 234 | module.exports = { |
| 235 | CLEANUP_MAX_RETRIES, |
| 236 | CLEANUP_RETRY_DELAY_MS, |
| 237 | removeSmokeWorkspace, |
| 238 | }; |
| 239 |