| 4 | import { closeSync, fchmodSync, fsyncSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; |
| 5 | import { basename, dirname, join } from "node:path"; |
| 6 | import { homedir, platform } from "node:os"; |
| 7 | import { MAX_REDIRECTS, isHttpUrl } from "./constants.ts"; |
| 8 |
| 9 | function defaultDenoDir(): string { |
| 10 | if (process.env.DENO_DIR) return process.env.DENO_DIR; |
| 11 | switch (platform()) { |
| 12 | case "darwin": |
| 13 | return join(homedir(), "Library", "Caches", "deno"); |
| 14 | case "win32": |
| 15 | return join(process.env.LOCALAPPDATA || join(homedir(), "AppData", "Local"), "deno"); |
| 16 | default: |
| 17 | return join(process.env.XDG_CACHE_HOME || join(homedir(), ".cache"), "deno"); |
| 18 | } |
| 19 | } |
| 20 |
| 21 | const CACHE_DIR = join(defaultDenoDir(), "remote"); |
| 22 | // Deno appends this marker + JSON after source bytes and uses it alone for |
| 23 | // redirect stubs. Keep this byte format stable so both runtimes share the cache. |
| 24 | const META_MARKER = Buffer.from("\n// denoCacheMetadata="); |
| 25 |
| 26 | export type ModuleSource = string | Uint8Array; |
| 27 |
| 28 | export interface CachePaths { |
| 29 | dir: string; |
| 30 | file: string; |
| 31 | } |
| 32 |
| 33 | export interface CacheEntry { |
| 34 | /** Raw source text, or untouched bytes for a WebAssembly module. */ |
| 35 | source: ModuleSource; |
| 36 | /** Value of the Content-Type response header, including any parameters. */ |
| 37 | contentType: string; |
| 38 | /** The URL as originally requested, including its module-identity fragment. */ |
| 39 | url: string; |
| 40 | /** The final URL after following all redirects. */ |
| 41 | finalUrl: string; |
| 42 | /** Every URL traversed: [original, ...intermediates, final]. */ |
| 43 | redirectChain: string[]; |
| 44 | } |
| 45 |
| 46 | interface DenoCacheMetadata { |
| 47 | headers: Record<string, string>; |
| 48 | url: string; |
| 49 | time: number; |
| 50 | } |
| 51 |
| 52 | /** Deno hashes pathname + query; fragments identify modules, not HTTP responses. */ |
| 53 | export function cachePaths(url: string): CachePaths { |
| 54 | const parsed = new URL(url); |
| 55 | parsed.hash = ""; |
| 56 | // URL.search is empty for both an absent query and a bare ?. Deno's cache |
| 57 | // distinguishes them, so retain that delimiter when hashing the resource. |
| 58 | const query = parsed.href.includes("?") ? parsed.search || "?" : ""; |
| 59 | const hash = createHash("sha256").update(parsed.pathname + query).digest("hex"); |
| 60 | // Deno 2.9.8 escapes host underscores and reserves _port_ for explicit ports. |
| 61 | const host = parsed.hostname.replaceAll("_", "%5f") + (parsed.port ? `_port_${parsed.port}` : ""); |
| 62 | const authority = host.length > 250 ? `#${createHash("sha256").update(parsed.host).digest("hex")}` : host; |
| 63 | const dir = join(CACHE_DIR, parsed.protocol.slice(0, -1), authority); |
| 64 | return { dir, file: join(dir, hash) }; |
| 65 | } |
| 66 |
| 67 | function inferContentType(url: string): string { |
| 68 | const pathname = new URL(url).pathname; |
| 69 | if (pathname.endsWith(".json")) return "application/json"; |
| 70 | if (pathname.endsWith(".wasm")) return "application/wasm"; |
| 71 | if (/\.(?:ts|tsx|mts|cts)$/.test(pathname)) return "text/typescript"; |
| 72 | return "application/javascript"; |
| 73 | } |
| 74 |
| 75 | /** Decode text modules while retaining the binary source required by Wasm loaders. */ |
| 76 | export function decodeModuleSource(bytes: Uint8Array, url: string, contentType: string): ModuleSource { |
| 77 | if (contentType.toLowerCase().includes("application/wasm") || new URL(url).pathname.endsWith(".wasm")) { |
| 78 | return bytes; |
| 79 | } |
| 80 | const charset = /(?:^|;)\s*charset\s*=\s*(?:"([^"]*)"|'([^']*)'|([^;\s]*))/i.exec(contentType); |
| 81 | // Deno defaults remote files to UTF-8, decodes with the declared WHATWG |
| 82 | // charset without BOM sniffing, then removes one decoded leading BOM. |
| 83 | const text = new TextDecoder(charset ? charset[1] ?? charset[2] ?? charset[3] : "utf-8", { ignoreBOM: true }).decode(bytes); |
| 84 | return text.startsWith("\uFEFF") ? text.slice(1) : text; |
| 85 | } |
| 86 |
| 87 | function isMetadata(value: unknown): value is DenoCacheMetadata { |
| 88 | return typeof value === "object" && value !== null && |
| 89 | "url" in value && typeof value.url === "string" && |
| 90 | "headers" in value && typeof value.headers === "object" && value.headers !== null && |
| 91 | !Array.isArray(value.headers) && Object.values(value.headers).every((header) => typeof header === "string"); |
| 92 | } |
| 93 |
| 94 | function withoutFragment(url: string): string { |
| 95 | const parsed = new URL(url); |
| 96 | parsed.hash = ""; |
| 97 | return parsed.href; |
| 98 | } |
| 99 |
| 100 | /** Read source bytes or follow Deno redirect stubs; incomplete entries are misses. */ |
| 101 | export function readCache(url: string, depth = 0): CacheEntry | null { |
| 102 | if (depth > MAX_REDIRECTS) return null; |
| 103 | try { |
| 104 | url = new URL(url).href; |
| 105 | const path = cachePaths(url).file; |
| 106 | let raw: Buffer; |
| 107 | for (let attempt = 0; ; attempt++) { |
| 108 | try { |
| 109 | raw = readFileSync(path); |
| 110 | break; |
| 111 | } catch (error) { |
| 112 | if (process.platform !== "win32" || attempt >= 20 || |
| 113 | !(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error; |
| 114 | Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1); |
| 115 | } |
| 116 | } |
| 117 | const metadataOffset = raw.lastIndexOf(META_MARKER); |
| 118 | if (metadataOffset === -1) return null; |
| 119 | const metadata: unknown = JSON.parse(raw.subarray(metadataOffset + META_MARKER.length).toString("utf8")); |
| 120 | if (!isMetadata(metadata) || withoutFragment(metadata.url) !== withoutFragment(url)) return null; |
| 121 | // Deno 2.9.8 may cache unsuccessful responses as body-less 404 entries. |
| 122 | if ("x-deno-not-found" in metadata.headers) return null; |
| 123 |
| 124 | // A Location header distinguishes redirect stubs from valid empty modules. |
| 125 | const location = metadata.headers.location; |
| 126 | if (location !== undefined) { |
| 127 | if (!location) return null; |
| 128 | // Deno joins Location directly: absent fragments are not inherited. |
| 129 | const target = new URL(location, url); |
| 130 | if (!isHttpUrl(target.href)) return null; |
| 131 | const entry = readCache(target.href, depth + 1); |
| 132 | return entry ? { ...entry, url, redirectChain: [url, ...entry.redirectChain] } : null; |
| 133 | } |
| 134 |
| 135 | // Source entry: <source bytes> followed by the metadata marker and JSON. |
| 136 | const contentType = metadata.headers["content-type"] || inferContentType(url); |
| 137 | return { |
| 138 | source: decodeModuleSource(raw.subarray(0, metadataOffset), url, contentType), |
| 139 | contentType, |
| 140 | url, |
| 141 | finalUrl: url, |
| 142 | redirectChain: [url], |
| 143 | }; |
| 144 | } catch { |
| 145 | return null; |
| 146 | } |
| 147 | } |
| 148 |
| 149 | /** |
| 150 | * Replace a file only after its complete contents are on disk. A sibling temp |
| 151 | * file keeps rename atomic, preserves existing modes, and is cleaned on errors. |
| 152 | * Shared by the remote cache, lock file and readable temporary modules. |
| 153 | */ |
| 154 | export function writeFileAtomicSync(path: string, source: ModuleSource): void { |
| 155 | let target = path; |
| 156 | let mode: number | undefined; |
| 157 | try { |
| 158 | target = realpathSync(path); |
| 159 | mode = statSync(target).mode & 0o777; |
| 160 | } catch (error) { |
| 161 | if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error; |
| 162 | } |
| 163 | mkdirSync(dirname(target), { recursive: true }); |
| 164 | const temporaryPath = join(dirname(target), `.${basename(target)}.${randomUUID()}.tmp`); |
| 165 | let descriptor: number | undefined; |
| 166 | try { |
| 167 | descriptor = openSync(temporaryPath, "wx", mode ?? (0o666 & ~process.umask())); |
| 168 | writeFileSync(descriptor, source); |
| 169 | // open() applies umask even when given an existing mode. Restore that mode |
| 170 | // explicitly, while new files still respect the caller's umask. |
| 171 | if (mode !== undefined) fchmodSync(descriptor, mode); |
| 172 | fsyncSync(descriptor); |
| 173 | closeSync(descriptor); |
| 174 | descriptor = undefined; |
| 175 | // Windows rename does not replace an existing destination. |
| 176 | if (process.platform === "win32") rmSync(target, { force: true }); |
| 177 | renameSync(temporaryPath, target); |
| 178 | } finally { |
| 179 | if (descriptor !== undefined) closeSync(descriptor); |
| 180 | rmSync(temporaryPath, { force: true }); |
| 181 | } |
| 182 | } |
| 183 |
| 184 | /** Write one Deno-format stub per redirect hop plus the final source entry. */ |
| 185 | export function writeCache( |
| 186 | redirectChain: string[], source: ModuleSource, contentType: string, redirectLocations?: string[], |
| 187 | ): void { |
| 188 | const finalUrl = redirectChain.at(-1); |
| 189 | if (!finalUrl) throw new TypeError("A cache entry must have a URL"); |
| 190 |
| 191 | const writeEntry = (url: string, bytes: Uint8Array, headers: Record<string, string>): void => { |
| 192 | const { dir, file } = cachePaths(url); |
| 193 | mkdirSync(dir, { recursive: true }); |
| 194 | const metadata: DenoCacheMetadata = { headers, url: new URL(url).href, time: Math.floor(Date.now() / 1000) }; |
| 195 | writeFileAtomicSync(file, Buffer.concat([bytes, META_MARKER, Buffer.from(JSON.stringify(metadata))])); |
| 196 | }; |
| 197 |
| 198 | // Publish the source before its stubs so a reader never follows a new stub |
| 199 | // to a source entry that has not been written yet. |
| 200 | writeEntry(finalUrl, typeof source === "string" ? Buffer.from(source) : source, { "content-type": contentType }); |
| 201 | for (let index = redirectChain.length - 2; index >= 0; index--) { |
| 202 | writeEntry(redirectChain[index]!, Buffer.alloc(0), { |
| 203 | "content-length": "0", |
| 204 | // Preserve the exact target, including an explicit fragment or trailing #. |
| 205 | location: redirectLocations?.[index] ?? redirectChain[index + 1]!, |
| 206 | }); |
| 207 | } |
| 208 | } |
| 209 |
| 210 | /** Remove all cached remote modules from $DENO_DIR/remote/. */ |
| 211 | export function clearCache(): void { |
| 212 | rmSync(CACHE_DIR, { recursive: true, force: true }); |
| 213 | } |
| 214 |