1 | 'use strict';
|
2 |
|
3 | Object.defineProperty(exports, '__esModule', { value: true });
|
4 |
|
5 | const resolveCwd = require('resolve-cwd');
|
6 | const umap = require('umap');
|
7 | const path = require('path');
|
8 | const escalade = require('escalade');
|
9 | const fetch = require('node-fetch');
|
10 | let cache = umap(new Map);
|
11 | let cdn = "https://cdn.skypack.dev";
|
12 | let default_options = {
|
13 | pin: true,
|
14 | min: true
|
15 | };
|
16 | async 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 |
|
31 | return version || "latest";
|
32 | }
|
33 | catch (e) {
|
34 | return "latest";
|
35 | }
|
36 | }
|
37 | async function skypin(dependency, options) {
|
38 | options = { ...default_options, ...options };
|
39 | if (dependency.startsWith('.') || dependency.startsWith('https://') || dependency.startsWith('http://')) {
|
40 |
|
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 |
|
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 | }
|
57 | async function lookup(module_id, minified = true) {
|
58 | return cache.get(module_id) || cache.set(module_id, (await fetchSkypack(module_id))[minified ? 'minified' : 'normal']);
|
59 | }
|
60 | async 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');
|
64 | let x_import_url = response.headers.get('x-import-url');
|
65 | let x_pinned_url = response.headers.get('x-pinned-url') || x_import_url;
|
66 | if (x_import_status === 'NEW' && x_import_url) {
|
67 | await fetch(`${cdn}${x_import_url}`);
|
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 |
|
83 | exports.skypin = skypin;
|