1 | const resolveCwd = require('resolve-cwd');
|
2 | const umap = require('umap');
|
3 | const path = require('path');
|
4 | const escalade = require('escalade');
|
5 | const fetch = require('node-fetch');
|
6 | let cache = umap(new Map);
|
7 | let cdn = "https://cdn.skypack.dev";
|
8 | let default_options = {
|
9 | pinned: true,
|
10 | minified: true
|
11 | };
|
12 | async function localVersion(dependency) {
|
13 | try {
|
14 | let version = "";
|
15 | let pkg_path = await escalade(path.dirname(resolveCwd(dependency)), (dir, names) => {
|
16 | if (names.includes('package.json')) {
|
17 | let { name, version } = require(path.join(dir, 'package.json'));
|
18 | if (name === dependency && version) {
|
19 | return 'package.json';
|
20 | }
|
21 | }
|
22 | });
|
23 | if (pkg_path) {
|
24 | version = require(pkg_path).version;
|
25 | }
|
26 |
|
27 | return version || "latest";
|
28 | }
|
29 | catch (e) {
|
30 | return "latest";
|
31 | }
|
32 | }
|
33 | async function skypin(dependency, options) {
|
34 | options = { ...default_options, ...options };
|
35 | if (dependency.startsWith('.') || dependency.startsWith('https://') || dependency.startsWith('http://')) {
|
36 |
|
37 | return dependency;
|
38 | }
|
39 | let [id, version] = dependency.split('@').filter(s => s.length);
|
40 | if (!version) {
|
41 |
|
42 | version = await localVersion(dependency);
|
43 | }
|
44 | let module_id = `${id}@${version}`;
|
45 | if (options.pinned) {
|
46 | return await lookup(module_id, options.minified);
|
47 | }
|
48 | else {
|
49 | return `${cdn}/${module_id}`;
|
50 | }
|
51 | }
|
52 | async function lookup(module_id, minified = true) {
|
53 | return cache.get(module_id) || cache.set(module_id, (await fetchSkypack(module_id))[minified ? 'minified' : 'normal']);
|
54 | }
|
55 | async function fetchSkypack(module_id) {
|
56 | try {
|
57 | const response = await fetch(`${cdn}/${module_id}`);
|
58 | let x_import_status = response.headers.get('x-import-status');
|
59 | let x_import_url = response.headers.get('x-import-url');
|
60 | let x_pinned_url = response.headers.get('x-pinned-url') || x_import_url;
|
61 | if (x_import_status === 'NEW' && x_import_url) {
|
62 | await fetch(`${cdn}${x_import_url}`);
|
63 | return await fetchSkypack(module_id);
|
64 | }
|
65 | let lastSlash = x_pinned_url.lastIndexOf('/');
|
66 | return {
|
67 | normal: `${cdn}${x_pinned_url}`,
|
68 | minified: `${cdn}${x_pinned_url.slice(0, lastSlash) + '/min' + x_pinned_url.slice(lastSlash)}`
|
69 | };
|
70 | }
|
71 | catch (e) {
|
72 | console.log("Error fetching module from skypack. Returning empty strings");
|
73 | console.log(e);
|
74 | return { normal: "", minified: "" };
|
75 | }
|
76 | }
|
77 |
|
78 | export { skypin };
|