All files / src loader.js

46.66% Statements 21/45
50% Branches 10/20
28.57% Functions 2/7
45.94% Lines 17/37

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64    57x                                                 57x             47x 47x 47x 1x   46x 2x 2x 1x   44x 44x 44x         44x 44x         47x 47x          
import { stringToUint8Array } from "./binary.js";
 
export const runningInNode = typeof window === "undefined";
 
function loadDataHttp(url) {
    return new Promise(function (resolve, reject) {
        const request = new XMLHttpRequest();
        request.open("GET", url, true);
        request.overrideMimeType("text/plain; charset=x-user-defined");
        request.onload = function () {
            if (request.status !== 200) {
                reject(new Error("Unable to load " + url + ", http code " + request.status));
                return;
            }
            if (typeof request.response !== "string") {
                resolve(request.response);
            } else {
                resolve(stringToUint8Array(request.response));
            }
        };
        request.onerror = function () {
            reject(new Error("A network error occurred loading " + url));
        };
        request.send(null);
    });
}
 
let _nodeBasePath = null;
 
export function setNodeBasePath(basePath) {
    _nodeBasePath = basePath;
}
 
async function loadDataNode(url) {
    if (url.startsWith("file:")) {
        const fs = await import("fs");
        const { fileURLToPath } = await import("url");
        return fs.readFileSync(fileURLToPath(url));
    }
    if (/^https?:\/\//.test(url)) {
        const response = await fetch(url);
        if (!response.ok) throw new Error(`Unable to load ${url}, http code ${response.status}`);
        return new Uint8Array(await response.arrayBuffer());
    }
    const fs = await import("fs");
    const nodePath = await import("path");
    Iif (_nodeBasePath) {
        const publicPath = nodePath.join(_nodeBasePath, "public", url);
        if (fs.existsSync(publicPath)) return fs.readFileSync(publicPath);
        return fs.readFileSync(nodePath.join(_nodeBasePath, url));
    }
    Iif (url[0] === "/") url = "." + url;
    Eif (fs.existsSync("public/" + url)) return fs.readFileSync("public/" + url);
    return fs.readFileSync(url);
}
 
export function loadData(url) {
    if (runningInNode) {
        return loadDataNode(url);
    } else E{
        return loadDataHttp(url);
    }
}