jdl
Version:
jsdelivr-download
64 lines (63 loc) • 1.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.downloadBinary = downloadBinary;
exports.download = download;
const HOST = "https://cdn.jsdelivr.net";
async function downloadBinary(url) {
const buf = await fetch(url).then((resp) => resp.arrayBuffer());
return new Uint8Array(buf);
}
async function parse(html) {
const table = getTable(html);
if (!table) {
return [];
}
const regex = /<a[^>]+href="([^"]+)"[^>]*>([^<]+)<\/a>/g;
const v = [];
for (const i of Array.from(table.matchAll(regex), ([, url, name]) => {
const isDir = url.endsWith("/");
const path = url.split("/").slice(4).join("/");
return {
path,
url: HOST + url,
name,
isDir,
};
})) {
if (!i.isDir) {
i.buffer = await downloadBinary(i.url);
}
if (i.name !== "...") {
v.push(i);
}
}
return v;
}
function getTable(html) {
const regex = /<table[^>]*>([\s\S]*?)<\/table>/i;
const match = html.match(regex);
return match ? match[1].trim() : null;
}
async function getFiles(user, repo, url) {
const html = await fetch(url).then((resp) => resp.text());
const files = await parse(html);
const v = [];
for (const file of files) {
if (file.isDir) {
const subUrl = url + file.path;
const subFiles = await getFiles(user, repo, subUrl);
for (const k of subFiles) {
v.push(k);
}
}
else {
v.push(file);
}
}
return v;
}
function download(user, repo) {
const url = HOST + `/gh/${user}/${repo}/`;
const files = getFiles(user, repo, url);
return files;
}