Skip to main content
Module

x/eszip/loader.ts

A compact file format to losslessly serialize an ECMAScript module graph into a single file
Go to Latest
File
// Adapted from deno_graph// https://github.com/denoland/deno_graph/blob/main/lib/loader.ts
export interface LoadResponseModule { /** A module with code has been loaded. */ kind: "module"; /** The string URL of the resource. If there were redirects, the final * specifier should be set here, otherwise the requested specifier. */ specifier: string; /** For remote resources, a record of headers should be set, where the key's * have been normalized to be lower case values. */ headers?: Record<string, string>; /** The string value of the loaded resources. */ content: string;}
export interface LoadResponseExternalBuiltIn { /** The loaded module is either _external_ or _built-in_ to the runtime. */ kind: "external" | "builtIn"; /** The string URL of the resource. If there were redirects, the final * specifier should be set here, otherwise the requested specifier. */ specifier: string;}
export type LoadResponse = LoadResponseModule | LoadResponseExternalBuiltIn;
export async function load( specifier: string,): Promise<LoadResponse | undefined> { const url = new URL(specifier); try { switch (url.protocol) { case "file:": { const content = await Deno.readTextFile(url); return { kind: "module", specifier, content, }; } case "http:": case "https:": { const response = await fetch(String(url), { redirect: "follow" }); if (response.status !== 200) { // ensure the body is read as to not leak resources await response.arrayBuffer(); return undefined; } const content = await response.text(); const headers: Record<string, string> = {}; for (const [key, value] of response.headers) { headers[key.toLowerCase()] = value; } return { kind: "module", specifier: response.url, headers, content, }; } default: return undefined; } } catch { return undefined; }}