cdn-resolve
Version:
Resolves import paths to their CDN equivalents
54 lines (50 loc) • 1.66 kB
JavaScript
;
// src/parse.ts
function parsePackage(pkg) {
const matched = /^(@(?<scope>[^/]+)\/(?<name>[^@/]+))(?:@(?<version>[^/]+))?(?<path>\/.*)?$/.exec(
pkg
) || /^(?<name>[^@/]+)(?:@(?<version>[^/]+))?(?<path>\/.*)?$/.exec(pkg);
if (!matched || !matched.groups?.name) {
throw new Error(`Invalid package name: ${pkg}`);
}
const version = matched.groups?.version || "latest";
const path = matched.groups?.path;
const scope = matched.groups?.scope;
const name = scope ? `@${scope}/${matched.groups.name}` : matched.groups.name;
return {
name,
version,
path,
scope,
full: `${name}@${version}${path || ""}`
};
}
// src/skypack.ts
function buildSkypackUrl(module, options) {
try {
const pkg = parsePackage(module);
const url = new URL(pkg.full, "https://cdn.skypack.dev/");
if (options?.dts) {
url.searchParams.set("dts", "true");
}
if (options?.min) {
url.searchParams.set("min", "true");
}
return url;
} catch {
return void 0;
}
}
async function resolveSkypackHeaders(url) {
if (url instanceof URL) {
url = url.toString();
}
const headers = await fetch(url).then((res) => res.headers);
return {
typesUrl: headers.has("x-typescript-types") ? `https://cdn.skypack.dev${headers.get("x-typescript-types")}` : void 0,
pinnedUrl: headers.has("x-pinned-url") ? `https://cdn.skypack.dev${headers.get("x-pinned-url")}` : void 0,
importUrl: headers.has("x-import-url") ? `https://cdn.skypack.dev${headers.get("x-import-url")}` : void 0
};
}
exports.buildSkypackUrl = buildSkypackUrl;
exports.resolveSkypackHeaders = resolveSkypackHeaders;