-
Notifications
You must be signed in to change notification settings - Fork 102
/
zip.ts
197 lines (181 loc) · 6.05 KB
/
zip.ts
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import { InlineConfig } from '~/types';
import path from 'node:path';
import fs from 'fs-extra';
import { kebabCaseAlphanumeric } from '~/core/utils/strings';
import { getPackageJson } from '~/core/utils/package';
import { minimatch } from 'minimatch';
import { formatDuration } from '~/core/utils/time';
import { printFileList } from '~/core/utils/log/printFileList';
import { internalBuild } from '~/core/utils/building';
import { registerWxt, wxt } from './wxt';
import JSZip from 'jszip';
import glob from 'fast-glob';
import { normalizePath } from './utils/paths';
/**
* Build and zip the extension for distribution.
* @param config Optional config that will override your `<root>/wxt.config.ts`.
* @returns A list of all files included in the ZIP.
*/
export async function zip(config?: InlineConfig): Promise<string[]> {
await registerWxt('build', config);
const output = await internalBuild();
const start = Date.now();
wxt.logger.info('Zipping extension...');
const zipFiles: string[] = [];
const projectName =
wxt.config.zip.name ??
kebabCaseAlphanumeric(
(await getPackageJson())?.name || path.dirname(process.cwd()),
);
const applyTemplate = (template: string): string =>
template
.replaceAll('{{name}}', projectName)
.replaceAll('{{browser}}', wxt.config.browser)
.replaceAll(
'{{version}}',
output.manifest.version_name ?? output.manifest.version,
)
.replaceAll('{{mode}}', wxt.config.mode)
.replaceAll('{{manifestVersion}}', `mv${wxt.config.manifestVersion}`);
await fs.ensureDir(wxt.config.outBaseDir);
// ZIP output directory
const outZipFilename = applyTemplate(wxt.config.zip.artifactTemplate);
const outZipPath = path.resolve(wxt.config.outBaseDir, outZipFilename);
await zipDir(wxt.config.outDir, outZipPath);
zipFiles.push(outZipPath);
// ZIP sources for Firefox
if (wxt.config.browser === 'firefox') {
const { overrides, files: downloadedPackages } =
await downloadPrivatePackages();
const sourcesZipFilename = applyTemplate(wxt.config.zip.sourcesTemplate);
const sourcesZipPath = path.resolve(
wxt.config.outBaseDir,
sourcesZipFilename,
);
await zipDir(wxt.config.zip.sourcesRoot, sourcesZipPath, {
include: wxt.config.zip.includeSources,
exclude: wxt.config.zip.excludeSources,
transform(absolutePath, zipPath, content) {
if (zipPath.endsWith('package.json')) {
return addOverridesToPackageJson(absolutePath, content, overrides);
}
},
additionalFiles: downloadedPackages,
});
zipFiles.push(sourcesZipPath);
}
await printFileList(
wxt.logger.success,
`Zipped extension in ${formatDuration(Date.now() - start)}`,
wxt.config.outBaseDir,
zipFiles,
);
return zipFiles;
}
async function zipDir(
directory: string,
outputPath: string,
options?: {
include?: string[];
exclude?: string[];
transform?: (
absolutePath: string,
zipPath: string,
content: string,
) => Promise<string | undefined | void> | string | undefined | void;
additionalWork?: (archive: JSZip) => Promise<void> | void;
additionalFiles?: string[];
},
): Promise<void> {
const archive = new JSZip();
const files = (
await glob('**/*', {
cwd: directory,
// Ignore node_modules, otherwise this glob step takes forever
ignore: ['**/node_modules'],
onlyFiles: true,
})
).filter((relativePath) => {
return (
wxt.config.zip.includeSources.some((pattern) =>
minimatch(relativePath, pattern),
) ||
!wxt.config.zip.excludeSources.some((pattern) =>
minimatch(relativePath, pattern),
)
);
});
const filesToZip = [
...files,
...(options?.additionalFiles ?? []).map((file) =>
path.relative(directory, file),
),
];
for (const file of filesToZip) {
const absolutePath = path.resolve(directory, file);
if (file.endsWith('.json')) {
const content = await fs.readFile(absolutePath, 'utf-8');
archive.file(
file,
(await options?.transform?.(absolutePath, file, content)) || content,
);
} else {
const content = await fs.readFile(absolutePath);
archive.file(file, content);
}
}
await options?.additionalWork?.(archive);
const buffer = await archive.generateAsync({
type: 'base64',
...(wxt.config.zip.compressionLevel === 0
? { compression: 'STORE' }
: {
compression: 'DEFLATE',
compressionOptions: { level: wxt.config.zip.compressionLevel },
}),
});
await fs.writeFile(outputPath, buffer, 'base64');
}
async function downloadPrivatePackages() {
const overrides: Record<string, string> = {};
const files: string[] = [];
if (wxt.config.zip.downloadPackages.length > 0) {
const _downloadPackages = new Set(wxt.config.zip.downloadPackages);
const allPackages = await wxt.pm.listDependencies({
all: true,
cwd: wxt.config.root,
});
const downloadPackages = allPackages.filter((pkg) =>
_downloadPackages.has(pkg.name),
);
for (const pkg of downloadPackages) {
wxt.logger.info(`Downloading package: ${pkg.name}@${pkg.version}`);
const id = `${pkg.name}@${pkg.version}`;
const tgzPath = await wxt.pm.downloadDependency(
id,
wxt.config.zip.downloadedPackagesDir,
);
files.push(tgzPath);
overrides[id] = tgzPath;
}
}
return { overrides, files };
}
function addOverridesToPackageJson(
absolutePackageJsonPath: string,
content: string,
overrides: Record<string, string>,
): string {
if (Object.keys(overrides).length === 0) return content;
const packageJsonDir = path.dirname(absolutePackageJsonPath);
const oldPackage = JSON.parse(content);
const newPackage = {
...oldPackage,
[wxt.pm.overridesKey]: { ...oldPackage[wxt.pm.overridesKey] },
};
Object.entries(overrides).forEach(([key, absolutePath]) => {
newPackage[wxt.pm.overridesKey][key] =
'file://./' + normalizePath(path.relative(packageJsonDir, absolutePath));
});
return JSON.stringify(newPackage, null, 2);
}