Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/bundlejs-api.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677import type { AsyncDisposableStack } from "@bundle/utils/dispose";import { LruCache } from "./lru.ts";
/** * Fetch-and-cache module with proper redirect handling. * * **Key design decision**: Always cache under the *final* URL (`response.url`), * not the original request URL. This ensures: * * 1. Relative imports resolve correctly (bundlers need the final URL as base) * 2. No stale redirect targets when CDN aliases like `@latest` change * 3. Direct requests to final URLs hit cache * * For efficiency, we also maintain a redirect map so requests to aliased URLs * can find cached content without re-fetching. * * @example How Redirects Now Work * ``` * Request: https://esm.sh/lodash@latest * ↓ * fetch-and-cache: fetch with redirect:'follow' * ↓ * Response.url: https://esm.sh/lodash@4.17.21 * ↓ * Cache: stores under final URL + records redirect mapping * ↓ * http.ts: receives { url: "https://esm.sh/lodash@4.17.21", content, ... } * ↓ * pluginData.url = final URL * ↓ * Relative import "./debounce" resolves against final URL ✓ * ``` */
// ============================================================================// Configuration// ============================================================================
/** LRU cache capacity for responses */export const CACHE_CAPACITY = 300;
/** LRU cache capacity for redirect mappings */export const REDIRECT_MAP_CAPACITY = 500;
/** Default retry attempts for failed requests */export const DEFAULT_RETRIES = 1;
// ============================================================================// Caches// ============================================================================
/** In-memory LRU cache for responses, keyed by final URL */export const responseCache = new LruCache<string, Response>(CACHE_CAPACITY);
/** * Maps original URLs to their final redirect targets. * Enables cache hits when requesting aliased URLs (e.g., `lodash@latest` → `lodash@4.17.21`) */export const redirectMap = new LruCache<string, string>(REDIRECT_MAP_CAPACITY);
/** Cache API storage name */export const CACHE_NAME = "EXTERNAL_FETCHES";
/** Feature detection */export const SUPPORTS_CACHE_API = "caches" in globalThis;export const SUPPORTS_REQUEST_API = "Request" in globalThis;
// ============================================================================// Types// ============================================================================
export interface FetchResult { /** The final URL after any redirects */ url: string; /** The response (cloned if requested) */ response: Response; /** Whether this came from cache */ fromCache: boolean; /** Whether a redirect occurred */ redirected: boolean; /** * Background stale-while-revalidate refresh promise, if one was fired. * * When a cached response triggers a background refresh, this promise * tracks that work. Callers can await it for deterministic cleanup, * or ignore it if the `scope` option already adopted the promise. */ pending?: Promise<void>;}
export interface FetchOptions { /** Additional fetch options (headers, method, etc.) */ init?: RequestInit; /** Number of retry attempts on failure. Default: 2 */ retries?: number; /** * Cache behavior: * - 'normal': Use cache, update in background (stale-while-revalidate) * - 'force': Always use cache if available, never revalidate * - 'reload': Bypass cache, fetch fresh, update cache * - 'no-store': Bypass cache entirely, don't store response * Default: 'normal' */ cacheMode?: 'normal' | 'force' | 'reload' | 'no-store'; /** * Abort signal scoped to the build's lifetime. * * When provided, background stale-while-revalidate refreshes carry this * signal so they are cancelled when the build finishes. This prevents * Deno's test-runner sanitizer from detecting leaked `fetchCancelHandle` * or `op_cache_put` resources. * * The signal is **only** applied to background refreshes — primary * (awaited) fetches are not affected, so in-progress builds won't be * interrupted. * * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal */ signal?: AbortSignal; /** * Per-build disposal scope (`AsyncDisposableStack`). * * When provided, background stale-while-revalidate refresh promises are * **adopted** into this scope via `scope.adopt(bgPromise, awaiter)`. This * ensures `disposeAsync()` awaits settlement of every in-flight background * operation — including `cache.put()` calls that `AbortSignal` alone * cannot cancel — before the build boundary closes. * * Without this, fire-and-forget `backgroundRefresh` promises can outlive * the build and leak Deno runtime ops (`op_cache_put`, `fetchCancelHandle`). * * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncDisposableStack/adopt */ scope?: AsyncDisposableStack;}
// ============================================================================// Cache API wrapper// ============================================================================
let openCachePromise: Promise<Cache> | null = null;
/** * Opens the Cache API storage (singleton pattern) */export function openCache(): Promise<Cache> { if (!SUPPORTS_CACHE_API) { throw new Error("Cache API not supported in this environment"); } if (!openCachePromise) { openCachePromise = caches.open(CACHE_NAME); } return openCachePromise;}
// ============================================================================// In-flight request deduplication// ============================================================================
/** * Capacity for the in-flight request deduplication map. * * Limits memory when many unique URLs are fetched concurrently. * Once full, the oldest entry is evicted (LRU) so a duplicate request * will simply start a fresh fetch — correctness is preserved, only the * dedup optimisation is lost. */export const INFLIGHT_CAPACITY = 200;
/** * Maps a URL to its **in-progress** network fetch promise. * * When two callers request the same URL before the first fetch settles, * the second caller joins the existing promise instead of issuing a * duplicate HTTP request. The entry is removed as soon as the promise * settles so subsequent requests go to the normal cache-or-fetch path. * * This also bounds the number of concurrent fire-and-forget * `backgroundRefresh` calls: if a background refresh for URL X is already * in progress, the next stale-while-revalidate hit simply joins the * existing refresh rather than spawning a second one. */export const inflight = new LruCache<string, Promise<Response>>(INFLIGHT_CAPACITY);
// ============================================================================// Core fetch implementation// ============================================================================
/** * Resolves a URL through the redirect map to find the final cached URL. * Returns the original URL if no redirect mapping exists. */function resolveRedirect(url: string): string { return redirectMap.get(url) ?? url;}
/** * Looks up a URL in cache, checking both the direct URL and any redirect mappings. */async function lookupCache(url: string, cacheApi?: Cache): Promise<Response | undefined> { const finalUrl = resolveRedirect(url); if (SUPPORTS_CACHE_API && cacheApi) { const cached = await cacheApi.match(finalUrl); if (cached) return cached; } return responseCache.get(finalUrl);}
/** * Stores a response in cache under the final URL. * If a redirect occurred, also stores the mapping from original → final URL. */async function storeInCache( originalUrl: string, finalUrl: string, response: Response, cacheApi?: Cache, signal?: AbortSignal,): Promise<void> { // Only cache successful GET responses // Note: response.ok is false for 3xx, but fetch with redirect:'follow' // resolves with the final 2xx response, so we're caching the final response if (!response.ok) { // Cancel unconsumed body to prevent resource leak. // Must be awaited so `CacheResponseResource` handles are released // before the caller's scope closes. await response.body?.cancel(); return; }
// If the build finished (signal aborted) between fetch-complete and // cache-write, skip the write to avoid starting an `op_cache_put` that // would outlive the caller. if (signal?.aborted) { await response.body?.cancel(); return; }
try { if (SUPPORTS_CACHE_API && cacheApi) { // Cache API: store under final URL await cacheApi.put(new Request(finalUrl), response); } else { // In-memory fallback: store under final URL responseCache.set(finalUrl, response); } // Track redirect mapping if URLs differ if (originalUrl !== finalUrl) { redirectMap.set(originalUrl, finalUrl); } } catch (err) { // Swallow errors that occur because the signal fired mid-write if (signal?.aborted) return; console.error(`[cache] Failed to store response for ${finalUrl}:`, err); }}
/** * Performs the actual network fetch with retry logic. */function doFetch( url: string, init: RequestInit = {}, _retries: number): Promise<Response> { const fetchWithRedirect = async () => { const response = await fetch(url, { redirect: "follow", ...init, }); if (!response.ok) { // Cancel the body before throwing — prevents leaked response streams // when the caller never reads the body of a failed request. // Awaited to ensure `CacheResponseResource` is fully released. await response.body?.cancel(); throw new Error(`HTTP ${response.status}: ${response.statusText} for ${url}`); } return response; };
// TODO: re-enable retry logic // if (_retries > 0) { // return retry(fetchWithRedirect, { maxAttempts: _retries + 1 }); // } return fetchWithRedirect();}
/** * Background refresh with smart fallback for stale-while-revalidate. * * Tries the original URL first to discover version updates (e.g., @latest → @4.17.22). * Falls back to the final URL if original returns 404 (e.g., extensionless URLs). * * This handles two cases: * 1. Version aliases (@latest): original URL works, may resolve to newer version * 2. Extension probing (dbcs-codec → dbcs-codec.js): original 404s, use final URL */async function backgroundRefresh( originalUrl: string, finalUrl: string, init: RequestInit, retries: number, cacheApi?: Cache): Promise<void> { // Bail early if already aborted (e.g. build finished before refresh started) if (init.signal?.aborted) return;
try { // Try original URL first — this allows version discovery for @latest etc. const response = await doFetch(originalUrl, init, retries);
// Check abort *after* fetch completes but *before* the cache write. // Avoids starting an `op_cache_put` that would outlive the caller. if (init.signal?.aborted) { await response.body?.cancel(); return; }
const resolvedUrl = response.url || originalUrl; await storeInCache(originalUrl, resolvedUrl, response, cacheApi, init.signal ?? undefined); } catch (err) { // Silently swallow abort errors — expected during build cleanup if (err instanceof DOMException && err.name === "AbortError") return; if (init.signal?.aborted) return;
// If original URL failed with 404 and we have a different final URL, // try the final URL (handles extension probing case) const is404 = err instanceof Error && err.message.includes("404");
if (is404 && originalUrl !== finalUrl) { try { if (init.signal?.aborted) return;
const response = await doFetch(finalUrl, init, retries);
if (init.signal?.aborted) { await response.body?.cancel(); return; }
const resolvedUrl = response.url || finalUrl; await storeInCache(finalUrl, resolvedUrl, response, cacheApi, init.signal ?? undefined); } catch (fallbackErr) { if (fallbackErr instanceof DOMException && fallbackErr.name === "AbortError") return; if (init.signal?.aborted) return;
// Both failed — log but don't throw (background operation) console.error(`[cache] Background refresh failed for ${finalUrl}:`, fallbackErr); } } else { // Not a 404 or no fallback available — log the original error console.error(`[cache] Background refresh failed for ${originalUrl}:`, err); } }}
/** * Main fetch function with caching and proper redirect handling. * * **Important**: The returned `url` is the *final* URL after redirects. * Use this for resolving relative imports in fetched content. * * @example * ```ts * // Basic usage * const { url, response } = await fetchWithCache('https://esm.sh/lodash@latest'); * // url is now 'https://esm.sh/lodash@4.17.21' (the final URL) * * // The final URL is critical for relative imports: * // If lodash/index.js imports './debounce', resolve against the final URL * const debounceUrl = new URL('./debounce', url).toString(); * ``` */export async function fetchWithCache( url: string, options: FetchOptions = {}): Promise<FetchResult> { const { init = {}, retries = DEFAULT_RETRIES, cacheMode = 'normal', } = options;
// Only cache GET requests (not HEAD, POST, etc.) const method = init.method?.toUpperCase() ?? 'GET'; const canCache = method === 'GET' && cacheMode !== 'no-store'; const cacheApi = SUPPORTS_CACHE_API ? await openCache() : undefined;
// Check cache first (unless reload mode) if (canCache && cacheMode !== 'reload') { const cached = await lookupCache(url, cacheApi); if (cached) { const finalUrl = resolveRedirect(url); // Stale-while-revalidate: return cached, refresh in background. // // When an AbortSignal is provided (per-build lifecycle), the signal // is threaded into the background fetch so it is cancelled when the // build finishes — preventing Deno's sanitizer from detecting // leaked `fetchCancelHandle` / `op_cache_put` resources. // // When no signal is provided, the refresh is plain fire-and-forget // — fine for standalone / REPL usage where leak detection isn't a // concern. // Track the background refresh promise (if any) so callers and the // disposal scope can await its settlement. let pending: Promise<void> | undefined;
if (cacheMode === 'normal' && options.signal) { // Background refresh requires a signal for lifecycle management. // Without a signal the fetch cannot be cancelled on disposal, // causing `fetchCancelHandle` resources to leak across test/build // boundaries. Callers that don't provide a signal (e.g. REPL) // simply skip the refresh — stale cached data is returned instead. const refreshInit: RequestInit = { ...init, signal: options.signal };
pending = backgroundRefresh(url, finalUrl, refreshInit, retries, cacheApi);
// Adopt the background promise into the build's disposal scope. // When `disposeAsync()` runs, the abort signal fires first (LIFO: // abort was registered last → runs first), cancelling in-flight // fetches. Then the adopt awaiter drains the settling promise, // ensuring `cache.put()` ops that were already in progress // complete before the test/build boundary closes. if (options.scope && !options.scope.disposed) { options.scope.adopt( pending, async (p) => { try { await p; } catch { /* swallow — abort errors are expected */ } }, ); } }
// Consume-and-reconstruct: read the full body from the cache response, // then build a fresh Response from the consumed bytes. // // Why not clone()? // Response.clone() uses ReadableStream.tee() internally. In Deno, // cancelling one tee branch of a CacheResponseResource-backed stream // can deadlock when the other branch hasn't been consumed yet. // By fully consuming the body here we release the native // CacheResponseResource handle immediately — no tee, no cancel, // no deadlock. // // Memory cost is negligible: these are source-code files that would // be buffered by tee() anyway, and the consumer reads the full body // shortly after. const body = await cached.arrayBuffer(); const returnResponse = new Response(body, { headers: cached.headers, status: cached.status, statusText: cached.statusText, });
return { url: finalUrl, response: returnResponse, fromCache: true, redirected: url !== finalUrl, pending, }; } }
// ----------------------------------------------------------------- // Network fetch with request deduplication // ----------------------------------------------------------------- // If another caller is already fetching the same URL, join that // promise instead of issuing a duplicate HTTP request. // When the shared fetch settles we read the result from cache so // every caller gets its own clone and the response body isn't // consumed twice. // -----------------------------------------------------------------
const existing = inflight.get(url); if (existing) { // Join the in-flight request, then read the result from cache. try { await existing; } catch { /* original caller handles the error */ }
const deduped = await lookupCache(url, cacheApi); if (deduped) { const finalUrl = resolveRedirect(url);
// Consume-and-reconstruct (same rationale as the primary cache-hit // path above): fully read the body so the CacheResponseResource // handle is released, then return a fresh Response. const body = await deduped.arrayBuffer(); const returnResponse = new Response(body, { headers: deduped.headers, status: deduped.status, statusText: deduped.statusText, });
return { url: finalUrl, response: returnResponse, fromCache: true, redirected: url !== finalUrl, }; } // Cache miss after dedup — fall through to a fresh fetch below. }
// Start the authoritative fetch and register it in the inflight map // so concurrent callers can join. const fetchPromise = doFetch(url, init, retries); inflight.set(url, fetchPromise);
let response: Response; try { response = await fetchPromise; } finally { inflight.delete(url); }
const finalUrl = response.url || url; const redirected = response.redirected || url !== finalUrl; // Make ONE clone for cache (because cache.put consumes the body) if (canCache) { // Pass the clone into caching, so storeInCache DOES NOT clone again. await storeInCache(url, finalUrl, response.clone(), cacheApi); }
// Return the original response. // This keeps exactly two branches total: (1) cache clone, (2) original return. return { url: finalUrl, response, fromCache: false, redirected, };}
// ============================================================================// Convenience functions// ============================================================================
/** * Fetches content and returns it as a Uint8Array along with metadata. * This is the most common pattern for bundlers. */export async function fetchContent( url: string, options: FetchOptions = {}): Promise<{ url: string; content: Uint8Array; contentType: string | null; fromCache: boolean; redirected: boolean;}> { const { url: finalUrl, response, fromCache, redirected } = await fetchWithCache(url, options); const contentType = response.headers.get("content-type"); const content = new Uint8Array(await response.arrayBuffer()); return { url: finalUrl, content, contentType, fromCache, redirected };}
/** * Fetches only headers (useful for probing URLs without downloading content). * Uses HEAD request with GET fallback for servers that don't support HEAD. */export async function fetchHeaders( url: string, options: Omit<FetchOptions, 'clone'> = {}): Promise<{ url: string; contentType: string | null; fromCache: boolean;}> { const { init = {}, retries = 0, cacheMode = 'normal', signal } = options; // Try HEAD first try { const { url: finalUrl, response, fromCache } = await fetchWithCache(url, { init: { ...init, method: 'HEAD' }, retries: 0, cacheMode, signal, }); const contentType = response.headers.get("content-type");
// We only need headers from the HEAD probe. Explicitly cancel the response // so Cloudflare does not keep the request counted as in-flight. try { await response.body?.cancel(); } catch { /* ignore cancel errors */ } return { url: finalUrl, contentType, fromCache }; } catch (_) { // HEAD failed, try GET with immediate body cancellation const { url: finalUrl, response, fromCache } = await fetchWithCache(url, { init: { ...init, method: 'GET' }, retries, cacheMode: 'no-store', // Don't cache partial responses signal, }); const contentType = response.headers.get("content-type"); // Cancel body immediately - we only wanted headers try { await response.body?.cancel(); } catch { /* ignore cancel errors */ }
if (contentType && /text\/html/i.test(contentType)) { throw new Error(`Received HTML instead of expected content for ${finalUrl}`); } return { url: finalUrl, contentType, fromCache }; }}
// ============================================================================// Cache management// ============================================================================
/** * Clears all cached data (both in-memory and Cache API) */export async function clearCache(): Promise<void> { responseCache.clear(); redirectMap.clear(); inflight.clear(); if (SUPPORTS_CACHE_API) { try { await caches.delete(CACHE_NAME); } catch (e) { console.error(e) } openCachePromise = null; }}
/** * Removes a specific URL from cache (both original and final URL mappings) */export async function invalidate(url: string): Promise<void> { const finalUrl = resolveRedirect(url); responseCache.delete(finalUrl); redirectMap.delete(url); inflight.delete(url); if (SUPPORTS_CACHE_API) { try { const cache = await openCache(); await cache.delete(finalUrl); } catch (e) { console.error(e) } }}
// ============================================================================// Legacy API compatibility (deprecated, use new functions)// ============================================================================
/** * @deprecated Use `fetchWithCache` instead */export async function getRequest( url: RequestInfo | URL, opts: { cacheMode?: FetchOptions['cacheMode']; retry?: number; fetchOpts?: RequestInit } = {}): Promise<Response> { const urlString = url.toString(); const { response } = await fetchWithCache(urlString, { init: opts.fetchOpts, retries: opts.retry, cacheMode: opts.cacheMode, }); return response;}