| 5 | import { constants as osConstants, platform } from "node:os"; |
| 6 | import { resolve } from "node:path"; |
| 7 | import { parseArgs } from "node:util"; |
| 8 | import { DEFAULT_CDN, NAME, isHttpUrl } from "./constants.ts"; |
| 9 | import { clearCache } from "./cache.ts"; |
| 10 | import { styleText } from "./style-text.ts"; |
| 11 |
| 12 | // Resolve the preload path without registering hooks in the wrapper process. |
| 13 | const registerImportMetaUrl = new URL(import.meta.url.endsWith(".ts") ? "./register-hooks.ts" : "./register-hooks.js", import.meta.url).href; |
| 14 |
| 15 | const ownOptions = { |
| 16 | help: { type: "boolean", short: "h" }, |
| 17 | "clear-cache": { type: "boolean" }, |
| 18 | tmp: { type: "boolean" }, |
| 19 | reload: { type: "boolean" }, |
| 20 | lock: { type: "boolean" }, |
| 21 | "lock-file": { type: "string" }, |
| 22 | frozen: { type: "boolean" }, |
| 23 | cdn: { type: "boolean" }, |
| 24 | } as const; |
| 25 |
| 26 | /** |
| 27 | * Consume only the leading options belonging to this CLI. Once Node's arguments |
| 28 | * start, leave the entire remainder untouched: only Node knows their grammar. |
| 29 | */ |
| 30 | function consumeOptions(args: string[]) { |
| 31 | const ownArgs: string[] = []; |
| 32 | const ownNames = new Set<string>(Object.keys(ownOptions).map((name) => `--${name}`)); |
| 33 | ownNames.add("-h"); |
| 34 | let customCdn: string | undefined; |
| 35 | for (let index = 0; index < args.length; index++) { |
| 36 | const argument = args[index]!; |
| 37 | const separator = argument.indexOf("="); |
| 38 | const name = separator === -1 ? argument : argument.slice(0, separator); |
| 39 | const value = separator === -1 ? undefined : argument.slice(separator + 1); |
| 40 | if (ownNames.has(name)) { |
| 41 | if (name === "--cdn" && value !== undefined) { |
| 42 | customCdn = value; |
| 43 | ownArgs.push("--cdn"); |
| 44 | } else { |
| 45 | if (name === "--cdn") customCdn = undefined; |
| 46 | ownArgs.push(argument); |
| 47 | if (name === "--lock-file" && value === undefined) { |
| 48 | const next = args[++index]; |
| 49 | if (!next || next.startsWith("-")) throw new TypeError(`${name} requires a path`); |
| 50 | ownArgs.push(next); |
| 51 | } |
| 52 | } |
| 53 | } else { |
| 54 | return { ownArgs, nodeArgs: args.slice(index), customCdn }; |
| 55 | } |
| 56 | } |
| 57 | return { ownArgs, nodeArgs: [], customCdn }; |
| 58 | } |
| 59 |
| 60 | const { ownArgs, nodeArgs, customCdn } = consumeOptions(process.argv.slice(2)); |
| 61 | const { values } = parseArgs({ args: ownArgs, options: ownOptions, strict: true }); |
| 62 | const cdnBase = values.cdn ? customCdn ?? DEFAULT_CDN : undefined; |
| 63 |
| 64 | // No entry is required: Node can evaluate code, read stdin, or start its REPL. |
| 65 | if (values.help) { |
| 66 | const dim = (s: string) => styleText("dim", s); |
| 67 | const y = (s: string) => styleText("yellow", s); |
| 68 | const c = (s: string) => styleText("cyan", s); |
| 69 | const b = (s: string) => styleText("bold", s); |
| 70 |
| 71 | const defaultCacheRoot = platform() === "darwin" ? "~/Library/Caches/deno" : platform() === "win32" ? "%LOCALAPPDATA%\\deno" : "~/.cache/deno"; |
| 72 | console.log(` |
| 73 | ${b(NAME)} ${dim("—")} run Node.js scripts that import from HTTP(S) URLs |
| 74 |
| 75 | ${b("Usage:")} |
| 76 | ${c(NAME)} ${dim("[options]")} ${dim("[node-flags]")} ${dim("[script-or-url]")} ${dim("[script-args...]")} |
| 77 | ${c(NAME)} ${y("--clear-cache")} |
| 78 |
| 79 | Put ${NAME} options first; the remaining arguments are passed to Node.js as-is. |
| 80 | Node.js handles its own flags, execution modes, and script arguments. |
| 81 |
| 82 | ${b("Examples:")} |
| 83 | ${dim("$")} ${c(NAME)} ./app.mjs |
| 84 | ${dim("$")} ${c(NAME)} https://raw.esm.sh/armor64/dist/cli.js |
| 85 | ${dim("$")} ${c(NAME)} ${y("--reload")} ./app.mjs ${dim("# reload remote modules")} |
| 86 | ${dim("$")} ${c(NAME)} ${y("--lock")} ./app.mjs ${dim("# check/write deno.lock")} |
| 87 | ${dim("$")} ${c(NAME)} ${y("--inspect")} ./app.mjs ${dim("# pass --inspect to node")} |
| 88 | ${dim("$")} ${c(NAME)} https://example.com/cli.js -h ${dim("# -h forwarded to script")} |
| 89 |
| 90 | ${b("Options:")} |
| 91 | ${y("--reload")} Bypass cache, re-fetch all remote modules |
| 92 | ${y("--lock")} Check/write a lock file ${dim("(default: ./deno.lock)")} |
| 93 | ${y("--lock-file")} ${dim("<path>")} Lock file path ${dim("(implies --lock)")} |
| 94 | ${y("--frozen")} Error if lock file is out of date ${dim("(use with --lock)")} |
| 95 | ${y("--tmp")} Write fetched modules to a tmp dir with readable paths |
| 96 | ${dim("(modules see themselves as local files under /tmp/node-url-import/)")} |
| 97 | ${y("--cdn")}${dim("[=<url>]")} Resolve missing bare packages via a CDN ${dim(`(e.g. ws → ${DEFAULT_CDN}ws)`)} |
| 98 | ${dim(`(default: ${DEFAULT_CDN}; node_modules first)`)} |
| 99 |
| 100 | ${b("Environment:")} |
| 101 | ${y("DENO_DIR")} Deno cache root ${dim(`(default: ${defaultCacheRoot})`)} |
| 102 | ${y("DENO_AUTH_TOKENS")} HTTP auth: token@host or user:password@host ${dim("(; separated)")} |
| 103 | ${y("URL_IMPORT_TMP=1")} Same as --tmp |
| 104 | ${y("URL_IMPORT_RELOAD=1")} Same as --reload |
| 105 | ${y("URL_IMPORT_LOCK")}${dim("=path")} Same as --lock <file> |
| 106 | ${y("URL_IMPORT_FROZEN=1")} Same as --frozen |
| 107 | ${y("URL_IMPORT_CDN")}${dim("=<url>")} Same as --cdn=<url> |
| 108 | `); |
| 109 | process.exit(0); |
| 110 | } |
| 111 |
| 112 | if (values["clear-cache"]) { |
| 113 | clearCache(); |
| 114 | console.log(`${styleText("green", "✓")} Cache cleared.`); |
| 115 | process.exit(0); |
| 116 | } |
| 117 |
| 118 | // Pass our flags to the child process via environment variables. |
| 119 | const env: Record<string, string | undefined> = { ...process.env }; |
| 120 |
| 121 | // Let Node choose the entry, then recover its exact URL during registration. |
| 122 | // Keep candidate positions and separators, not a second parser for Node flags. |
| 123 | delete env.URL_IMPORT_MAIN; |
| 124 | delete env.URL_IMPORT_MAIN_CANDIDATES; |
| 125 | const mainCandidates: Record<string, string> = {}; |
| 126 | for (let index = 0; index < nodeArgs.length; index++) { |
| 127 | const argument = nodeArgs[index]!; |
| 128 | if (isHttpUrl(argument) || argument === "--") mainCandidates[index] = argument; |
| 129 | } |
| 130 | if (Object.keys(mainCandidates).length) env.URL_IMPORT_MAIN_CANDIDATES = JSON.stringify(mainCandidates); |
| 131 | for (const [option, variable] of [["tmp", "URL_IMPORT_TMP"], ["reload", "URL_IMPORT_RELOAD"], ["frozen", "URL_IMPORT_FROZEN"]] as const) { |
| 132 | if (values[option]) env[variable] = "1"; |
| 133 | } |
| 134 | if (values["lock-file"]) { |
| 135 | env.URL_IMPORT_LOCK = resolve(values["lock-file"]); |
| 136 | } else if (values.lock) { |
| 137 | env.URL_IMPORT_LOCK = resolve("deno.lock"); |
| 138 | } |
| 139 | if (values.frozen && !env.URL_IMPORT_LOCK) env.URL_IMPORT_LOCK = resolve("deno.lock"); |
| 140 | if (cdnBase) { |
| 141 | const parsed = new URL(cdnBase); |
| 142 | if (!isHttpUrl(parsed.href) || parsed.search || parsed.hash) throw new TypeError("The CDN base must be an HTTP(S) URL without query or fragment"); |
| 143 | env.URL_IMPORT_CDN = parsed.href.endsWith("/") ? parsed.href : parsed.href + "/"; |
| 144 | } |
| 145 | if (!process.stdout.isTTY && !process.stderr.isTTY) env.FORCE_COLOR = "0"; |
| 146 |
| 147 | const child = spawn(process.execPath, ["--import", registerImportMetaUrl, ...nodeArgs], { |
| 148 | stdio: "inherit", |
| 149 | env, |
| 150 | }); |
| 151 |
| 152 | // Keep the wrapper responsive to process-manager and terminal signals while |
| 153 | // Node runs. A target may handle a signal and exit normally; wait for its result. |
| 154 | const signals = process.platform === "win32" ? ["SIGINT", "SIGTERM", "SIGBREAK"] as const : ["SIGHUP", "SIGINT", "SIGQUIT", "SIGTERM"] as const; |
| 155 | const signalHandlers = new Map<NodeJS.Signals, () => void>(); |
| 156 | for (const signal of signals) { |
| 157 | const forward = (): void => { child.kill(signal); }; |
| 158 | signalHandlers.set(signal, forward); |
| 159 | process.on(signal, forward); |
| 160 | } |
| 161 |
| 162 | child.once("error", (error) => { |
| 163 | console.error(error.message); |
| 164 | process.exitCode = 1; |
| 165 | }); |
| 166 | child.once("close", (code, signal) => { |
| 167 | for (const [name, handler] of signalHandlers) process.removeListener(name, handler); |
| 168 | if (signal && process.platform !== "win32") { |
| 169 | // Re-raise after removing our handlers so callers observe the same signal. |
| 170 | process.kill(process.pid, signal); |
| 171 | } else { |
| 172 | process.exitCode = signal ? 128 + osConstants.signals[signal] : code ?? 1; |
| 173 | } |
| 174 | }); |
| 175 |