UNPKG

3.26 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5const resolveCwd = require('resolve-cwd');
6const umap = require('umap');
7const path = require('path');
8const escalade = require('escalade');
9const fetch = require('node-fetch');
10let cache = umap(new Map);
11let cdn = "https://cdn.skypack.dev";
12let default_options = {
13 pin: true,
14 min: true
15};
16async function localVersion(dependency) {
17 try {
18 let version = "";
19 let pkg_path = await escalade(path.dirname(resolveCwd(dependency)), (dir, names) => {
20 if (names.includes('package.json')) {
21 let { name, version } = require(path.join(dir, 'package.json'));
22 if (name === dependency && version) {
23 return 'package.json';
24 }
25 }
26 });
27 if (pkg_path) {
28 version = require(pkg_path).version;
29 }
30 // if we couldn't locate it locally, assume latest version
31 return version || "latest";
32 }
33 catch (e) {
34 return "latest";
35 }
36}
37async function skypin(dependency, options) {
38 options = { ...default_options, ...options };
39 if (dependency.startsWith('.') || dependency.startsWith('https://') || dependency.startsWith('http://')) {
40 // if local dependency or existing web url, don't edit
41 return dependency;
42 }
43 let [id, version] = dependency.split('@').filter(s => s.length);
44 id = dependency.charAt(0) === '@' ? `@${id}` : id;
45 if (!version) {
46 // if version wasn't specified, try to use local version (fallback to latest)
47 version = await localVersion(dependency);
48 }
49 let module_id = `${id}@${version}`;
50 if (options.pin) {
51 return await lookup(module_id, options.min);
52 }
53 else {
54 return `${cdn}/${module_id}`;
55 }
56}
57async function lookup(module_id, minified = true) {
58 return cache.get(module_id) || cache.set(module_id, (await fetchSkypack(module_id))[minified ? 'minified' : 'normal']);
59}
60async function fetchSkypack(module_id) {
61 try {
62 const response = await fetch(`${cdn}/${module_id}`);
63 let x_import_status = response.headers.get('x-import-status'); // NEW | SUCCESS
64 let x_import_url = response.headers.get('x-import-url'); // /new/it-helpers@v0.0.1/dist=es2020 | /-/it-helpers@v0.0.1-hYEkfsvYtBqTC0EmayFU/dist=es2020/it-helpers.js
65 let x_pinned_url = response.headers.get('x-pinned-url') || x_import_url; // /pin/it-helpers@v0.0.1-hYEkfsvYtBqTC0EmayFU/it-helpers.js
66 if (x_import_status === 'NEW' && x_import_url) {
67 await fetch(`${cdn}${x_import_url}`); // will likely take a few seconds
68 return await fetchSkypack(module_id);
69 }
70 let lastSlash = x_pinned_url.lastIndexOf('/');
71 return {
72 normal: `${cdn}${x_pinned_url}`,
73 minified: `${cdn}${x_pinned_url.slice(0, lastSlash) + '/min' + x_pinned_url.slice(lastSlash)}`
74 };
75 }
76 catch (e) {
77 console.log(`Error fetching module "${module_id}" from skypack. Returning empty strings`);
78 console.log(e);
79 return { normal: "", minified: "" };
80 }
81}
82
83exports.skypin = skypin;