@kubohiroya/sb3-toolchain 0.11.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 +19 -4
  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 +22 -13
  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,754 +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
- compareExtensionApiManifests,
8
- defaultExtensionApiManifestSizeLimit,
9
- extensionApiManifestIntegrity,
10
- formatExtensionApiCompatibilityChanges,
11
- parseExtensionApiManifest,
12
- validateExtensionApiManifestSourceMetadata,
13
- validateManagedExtensionApiManifest,
14
- } from './extension-api-manifest.js';
15
- import {
16
- extensionHeaderId,
17
- extensionIntegrity,
18
- validateExtensionSourceMetadata,
19
- validateManagedExtensionContents,
20
- } from './extension-dependencies.js';
21
- import {rewriteExtensionIdDocuments, validateNewExtensionId} from './extension-id-migration.js';
22
- import {readNpmExtensionSource} from './npm-extension-source.js';
23
- import {
24
- assertNoInterruptedRollback,
25
- compareDirectories,
26
- pathExists,
27
- replaceDirectoryTransactionally,
28
- } from './output-safety.js';
29
- import {
30
- createDeterministicSb3,
31
- inspectSb3SourceForExtensionSync,
32
- validateSb3Source,
33
- } from './source.js';
34
-
35
- export const defaultExtensionArtifactSizeLimit = 5 * 1024 * 1024;
36
- const githubApiResponseSizeLimit = 1024 * 1024;
37
-
38
- function assert(condition, message) {
39
- if (!condition) {
40
- throw new Error(message);
41
- }
42
- }
43
-
44
- function assertFetch(fetchImplementation) {
45
- assert(
46
- typeof fetchImplementation === 'function',
47
- 'A Fetch API implementation is required for GitHub extension operations.',
48
- );
49
- return fetchImplementation;
50
- }
51
-
52
- function githubHeaders(accept) {
53
- return {
54
- Accept: accept,
55
- 'User-Agent': 'sb3-toolchain',
56
- 'X-GitHub-Api-Version': '2022-11-28',
57
- };
58
- }
59
-
60
- function rawArtifactUrl(source, commit, artifactPath = source.artifact) {
61
- const artifact = artifactPath
62
- .split('/')
63
- .map((segment) => encodeURIComponent(segment))
64
- .join('/');
65
- return `https://raw.githubusercontent.com/${source.repository}/${commit}/${artifact}`;
66
- }
67
-
68
- async function downloadExtensionApiManifest(
69
- extension,
70
- commit,
71
- fetchImplementation,
72
- maximumManifestBytes,
73
- expectedId = extension.id,
74
- ) {
75
- const metadata = validateExtensionApiManifestSourceMetadata(extension);
76
- if (!metadata) return null;
77
- const contents = await fetchBytes(
78
- fetchImplementation,
79
- rawArtifactUrl(extension.source, commit, metadata.artifact),
80
- maximumManifestBytes,
81
- `GitHub extension API manifest download for ${extension.id}`,
82
- 'application/json',
83
- );
84
- const manifest = parseExtensionApiManifest(contents, {expectedId});
85
- return {contents, manifest};
86
- }
87
-
88
- function githubCommitUrl(source) {
89
- return (
90
- `https://api.github.com/repos/${source.repository}/commits/` + encodeURIComponent(source.ref)
91
- );
92
- }
93
-
94
- async function readLimitedResponse(response, maximumBytes, description) {
95
- const contentLength = response.headers?.get?.('content-length');
96
- if (contentLength !== null && contentLength !== undefined) {
97
- const parsedLength = Number(contentLength);
98
- assert(
99
- Number.isSafeInteger(parsedLength) && parsedLength >= 0,
100
- `${description} returned an invalid Content-Length.`,
101
- );
102
- assert(parsedLength <= maximumBytes, `${description} exceeds the ${maximumBytes}-byte limit.`);
103
- }
104
-
105
- if (!response.body?.getReader) {
106
- const contents = Buffer.from(await response.arrayBuffer());
107
- assert(
108
- contents.length <= maximumBytes,
109
- `${description} exceeds the ${maximumBytes}-byte limit.`,
110
- );
111
- return contents;
112
- }
113
-
114
- const reader = response.body.getReader();
115
- const chunks = [];
116
- let totalLength = 0;
117
- try {
118
- while (true) {
119
- const {done, value} = await reader.read();
120
- if (done) break;
121
- totalLength += value.byteLength;
122
- assert(totalLength <= maximumBytes, `${description} exceeds the ${maximumBytes}-byte limit.`);
123
- chunks.push(Buffer.from(value));
124
- }
125
- } catch (error) {
126
- await reader.cancel(error).catch(() => {});
127
- throw error;
128
- }
129
- return Buffer.concat(chunks, totalLength);
130
- }
131
-
132
- async function fetchBytes(fetchImplementation, url, maximumBytes, description, accept) {
133
- const parsedUrl = new URL(url);
134
- assert(parsedUrl.protocol === 'https:', `${description} requires HTTPS.`);
135
- let response;
136
- try {
137
- response = await fetchImplementation(url, {
138
- headers: githubHeaders(accept),
139
- redirect: 'error',
140
- });
141
- } catch (error) {
142
- throw new Error(`${description} request failed: ${error.message}`, {cause: error});
143
- }
144
- assert(
145
- response && typeof response === 'object',
146
- `${description} request returned an invalid response.`,
147
- );
148
- assert(
149
- response.redirected !== true &&
150
- (!response.url || new URL(response.url).href === parsedUrl.href),
151
- `${description} refused a redirected response.`,
152
- );
153
- assert(response.ok, `${description} request failed with HTTP ${response.status ?? '(unknown)'}.`);
154
- return readLimitedResponse(response, maximumBytes, description);
155
- }
156
-
157
- async function resolveGithubCommit(extension, fetchImplementation) {
158
- const source = extension.source;
159
- if (/^[a-f0-9]{40}$/u.test(source.ref)) {
160
- return source.ref;
161
- }
162
- const contents = await fetchBytes(
163
- fetchImplementation,
164
- githubCommitUrl(source),
165
- githubApiResponseSizeLimit,
166
- `GitHub ref lookup for ${extension.id}`,
167
- 'application/vnd.github+json',
168
- );
169
- let response;
170
- try {
171
- response = JSON.parse(contents.toString('utf8'));
172
- } catch (error) {
173
- throw new Error(`GitHub ref lookup for ${extension.id} returned invalid JSON.`, {cause: error});
174
- }
175
- assert(
176
- typeof response?.sha === 'string' && /^[a-f0-9]{40}$/u.test(response.sha),
177
- `GitHub ref lookup for ${extension.id} returned an invalid commit SHA.`,
178
- );
179
- return response.sha;
180
- }
181
-
182
- async function downloadExtension(
183
- extension,
184
- commit,
185
- fetchImplementation,
186
- maximumArtifactBytes,
187
- expectedId = extension.id,
188
- ) {
189
- const contents = await fetchBytes(
190
- fetchImplementation,
191
- rawArtifactUrl(extension.source, commit),
192
- maximumArtifactBytes,
193
- `GitHub artifact download for ${extension.id}`,
194
- 'application/javascript, text/javascript;q=0.9, */*;q=0.1',
195
- );
196
- const actualId = extensionHeaderId(contents);
197
- assert(
198
- actualId === expectedId,
199
- `Downloaded extension header ID mismatch for ${extension.id}: ` +
200
- `expected ${expectedId}, got ${actualId ?? '(missing)'}`,
201
- );
202
- return contents;
203
- }
204
-
205
- function managedExtensions(source) {
206
- return source.extensions.filter((extension) => extension.source !== undefined);
207
- }
208
-
209
- async function inspectExtensionSource(sourceDirectory, {willReplace = false} = {}) {
210
- const resolvedSourceDirectory = path.resolve(sourceDirectory);
211
- if (willReplace) {
212
- assert(
213
- resolvedSourceDirectory !== path.parse(resolvedSourceDirectory).root,
214
- 'Refusing to replace a filesystem root during extension synchronization.',
215
- );
216
- assert(
217
- !(await pathExists(path.join(resolvedSourceDirectory, '.git'))),
218
- 'Refusing to replace a Git repository root during extension synchronization.',
219
- );
220
- }
221
- const stats = await lstat(resolvedSourceDirectory);
222
- assert(
223
- stats.isDirectory() && !stats.isSymbolicLink(),
224
- `SB3 source must be a directory, not a file or symbolic link: ${resolvedSourceDirectory}`,
225
- );
226
- if (willReplace) {
227
- await assertNoInterruptedRollback(resolvedSourceDirectory);
228
- }
229
- return inspectSb3SourceForExtensionSync(resolvedSourceDirectory);
230
- }
231
-
232
- async function installCandidate({
233
- candidateDirectory,
234
- confirmReplace,
235
- initialSourceFingerprint,
236
- sourceDirectory,
237
- yes,
238
- }) {
239
- const comparison = await compareDirectories(sourceDirectory, candidateDirectory);
240
- assert(
241
- comparison.existingFingerprint === initialSourceFingerprint,
242
- 'SB3 source changed while extension artifacts were being fetched; refusing to replace it.',
243
- );
244
- if (comparison.identical) {
245
- await rm(candidateDirectory, {recursive: true, force: true});
246
- return {changed: false, comparison, rollbackCleanupWarning: null};
247
- }
248
-
249
- const context = {comparison, sourceDirectory};
250
- if (!yes) {
251
- assert(
252
- typeof confirmReplace === 'function',
253
- `Managed extension files differ in ${sourceDirectory}. ` +
254
- 'Non-interactive replacement requires --yes.',
255
- );
256
- assert(
257
- await confirmReplace(context),
258
- 'Extension synchronization cancelled; the existing source was not changed.',
259
- );
260
- }
261
-
262
- const latestComparison = await compareDirectories(sourceDirectory, candidateDirectory);
263
- assert(
264
- latestComparison.existingFingerprint === comparison.existingFingerprint &&
265
- latestComparison.candidateFingerprint === comparison.candidateFingerprint,
266
- 'SB3 source or extension candidate changed during synchronization; refusing to replace it.',
267
- );
268
- const replacement = await replaceDirectoryTransactionally(candidateDirectory, sourceDirectory);
269
- return {changed: true, comparison, ...replacement};
270
- }
271
-
272
- async function updateCandidate({
273
- allowBreakingApi,
274
- apiManifestArtifact,
275
- confirmReplace,
276
- fetchImplementation,
277
- maximumArtifactBytes,
278
- maximumManifestBytes,
279
- migrateToId,
280
- mode,
281
- selectedExtensionId,
282
- sourceArtifact,
283
- sourceDirectory,
284
- yes,
285
- }) {
286
- assert(
287
- Number.isSafeInteger(maximumArtifactBytes) && maximumArtifactBytes > 0,
288
- 'maximumArtifactBytes must be a positive integer.',
289
- );
290
- assert(
291
- Number.isSafeInteger(maximumManifestBytes) && maximumManifestBytes > 0,
292
- 'maximumManifestBytes must be a positive integer.',
293
- );
294
- assert(!allowBreakingApi || yes, '--allow-breaking-api requires --yes.');
295
- const source = await inspectExtensionSource(sourceDirectory, {willReplace: true});
296
- const initialComparison = await compareDirectories(
297
- source.resolvedSourceDirectory,
298
- source.resolvedSourceDirectory,
299
- );
300
- assert(
301
- initialComparison.identical &&
302
- initialComparison.existingFingerprint === initialComparison.candidateFingerprint,
303
- 'SB3 source changed while its initial state was being inspected.',
304
- );
305
- const managed = managedExtensions(source);
306
- assert(managed.length > 0, 'No managed embedded extensions were found.');
307
- if (selectedExtensionId !== undefined) {
308
- assert(
309
- managed.some((extension) => extension.id === selectedExtensionId),
310
- `Managed extension was not found: ${selectedExtensionId}`,
311
- );
312
- }
313
- const selected = managed.filter(
314
- (extension) => selectedExtensionId === undefined || extension.id === selectedExtensionId,
315
- );
316
- if (migrateToId !== undefined) {
317
- assert(mode === 'update', 'Extension ID migration is only available during update.');
318
- assert(
319
- selectedExtensionId !== undefined,
320
- 'Extension ID migration requires an explicit existing extension ID.',
321
- );
322
- validateNewExtensionId(migrateToId);
323
- assert(
324
- selected.every((extension) => extension.source.provider === 'github'),
325
- 'Extension ID migration is not supported for npm-managed extensions.',
326
- );
327
- }
328
- assert(
329
- sourceArtifact === undefined || migrateToId !== undefined,
330
- 'A replacement artifact path requires an extension ID migration.',
331
- );
332
- assert(
333
- apiManifestArtifact === undefined || migrateToId !== undefined,
334
- 'A replacement API manifest artifact path requires an extension ID migration.',
335
- );
336
- if (migrateToId !== undefined) {
337
- const extensionManifest = JSON.parse(
338
- await readFile(
339
- path.join(source.resolvedSourceDirectory, source.sourceManifest.embeddedExtensions),
340
- 'utf8',
341
- ),
342
- );
343
- rewriteExtensionIdDocuments({
344
- apiManifestArtifact,
345
- extensionManifest,
346
- newId: migrateToId,
347
- oldId: selectedExtensionId,
348
- project: source.project,
349
- sourceArtifact,
350
- });
351
- }
352
-
353
- const downloads = await Promise.all(
354
- selected.map(async (extension) => {
355
- let effectiveExtension = extension;
356
- if (sourceArtifact !== undefined || apiManifestArtifact !== undefined) {
357
- const effectiveSource = {...extension.source};
358
- if (sourceArtifact !== undefined) effectiveSource.artifact = sourceArtifact;
359
- if (apiManifestArtifact !== undefined) {
360
- assert(
361
- effectiveSource.apiManifest,
362
- `Extension ${extension.id} has no managed API manifest metadata.`,
363
- );
364
- effectiveSource.apiManifest = {
365
- ...effectiveSource.apiManifest,
366
- artifact: apiManifestArtifact,
367
- };
368
- }
369
- effectiveExtension = {...extension, source: effectiveSource};
370
- }
371
- validateExtensionSourceMetadata(effectiveExtension);
372
- if (effectiveExtension.source.provider === 'npm') {
373
- const npmSource = await readNpmExtensionSource(
374
- effectiveExtension,
375
- source.resolvedSourceDirectory,
376
- {
377
- allowVersionMismatch: mode === 'update',
378
- maximumArtifactBytes,
379
- maximumManifestBytes,
380
- },
381
- );
382
- const apiManifestDownload = npmSource.apiManifestContents
383
- ? {
384
- contents: npmSource.apiManifestContents,
385
- manifest: parseExtensionApiManifest(npmSource.apiManifestContents, {
386
- expectedId: extension.id,
387
- }),
388
- }
389
- : null;
390
- let compatibilityChanges = [];
391
- if (mode === 'sync') {
392
- validateManagedExtensionContents(extension, npmSource.contents);
393
- if (apiManifestDownload) {
394
- validateManagedExtensionApiManifest(extension, apiManifestDownload.contents);
395
- }
396
- } else if (apiManifestDownload) {
397
- const installedApiManifestContents = source.extensionApiManifestContents.get(
398
- extension.id,
399
- );
400
- assert(
401
- installedApiManifestContents,
402
- `Managed extension API manifest is missing for ${extension.id}.`,
403
- );
404
- const installedApiManifest = validateManagedExtensionApiManifest(
405
- extension,
406
- installedApiManifestContents,
407
- ).manifest;
408
- compatibilityChanges = compareExtensionApiManifests(
409
- installedApiManifest,
410
- apiManifestDownload.manifest,
411
- );
412
- }
413
- return {
414
- apiManifestDownload,
415
- commit: null,
416
- compatibilityChanges,
417
- contents: npmSource.contents,
418
- effectiveExtension,
419
- extension,
420
- npmVersion: npmSource.version,
421
- };
422
- }
423
- const githubFetch = assertFetch(fetchImplementation);
424
- const commit =
425
- mode === 'sync'
426
- ? extension.source.resolvedCommit
427
- : await resolveGithubCommit(extension, githubFetch);
428
- const expectedId = migrateToId ?? extension.id;
429
- const [contents, apiManifestDownload] = await Promise.all([
430
- downloadExtension(
431
- effectiveExtension,
432
- commit,
433
- githubFetch,
434
- maximumArtifactBytes,
435
- expectedId,
436
- ),
437
- downloadExtensionApiManifest(
438
- effectiveExtension,
439
- commit,
440
- githubFetch,
441
- maximumManifestBytes,
442
- expectedId,
443
- ),
444
- ]);
445
- let compatibilityChanges = [];
446
- if (mode === 'sync') {
447
- validateManagedExtensionContents(extension, contents);
448
- if (apiManifestDownload) {
449
- validateManagedExtensionApiManifest(extension, apiManifestDownload.contents);
450
- }
451
- } else if (apiManifestDownload) {
452
- const installedApiManifestContents = source.extensionApiManifestContents.get(extension.id);
453
- assert(
454
- installedApiManifestContents,
455
- `Managed extension API manifest is missing for ${extension.id}.`,
456
- );
457
- const installedApiManifest = validateManagedExtensionApiManifest(
458
- extension,
459
- installedApiManifestContents,
460
- ).manifest;
461
- compatibilityChanges = compareExtensionApiManifests(
462
- installedApiManifest,
463
- apiManifestDownload.manifest,
464
- );
465
- }
466
- return {
467
- apiManifestDownload,
468
- commit,
469
- compatibilityChanges,
470
- contents,
471
- effectiveExtension,
472
- extension,
473
- };
474
- }),
475
- );
476
- const breakingApiChanges = downloads.flatMap((download) =>
477
- download.compatibilityChanges
478
- .filter((change) => change.breaking)
479
- .map((change) => ({...change, extensionId: download.extension.id})),
480
- );
481
- if (breakingApiChanges.length > 0 && !allowBreakingApi) {
482
- const details = downloads
483
- .filter((download) => download.compatibilityChanges.some((change) => change.breaking))
484
- .map((download) =>
485
- formatExtensionApiCompatibilityChanges(
486
- download.extension.id,
487
- download.compatibilityChanges.filter((change) => change.breaking),
488
- ),
489
- )
490
- .join('\n');
491
- throw new Error(
492
- `Extension API update contains ${breakingApiChanges.length} breaking change(s). ` +
493
- 'Review the reported paths, then use --allow-breaking-api with --yes to apply.\n' +
494
- details,
495
- );
496
- }
497
-
498
- const parentDirectory = path.dirname(source.resolvedSourceDirectory);
499
- const candidateDirectory = await mkdtemp(
500
- path.join(parentDirectory, `.${path.basename(source.resolvedSourceDirectory)}.extensions-`),
501
- );
502
- let installed = false;
503
- try {
504
- await cp(source.resolvedSourceDirectory, candidateDirectory, {
505
- preserveTimestamps: true,
506
- recursive: true,
507
- verbatimSymlinks: true,
508
- });
509
- const manifestPath = path.join(candidateDirectory, source.sourceManifest.embeddedExtensions);
510
- const manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
511
- const projectPath = path.join(candidateDirectory, source.sourceManifest.project);
512
- const entriesById = new Map(manifest.extensions.map((extension) => [extension.id, extension]));
513
- let manifestChanged = false;
514
- let migration;
515
- for (const {
516
- apiManifestDownload,
517
- commit,
518
- contents,
519
- effectiveExtension,
520
- extension,
521
- npmVersion,
522
- } of downloads) {
523
- if (migrateToId !== undefined) {
524
- const project = JSON.parse(await readFile(projectPath, 'utf8'));
525
- migration = rewriteExtensionIdDocuments({
526
- apiManifestArtifact,
527
- extensionManifest: manifest,
528
- newId: migrateToId,
529
- oldId: extension.id,
530
- project,
531
- sourceArtifact: effectiveExtension.source.artifact,
532
- });
533
- const migratedExtension = migration.extensionManifest.extensions[migration.extensionIndex];
534
- migratedExtension.source.resolvedCommit = commit;
535
- migratedExtension.source.integrity = extensionIntegrity(contents);
536
- if (apiManifestDownload) {
537
- migratedExtension.source.apiManifest.integrity = extensionApiManifestIntegrity(
538
- apiManifestDownload.contents,
539
- );
540
- }
541
- const writes = [
542
- writeFile(projectPath, `${JSON.stringify(migration.project, null, 2)}\n`),
543
- writeFile(manifestPath, `${JSON.stringify(migration.extensionManifest, null, 2)}\n`),
544
- writeFile(path.join(candidateDirectory, migration.newPath), contents),
545
- ];
546
- if (apiManifestDownload && migration.newApiManifestPath) {
547
- writes.push(
548
- writeFile(
549
- path.join(candidateDirectory, migration.newApiManifestPath),
550
- apiManifestDownload.contents,
551
- ),
552
- );
553
- }
554
- await Promise.all(writes);
555
- await rm(path.join(candidateDirectory, migration.oldPath));
556
- if (migration.oldApiManifestPath) {
557
- await rm(path.join(candidateDirectory, migration.oldApiManifestPath));
558
- }
559
- continue;
560
- }
561
- await writeFile(path.join(candidateDirectory, extension.path), contents);
562
- if (apiManifestDownload) {
563
- await writeFile(
564
- path.join(candidateDirectory, extension.source.apiManifest.path),
565
- apiManifestDownload.contents,
566
- );
567
- }
568
- if (mode === 'update') {
569
- const candidateExtension = entriesById.get(extension.id);
570
- assert(candidateExtension, `Extension manifest entry disappeared: ${extension.id}`);
571
- const integrity = extensionIntegrity(contents);
572
- manifestChanged = manifestChanged || candidateExtension.source.integrity !== integrity;
573
- if (candidateExtension.source.provider === 'npm') {
574
- manifestChanged = manifestChanged || candidateExtension.source.version !== npmVersion;
575
- candidateExtension.source.version = npmVersion;
576
- } else {
577
- manifestChanged = manifestChanged || candidateExtension.source.resolvedCommit !== commit;
578
- candidateExtension.source.resolvedCommit = commit;
579
- }
580
- candidateExtension.source.integrity = integrity;
581
- if (apiManifestDownload) {
582
- const apiManifestIntegrity = extensionApiManifestIntegrity(apiManifestDownload.contents);
583
- manifestChanged =
584
- manifestChanged ||
585
- candidateExtension.source.apiManifest.integrity !== apiManifestIntegrity;
586
- candidateExtension.source.apiManifest.integrity = apiManifestIntegrity;
587
- candidateExtension.source.apiManifest.formatVersion =
588
- apiManifestDownload.manifest.formatVersion;
589
- }
590
- }
591
- }
592
- if (manifestChanged && migrateToId === undefined) {
593
- await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
594
- }
595
- if (migration) {
596
- await createDeterministicSb3(candidateDirectory);
597
- } else {
598
- await validateSb3Source(candidateDirectory);
599
- }
600
- const result = await installCandidate({
601
- candidateDirectory,
602
- confirmReplace,
603
- initialSourceFingerprint: initialComparison.existingFingerprint,
604
- sourceDirectory: source.resolvedSourceDirectory,
605
- yes,
606
- });
607
- installed = true;
608
- return {
609
- ...result,
610
- apiCompatibility: downloads
611
- .filter(({apiManifestDownload}) => apiManifestDownload !== null)
612
- .map(({compatibilityChanges, extension}) => ({
613
- changes: compatibilityChanges,
614
- id: migrateToId ?? extension.id,
615
- previousId: migrateToId === undefined ? undefined : extension.id,
616
- })),
617
- extensions: downloads.map(({commit, extension, npmVersion}) =>
618
- extension.source.provider === 'npm'
619
- ? {
620
- id: extension.id,
621
- package: extension.source.package,
622
- version: npmVersion,
623
- }
624
- : {
625
- id: migrateToId ?? extension.id,
626
- previousId: migrateToId === undefined ? undefined : extension.id,
627
- resolvedCommit: commit,
628
- },
629
- ),
630
- migration:
631
- migration === undefined
632
- ? null
633
- : {
634
- counts: migration.counts,
635
- fromId: selectedExtensionId,
636
- toId: migrateToId,
637
- totalChanges: migration.totalChanges,
638
- unclassifiedReferences: migration.unclassifiedReferences,
639
- },
640
- mode,
641
- sourceDirectory: source.resolvedSourceDirectory,
642
- };
643
- } finally {
644
- if (!installed) {
645
- await rm(candidateDirectory, {recursive: true, force: true});
646
- }
647
- }
648
- }
649
-
650
- export async function extensionStatus(
651
- sourceDirectory,
652
- {fetch: fetchImplementation = globalThis.fetch} = {},
653
- ) {
654
- const source = await inspectExtensionSource(sourceDirectory);
655
- return Promise.all(
656
- managedExtensions(source).map(async (extension) => {
657
- let local = 'valid';
658
- try {
659
- validateManagedExtensionContents(extension, source.extensionContents.get(extension.id));
660
- if (extension.source.apiManifest) {
661
- validateManagedExtensionApiManifest(
662
- extension,
663
- source.extensionApiManifestContents.get(extension.id),
664
- );
665
- }
666
- } catch {
667
- local = 'modified';
668
- }
669
- if (extension.source.provider === 'npm') {
670
- const npmSource = await readNpmExtensionSource(extension, source.resolvedSourceDirectory, {
671
- allowVersionMismatch: true,
672
- maximumArtifactBytes: defaultExtensionArtifactSizeLimit,
673
- maximumManifestBytes: defaultExtensionApiManifestSizeLimit,
674
- });
675
- if (npmSource.version === extension.source.version) {
676
- validateManagedExtensionContents(extension, npmSource.contents);
677
- if (npmSource.apiManifestContents) {
678
- validateManagedExtensionApiManifest(extension, npmSource.apiManifestContents);
679
- }
680
- }
681
- return {
682
- id: extension.id,
683
- installedVersion: npmSource.version,
684
- local,
685
- package: extension.source.package,
686
- state: npmSource.version === extension.source.version ? 'current' : 'update-available',
687
- version: extension.source.version,
688
- };
689
- }
690
- const remoteCommit = await resolveGithubCommit(extension, assertFetch(fetchImplementation));
691
- return {
692
- id: extension.id,
693
- local,
694
- ref: extension.source.ref,
695
- remoteCommit,
696
- resolvedCommit: extension.source.resolvedCommit,
697
- state: remoteCommit === extension.source.resolvedCommit ? 'current' : 'update-available',
698
- };
699
- }),
700
- );
701
- }
702
-
703
- export async function syncExtensions({
704
- confirmReplace,
705
- fetch: fetchImplementation = globalThis.fetch,
706
- maximumArtifactBytes = defaultExtensionArtifactSizeLimit,
707
- maximumManifestBytes = defaultExtensionApiManifestSizeLimit,
708
- sourceDirectory,
709
- yes = false,
710
- }) {
711
- return updateCandidate({
712
- allowBreakingApi: false,
713
- apiManifestArtifact: undefined,
714
- confirmReplace,
715
- fetchImplementation,
716
- maximumArtifactBytes,
717
- maximumManifestBytes,
718
- migrateToId: undefined,
719
- mode: 'sync',
720
- selectedExtensionId: undefined,
721
- sourceArtifact: undefined,
722
- sourceDirectory,
723
- yes,
724
- });
725
- }
726
-
727
- export async function updateExtensions({
728
- allowBreakingApi = false,
729
- apiManifestArtifact,
730
- confirmReplace,
731
- extensionId,
732
- fetch: fetchImplementation = globalThis.fetch,
733
- maximumArtifactBytes = defaultExtensionArtifactSizeLimit,
734
- maximumManifestBytes = defaultExtensionApiManifestSizeLimit,
735
- migrateToId,
736
- sourceArtifact,
737
- sourceDirectory,
738
- yes = false,
739
- }) {
740
- return updateCandidate({
741
- allowBreakingApi,
742
- apiManifestArtifact,
743
- confirmReplace,
744
- fetchImplementation,
745
- maximumArtifactBytes,
746
- maximumManifestBytes,
747
- migrateToId,
748
- mode: 'update',
749
- selectedExtensionId: extensionId,
750
- sourceArtifact,
751
- sourceDirectory,
752
- yes,
753
- });
754
- }