-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
find-source.js
74 lines (59 loc) · 2.12 KB
/
find-source.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import fs from 'node:fs/promises';
import path from 'node:path';
import process from 'node:process';
const isZip = filepath => path.extname(filepath) === '.zip';
// Node hates race conditons and ease of use
// https://github.com/nodejs/node/issues/39960#issuecomment-909444667
async function exists(f) {
try {
await fs.stat(f);
return true;
} catch {
return false;
}
}
async function processDirectory(resolvedPath, errorStart = 'The') {
if (!await exists(resolvedPath)) {
throw new Error(`${errorStart} directory was not found: ${resolvedPath}`);
}
const manifestPath = path.join(resolvedPath, 'manifest.json');
if (!await exists(manifestPath)) {
throw new Error(`${errorStart} directory does not contain manifest.json: ${resolvedPath}`);
}
let manifest;
try {
manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'));
if (typeof manifest.manifest_version === 'number') {
return resolvedPath;
}
} catch {}
throw new Error(`${errorStart} directory does not contain a valid manifest.json: ${resolvedPath}`);
}
async function getPathFromPackageJson() {
const cwd = process.cwd();
const packageJsonPath = path.join(cwd, 'package.json');
if (!await exists(packageJsonPath)) {
return undefined;
}
const pkg = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));
if (!pkg.webExt?.sourceDir) {
return undefined;
}
const resolvedPath = path.resolve(cwd, pkg.webExt.sourceDir);
return processDirectory(resolvedPath, 'Reading webExt.sourceDir from package.json, the');
}
export default async function findSource(flag) {
const cwd = process.cwd();
if (flag) {
const resolvedPath = path.resolve(cwd, flag);
if (!isZip(resolvedPath)) {
return processDirectory(resolvedPath);
}
if (!await exists(resolvedPath)) {
throw new Error(`Zipped extension not found: ${resolvedPath}`);
}
return resolvedPath;
}
return await getPathFromPackageJson()
?? processDirectory(cwd, 'Using the cwd, the');
}