Something went wrong. Try again.
Monorepo for the nibling.run platform
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738/** * Turns a `node`, `npm`, or `npx` command line into what `kernel.exec` takes, as * examples/slopbox/launchers.js does. `npm` and `npx` are the guest npm the kernel seeds at * /usr/local/bin and parse their own arguments. `node -e`, `-p`, and `-v` run `source` from a file the * caller writes at `entry` first and deletes after the process exits. */export type Launch = | { readonly entry: string; readonly argv: readonly string[]; readonly source?: string } | { readonly error: string; readonly code: number };
let evals = 0;
/** `nextEval` numbers the files `-e`, `-p`, and `-v` write, so two sessions' never collide. */export function launch([command, ...args]: readonly string[], cwd: string, nextEval: () => number = () => ++evals): Launch | undefined { if (command === "npm" || command === "npx") return { entry: `/usr/local/bin/${command}`, argv: args }; if (command !== "node") return undefined; const [first, ...rest] = args; const run = (source: string, argv: readonly string[]) => { const ext = /^\s*(?:import|export)\b/m.test(source) ? "mjs" : "cjs"; return { entry: `${cwd}/.nib-eval-${nextEval()}.${ext}`, argv, source }; }; if (first === undefined) return { error: "node: the REPL is not available in this terminal; pass a file or -e", code: 1 }; if (first === "-v" || first === "--version") return run("console.log(process.version)", []); if (first === "-e" || first === "--eval") return run(rest[0] ?? "", rest.slice(1)); if (first === "-p" || first === "--print") return run(`console.log((${rest[0] ?? ""}))`, rest.slice(1)); if (first.startsWith("-")) return { error: `node: bad option: ${first}`, code: 9 }; return { entry: resolve(cwd, first), argv: rest };}
function resolve(cwd: string, path: string): string { const parts: string[] = []; for (const part of (path.startsWith("/") ? path : `${cwd}/${path}`).split("/")) { if (part === "..") parts.pop(); else if (part && part !== ".") parts.push(part); } return `/${parts.join("/")}`;}