| 4 | import { createServer } from "node:http"; |
| 5 | import { spawn } from "node:child_process"; |
| 6 | import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; |
| 7 | import { tmpdir } from "node:os"; |
| 8 | import { join } from "node:path"; |
| 9 | import { fileURLToPath, pathToFileURL } from "node:url"; |
| 10 |
| 11 | const requests: string[] = []; |
| 12 | const authRequests: { url: string; authorization: string | undefined }[] = []; |
| 13 | const targetAuthRequests: { url: string; authorization: string | undefined }[] = []; |
| 14 | let authTargetUrl: string; |
| 15 | const authTargetServer = createServer((request, response) => { |
| 16 | targetAuthRequests.push({ url: request.url!, authorization: request.headers.authorization }); |
| 17 | if (request.headers.authorization !== "Bearer target-token") { |
| 18 | response.writeHead(401).end(); |
| 19 | return; |
| 20 | } |
| 21 | response.setHeader("Content-Type", "application/javascript"); |
| 22 | response.end("export default 43;"); |
| 23 | }); |
| 24 | const server = createServer((request, response) => { |
| 25 | requests.push(request.url!); |
| 26 | if (request.url?.startsWith("/auth/") || request.url === "/redirect-private.mjs") { |
| 27 | authRequests.push({ url: request.url, authorization: request.headers.authorization }); |
| 28 | } |
| 29 | if (request.url === "/redirect-private.mjs") { |
| 30 | if (request.headers.authorization !== "Bearer source-token") { |
| 31 | response.writeHead(401).end(); |
| 32 | return; |
| 33 | } |
| 34 | response.writeHead(302, { Location: `${authTargetUrl}/module.mjs` }).end(); |
| 35 | return; |
| 36 | } |
| 37 | const redirects: Record<string, string> = { |
| 38 | "/entry.mjs": "/v1/main.mjs", |
| 39 | "/v1/child.mjs": "/v2/child.mjs", |
| 40 | "/cjs/redirect-main.cjs": "/cjs/v1/main.cjs", |
| 41 | "/cjs/v1/redirect-child.cjs": "/cjs/v2/child.cjs", |
| 42 | }; |
| 43 | const redirect = redirects[request.url!]; |
| 44 | if (redirect) { |
| 45 | response.writeHead(302, { Location: redirect }).end(); |
| 46 | return; |
| 47 | } |
| 48 | response.setHeader("Content-Type", request.url?.endsWith(".cts") ? "text/typescript" : |
| 49 | request.url === "/data.json" ? "application/json" : "application/javascript"); |
| 50 | const sources: Record<string, string> = { |
| 51 | "/v1/main.mjs": 'import { value, location } from "./child.mjs"; console.log(JSON.stringify({ value, location, main: import.meta.main, url: import.meta.url }));', |
| 52 | "/v2/child.mjs": 'export { default as value } from "./dep.mjs"; export const location = import.meta.url;', |
| 53 | "/v2/dep.mjs": 'export default "correct";', |
| 54 | "/v1/dep.mjs": 'export default "wrong";', |
| 55 | "/reload.mjs": 'export default 42;', |
| 56 | "/data.json": '{"answer":42}', |
| 57 | "/json-code.mjs": 'globalThis.executedAsCode = true; export default 42;', |
| 58 | "/worker-main.mjs": 'import { Worker, isMainThread, parentPort } from "node:worker_threads"; if (isMainThread) { const worker = new Worker(new URL(process.argv[2])); worker.on("message", message => console.log(message)); } else { parentPort.postMessage("wrong-remote-worker"); }', |
| 59 | "/identity-worker.mjs?value=%23%3F": 'import { Worker } from "node:worker_threads"; const worker = new Worker(new URL(process.argv[2])); const workerEnv = await new Promise(resolve => worker.once("message", resolve)); console.log(JSON.stringify({ url: import.meta.url, main: import.meta.main, argv: process.argv.slice(2), mainEnv: process.env.URL_IMPORT_MAIN, candidatesEnv: process.env.URL_IMPORT_MAIN_CANDIDATES, workerEnv }));', |
| 60 | "/identity.mjs?value=%23%3F": 'console.log(JSON.stringify({ url: import.meta.url, main: import.meta.main, argv: process.argv.slice(2) }));', |
| 61 | "/cdn/node-url-import-uninstalled@2/sub": 'export default 73;', |
| 62 | "/cdn/cdn-only-fixture": 'export default "cdn-fixture";', |
| 63 | "/bare-parent.mjs": 'import ts from "typescript"; console.log(JSON.stringify({ version: ts.version }));', |
| 64 | "/typed.cts": 'const value: number = 17; module.exports = value;', |
| 65 | "/npm-parent.mjs": 'import ts from "npm:typescript@6"; console.log(JSON.stringify({ version: ts.version }));', |
| 66 | "/cjs/main.cjs": 'module.exports = require("./child.cjs");', |
| 67 | "/cjs/child.cjs": 'module.exports = 42;', |
| 68 | "/cjs/import-parent.mjs": 'import value from "./esm-import-main.cjs"; console.log(JSON.stringify(value));', |
| 69 | "/cjs/esm-import-main.cjs": 'const child = require("./esm-import-child.cjs"); const childPath = child.filename; module.exports = { filename: __filename, cacheIdentity: require.cache[__filename]?.exports === module.exports, childPath, childFilename: child.filename, childCacheIdentity: require.cache[childPath]?.exports === child, leafPath: child.leafPath, leafFilename: child.leafFilename, leafCacheIdentity: child.leafCacheIdentity, value: child.value };', |
| 70 | "/cjs/esm-import-child.cjs": 'const leaf = require("./esm-import-leaf.cts"); const leafPath = leaf.filename; module.exports = { value: leaf.value, filename: __filename, cacheIdentity: require.cache[__filename]?.exports === module.exports, leafPath, leafFilename: leaf.filename, leafCacheIdentity: require.cache[leafPath]?.exports === leaf };', |
| 71 | "/cjs/esm-import-leaf.cts": 'const value: number = 42; module.exports = { value, filename: __filename, cacheIdentity: require.cache[__filename]?.exports === module.exports };', |
| 72 | "/cjs/cts-import-parent.mjs": 'import value from "./cts-import-main.cts"; console.log(JSON.stringify(value));', |
| 73 | "/cjs/cts-import-main.cts": 'const base: number = 10; const child = require("./cts-import-child.cjs"); const typedChild = require("./cts-import-child.cts"); module.exports = { value: base + child.value + typedChild.value, mainIsMain: require.main === module, cacheIdentity: require.cache[__filename]?.exports === module.exports, childCacheIdentity: require.cache[child.filename]?.exports === child, typedChildCacheIdentity: require.cache[typedChild.filename]?.exports === typedChild };', |
| 74 | "/cjs/cts-import-child.cjs": 'module.exports = { value: 20, filename: __filename };', |
| 75 | "/cjs/cts-import-child.cts": 'const value: number = 12; module.exports = { value, filename: __filename };', |
| 76 | "/cjs/cts-cli-main.cts": 'const base: number = 10; const child = require("./cts-import-child.cjs"); const typedChild = require("./cts-import-child.cts"); console.log(JSON.stringify({ value: base + child.value + typedChild.value, isMain: require.main === module, cacheIdentity: require.cache[__filename]?.exports === module.exports, childCacheIdentity: require.cache[child.filename]?.exports === child, typedChildCacheIdentity: require.cache[typedChild.filename]?.exports === typedChild }));', |
| 77 | "/cjs/cli-main.cjs": 'const child = require("./child.cjs"); console.log(child);', |
| 78 | "/cjs/identity-main.cjs?variant=1": 'globalThis.cliMainExecutions = (globalThis.cliMainExecutions ?? 0) + 1; exports.ready = true; const self = require("./identity-main.cjs?variant=1#fragment"); const child = require("./identity-child.cjs"); console.log(JSON.stringify({ isMain: require.main === module, moduleLoaded: module.loaded, selfExports: self === module.exports, childSawExports: child.mainExports.ready, executions: globalThis.cliMainExecutions, argv: process.argv.slice(2) }));', |
| 79 | "/cjs/identity-child.cjs": 'const main = require("./identity-main.cjs?variant=1#fragment"); module.exports = { mainExports: main };', |
| 80 | "/cjs/v1/main.cjs": 'const child = require("./redirect-child.cjs"); console.log(child);', |
| 81 | "/cjs/v2/child.cjs": 'module.exports = require("./leaf.cjs");', |
| 82 | "/cjs/v2/leaf.cjs": 'module.exports = "redirected-child";', |
| 83 | "/auth/esm.mjs": 'import value from "./dependency.mjs"; console.log(value);', |
| 84 | "/auth/dependency.mjs": "export default 42;", |
| 85 | "/auth/cjs.cjs": 'module.exports = require("./dependency.cjs");', |
| 86 | "/auth/dependency.cjs": "module.exports = 42;", |
| 87 | }; |
| 88 | const expectedAuthorization: Record<string, string[]> = { |
| 89 | "/auth/esm.mjs": ["Bearer sync-token", "Bearer async-token"], |
| 90 | "/auth/dependency.mjs": ["Bearer sync-token", "Bearer async-token"], |
| 91 | "/auth/cjs.cjs": ["Basic dXNlcjpwYXNzd29yZA=="], |
| 92 | "/auth/dependency.cjs": ["Basic dXNlcjpwYXNzd29yZA=="], |
| 93 | }; |
| 94 | if (request.url && request.url in expectedAuthorization && |
| 95 | !expectedAuthorization[request.url]!.includes(request.headers.authorization ?? "")) { |
| 96 | response.writeHead(401).end(); |
| 97 | return; |
| 98 | } |
| 99 | response.end(sources[request.url!] ?? 'throw new Error("Unexpected module");'); |
| 100 | }); |
| 101 | let baseUrl: string; |
| 102 | let workspace: string; |
| 103 |
| 104 | before(async () => { |
| 105 | await new Promise<void>((resolve) => authTargetServer.listen(0, "127.0.0.1", resolve)); |
| 106 | const targetAddress = authTargetServer.address(); |
| 107 | assert.ok(targetAddress && typeof targetAddress !== "string"); |
| 108 | authTargetUrl = `http://127.0.0.1:${targetAddress.port}`; |
| 109 | await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve)); |
| 110 | const address = server.address(); |
| 111 | assert.ok(address && typeof address !== "string"); |
| 112 | baseUrl = `http://127.0.0.1:${address.port}`; |
| 113 | }); |
| 114 | after(async () => { |
| 115 | server.closeAllConnections(); |
| 116 | authTargetServer.closeAllConnections(); |
| 117 | await Promise.all([ |
| 118 | new Promise<void>((resolve) => server.close(() => resolve())), |
| 119 | new Promise<void>((resolve) => authTargetServer.close(() => resolve())), |
| 120 | ]); |
| 121 | }); |
| 122 | beforeEach(() => { |
| 123 | workspace = mkdtempSync(join(tmpdir(), "node-url-import-resolve-test-")); |
| 124 | requests.length = 0; |
| 125 | authRequests.length = 0; |
| 126 | targetAuthRequests.length = 0; |
| 127 | }); |
| 128 | afterEach(() => { rmSync(workspace, { recursive: true, force: true }); }); |
| 129 |
| 130 | function run(args: string[], extraEnv: Record<string, string> = {}) { |
| 131 | return new Promise<{ status: number | null; stdout: string; stderr: string }>((resolve, reject) => { |
| 132 | const child = spawn(process.execPath, args, { |
| 133 | env: { ...process.env, FORCE_COLOR: "0", DENO_DIR: join(workspace, "deno"), TMPDIR: workspace, ...extraEnv }, |
| 134 | stdio: ["ignore", "pipe", "pipe"], timeout: 15_000, |
| 135 | }); |
| 136 | let stdout = ""; |
| 137 | let stderr = ""; |
| 138 | child.stdout.on("data", (chunk) => { stdout += chunk; }); |
| 139 | child.stderr.on("data", (chunk) => { stderr += chunk; }); |
| 140 | child.on("error", reject); |
| 141 | child.on("close", (status) => resolve({ status, stdout, stderr })); |
| 142 | }); |
| 143 | } |
| 144 |
| 145 | const registerUrl = new URL("./register-hooks.ts", import.meta.url).href; |
| 146 | const cliPath = fileURLToPath(new URL("./cli.ts", import.meta.url)); |
| 147 |
| 148 | describe("remote resolution", () => { |
| 149 | it("sends DENO_AUTH_TOKENS credentials for CLI ESM imports and CommonJS requires", async () => { |
| 150 | const host = new URL(baseUrl).host; |
| 151 | const result = await run([cliPath, `${baseUrl}/auth/esm.mjs`], { |
| 152 | DENO_AUTH_TOKENS: `sync-token@${host}`, |
| 153 | }); |
| 154 | assert.equal(result.status, 0, result.stderr); |
| 155 | assert.equal(result.stdout.trim(), "42"); |
| 156 | assert.deepEqual(authRequests, [ |
| 157 | { url: "/auth/esm.mjs", authorization: "Bearer sync-token" }, |
| 158 | { url: "/auth/dependency.mjs", authorization: "Bearer sync-token" }, |
| 159 | ]); |
| 160 |
| 161 | authRequests.length = 0; |
| 162 | const cjs = await run([cliPath, "--eval", `console.log(require(${JSON.stringify(`${baseUrl}/auth/cjs.cjs`)}));`], { |
| 163 | DENO_AUTH_TOKENS: `user:password@${host}`, |
| 164 | }); |
| 165 | assert.equal(cjs.status, 0, cjs.stderr); |
| 166 | assert.equal(cjs.stdout.trim(), "42"); |
| 167 | assert.deepEqual(authRequests, [ |
| 168 | { url: "/auth/cjs.cjs", authorization: "Basic dXNlcjpwYXNzd29yZA==" }, |
| 169 | { url: "/auth/dependency.cjs", authorization: "Basic dXNlcjpwYXNzd29yZA==" }, |
| 170 | ]); |
| 171 | }); |
| 172 |
| 173 | it("keeps the preload DENO_AUTH_TOKENS value for the sync fetch worker", async () => { |
| 174 | const host = new URL(baseUrl).host; |
| 175 | const result = await run(["--import", registerUrl, "--input-type=module", "--eval", ` |
| 176 | process.env.DENO_AUTH_TOKENS = ${JSON.stringify(`late-token@${host}`)}; |
| 177 | await import(${JSON.stringify(`${baseUrl}/auth/esm.mjs`)}); |
| 178 | `], { DENO_AUTH_TOKENS: `sync-token@${host}` }); |
| 179 | assert.equal(result.status, 0, result.stderr); |
| 180 | assert.equal(result.stdout.trim(), "42"); |
| 181 | assert.deepEqual(authRequests, [ |
| 182 | { url: "/auth/esm.mjs", authorization: "Bearer sync-token" }, |
| 183 | { url: "/auth/dependency.mjs", authorization: "Bearer sync-token" }, |
| 184 | ]); |
| 185 | }); |
| 186 |
| 187 | it("sends DENO_AUTH_TOKENS credentials through the asynchronous loader", async () => { |
| 188 | const host = new URL(baseUrl).host; |
| 189 | const loaderUrl = new URL("./loader.ts", import.meta.url).href; |
| 190 | const result = await run(["--input-type=module", "--eval", ` |
| 191 | import { register } from "node:module"; |
| 192 | register(${JSON.stringify(loaderUrl)}, import.meta.url); |
| 193 | await import(${JSON.stringify(`${baseUrl}/auth/esm.mjs`)}); |
| 194 | `], { DENO_AUTH_TOKENS: `async-token@${host}` }); |
| 195 | assert.equal(result.status, 0, result.stderr); |
| 196 | assert.equal(result.stdout.trim(), "42"); |
| 197 | assert.deepEqual(authRequests, [ |
| 198 | { url: "/auth/esm.mjs", authorization: "Bearer async-token" }, |
| 199 | { url: "/auth/dependency.mjs", authorization: "Bearer async-token" }, |
| 200 | ]); |
| 201 | }); |
| 202 |
| 203 | it("selects credentials again after a cross-port redirect and does not leak them", async () => { |
| 204 | const sourceHost = new URL(baseUrl).host; |
| 205 | const targetHost = new URL(authTargetUrl).host; |
| 206 | const loaderUrl = new URL("./loader.ts", import.meta.url).href; |
| 207 | for (const mode of ["sync", "async"] as const) { |
| 208 | authRequests.length = 0; |
| 209 | targetAuthRequests.length = 0; |
| 210 | const registration = mode === "sync" |
| 211 | ? `import ${JSON.stringify(registerUrl)};` |
| 212 | : `import { register } from "node:module"; register(${JSON.stringify(loaderUrl)}, import.meta.url);`; |
| 213 | const loadRedirect = ` |
| 214 | ${registration} |
| 215 | const module = await import(${JSON.stringify(`${baseUrl}/redirect-private.mjs`)}); |
| 216 | console.log(module.default); |
| 217 | `; |
| 218 |
| 219 | const withoutTargetCredential = await run(["--input-type=module", "--eval", loadRedirect], { |
| 220 | DENO_AUTH_TOKENS: `source-token@${sourceHost}`, |
| 221 | URL_IMPORT_RELOAD: "1", |
| 222 | }); |
| 223 | assert.equal(withoutTargetCredential.status, 1, `${mode} hooks must reject the private target without its token`); |
| 224 | assert.deepEqual(authRequests, [ |
| 225 | { url: "/redirect-private.mjs", authorization: "Bearer source-token" }, |
| 226 | ]); |
| 227 | assert.deepEqual(targetAuthRequests, [{ url: "/module.mjs", authorization: undefined }]); |
| 228 | assert.match(withoutTargetCredential.stderr, /401/); |
| 229 |
| 230 | authRequests.length = 0; |
| 231 | targetAuthRequests.length = 0; |
| 232 | const withTargetCredential = await run(["--input-type=module", "--eval", loadRedirect], { |
| 233 | DENO_AUTH_TOKENS: `source-token@${sourceHost};target-token@${targetHost}`, |
| 234 | URL_IMPORT_RELOAD: "1", |
| 235 | }); |
| 236 | assert.equal(withTargetCredential.status, 0, withTargetCredential.stderr); |
| 237 | assert.equal(withTargetCredential.stdout.trim(), "43"); |
| 238 | assert.doesNotMatch(withTargetCredential.stderr, /source-token|target-token/); |
| 239 | assert.deepEqual(authRequests, [ |
| 240 | { url: "/redirect-private.mjs", authorization: "Bearer source-token" }, |
| 241 | ]); |
| 242 | assert.deepEqual(targetAuthRequests, [{ url: "/module.mjs", authorization: "Bearer target-token" }]); |
| 243 | } |
| 244 | }); |
| 245 |
| 246 | it("resolves relative dependencies against every final redirect URL", async () => { |
| 247 | const result = await run(["--import", registerUrl, "--eval", `import(${JSON.stringify(`${baseUrl}/entry.mjs`)});`]); |
| 248 | assert.equal(result.status, 0, result.stderr); |
| 249 | const output = JSON.parse(result.stdout); |
| 250 | assert.equal(output.value, "correct"); |
| 251 | assert.equal(output.location, `${baseUrl}/v2/child.mjs`); |
| 252 | assert.equal(output.url, `${baseUrl}/v1/main.mjs`); |
| 253 | }); |
| 254 |
| 255 | it("uses the redirected HTTP URL as the true CLI entry point", async () => { |
| 256 | const result = await run([cliPath, `${baseUrl}/entry.mjs`]); |
| 257 | assert.equal(result.status, 0, result.stderr); |
| 258 | const output = JSON.parse(result.stdout); |
| 259 | assert.equal(output.value, "correct"); |
| 260 | assert.equal(output.url, `${baseUrl}/v1/main.mjs`); |
| 261 | assert.equal(output.main, true); |
| 262 | }); |
| 263 |
| 264 | it("consumes a direct URL_IMPORT_MAIN and does not pass it to a Worker", async () => { |
| 265 | const target = `${baseUrl}/identity-worker.mjs?value=%23%3F#identity`; |
| 266 | const workerPath = join(workspace, "env-worker.mjs"); |
| 267 | writeFileSync(workerPath, 'import { parentPort } from "node:worker_threads"; parentPort.postMessage(JSON.stringify({ main: process.env.URL_IMPORT_MAIN, candidates: process.env.URL_IMPORT_MAIN_CANDIDATES }));'); |
| 268 | const result = await run(["--import", registerUrl, target, pathToFileURL(workerPath).href], { |
| 269 | URL_IMPORT_MAIN: target, |
| 270 | URL_IMPORT_MAIN_CANDIDATES: "{}", |
| 271 | }); |
| 272 | assert.equal(result.status, 0, result.stderr); |
| 273 | const output = JSON.parse(result.stdout); |
| 274 | assert.equal(output.url, target); |
| 275 | assert.equal(output.main, true); |
| 276 | assert.deepEqual(output.argv, [pathToFileURL(workerPath).href]); |
| 277 | assert.equal(output.mainEnv, undefined); |
| 278 | assert.equal(output.candidatesEnv, undefined); |
| 279 | assert.deepEqual(JSON.parse(output.workerEnv), {}); |
| 280 | assert.deepEqual(requests, ["/identity-worker.mjs?value=%23%3F"]); |
| 281 | }); |
| 282 |
| 283 | it("lets Node select a remote entry after its own valued flags", async () => { |
| 284 | const result = await run([cliPath, "--reload", "--title", "cli-title", `${baseUrl}/entry.mjs#identity`]); |
| 285 | assert.equal(result.status, 0, result.stderr); |
| 286 | const output = JSON.parse(result.stdout); |
| 287 | assert.equal(output.value, "correct"); |
| 288 | assert.equal(output.url, `${baseUrl}/v1/main.mjs`); |
| 289 | assert.equal(output.main, true); |
| 290 | }); |
| 291 |
| 292 | it("preserves a remote entry's exact query, fragment, and arguments after --", async () => { |
| 293 | const target = `${baseUrl}/identity.mjs?value=%23%3F#identity`; |
| 294 | const scriptArgs = ["--reload", "--clear-cache", `${baseUrl}/not-main.mjs`]; |
| 295 | const result = await run([cliPath, "--", target, ...scriptArgs]); |
| 296 | assert.equal(result.status, 0, result.stderr); |
| 297 | const output = JSON.parse(result.stdout); |
| 298 | assert.equal(output.url, target); |
| 299 | assert.equal(output.main, true); |
| 300 | assert.deepEqual(output.argv, scriptArgs); |
| 301 | assert.deepEqual(requests, ["/identity.mjs?value=%23%3F"]); |
| 302 | }); |
| 303 |
| 304 | it("does not mistake an HTTP-valued Node option for the remote entry", async () => { |
| 305 | const result = await run([cliPath, "--title", `${baseUrl}/not-main.mjs`, `${baseUrl}/entry.mjs`]); |
| 306 | assert.equal(result.status, 0, result.stderr); |
| 307 | const output = JSON.parse(result.stdout); |
| 308 | assert.equal(output.url, `${baseUrl}/v1/main.mjs`); |
| 309 | assert.equal(output.main, true); |
| 310 | assert.ok(!requests.includes("/not-main.mjs")); |
| 311 | }); |
| 312 |
| 313 | it("leaves HTTP arguments in eval mode untouched without selecting a remote main", async () => { |
| 314 | const target = `${baseUrl}/entry.mjs`; |
| 315 | const result = await run([cliPath, "--eval", 'console.log(JSON.stringify({ argv: process.argv.slice(1), main: process.env.URL_IMPORT_MAIN }));', "--", target]); |
| 316 | assert.equal(result.status, 0, result.stderr); |
| 317 | const output = JSON.parse(result.stdout); |
| 318 | assert.deepEqual(output.argv, [target]); |
| 319 | assert.equal(output.main, undefined); |
| 320 | assert.deepEqual(requests, []); |
| 321 | }); |
| 322 |
| 323 | it("downloads each module only once between resolve and load with reload enabled", async () => { |
| 324 | const result = await run(["--import", registerUrl, "--eval", `import(${JSON.stringify(`${baseUrl}/reload.mjs`)}).then(m => console.log(m.default));`], { URL_IMPORT_RELOAD: "1" }); |
| 325 | assert.equal(result.status, 0, result.stderr); |
| 326 | assert.equal(Number(result.stdout), 42); |
| 327 | assert.deepEqual(requests, ["/reload.mjs"]); |
| 328 | }); |
| 329 |
| 330 | it("resolves installed npm packages from a remote parent", async () => { |
| 331 | const result = await run([cliPath, `${baseUrl}/npm-parent.mjs`]); |
| 332 | assert.equal(result.status, 0, result.stderr); |
| 333 | assert.equal(typeof JSON.parse(result.stdout).version, "string"); |
| 334 | assert.deepEqual(requests, ["/npm-parent.mjs"]); |
| 335 | }); |
| 336 |
| 337 | it("falls back to the selected CDN for npm packages not installed locally", async () => { |
| 338 | const result = await run(["--import", registerUrl, "--eval", |
| 339 | 'import("npm:node-url-import-uninstalled@2/sub").then(m => console.log(m.default));'], |
| 340 | { URL_IMPORT_CDN: `${baseUrl}/cdn/` }); |
| 341 | assert.equal(result.status, 0, result.stderr); |
| 342 | assert.equal(Number(result.stdout), 73); |
| 343 | assert.deepEqual(requests, ["/cdn/node-url-import-uninstalled@2/sub"]); |
| 344 | }); |
| 345 |
| 346 | it("uses one canonical module identity for cached equivalent URLs", async () => { |
| 347 | for (const tmp of ["0", "1"]) { |
| 348 | const result = await run(["--import", registerUrl, "--input-type=module", "--eval", ` |
| 349 | import assert from "node:assert/strict"; |
| 350 | const { writeCache } = await import(${JSON.stringify(new URL("./cache.ts", import.meta.url).href)}); |
| 351 | const url = "https://canonical.test/mod.mjs?q=1#identity"; |
| 352 | writeCache([url], "export default {};", "application/javascript"); |
| 353 | const first = await import(url); |
| 354 | for (const variant of ["https://CANONICAL.test:443/mod.mjs?q=1#identity", "HTTPS://canonical.test/mod.mjs?q=1#identity", "https://canonical.test/dir/../mod.mjs?q=1#identity"]) { |
| 355 | assert.equal(await import(variant), first); |
| 356 | } |
| 357 | `], { URL_IMPORT_TMP: tmp }); |
| 358 | assert.equal(result.status, 0, result.stderr); |
| 359 | } |
| 360 | }); |
| 361 |
| 362 | it("does not redirect local Worker entries to the remote CLI main", async () => { |
| 363 | const workerPath = join(workspace, "worker.mjs"); |
| 364 | writeFileSync(workerPath, 'import { parentPort } from "node:worker_threads"; parentPort.postMessage("local-worker");'); |
| 365 | for (const tmp of ["0", "1"]) { |
| 366 | const result = await run([cliPath, `${baseUrl}/worker-main.mjs`, pathToFileURL(workerPath).href], { URL_IMPORT_TMP: tmp }); |
| 367 | assert.equal(result.status, 0, result.stderr); |
| 368 | assert.equal(result.stdout.trim(), "local-worker"); |
| 369 | } |
| 370 | }); |
| 371 |
| 372 | it("keeps package #imports local with a CDN enabled", async () => { |
| 373 | const packagePath = join(workspace, "package"); |
| 374 | mkdirSync(packagePath); |
| 375 | writeFileSync(join(packagePath, "package.json"), JSON.stringify({ type: "module", imports: { "#answer": "./answer.mjs" } })); |
| 376 | writeFileSync(join(packagePath, "answer.mjs"), "export default 42;"); |
| 377 | const entryPath = join(packagePath, "main.mjs"); |
| 378 | writeFileSync(entryPath, 'import answer from "#answer"; console.log(answer);'); |
| 379 | const result = await run([cliPath, `--cdn=${baseUrl}/cdn/`, entryPath]); |
| 380 | assert.equal(result.status, 0, result.stderr); |
| 381 | assert.equal(result.stdout.trim(), "42"); |
| 382 | assert.deepEqual(requests, []); |
| 383 | }); |
| 384 |
| 385 | it("resolves bare packages from node_modules before the CDN", async () => { |
| 386 | const packagePath = join(workspace, "package"); |
| 387 | mkdirSync(join(packagePath, "node_modules", "installed-fixture"), { recursive: true }); |
| 388 | writeFileSync(join(packagePath, "node_modules", "installed-fixture", "package.json"), |
| 389 | JSON.stringify({ name: "installed-fixture", type: "module", exports: { ".": "./main.mjs" } })); |
| 390 | writeFileSync(join(packagePath, "node_modules", "installed-fixture", "main.mjs"), 'export default "local";'); |
| 391 | const entryPath = join(packagePath, "main.mjs"); |
| 392 | writeFileSync(entryPath, 'import local from "installed-fixture"; import remote from "cdn-only-fixture"; console.log(JSON.stringify({ local, remote }));'); |
| 393 | const result = await run([cliPath, `--cdn=${baseUrl}/cdn/`, entryPath]); |
| 394 | assert.equal(result.status, 0, result.stderr); |
| 395 | assert.deepEqual(JSON.parse(result.stdout), { local: "local", remote: "cdn-fixture" }); |
| 396 | assert.deepEqual(requests, ["/cdn/cdn-only-fixture"]); |
| 397 | }); |
| 398 |
| 399 | it("lets remote modules use locally installed bare packages with a CDN enabled", async () => { |
| 400 | const result = await run(["--import", registerUrl, "--eval", `import(${JSON.stringify(`${baseUrl}/bare-parent.mjs`)});`], |
| 401 | { URL_IMPORT_CDN: `${baseUrl}/cdn/` }); |
| 402 | assert.equal(result.status, 0, result.stderr); |
| 403 | assert.equal(typeof JSON.parse(result.stdout).version, "string"); |
| 404 | assert.deepEqual(requests, ["/bare-parent.mjs"]); |
| 405 | }); |
| 406 |
| 407 | it("enforces JSON import attributes without executing JavaScript as data", async () => { |
| 408 | for (const tmp of ["0", "1"]) { |
| 409 | const result = await run(["--import", registerUrl, "--input-type=module", "--eval", ` |
| 410 | import assert from "node:assert/strict"; |
| 411 | const url = ${JSON.stringify(`${baseUrl}/data.json`)}; |
| 412 | await assert.rejects(import(url)); |
| 413 | await assert.rejects(import(url, { with: { type: "javascript" } })); |
| 414 | await assert.rejects(import(url, { with: { extra: "unsupported", type: "json" } })); |
| 415 | assert.equal((await import(url, { with: { type: "json" } })).default.answer, 42); |
| 416 | await assert.rejects(import(${JSON.stringify(`${baseUrl}/json-code.mjs`)}, { with: { type: "json" } })); |
| 417 | assert.equal(globalThis.executedAsCode, undefined); |
| 418 | `], { URL_IMPORT_TMP: tmp }); |
| 419 | assert.equal(result.status, 0, result.stderr); |
| 420 | } |
| 421 | }); |
| 422 |
| 423 | it("distinguishes native require(JSON) from user-supplied require conditions", async () => { |
| 424 | const url = `${baseUrl}/data.json`; |
| 425 | for (const tmp of ["0", "1"]) { |
| 426 | const esm = await run(["--import", registerUrl, "--conditions=require", "--input-type=module", "--eval", ` |
| 427 | import assert from "node:assert/strict"; |
| 428 | await assert.rejects(import(${JSON.stringify(url)})); |
| 429 | assert.equal((await import(${JSON.stringify(url)}, { with: { type: "json" } })).default.answer, 42); |
| 430 | `], { URL_IMPORT_TMP: tmp }); |
| 431 | assert.equal(esm.status, 0, esm.stderr); |
| 432 | const cjs = await run(["--import", registerUrl, "--conditions=import", "--eval", `console.log(require(${JSON.stringify(url)}).answer);`], { URL_IMPORT_TMP: tmp }); |
| 433 | assert.equal(cjs.status, 0, cjs.stderr); |
| 434 | assert.equal(cjs.stdout.trim(), "42"); |
| 435 | } |
| 436 | }); |
| 437 |
| 438 | it("loads CommonJS TypeScript with a TypeScript content type", async () => { |
| 439 | const result = await run(["--import", registerUrl, "--eval", `import(${JSON.stringify(`${baseUrl}/typed.cts`)}).then(m => console.log(m.default));`]); |
| 440 | assert.equal(result.status, 0, result.stderr); |
| 441 | assert.equal(Number(result.stdout), 17); |
| 442 | }); |
| 443 |
| 444 | it("keeps CommonJS relative requires working", async () => { |
| 445 | const result = await run(["--import", registerUrl, "--eval", `console.log(require(${JSON.stringify(`${baseUrl}/cjs/main.cjs`)}));`]); |
| 446 | assert.equal(result.status, 0, result.stderr); |
| 447 | assert.equal(Number(result.stdout), 42); |
| 448 | }); |
| 449 |
| 450 | it("loads ESM-imported CommonJS chains from real cached paths, including .cts", async () => { |
| 451 | const result = await run(["--import", registerUrl, "--eval", `import(${JSON.stringify(`${baseUrl}/cjs/import-parent.mjs`)});`], { |
| 452 | URL_IMPORT_TMP: "0", |
| 453 | }); |
| 454 | assert.equal(result.status, 0, result.stderr); |
| 455 | const output = JSON.parse(result.stdout); |
| 456 | assert.equal(output.cacheIdentity, true); |
| 457 | assert.equal(output.childCacheIdentity, true); |
| 458 | assert.equal(output.leafCacheIdentity, true); |
| 459 | assert.equal(output.childPath, output.childFilename); |
| 460 | assert.equal(output.leafPath, output.leafFilename); |
| 461 | assert.equal(output.value, 42); |
| 462 | for (const filename of [output.filename, output.childFilename, output.leafFilename]) { |
| 463 | assert.ok(filename.includes("/node-url-import/session-"), filename); |
| 464 | assert.ok(existsSync(filename), filename); |
| 465 | } |
| 466 | assert.match(output.filename, /\.cjs$/); |
| 467 | assert.match(output.childFilename, /\.cjs$/); |
| 468 | assert.match(output.leafFilename, /\.cts$/); |
| 469 | assert.deepEqual(requests, [ |
| 470 | "/cjs/import-parent.mjs", |
| 471 | "/cjs/esm-import-main.cjs", |
| 472 | "/cjs/esm-import-child.cjs", |
| 473 | "/cjs/esm-import-leaf.cts", |
| 474 | ]); |
| 475 | }); |
| 476 |
| 477 | it("loads relative CJS and CTS dependencies from an ESM-imported remote CTS module", async () => { |
| 478 | for (const tmp of ["0", "1"]) { |
| 479 | requests.length = 0; |
| 480 | const result = await run(["--import", registerUrl, "--eval", `import(${JSON.stringify(`${baseUrl}/cjs/cts-import-parent.mjs`)});`], { |
| 481 | URL_IMPORT_TMP: tmp, |
| 482 | DENO_DIR: join(workspace, `deno-cts-import-${tmp}`), |
| 483 | }); |
| 484 | assert.equal(result.status, 0, `URL_IMPORT_TMP=${tmp}\n${result.stderr}`); |
| 485 | assert.deepEqual(JSON.parse(result.stdout), { |
| 486 | value: 42, |
| 487 | mainIsMain: false, |
| 488 | cacheIdentity: true, |
| 489 | childCacheIdentity: true, |
| 490 | typedChildCacheIdentity: true, |
| 491 | }); |
| 492 | assert.deepEqual(requests, [ |
| 493 | "/cjs/cts-import-parent.mjs", |
| 494 | "/cjs/cts-import-main.cts", |
| 495 | "/cjs/cts-import-child.cjs", |
| 496 | "/cjs/cts-import-child.cts", |
| 497 | ]); |
| 498 | } |
| 499 | }); |
| 500 |
| 501 | it("runs a remote CTS CLI main with relative CJS and CTS requires", async () => { |
| 502 | for (const tmp of ["0", "1"]) { |
| 503 | requests.length = 0; |
| 504 | const result = await run([cliPath, `${baseUrl}/cjs/cts-cli-main.cts`], { |
| 505 | URL_IMPORT_TMP: tmp, |
| 506 | DENO_DIR: join(workspace, `deno-cts-cli-${tmp}`), |
| 507 | }); |
| 508 | assert.equal(result.status, 0, `URL_IMPORT_TMP=${tmp}\n${result.stderr}`); |
| 509 | assert.deepEqual(JSON.parse(result.stdout), { |
| 510 | value: 42, |
| 511 | isMain: true, |
| 512 | cacheIdentity: true, |
| 513 | childCacheIdentity: true, |
| 514 | typedChildCacheIdentity: true, |
| 515 | }); |
| 516 | assert.deepEqual(requests, [ |
| 517 | "/cjs/cts-cli-main.cts", |
| 518 | "/cjs/cts-import-child.cjs", |
| 519 | "/cjs/cts-import-child.cts", |
| 520 | ]); |
| 521 | } |
| 522 | }); |
| 523 |
| 524 | it("runs a remote CommonJS CLI main with relative requires", async () => { |
| 525 | const results = []; |
| 526 | for (const tmp of ["0", "1"]) { |
| 527 | requests.length = 0; |
| 528 | const result = await run([cliPath, "--reload", `${baseUrl}/cjs/cli-main.cjs`], { |
| 529 | URL_IMPORT_TMP: tmp, |
| 530 | DENO_DIR: join(workspace, `deno-cjs-${tmp}`), |
| 531 | }); |
| 532 | results.push({ tmp, result, requests: [...requests] }); |
| 533 | } |
| 534 | for (const { tmp, result, requests: requested } of results) { |
| 535 | assert.equal(result.status, 0, `URL_IMPORT_TMP=${tmp}\n${result.stderr}`); |
| 536 | assert.equal(result.stdout.trim(), "42"); |
| 537 | assert.deepEqual(requested, ["/cjs/cli-main.cjs", "/cjs/child.cjs"]); |
| 538 | } |
| 539 | }); |
| 540 |
| 541 | it("preserves CommonJS main identity, query, fragment and CLI arguments", async () => { |
| 542 | const remoteLookingTitle = `${baseUrl}/not-the-main.mjs`; |
| 543 | const target = `${baseUrl}/cjs/identity-main.cjs?variant=1#fragment`; |
| 544 | const result = await run([ |
| 545 | cliPath, |
| 546 | `--title=${remoteLookingTitle}`, |
| 547 | "--", |
| 548 | target, |
| 549 | "argument", |
| 550 | "--reload", |
| 551 | ]); |
| 552 | assert.equal(result.status, 0, result.stderr); |
| 553 | assert.deepEqual(JSON.parse(result.stdout), { |
| 554 | isMain: true, |
| 555 | moduleLoaded: false, |
| 556 | selfExports: true, |
| 557 | childSawExports: true, |
| 558 | executions: 1, |
| 559 | argv: ["argument", "--reload"], |
| 560 | }); |
| 561 | assert.deepEqual(requests, [ |
| 562 | "/cjs/identity-main.cjs?variant=1", |
| 563 | "/cjs/identity-child.cjs", |
| 564 | ]); |
| 565 | }); |
| 566 |
| 567 | it("resolves CommonJS CLI main and transitive require bases after redirects", async () => { |
| 568 | const result = await run([cliPath, `${baseUrl}/cjs/redirect-main.cjs`]); |
| 569 | assert.equal(result.status, 0, result.stderr); |
| 570 | assert.equal(result.stdout.trim(), "redirected-child"); |
| 571 | assert.deepEqual(requests, [ |
| 572 | "/cjs/redirect-main.cjs", |
| 573 | "/cjs/v1/main.cjs", |
| 574 | "/cjs/v1/redirect-child.cjs", |
| 575 | "/cjs/v2/child.cjs", |
| 576 | "/cjs/v2/leaf.cjs", |
| 577 | ]); |
| 578 | }); |
| 579 | }); |
| 580 |