| 6 |
| * |
| 7 | * Each URL, including query and fragment, gets its own module file. The reverse |
| 8 | * map retains the exact URL rather than reconstructing it from a synthetic file |
| 9 | * name, so extensionless URLs keep their original relative-import base. |
| 10 | * Used automatically for CommonJS with sync hooks, and for all remote modules |
| 11 | * when URL_IMPORT_TMP=1 (normally set by the CLI's --tmp option). |
| 12 | */ |
| 13 |
| 14 | import process from "node:process"; |
| 15 | import { tmpdir } from "node:os"; |
| 16 | import { createHash } from "node:crypto"; |
| 17 | import { join, dirname, extname, resolve } from "node:path"; |
| 18 | import { mkdirSync, mkdtempSync, realpathSync } from "node:fs"; |
| 19 | import { fileURLToPath } from "node:url"; |
| 20 | import { NAME } from "./constants.ts"; |
| 21 | import { writeFileAtomicSync } from "./cache.ts"; |
| 22 | import type { ModuleSource } from "./cache.ts"; |
| 23 |
| 24 | /** Whether all remote modules should use readable temporary files. */ |
| 25 | export const tmpEnabled = process.env.URL_IMPORT_TMP === "1"; |
| 26 | const sourceUrls = new Map<string, string>(); |
| 27 | const KNOWN_EXTENSIONS = new Set([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".json", ".wasm"]); |
| 28 | let temporaryRoot: string | undefined; |
| 29 |
| 30 | function getTemporaryRoot(): string { |
| 31 | if (!temporaryRoot) { |
| 32 | const parent = join(tmpdir(), NAME); |
| 33 | mkdirSync(parent, { recursive: true }); |
| 34 | // Node realpaths CJS files before relative require() calls. Store the |
| 35 | // same spelling so symlinked temp roots retain their reverse URL mapping. |
| 36 | temporaryRoot = realpathSync(mkdtempSync(join(parent, "session-"))); |
| 37 | } |
| 38 | return temporaryRoot; |
| 39 | } |
| 40 |
| 41 | /** Choose an unambiguous Node file extension for an extensionless remote URL. */ |
| 42 | function extensionForContentType(contentType: string): string { |
| 43 | const type = contentType.toLowerCase(); |
| 44 | if (type.includes("text/typescript") || type.includes("application/typescript")) return ".ts"; |
| 45 | if (type.includes("application/json")) return ".json"; |
| 46 | if (type.includes("application/wasm")) return ".wasm"; |
| 47 | // .mjs keeps JS modules ESM regardless of package.json files above the tmp root. |
| 48 | return ".mjs"; |
| 49 | } |
| 50 |
| 51 | function safePathSegment(segment: string): string { |
| 52 | return segment.replace(/[^a-zA-Z0-9_.@-]/g, (character) => encodeURIComponent(character)); |
| 53 | } |
| 54 |
| 55 | /** Map an exact HTTP URL to a unique readable module path and register its reverse mapping. */ |
| 56 | export function urlToTmpPath(url: string, contentType = ""): string { |
| 57 | const parsed = new URL(url); |
| 58 | const extension = extname(parsed.pathname); |
| 59 | const pathSegments = parsed.pathname.split("/").filter(Boolean).map(safePathSegment); |
| 60 | const identity = createHash("sha256").update(parsed.href).digest("hex").slice(0, 16); |
| 61 | const inferredExtension = KNOWN_EXTENSIONS.has(extension) ? extension : extensionForContentType(contentType); |
| 62 | const path = join(getTemporaryRoot(), parsed.protocol.slice(0, -1), safePathSegment(parsed.host), |
| 63 | ...pathSegments, `module-${identity}${inferredExtension}`); |
| 64 | sourceUrls.set(resolve(path), parsed.href); |
| 65 | return path; |
| 66 | } |
| 67 |
| 68 | /** Recover the original HTTP URL only for module paths generated in this session. */ |
| 69 | export function tmpPathToUrl(fileUrl: string): string | null { |
| 70 | try { |
| 71 | const path = fileUrl.startsWith("file:") ? fileURLToPath(fileUrl) : fileUrl; |
| 72 | return sourceUrls.get(resolve(path)) ?? null; |
| 73 | } catch { |
| 74 | return null; |
| 75 | } |
| 76 | } |
| 77 |
| 78 | /** Write text or binary source atomically, creating parent directories as needed. */ |
| 79 | export function writeTmpFile(path: string, source: ModuleSource): void { |
| 80 | mkdirSync(dirname(path), { recursive: true }); |
| 81 | writeFileAtomicSync(path, source); |
| 82 | } |
| 83 |