-
Notifications
You must be signed in to change notification settings - Fork 381
Expand file tree
/
Copy pathbuild.js
More file actions
324 lines (288 loc) · 9.49 KB
/
Copy pathbuild.js
File metadata and controls
324 lines (288 loc) · 9.49 KB
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import path from 'path';
import { createWriteStream } from 'fs';
import fs from 'fs/promises';
import parseJSON from 'parse-json';
import stripBom from 'strip-bom';
import defaultFromEvent from 'promise-toolbox/fromEvent';
import JSZip from 'jszip';
import defaultSourceWatcher from '../watcher.js';
import getValidatedManifest, { getManifestId } from '../util/manifest.js';
import { prepareArtifactsDir } from '../util/artifacts.js';
import { createLogger } from '../util/logger.js';
import { UsageError, isErrorWithCode } from '../errors.js';
import { createFileFilter as defaultFileFilterCreator } from '../util/file-filter.js';
const log = createLogger(import.meta.url);
const DEFAULT_FILENAME_TEMPLATE = '{name}-{version}.zip';
// 1980-01-01 UTC — the earliest timestamp representable in a ZIP entry.
const ZIP_EPOCH_SECONDS = 315532800;
// Build a ZIP buffer with deterministic byte output: entries are sorted
// alphabetically, and every entry's timestamp is fixed (overridable via the
// SOURCE_DATE_EPOCH environment variable, per the Reproducible Builds spec).
export async function createDeterministicZip(sourceDir, { filter } = {}) {
const epochSeconds = process.env.SOURCE_DATE_EPOCH
? Number(process.env.SOURCE_DATE_EPOCH)
: ZIP_EPOCH_SECONDS;
if (!Number.isFinite(epochSeconds)) {
throw new UsageError(
`Invalid SOURCE_DATE_EPOCH value: ${process.env.SOURCE_DATE_EPOCH}`,
);
}
const fixedDate = new Date(epochSeconds * 1000);
const resolvedRoot = path.resolve(sourceDir);
const entries = [];
async function walk(dir) {
const dirents = await fs.readdir(dir, { withFileTypes: true });
dirents.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
for (const dirent of dirents) {
const full = path.join(dir, dirent.name);
const stat = await fs.lstat(full);
if (filter && !filter(full, stat)) {
continue;
}
if (dirent.isDirectory()) {
entries.push({ full, isDir: true });
await walk(full);
} else if (dirent.isFile()) {
entries.push({ full, isDir: false });
}
}
}
await walk(resolvedRoot);
const zip = new JSZip();
for (const entry of entries) {
// ZIP entries always use forward slashes, regardless of host OS.
const relative = path
.relative(resolvedRoot, entry.full)
.split(path.sep)
.join('/');
// `createFolders: false` keeps JSZip from injecting parent-folder
// entries with a current-time `Date()`. The walk above already emits
// every directory explicitly, so we control all entry timestamps.
if (entry.isDir) {
zip.file(relative, null, {
dir: true,
date: fixedDate,
createFolders: false,
});
} else {
const data = await fs.readFile(entry.full);
zip.file(relative, data, { date: fixedDate, createFolders: false });
}
}
// platform: 'UNIX' fixes the external-attribute byte; without it JSZip
// derives it from process.platform, which would make the same source
// produce different bytes on Windows vs Linux.
return zip.generateAsync({
compression: 'DEFLATE',
type: 'nodebuffer',
platform: 'UNIX',
});
}
export function safeFileName(name) {
return name.toLowerCase().replace(/[^a-z0-9.-]+/g, '_');
}
// defaultPackageCreator types and implementation.
// This defines the _locales/messages.json type. See:
// https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Internationalization#Providing_localized_strings_in__locales
export async function getDefaultLocalizedName({ messageFile, manifestData }) {
let messageData;
let messageContents;
let extensionName = manifestData.name;
try {
messageContents = await fs.readFile(messageFile, { encoding: 'utf-8' });
} catch (error) {
throw new UsageError(
`Error reading messages.json file at ${messageFile}: ${error}`,
);
}
messageContents = stripBom(messageContents);
const { default: stripJsonComments } = await import('strip-json-comments');
try {
messageData = parseJSON(stripJsonComments(messageContents));
} catch (error) {
throw new UsageError(
`Error parsing messages.json file at ${messageFile}: ${error}`,
);
}
extensionName = manifestData.name.replace(
/__MSG_([A-Za-z0-9@_]+?)__/g,
(match, messageName) => {
if (!(messageData[messageName] && messageData[messageName].message)) {
const error = new UsageError(
`The locale file ${messageFile} ` + `is missing key: ${messageName}`,
);
throw error;
} else {
return messageData[messageName].message;
}
},
);
return Promise.resolve(extensionName);
}
// https://stackoverflow.com/a/22129960
export function getStringPropertyValue(prop, obj) {
const properties = prop.split('.');
const value = properties.reduce((prev, curr) => prev && prev[curr], obj);
if (!['string', 'number'].includes(typeof value)) {
throw new UsageError(
`Manifest key "${prop}" is missing or has an invalid type: ${value}`,
);
}
const stringValue = `${value}`;
if (!stringValue.length) {
throw new UsageError(`Manifest key "${prop}" value is an empty string`);
}
return stringValue;
}
function getPackageNameFromTemplate(filenameTemplate, manifestData) {
const packageName = filenameTemplate.replace(
/{([A-Za-z0-9._]+?)}/g,
(match, manifestProperty) => {
return safeFileName(
getStringPropertyValue(manifestProperty, manifestData),
);
},
);
// Validate the resulting packageName string, after interpolating the manifest property
// specified in the template string.
const parsed = path.parse(packageName);
if (parsed.dir) {
throw new UsageError(
`Invalid filename template "${filenameTemplate}". ` +
`Filename "${packageName}" should not contain a path`,
);
}
if (!['.zip', '.xpi'].includes(parsed.ext)) {
throw new UsageError(
`Invalid filename template "${filenameTemplate}". ` +
`Filename "${packageName}" should have a zip or xpi extension`,
);
}
return packageName;
}
export async function defaultPackageCreator(
{
manifestData,
sourceDir,
fileFilter,
artifactsDir,
overwriteDest,
showReadyMessage,
filename = DEFAULT_FILENAME_TEMPLATE,
},
{ fromEvent = defaultFromEvent } = {},
) {
let id;
if (manifestData) {
id = getManifestId(manifestData);
log.debug(`Using manifest id=${id || '[not specified]'}`);
} else {
manifestData = await getValidatedManifest(sourceDir);
}
const buffer = await createDeterministicZip(sourceDir, {
filter: (...args) => fileFilter.wantFile(...args),
});
let filenameTemplate = filename;
let { default_locale } = manifestData;
if (default_locale) {
default_locale = default_locale.replace(/-/g, '_');
const messageFile = path.join(
sourceDir,
'_locales',
default_locale,
'messages.json',
);
log.debug('Manifest declared default_locale, localizing extension name');
const extensionName = await getDefaultLocalizedName({
messageFile,
manifestData,
});
// allow for a localized `{name}`, without mutating `manifestData`
filenameTemplate = filenameTemplate.replace(/{name}/g, extensionName);
}
const packageName = safeFileName(
getPackageNameFromTemplate(filenameTemplate, manifestData),
);
const extensionPath = path.join(artifactsDir, packageName);
// Added 'wx' flags to avoid overwriting of existing package.
const stream = createWriteStream(extensionPath, { flags: 'wx' });
stream.write(buffer, () => {
stream.end();
});
try {
await fromEvent(stream, 'close');
} catch (error) {
if (!isErrorWithCode('EEXIST', error)) {
throw error;
}
if (!overwriteDest) {
throw new UsageError(
`Extension exists at the destination path: ${extensionPath}\n` +
'Use --overwrite-dest to enable overwriting.',
);
}
log.info(`Destination exists, overwriting: ${extensionPath}`);
const overwriteStream = createWriteStream(extensionPath);
overwriteStream.write(buffer, () => {
overwriteStream.end();
});
await fromEvent(overwriteStream, 'close');
}
if (showReadyMessage) {
log.info(`Your web extension is ready: ${extensionPath}`);
}
return { extensionPath };
}
// Build command types and implementation.
export default async function build(
{
sourceDir,
artifactsDir,
asNeeded = false,
overwriteDest = false,
ignoreFiles = [],
filename = DEFAULT_FILENAME_TEMPLATE,
},
{
manifestData,
createFileFilter = defaultFileFilterCreator,
fileFilter = createFileFilter({
sourceDir,
artifactsDir,
ignoreFiles,
}),
onSourceChange = defaultSourceWatcher,
packageCreator = defaultPackageCreator,
showReadyMessage = true,
} = {},
) {
const rebuildAsNeeded = asNeeded; // alias for `build --as-needed`
log.info(`Building web extension from ${sourceDir}`);
const createPackage = () =>
packageCreator({
manifestData,
sourceDir,
fileFilter,
artifactsDir,
overwriteDest,
showReadyMessage,
filename,
});
await prepareArtifactsDir(artifactsDir);
const result = await createPackage();
if (rebuildAsNeeded) {
log.info('Rebuilding when files change...');
onSourceChange({
sourceDir,
artifactsDir,
onChange: () => {
return createPackage().catch((error) => {
log.error(error.stack);
throw error;
});
},
shouldWatchFile: (...args) => fileFilter.wantFile(...args),
});
}
return result;
}