@kubohiroya/sb3-toolchain 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.ja.md +17 -1
  3. package/README.md +17 -1
  4. package/dist/archive.d.ts +1 -0
  5. package/dist/archive.js +16 -0
  6. package/dist/archive.js.map +1 -0
  7. package/dist/assert.d.ts +2 -0
  8. package/dist/assert.js +11 -0
  9. package/dist/assert.js.map +1 -0
  10. package/dist/bin.d.ts +1 -0
  11. package/dist/bin.js +12 -0
  12. package/dist/bin.js.map +1 -0
  13. package/dist/build.d.ts +23 -0
  14. package/dist/build.js +111 -0
  15. package/dist/build.js.map +1 -0
  16. package/dist/cli.d.ts +87 -0
  17. package/dist/cli.js +544 -0
  18. package/dist/cli.js.map +1 -0
  19. package/dist/constants.d.ts +2 -0
  20. package/dist/constants.js +7 -0
  21. package/dist/constants.js.map +1 -0
  22. package/dist/extension-api-manifest.d.ts +46 -0
  23. package/dist/extension-api-manifest.js +211 -0
  24. package/dist/extension-api-manifest.js.map +1 -0
  25. package/dist/extension-bundle-archive.d.ts +36 -0
  26. package/dist/extension-bundle-archive.js +302 -0
  27. package/dist/extension-bundle-archive.js.map +1 -0
  28. package/dist/extension-bundle-configuration.d.ts +55 -0
  29. package/dist/extension-bundle-configuration.js +200 -0
  30. package/dist/extension-bundle-configuration.js.map +1 -0
  31. package/dist/extension-bundle.d.ts +39 -0
  32. package/dist/extension-bundle.js +580 -0
  33. package/dist/extension-bundle.js.map +1 -0
  34. package/dist/extension-dependencies.d.ts +18 -0
  35. package/dist/extension-dependencies.js +59 -0
  36. package/dist/extension-dependencies.js.map +1 -0
  37. package/dist/extension-id-migration.d.ts +83 -0
  38. package/dist/extension-id-migration.js +292 -0
  39. package/dist/extension-id-migration.js.map +1 -0
  40. package/dist/extension-sync.d.ts +111 -0
  41. package/dist/extension-sync.js +463 -0
  42. package/dist/extension-sync.js.map +1 -0
  43. package/dist/import.d.ts +39 -0
  44. package/dist/import.js +244 -0
  45. package/dist/import.js.map +1 -0
  46. package/dist/index.d.ts +31 -0
  47. package/dist/index.js +18 -0
  48. package/dist/npm-extension-source.d.ts +13 -0
  49. package/dist/npm-extension-source.js +63 -0
  50. package/dist/npm-extension-source.js.map +1 -0
  51. package/dist/output-safety.d.ts +29 -0
  52. package/dist/output-safety.js +213 -0
  53. package/dist/output-safety.js.map +1 -0
  54. package/dist/project-asset-additions.d.ts +29 -0
  55. package/dist/project-asset-additions.js +412 -0
  56. package/dist/project-asset-additions.js.map +1 -0
  57. package/dist/release-snapshot.d.ts +75 -0
  58. package/dist/release-snapshot.js +177 -0
  59. package/dist/release-snapshot.js.map +1 -0
  60. package/dist/source.d.ts +41 -0
  61. package/dist/source.js +282 -0
  62. package/dist/source.js.map +1 -0
  63. package/dist/turbowarp-clean-up.d.ts +18 -0
  64. package/dist/turbowarp-clean-up.js +266 -0
  65. package/dist/turbowarp-clean-up.js.map +1 -0
  66. package/dist/types.d.ts +80 -0
  67. package/package.json +29 -21
  68. package/bin/sb3-toolchain.mjs +0 -9
  69. package/src/archive.js +0 -35
  70. package/src/build.js +0 -188
  71. package/src/cli.js +0 -748
  72. package/src/constants.js +0 -4
  73. package/src/extension-api-manifest.js +0 -336
  74. package/src/extension-bundle-archive.js +0 -422
  75. package/src/extension-bundle-configuration.js +0 -265
  76. package/src/extension-bundle.js +0 -695
  77. package/src/extension-dependencies.js +0 -114
  78. package/src/extension-id-migration.js +0 -496
  79. package/src/extension-sync.js +0 -754
  80. package/src/import.js +0 -397
  81. package/src/index.js +0 -75
  82. package/src/npm-extension-source.js +0 -111
  83. package/src/output-safety.js +0 -322
  84. package/src/project-asset-additions.js +0 -560
  85. package/src/release-snapshot.js +0 -247
  86. package/src/source.js +0 -468
  87. package/src/turbowarp-clean-up.js +0 -295
