1 | import rimraf from 'rimraf';
|
2 | import cacache from 'cacache';
|
3 | import globalCacheDir from 'cachedir';
|
4 | import etag from 'etag';
|
5 | import execa from 'execa';
|
6 | import projectCacheDir from 'find-cache-dir';
|
7 | import findUp from 'find-up';
|
8 | import fs from 'fs';
|
9 | import got from 'got';
|
10 | import open from 'open';
|
11 | import path from 'path';
|
12 | import mkdirp from 'mkdirp';
|
13 | export const PIKA_CDN = `https://cdn.pika.dev`;
|
14 | export const GLOBAL_CACHE_DIR = globalCacheDir('snowpack');
|
15 | export const RESOURCE_CACHE = path.join(GLOBAL_CACHE_DIR, 'pkg-cache-1.4');
|
16 | export const BUILD_CACHE = path.join(GLOBAL_CACHE_DIR, 'build-cache-1.4');
|
17 | export const PROJECT_CACHE_DIR = projectCacheDir({ name: 'snowpack' });
|
18 | export const DEV_DEPENDENCIES_DIR = path.join(PROJECT_CACHE_DIR, 'dev');
|
19 | const LOCKFILE_HASH_FILE = '.hash';
|
20 | export const HAS_CDN_HASH_REGEX = /\-[a-zA-Z0-9]{16,}/;
|
21 |
|
22 | export const HTML_JS_REGEX = /(<script.*?>)(.*?)<\/script>/gms;
|
23 | export function isYarn(cwd) {
|
24 | return fs.existsSync(path.join(cwd, 'yarn.lock'));
|
25 | }
|
26 | export async function readLockfile(cwd) {
|
27 | try {
|
28 | var lockfileContents = fs.readFileSync(path.join(cwd, 'snowpack.lock.json'), {
|
29 | encoding: 'utf8',
|
30 | });
|
31 | }
|
32 | catch (err) {
|
33 |
|
34 | return null;
|
35 | }
|
36 |
|
37 | return JSON.parse(lockfileContents);
|
38 | }
|
39 | export async function writeLockfile(loc, importMap) {
|
40 | const sortedImportMap = { imports: {} };
|
41 | for (const key of Object.keys(importMap.imports).sort()) {
|
42 | sortedImportMap.imports[key] = importMap.imports[key];
|
43 | }
|
44 | fs.writeFileSync(loc, JSON.stringify(sortedImportMap, undefined, 2), { encoding: 'utf8' });
|
45 | }
|
46 | export function fetchCDNResource(resourceUrl, responseType) {
|
47 | if (!resourceUrl.startsWith(PIKA_CDN)) {
|
48 | resourceUrl = PIKA_CDN + resourceUrl;
|
49 | }
|
50 |
|
51 | return got(resourceUrl, {
|
52 | responseType: responseType,
|
53 | headers: { 'user-agent': `snowpack/v1.4 (https://snowpack.dev)` },
|
54 | throwHttpErrors: false,
|
55 | });
|
56 | }
|
57 | export function isTruthy(item) {
|
58 | return Boolean(item);
|
59 | }
|
60 |
|
61 | export function parsePackageImportSpecifier(imp) {
|
62 | const impParts = imp.split('/');
|
63 | if (imp.startsWith('@')) {
|
64 | const [scope, name, ...rest] = impParts;
|
65 | return [`${scope}/${name}`, rest.join('/') || null];
|
66 | }
|
67 | const [name, ...rest] = impParts;
|
68 | return [name, rest.join('/') || null];
|
69 | }
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 | export function resolveDependencyManifest(dep, cwd) {
|
79 |
|
80 |
|
81 |
|
82 |
|
83 | try {
|
84 | const depManifest = require.resolve(`${dep}/package.json`, { paths: [cwd] });
|
85 | return [depManifest, require(depManifest)];
|
86 | }
|
87 | catch (err) {
|
88 |
|
89 | if (err.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED') {
|
90 | return [null, null];
|
91 | }
|
92 | }
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 | let result = [null, null];
|
99 | try {
|
100 | const fullPath = require.resolve(dep, { paths: [cwd] });
|
101 |
|
102 |
|
103 | const searchPath = `${path.sep}node_modules${path.sep}${dep.replace('/', path.sep)}`;
|
104 | const indexOfSearch = fullPath.lastIndexOf(searchPath);
|
105 | if (indexOfSearch >= 0) {
|
106 | const manifestPath = fullPath.substring(0, indexOfSearch + searchPath.length + 1) + 'package.json';
|
107 | result[0] = manifestPath;
|
108 | const manifestStr = fs.readFileSync(manifestPath, { encoding: 'utf8' });
|
109 | result[1] = JSON.parse(manifestStr);
|
110 | }
|
111 | }
|
112 | catch (err) {
|
113 |
|
114 | }
|
115 | finally {
|
116 | return result;
|
117 | }
|
118 | }
|
119 |
|
120 |
|
121 |
|
122 |
|
123 | export const MISSING_PLUGIN_SUGGESTIONS = {
|
124 | '.svelte': 'Try installing rollup-plugin-svelte and adding it to Snowpack (https://www.snowpack.dev/#custom-rollup-plugins)',
|
125 | '.vue': 'Try installing rollup-plugin-vue and adding it to Snowpack (https://www.snowpack.dev/#custom-rollup-plugins)',
|
126 | };
|
127 | const appNames = {
|
128 | win32: {
|
129 | brave: 'brave',
|
130 | chrome: 'chrome',
|
131 | },
|
132 | darwin: {
|
133 | brave: 'Brave Browser',
|
134 | chrome: 'Google Chrome',
|
135 | },
|
136 | linux: {
|
137 | brave: 'brave',
|
138 | chrome: 'google-chrome',
|
139 | },
|
140 | };
|
141 | export async function openInBrowser(protocol, port, browser) {
|
142 | const url = `${protocol}//localhost:${port}`;
|
143 | browser = /chrome/i.test(browser)
|
144 | ? appNames[process.platform]['chrome']
|
145 | : /brave/i.test(browser)
|
146 | ? appNames[process.platform]['brave']
|
147 | : browser;
|
148 | if (process.platform === 'darwin' && /chrome|default/i.test(browser)) {
|
149 |
|
150 |
|
151 |
|
152 | try {
|
153 | await execa.command('ps cax | grep "Google Chrome"', {
|
154 | shell: true,
|
155 | });
|
156 | await execa('osascript ../assets/openChrome.applescript "' + encodeURI(url) + '"', {
|
157 | cwd: __dirname,
|
158 | stdio: 'ignore',
|
159 | shell: true,
|
160 | });
|
161 | return true;
|
162 | }
|
163 | catch (err) {
|
164 |
|
165 | open(url);
|
166 | }
|
167 | }
|
168 | else {
|
169 | browser === 'default' ? open(url) : open(url, { app: browser });
|
170 | }
|
171 | }
|
172 | export async function checkLockfileHash(dir) {
|
173 | const lockfileLoc = await findUp(['package-lock.json', 'yarn.lock']);
|
174 | if (!lockfileLoc) {
|
175 | return true;
|
176 | }
|
177 | const hashLoc = path.join(dir, LOCKFILE_HASH_FILE);
|
178 | const newLockHash = etag(await fs.promises.readFile(lockfileLoc, 'utf-8'));
|
179 | const oldLockHash = await fs.promises.readFile(hashLoc, 'utf-8').catch(() => '');
|
180 | return newLockHash === oldLockHash;
|
181 | }
|
182 | export async function updateLockfileHash(dir) {
|
183 | const lockfileLoc = await findUp(['package-lock.json', 'yarn.lock']);
|
184 | if (!lockfileLoc) {
|
185 | return;
|
186 | }
|
187 | const hashLoc = path.join(dir, LOCKFILE_HASH_FILE);
|
188 | const newLockHash = etag(await fs.promises.readFile(lockfileLoc));
|
189 | await mkdirp(path.dirname(hashLoc));
|
190 | await fs.promises.writeFile(hashLoc, newLockHash);
|
191 | }
|
192 | export async function clearCache() {
|
193 | return Promise.all([
|
194 | cacache.rm.all(RESOURCE_CACHE),
|
195 | cacache.rm.all(BUILD_CACHE),
|
196 | rimraf.sync(PROJECT_CACHE_DIR),
|
197 | ]);
|
198 | }
|
199 |
|
200 |
|
201 |
|
202 |
|
203 |
|
204 |
|
205 | export function findMatchingMountScript(scripts, spec) {
|
206 |
|
207 | if (spec.startsWith('./') ||
|
208 | spec.startsWith('../') ||
|
209 | spec.startsWith('/') ||
|
210 | spec.startsWith('http://') ||
|
211 | spec.startsWith('https://')) {
|
212 | return null;
|
213 | }
|
214 | return scripts
|
215 | .filter((script) => script.type === 'mount')
|
216 | .find(({ args }) => spec.startsWith(args.fromDisk));
|
217 | }
|
218 |
|
219 | export function getExt(fileName) {
|
220 | return {
|
221 |
|
222 | baseExt: path.extname(fileName).toLocaleLowerCase(),
|
223 |
|
224 | expandedExt: path.basename(fileName).replace(/[^.]+/, '').toLocaleLowerCase(),
|
225 | };
|
226 | }
|