@@ -1,422 +0,0 @@
1
- // SPDX-License-Identifier: MPL-2.0
2
-
3
- import {lstat, readFile} from 'node:fs/promises';
4
- import path from 'node:path';
5
-
6
- import {strFromU8, strToU8, unzipSync, zipSync} from 'fflate';
7
-
8
- import {validateArchiveEntryName} from './archive.js';
9
- import {writeSb3Archive} from './build.js';
10
- import {extensionBundleRecoveryMarker} from './extension-bundle.js';
11
- import {extensionHeaderMetadata} from './extension-dependencies.js';
12
- import {decodeExtensionDataUrl} from './import.js';
13
- import {fixedZipTimestamp} from './source.js';
14
-
15
- function assert(condition, message) {
16
- if (!condition) throw new Error(message);
17
- }
18
-
19
- function isObject(value) {
20
- return value && typeof value === 'object' && !Array.isArray(value);
21
- }
22
-
23
- function arraysEqual(left, right) {
24
- return JSON.stringify(left) === JSON.stringify(right);
25
- }
26
-
27
- function validateId(id, description) {
28
- assert(
29
- typeof id === 'string' && /^[a-z0-9]+$/u.test(id),
30
- `${description} must use TurboWarp's [a-z0-9]+ format: ${JSON.stringify(id)}`,
31
- );
32
- return id;
33
- }
34
-
35
- function decodeBase64Json(payload, description) {
36
- assert(
37
- typeof payload === 'string' && /^[A-Za-z0-9+/]*={0,2}$/u.test(payload),
38
- `${description} contains invalid base64.`,
39
- );
40
- const unpadded = payload.replace(/=+$/u, '');
41
- assert(unpadded.length % 4 !== 1, `${description} contains invalid base64.`);
42
- try {
43
- return JSON.parse(
44
- Buffer.from(unpadded.padEnd(Math.ceil(unpadded.length / 4) * 4, '='), 'base64').toString(
45
- 'utf8',
46
- ),
47
- );
48
- } catch (error) {
49
- throw new Error(`${description} contains invalid JSON: ${error.message}`, {cause: error});
50
- }
51
- }
52
-
53
- function recoveryPayloadFromSource(source, requiredBundleId = undefined) {
54
- const prefix = `// ${extensionBundleRecoveryMarker}: `;
55
- const payloads = source
56
- .split(/\r?\n/u)
57
- .filter((line) => line.startsWith(prefix))
58
- .map((line) => line.slice(prefix.length));
59
- if (payloads.length === 0) {
60
- assert(
61
- requiredBundleId === undefined,
62
- `Extension ${requiredBundleId} has no ${extensionBundleRecoveryMarker} recovery capsule.`,
63
- );
64
- return null;
65
- }
66
- assert(payloads.length === 1, 'Bundled extension contains more than one recovery capsule.');
67
- return payloads[0];
68
- }
69
-
70
- function validateOriginalOrder(value, description, nullable = false) {
71
- if (nullable && value === null) return null;
72
- assert(
73
- Array.isArray(value) && value.every((id) => typeof id === 'string' && id.length > 0),
74
- `Recovery capsule ${description} must be an array of IDs${nullable ? ' or null' : ''}.`,
75
- );
76
- assert(
77
- new Set(value).size === value.length,
78
- `Recovery capsule ${description} contains duplicate IDs.`,
79
- );
80
- return [...value];
81
- }
82
-
83
- function readRecoveryCapsule(extensionId, dataUrl, required = false) {
84
- assert(typeof dataUrl === 'string', `Extension URL for ${extensionId} must be a string.`);
85
- if (!dataUrl.startsWith('data:')) {
86
- assert(!required, `Extension ${extensionId} is not embedded as a data URL.`);
87
- return null;
88
- }
89
- const decodedBundle = decodeExtensionDataUrl(dataUrl);
90
- const payload = recoveryPayloadFromSource(
91
- Buffer.from(decodedBundle.source).toString('utf8'),
92
- required ? extensionId : undefined,
93
- );
94
- if (payload === null) return null;
95
- const capsule = decodeBase64Json(payload, `Extension ${extensionId} recovery capsule`);
96
- assert(isObject(capsule), `Extension ${extensionId} recovery capsule must be an object.`);
97
- assert(
98
- capsule.formatVersion === 1,
99
- `Unsupported extension bundle recovery format: ${capsule.formatVersion}`,
100
- );
101
- assert(isObject(capsule.bundle), `Extension ${extensionId} recovery capsule has no bundle.`);
102
- validateId(capsule.bundle.id, 'Recovery capsule bundle ID');
103
- assert(
104
- capsule.bundle.id === extensionId,
105
- `Recovery capsule bundle ID mismatch: expected ${extensionId}, got ${capsule.bundle.id}.`,
106
- );
107
- assert(
108
- typeof capsule.bundle.name === 'string' && capsule.bundle.name.length > 0,
109
- `Recovery capsule for ${extensionId} has no bundle name.`,
110
- );
111
- assert(
112
- Array.isArray(capsule.components) && capsule.components.length >= 2,
113
- `Recovery capsule for ${extensionId} must contain at least two components.`,
114
- );
115
-
116
- const seenIds = new Set();
117
- const components = capsule.components.map((component, index) => {
118
- assert(
119
- isObject(component),
120
- `Recovery component ${index} for ${extensionId} must be an object.`,
121
- );
122
- validateId(component.id, `Recovery component ${index} ID`);
123
- assert(!seenIds.has(component.id), `Recovery capsule repeats component: ${component.id}`);
124
- seenIds.add(component.id);
125
- const decoded = decodeExtensionDataUrl(component.dataUrl);
126
- assert(
127
- decoded.mediaType === 'text/javascript' || decoded.mediaType === 'application/javascript',
128
- `Recovery component ${component.id} must contain JavaScript.`,
129
- );
130
- const metadata = extensionHeaderMetadata(decoded.source);
131
- assert(
132
- metadata.id === component.id,
133
- `Recovery component header ID mismatch: expected ${component.id}, got ${metadata.id ?? '(missing)'}.`,
134
- );
135
- return {dataUrl: component.dataUrl, id: component.id};
136
- });
137
-
138
- return {
139
- bundle: {id: capsule.bundle.id, name: capsule.bundle.name},
140
- components,
141
- members: components.map((component) => component.id),
142
- originalExtensionIds: validateOriginalOrder(
143
- capsule.originalExtensionIds,
144
- 'originalExtensionIds',
145
- true,
146
- ),
147
- originalExtensionUrlIds: validateOriginalOrder(
148
- capsule.originalExtensionUrlIds,
149
- 'originalExtensionUrlIds',
150
- ),
151
- };
152
- }
153
-
154
- function collapseOrder(originalIds, bundles) {
155
- const bundlesByMember = new Map();
156
- for (const bundle of bundles) {
157
- for (const memberId of bundle.members) {
158
- assert(
159
- !bundlesByMember.has(memberId),
160
- `Active extension bundles overlap at member: ${memberId}`,
161
- );
162
- bundlesByMember.set(memberId, bundle.bundle.id);
163
- }
164
- }
165
- const emittedBundles = new Set();
166
- const output = [];
167
- for (const id of originalIds) {
168
- const bundleId = bundlesByMember.get(id);
169
- if (!bundleId) {
170
- output.push(id);
171
- } else if (!emittedBundles.has(bundleId)) {
172
- emittedBundles.add(bundleId);
173
- output.push(bundleId);
174
- }
175
- }
176
- return output;
177
- }
178
-
179
- function replaceBundledStorage(storage, target, counts) {
180
- if (!isObject(storage) || !Object.hasOwn(storage, target.bundle.id)) return storage;
181
- const bundleStorage = storage[target.bundle.id];
182
- assert(
183
- isObject(bundleStorage) &&
184
- bundleStorage.formatVersion === 1 &&
185
- isObject(bundleStorage.components),
186
- `Extension storage for ${target.bundle.id} is not a reversible format 1 bundle.`,
187
- );
188
- assert(
189
- Object.keys(bundleStorage).every((key) => key === 'formatVersion' || key === 'components'),
190
- `Extension storage for ${target.bundle.id} has unsupported bundle-level fields.`,
191
- );
192
- const memberIds = new Set(target.members);
193
- for (const componentId of Object.keys(bundleStorage.components)) {
194
- assert(
195
- memberIds.has(componentId),
196
- `Extension storage for ${target.bundle.id} contains unknown component: ${componentId}`,
197
- );
198
- assert(
199
- !Object.hasOwn(storage, componentId),
200
- `Cannot restore extension storage because member ID already exists: ${componentId}`,
201
- );
202
- }
203
- const replacement = {};
204
- for (const [id, value] of Object.entries(storage)) {
205
- if (id !== target.bundle.id) {
206
- replacement[id] = value;
207
- continue;
208
- }
209
- for (const memberId of target.members) {
210
- if (Object.hasOwn(bundleStorage.components, memberId)) {
211
- replacement[memberId] = bundleStorage.components[memberId];
212
- }
213
- }
214
- }
215
- counts.extensionStorage += 1;
216
- return replacement;
217
- }
218
-
219
- function restoreOpcodeValues(value, target, counts) {
220
- if (!value || typeof value !== 'object') return;
221
- if (Array.isArray(value)) {
222
- for (const entry of value) restoreOpcodeValues(entry, target, counts);
223
- return;
224
- }
225
- for (const [key, entry] of Object.entries(value)) {
226
- if (key === 'opcode' && typeof entry === 'string') {
227
- const bundlePrefix = `${target.bundle.id}_`;
228
- if (!entry.startsWith(bundlePrefix)) continue;
229
- const localOpcode = entry.slice(bundlePrefix.length);
230
- const memberId = target.members.find((id) => localOpcode.startsWith(`${id}__`));
231
- assert(memberId, `Bundle opcode cannot be assigned to a recovery component: ${entry}`);
232
- value[key] = `${memberId}_${localOpcode.slice(memberId.length + 2)}`;
233
- counts.opcodes += 1;
234
- } else {
235
- restoreOpcodeValues(entry, target, counts);
236
- }
237
- }
238
- }
239
-
240
- function collectRemainingBundleReferences(value, bundleId) {
241
- const references = [];
242
- const prefix = `${bundleId}_`;
243
- function visit(current, pointer) {
244
- if (typeof current === 'string') {
245
- if (current.startsWith(prefix)) references.push(pointer || '/');
246
- return;
247
- }
248
- if (!current || typeof current !== 'object') return;
249
- if (Array.isArray(current)) {
250
- current.forEach((entry, index) => visit(entry, `${pointer}/${index}`));
251
- return;
252
- }
253
- for (const [key, entry] of Object.entries(current)) visit(entry, `${pointer}/${key}`);
254
- }
255
- visit(value, '');
256
- return references;
257
- }
258
-
259
- function restoreProject(project, target, activeBundles) {
260
- const restored = structuredClone(project);
261
- const counts = {extensionStorage: 0, extensionUrls: 0, opcodes: 0, projectExtensions: 0};
262
- const remainingBundles = activeBundles.filter((bundle) => bundle.bundle.id !== target.bundle.id);
263
-
264
- assert(isObject(restored.extensionURLs), 'SB3 project.json extensionURLs must be an object.');
265
- const currentUrlIds = Object.keys(restored.extensionURLs);
266
- const expectedUrlIds = collapseOrder(target.originalExtensionUrlIds, activeBundles);
267
- assert(
268
- arraysEqual(currentUrlIds, expectedUrlIds),
269
- `Cannot safely restore extension URL order. Expected ${JSON.stringify(expectedUrlIds)}, ` +
270
- `got ${JSON.stringify(currentUrlIds)}.`,
271
- );
272
- const restoredUrlIds = collapseOrder(target.originalExtensionUrlIds, remainingBundles);
273
- const componentUrls = new Map(
274
- target.components.map((component) => [component.id, component.dataUrl]),
275
- );
276
- restored.extensionURLs = Object.fromEntries(
277
- restoredUrlIds.map((id) => [
278
- id,
279
- componentUrls.has(id) ? componentUrls.get(id) : restored.extensionURLs[id],
280
- ]),
281
- );
282
- counts.extensionUrls = target.members.length + 1;
283
-
284
- if (target.originalExtensionIds === null) {
285
- assert(
286
- restored.extensions === undefined,
287
- 'Cannot safely restore project.extensions because it was added after bundling.',
288
- );
289
- } else {
290
- assert(Array.isArray(restored.extensions), 'SB3 project.json extensions must be an array.');
291
- const expectedIds = collapseOrder(target.originalExtensionIds, activeBundles);
292
- assert(
293
- arraysEqual(restored.extensions, expectedIds),
294
- `Cannot safely restore project.extensions order. Expected ${JSON.stringify(expectedIds)}, ` +
295
- `got ${JSON.stringify(restored.extensions)}.`,
296
- );
297
- restored.extensions = collapseOrder(target.originalExtensionIds, remainingBundles);
298
- counts.projectExtensions = target.members.length + 1;
299
- }
300
-
301
- restored.extensionStorage = replaceBundledStorage(restored.extensionStorage, target, counts);
302
- for (const targetEntry of restored.targets ?? []) {
303
- if (targetEntry) {
304
- targetEntry.extensionStorage = replaceBundledStorage(
305
- targetEntry.extensionStorage,
306
- target,
307
- counts,
308
- );
309
- }
310
- }
311
-
312
- restoreOpcodeValues(restored.targets, target, counts);
313
- restoreOpcodeValues(restored.monitors, target, counts);
314
- const remainingReferences = collectRemainingBundleReferences(restored, target.bundle.id);
315
- assert(
316
- remainingReferences.length === 0,
317
- `Bundle ${target.bundle.id} has unsupported references at: ` +
318
- remainingReferences.slice(0, 8).join(', '),
319
- );
320
- return {counts, project: restored};
321
- }
322
-
323
- function parseProject(projectEntry) {
324
- try {
325
- const project = JSON.parse(strFromU8(projectEntry));
326
- assert(isObject(project), 'SB3 project.json must contain an object.');
327
- return project;
328
- } catch (error) {
329
- if (error.message === 'SB3 project.json must contain an object.') throw error;
330
- throw new Error(`SB3 project.json is invalid JSON: ${error.message}`, {cause: error});
331
- }
332
- }
333
-
334
- async function createArchiveUnbundlePlan({bundleId, inputPath, outputPath}) {
335
- validateId(bundleId, 'Extension bundle ID');
336
- assert(typeof inputPath === 'string', 'Input SB3 path is required.');
337
- assert(typeof outputPath === 'string', 'Unbundled SB3 output path is required.');
338
- const resolvedInputPath = path.resolve(inputPath);
339
- const resolvedOutputPath = path.resolve(outputPath);
340
- assert(
341
- path.extname(resolvedInputPath).toLowerCase() === '.sb3',
342
- `Input path must use the .sb3 extension: ${resolvedInputPath}`,
343
- );
344
- assert(
345
- path.extname(resolvedOutputPath).toLowerCase() === '.sb3',
346
- `Output path must use the .sb3 extension: ${resolvedOutputPath}`,
347
- );
348
- const stats = await lstat(resolvedInputPath);
349
- assert(
350
- stats.isFile() && !stats.isSymbolicLink(),
351
- `Input SB3 must be a regular file, not a symbolic link: ${resolvedInputPath}`,
352
- );
353
- const archiveEntries = unzipSync(new Uint8Array(await readFile(resolvedInputPath)));
354
- const entries = Object.entries(archiveEntries);
355
- assert(entries.length > 0, 'SB3 archive is empty.');
356
- for (const [entryName] of entries) {
357
- validateArchiveEntryName(entryName);
358
- assert(
359
- !/^(?:0|[1-9][0-9]*)$/u.test(entryName),
360
- `Integer-like ZIP entry names cannot preserve archive order: ${entryName}`,
361
- );
362
- }
363
- assert(archiveEntries['project.json'], 'SB3 archive does not contain project.json.');
364
- const project = parseProject(archiveEntries['project.json']);
365
- assert(isObject(project.extensionURLs), 'SB3 project.json extensionURLs must be an object.');
366
-
367
- const activeBundles = [];
368
- for (const [extensionId, dataUrl] of Object.entries(project.extensionURLs)) {
369
- const recovery = readRecoveryCapsule(extensionId, dataUrl, extensionId === bundleId);
370
- if (recovery) activeBundles.push(recovery);
371
- }
372
- const target = activeBundles.find((bundle) => bundle.bundle.id === bundleId);
373
- assert(target, `Reversible extension bundle was not found: ${bundleId}`);
374
- const restored = restoreProject(project, target, activeBundles);
375
- const outputEntries = Object.fromEntries(
376
- entries.map(([entryName, contents]) => [
377
- entryName,
378
- entryName === 'project.json' ? strToU8(`${JSON.stringify(restored.project)}\n`) : contents,
379
- ]),
380
- );
381
- const archive = zipSync(outputEntries, {level: 6, mtime: fixedZipTimestamp});
382
- return {
383
- archive,
384
- bundleId,
385
- counts: restored.counts,
386
- entryCount: entries.length,
387
- inputPath: resolvedInputPath,
388
- members: [...target.members],
389
- outputPath: resolvedOutputPath,
390
- };
391
- }
392
-
393
- function publicArchivePlan(plan) {
394
- return {
395
- bundleId: plan.bundleId,
396
- counts: plan.counts,
397
- entryCount: plan.entryCount,
398
- inputPath: plan.inputPath,
399
- members: plan.members,
400
- outputPath: plan.outputPath,
401
- };
402
- }
403
-
404
- export async function planBundledSb3Unbundle(options) {
405
- const plan = await createArchiveUnbundlePlan(options);
406
- return {applied: false, changed: true, ...publicArchivePlan(plan)};
407
- }
408
-
409
- export async function unbundleSb3({bundleId, inputPath, outputPath, yes = false}) {
410
- const plan = await createArchiveUnbundlePlan({bundleId, inputPath, outputPath});
411
- const publicPlan = publicArchivePlan(plan);
412
- if (!yes) {
413
- return {
414
- applied: false,
415
- changed: true,
416
- ...publicPlan,
417
- rollbackCleanupWarning: null,
418
- };
419
- }
420
- const written = await writeSb3Archive({archive: plan.archive, outputPath: plan.outputPath, yes});
421
- return {applied: true, ...publicPlan, ...written};
422
- }
@@ -1,265 +0,0 @@
1
- // SPDX-License-Identifier: MPL-2.0
2
-
3
- import {cp, lstat, mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';
4
- import path from 'node:path';
5
-
6
- import {
7
- buildExtensionBundles,
8
- validateBundleId,
9
- validateBundleName,
10
- validateExtensionBundleConfigurations,
11
- } from './extension-bundle.js';
12
- import {
13
- assertNoInterruptedRollback,
14
- compareDirectories,
15
- pathExists,
16
- replaceDirectoryTransactionally,
17
- } from './output-safety.js';
18
- import {createDeterministicSb3, inspectSb3SourceForExtensionSync} from './source.js';
19
-
20
- function assert(condition, message) {
21
- if (!condition) {
22
- throw new Error(message);
23
- }
24
- }
25
-
26
- async function inspectConfigurationSource(sourceDirectory, willReplace) {
27
- const resolvedSourceDirectory = path.resolve(sourceDirectory);
28
- if (willReplace) {
29
- assert(
30
- resolvedSourceDirectory !== path.parse(resolvedSourceDirectory).root,
31
- 'Refusing to replace a filesystem root while configuring extension bundles.',
32
- );
33
- assert(
34
- !(await pathExists(path.join(resolvedSourceDirectory, '.git'))),
35
- 'Refusing to replace a Git repository root while configuring extension bundles.',
36
- );
37
- }
38
- const stats = await lstat(resolvedSourceDirectory);
39
- assert(
40
- stats.isDirectory() && !stats.isSymbolicLink(),
41
- `SB3 source must be a directory, not a file or symbolic link: ${resolvedSourceDirectory}`,
42
- );
43
- if (willReplace) await assertNoInterruptedRollback(resolvedSourceDirectory);
44
- return inspectSb3SourceForExtensionSync(resolvedSourceDirectory);
45
- }
46
-
47
- async function readExtensionManifest(source) {
48
- const manifestPath = path.join(
49
- source.resolvedSourceDirectory,
50
- source.sourceManifest.embeddedExtensions,
51
- );
52
- return JSON.parse(await readFile(manifestPath, 'utf8'));
53
- }
54
-
55
- async function configurationContext({
56
- bundleId,
57
- bundleName,
58
- extensionIds,
59
- recoveryCapsule,
60
- sourceDirectory,
61
- willReplace,
62
- }) {
63
- validateBundleId(bundleId);
64
- validateBundleName(bundleName);
65
- assert(typeof recoveryCapsule === 'boolean', 'recoveryCapsule must be a boolean.');
66
- const source = await inspectConfigurationSource(sourceDirectory, willReplace);
67
- const extensionManifest = await readExtensionManifest(source);
68
- const existingBundles = validateExtensionBundleConfigurations(
69
- extensionManifest.extensionBundles,
70
- extensionManifest.extensions,
71
- );
72
- assert(
73
- !existingBundles.some((bundle) => bundle.id === bundleId),
74
- `Extension bundle already exists: ${bundleId}`,
75
- );
76
- const alreadyBundled = new Set(existingBundles.flatMap((bundle) => bundle.members));
77
- const members =
78
- extensionIds && extensionIds.length > 0
79
- ? [...extensionIds]
80
- : source.extensions
81
- .map((extension) => extension.id)
82
- .filter((extensionId) => !alreadyBundled.has(extensionId));
83
- const candidateManifest = structuredClone(extensionManifest);
84
- candidateManifest.extensionBundles = [
85
- ...existingBundles,
86
- {
87
- id: bundleId,
88
- members,
89
- name: bundleName,
90
- ...(recoveryCapsule === true ? {recoveryCapsule: true} : {}),
91
- },
92
- ];
93
- const extensionBundles = validateExtensionBundleConfigurations(
94
- candidateManifest.extensionBundles,
95
- candidateManifest.extensions,
96
- );
97
- const buildPlan = buildExtensionBundles({
98
- extensionBundles,
99
- extensionContents: source.extensionContents,
100
- extensions: source.extensions,
101
- project: source.project,
102
- });
103
- const configuredBundle = buildPlan.bundlePlans.find((plan) => plan.bundle.id === bundleId);
104
- return {buildPlan, candidateManifest, configuredBundle, extensionManifest, source};
105
- }
106
-
107
- export async function planExtensionBundle({
108
- bundleId,
109
- bundleName,
110
- extensionIds,
111
- recoveryCapsule = false,
112
- sourceDirectory,
113
- }) {
114
- const context = await configurationContext({
115
- bundleId,
116
- bundleName,
117
- extensionIds,
118
- recoveryCapsule,
119
- sourceDirectory,
120
- willReplace: false,
121
- });
122
- return {
123
- applied: false,
124
- bundleId,
125
- bundleName,
126
- changed: true,
127
- components: context.configuredBundle.components.map((component) => component.metadata),
128
- counts: context.configuredBundle.counts,
129
- members: [...context.configuredBundle.bundle.members],
130
- recoveryCapsule: context.configuredBundle.bundle.recoveryCapsule === true,
131
- sourceDirectory: context.source.resolvedSourceDirectory,
132
- };
133
- }
134
-
135
- async function installManifestConfiguration(context, operation) {
136
- const initialComparison = await compareDirectories(
137
- context.source.resolvedSourceDirectory,
138
- context.source.resolvedSourceDirectory,
139
- );
140
- assert(
141
- initialComparison.identical &&
142
- initialComparison.existingFingerprint === initialComparison.candidateFingerprint,
143
- `SB3 source changed while its initial ${operation} state was inspected.`,
144
- );
145
- const parentDirectory = path.dirname(context.source.resolvedSourceDirectory);
146
- const candidateDirectory = await mkdtemp(
147
- path.join(parentDirectory, `.${path.basename(context.source.resolvedSourceDirectory)}.bundle-`),
148
- );
149
- let installed = false;
150
- try {
151
- await cp(context.source.resolvedSourceDirectory, candidateDirectory, {
152
- preserveTimestamps: true,
153
- recursive: true,
154
- verbatimSymlinks: true,
155
- });
156
- await writeFile(
157
- path.join(candidateDirectory, context.source.sourceManifest.embeddedExtensions),
158
- `${JSON.stringify(context.candidateManifest, null, 2)}\n`,
159
- );
160
- await createDeterministicSb3(candidateDirectory);
161
- const comparison = await compareDirectories(
162
- context.source.resolvedSourceDirectory,
163
- candidateDirectory,
164
- );
165
- assert(
166
- comparison.existingFingerprint === initialComparison.existingFingerprint,
167
- `SB3 source changed while the ${operation} candidate was prepared; refusing to replace it.`,
168
- );
169
- assert(!comparison.identical, `Extension bundle ${operation} produced no source changes.`);
170
- const latestComparison = await compareDirectories(
171
- context.source.resolvedSourceDirectory,
172
- candidateDirectory,
173
- );
174
- assert(
175
- latestComparison.existingFingerprint === comparison.existingFingerprint &&
176
- latestComparison.candidateFingerprint === comparison.candidateFingerprint,
177
- `SB3 source or ${operation} candidate changed during the operation; refusing to replace it.`,
178
- );
179
- const replacement = await replaceDirectoryTransactionally(
180
- candidateDirectory,
181
- context.source.resolvedSourceDirectory,
182
- );
183
- installed = true;
184
- return {comparison, ...replacement};
185
- } finally {
186
- if (!installed) await rm(candidateDirectory, {recursive: true, force: true});
187
- }
188
- }
189
-
190
- export async function bundleExtensions({
191
- bundleId,
192
- bundleName,
193
- extensionIds,
194
- recoveryCapsule = false,
195
- sourceDirectory,
196
- yes = false,
197
- }) {
198
- const context = await configurationContext({
199
- bundleId,
200
- bundleName,
201
- extensionIds,
202
- recoveryCapsule,
203
- sourceDirectory,
204
- willReplace: yes,
205
- });
206
- const plan = {
207
- bundleId,
208
- bundleName,
209
- components: context.configuredBundle.components.map((component) => component.metadata),
210
- counts: context.configuredBundle.counts,
211
- members: [...context.configuredBundle.bundle.members],
212
- recoveryCapsule: context.configuredBundle.bundle.recoveryCapsule === true,
213
- sourceDirectory: context.source.resolvedSourceDirectory,
214
- };
215
- if (!yes) {
216
- return {applied: false, changed: true, ...plan, rollbackCleanupWarning: null};
217
- }
218
- const installation = await installManifestConfiguration(context, 'configuration');
219
- return {applied: true, changed: true, ...installation, ...plan};
220
- }
221
-
222
- async function unbundleContext({bundleId, sourceDirectory, willReplace}) {
223
- validateBundleId(bundleId);
224
- const source = await inspectConfigurationSource(sourceDirectory, willReplace);
225
- const extensionManifest = await readExtensionManifest(source);
226
- const extensionBundles = validateExtensionBundleConfigurations(
227
- extensionManifest.extensionBundles,
228
- extensionManifest.extensions,
229
- );
230
- const removedBundle = extensionBundles.find((bundle) => bundle.id === bundleId);
231
- assert(removedBundle, `Extension bundle was not found: ${bundleId}`);
232
- const candidateManifest = structuredClone(extensionManifest);
233
- const remainingBundles = extensionBundles.filter((bundle) => bundle.id !== bundleId);
234
- if (remainingBundles.length === 0) {
235
- delete candidateManifest.extensionBundles;
236
- } else {
237
- candidateManifest.extensionBundles = remainingBundles;
238
- }
239
- return {candidateManifest, extensionManifest, removedBundle, source};
240
- }
241
-
242
- export async function planExtensionUnbundle({bundleId, sourceDirectory}) {
243
- const context = await unbundleContext({bundleId, sourceDirectory, willReplace: false});
244
- return {
245
- applied: false,
246
- bundleId,
247
- changed: true,
248
- members: [...context.removedBundle.members],
249
- sourceDirectory: context.source.resolvedSourceDirectory,
250
- };
251
- }
252
-
253
- export async function unbundleExtensions({bundleId, sourceDirectory, yes = false}) {
254
- const context = await unbundleContext({bundleId, sourceDirectory, willReplace: yes});
255
- const plan = {
256
- bundleId,
257
- members: [...context.removedBundle.members],
258
- sourceDirectory: context.source.resolvedSourceDirectory,
259
- };
260
- if (!yes) {
261
- return {applied: false, changed: true, ...plan, rollbackCleanupWarning: null};
262
- }
263
- const installation = await installManifestConfiguration(context, 'removal');
264
- return {applied: true, changed: true, ...installation, ...plan};
265
- }