@kubohiroya/sb3-toolchain 0.11.0 → 0.13.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 +30 -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 +65 -0
  23. package/dist/extension-api-manifest.js +231 -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 +31 -20
  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,114 +0,0 @@
1
- // SPDX-License-Identifier: MPL-2.0
2
-
3
- import {createHash} from 'node:crypto';
4
-
5
- import {validateArchiveEntryName} from './archive.js';
6
- import {validateExtensionApiManifestSourceMetadata} from './extension-api-manifest.js';
7
-
8
- function assert(condition, message) {
9
- if (!condition) {
10
- throw new Error(message);
11
- }
12
- }
13
-
14
- export function extensionIntegrity(contents) {
15
- return `sha256-${createHash('sha256').update(contents).digest('base64')}`;
16
- }
17
-
18
- export function extensionHeaderId(contents) {
19
- return extensionHeaderMetadata(contents).id;
20
- }
21
-
22
- export function extensionHeaderMetadata(contents) {
23
- const source = Buffer.from(contents).toString('utf8');
24
- const readField = (field) =>
25
- source.match(new RegExp(`^// ${field}: (.+)\\r?$`, 'mu'))?.[1]?.trim() ?? null;
26
- const id = readField('ID');
27
- return {
28
- author: readField('By'),
29
- description: readField('Description'),
30
- id: id && /^[A-Za-z0-9._-]+$/u.test(id) ? id : null,
31
- license: readField('License'),
32
- name: readField('Name'),
33
- };
34
- }
35
-
36
- export function validateExtensionSourceMetadata(extension) {
37
- if (extension.source === undefined) {
38
- return null;
39
- }
40
-
41
- const source = extension.source;
42
- assert(
43
- source && typeof source === 'object' && !Array.isArray(source),
44
- `Managed extension source must be an object: ${extension.id}`,
45
- );
46
- if (source.provider === 'github') {
47
- assert(
48
- typeof source.repository === 'string' &&
49
- /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]+$/u.test(source.repository),
50
- `Invalid GitHub repository for extension ${extension.id}: ${source.repository}`,
51
- );
52
- assert(
53
- typeof source.ref === 'string' &&
54
- source.ref.length > 0 &&
55
- !/[\u0000-\u0020\u007f]/u.test(source.ref),
56
- `Invalid Git ref for extension ${extension.id}: ${source.ref}`,
57
- );
58
- assert(
59
- typeof source.resolvedCommit === 'string' && /^[a-f0-9]{40}$/u.test(source.resolvedCommit),
60
- `Managed extension ${extension.id} requires a 40-character resolvedCommit.`,
61
- );
62
- } else if (source.provider === 'npm') {
63
- assert(
64
- typeof source.package === 'string' &&
65
- /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u.test(source.package),
66
- `Invalid npm package for extension ${extension.id}: ${source.package}`,
67
- );
68
- assert(
69
- typeof source.version === 'string' &&
70
- /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u.test(source.version),
71
- `Managed npm extension ${extension.id} requires an exact semantic version.`,
72
- );
73
- } else {
74
- throw new Error(
75
- `Unsupported extension source provider for ${extension.id}: ${source.provider}`,
76
- );
77
- }
78
- assert(
79
- typeof source.artifact === 'string' && source.artifact.length > 0,
80
- `Managed extension ${extension.id} requires an artifact path.`,
81
- );
82
- validateArchiveEntryName(source.artifact);
83
- assert(
84
- !source.artifact.endsWith('/'),
85
- `Managed extension artifact must be a file: ${source.artifact}`,
86
- );
87
- assert(
88
- typeof source.integrity === 'string' && /^sha256-[A-Za-z0-9+/]{43}=$/u.test(source.integrity),
89
- `Managed extension ${extension.id} requires SHA-256 integrity.`,
90
- );
91
- validateExtensionApiManifestSourceMetadata(extension);
92
- return source;
93
- }
94
-
95
- export function validateManagedExtensionContents(extension, contents) {
96
- const source = validateExtensionSourceMetadata(extension);
97
- if (!source) {
98
- return null;
99
- }
100
-
101
- const actualIntegrity = extensionIntegrity(contents);
102
- assert(
103
- actualIntegrity === source.integrity,
104
- `Managed extension integrity mismatch for ${extension.id}: ` +
105
- `expected ${source.integrity}, got ${actualIntegrity}`,
106
- );
107
- const actualId = extensionHeaderId(contents);
108
- assert(
109
- actualId === extension.id,
110
- `Managed extension header ID mismatch for ${extension.id}: ` +
111
- `expected ${extension.id}, got ${actualId ?? '(missing)'}`,
112
- );
113
- return {actualId, integrity: actualIntegrity, source};
114
- }
@@ -1,496 +0,0 @@
1
- // SPDX-License-Identifier: MPL-2.0
2
-
3
- import {cp, lstat, mkdtemp, readFile, rename, rm, writeFile} from 'node:fs/promises';
4
- import path from 'node:path';
5
-
6
- import {
7
- extensionApiManifestIntegrity,
8
- parseExtensionApiManifest,
9
- } from './extension-api-manifest.js';
10
- import {extensionHeaderId, extensionIntegrity} from './extension-dependencies.js';
11
- import {
12
- assertNoInterruptedRollback,
13
- compareDirectories,
14
- pathExists,
15
- replaceDirectoryTransactionally,
16
- } from './output-safety.js';
17
- import {createDeterministicSb3, inspectSb3SourceForExtensionSync} from './source.js';
18
-
19
- function assert(condition, message) {
20
- if (!condition) {
21
- throw new Error(message);
22
- }
23
- }
24
-
25
- function escapeJsonPointer(value) {
26
- return value.replaceAll('~', '~0').replaceAll('/', '~1');
27
- }
28
-
29
- function referenceKey(file, kind, pointer) {
30
- return `${file}\u0000${kind}\u0000${pointer}`;
31
- }
32
-
33
- function collectUnclassifiedReferences(value, oldId, file, classified) {
34
- const references = [];
35
-
36
- function visit(current, pointer) {
37
- if (typeof current === 'string') {
38
- if (current.includes(oldId) && !classified.has(referenceKey(file, 'value', pointer))) {
39
- references.push({file, kind: 'value', path: pointer || '/', value: current});
40
- }
41
- return;
42
- }
43
- if (!current || typeof current !== 'object') return;
44
-
45
- if (Array.isArray(current)) {
46
- for (const [index, entry] of current.entries()) {
47
- visit(entry, `${pointer}/${index}`);
48
- }
49
- return;
50
- }
51
-
52
- for (const [key, entry] of Object.entries(current)) {
53
- const entryPointer = `${pointer}/${escapeJsonPointer(key)}`;
54
- if (key.includes(oldId) && !classified.has(referenceKey(file, 'key', entryPointer))) {
55
- references.push({file, kind: 'key', path: entryPointer, value: key});
56
- }
57
- visit(entry, entryPointer);
58
- }
59
- }
60
-
61
- visit(value, '');
62
- return references;
63
- }
64
-
65
- function replaceObjectKeyAtSamePosition(object, oldKey, newKey) {
66
- const replacement = {};
67
- for (const [key, value] of Object.entries(object)) {
68
- replacement[key === oldKey ? newKey : key] = value;
69
- }
70
- return replacement;
71
- }
72
-
73
- export function validateNewExtensionId(newId) {
74
- assert(
75
- typeof newId === 'string' && /^[a-z0-9]+$/u.test(newId),
76
- `New extension ID must use TurboWarp's [a-z0-9]+ format: ${JSON.stringify(newId)}`,
77
- );
78
- return newId;
79
- }
80
-
81
- export function rewriteExtensionIdDocuments({
82
- apiManifestArtifact = undefined,
83
- extensionManifest,
84
- newId,
85
- oldId,
86
- project,
87
- sourceArtifact = undefined,
88
- }) {
89
- assert(
90
- typeof oldId === 'string' && /^[A-Za-z0-9._-]+$/u.test(oldId),
91
- `Invalid existing extension ID: ${JSON.stringify(oldId)}`,
92
- );
93
- validateNewExtensionId(newId);
94
- assert(oldId !== newId, 'The existing and new extension IDs must differ.');
95
-
96
- const originalProject = structuredClone(project);
97
- const originalManifest = structuredClone(extensionManifest);
98
- const migratedProject = structuredClone(project);
99
- const migratedManifest = structuredClone(extensionManifest);
100
- const extensions = migratedManifest.extensions;
101
- assert(Array.isArray(extensions), 'Embedded extension manifest requires extensions.');
102
- const extensionIndex = extensions.findIndex((extension) => extension?.id === oldId);
103
- assert(extensionIndex !== -1, `Embedded extension was not found: ${oldId}`);
104
- assert(
105
- !extensions.some((extension) => extension?.id === newId),
106
- `Embedded extension ID already exists: ${newId}`,
107
- );
108
-
109
- const extensionUrls = migratedProject.extensionURLs;
110
- assert(
111
- extensionUrls && typeof extensionUrls === 'object' && !Array.isArray(extensionUrls),
112
- 'project.source.json extensionURLs must be an object.',
113
- );
114
- assert(
115
- Object.hasOwn(extensionUrls, oldId),
116
- `project.source.json has no extensionURLs entry for ${oldId}.`,
117
- );
118
- assert(
119
- !Object.hasOwn(extensionUrls, newId),
120
- `project.source.json extensionURLs already contains ${newId}.`,
121
- );
122
- assert(
123
- migratedProject.extensions === undefined || Array.isArray(migratedProject.extensions),
124
- 'project.source.json extensions must be an array when present.',
125
- );
126
- assert(
127
- migratedProject.monitors === undefined || Array.isArray(migratedProject.monitors),
128
- 'project.source.json monitors must be an array when present.',
129
- );
130
- if (migratedProject.extensions) {
131
- assert(
132
- !migratedProject.extensions.includes(newId),
133
- `project.source.json extensions already contains ${newId}.`,
134
- );
135
- }
136
-
137
- const counts = {
138
- apiManifestArtifacts: 0,
139
- blockOpcodes: 0,
140
- extensionFiles: 1,
141
- extensionUrlKeys: 0,
142
- extensionUrlValues: 0,
143
- manifestIds: 0,
144
- manifestPaths: 0,
145
- monitorOpcodes: 0,
146
- projectExtensions: 0,
147
- sourceArtifacts: 0,
148
- };
149
- const projectClassified = new Set();
150
- const manifestClassified = new Set();
151
-
152
- if (migratedProject.extensions) {
153
- for (const [index, extensionId] of migratedProject.extensions.entries()) {
154
- if (extensionId === oldId) {
155
- migratedProject.extensions[index] = newId;
156
- counts.projectExtensions += 1;
157
- projectClassified.add(referenceKey('project.source.json', 'value', `/extensions/${index}`));
158
- }
159
- }
160
- }
161
-
162
- const oldExtensionUrl = extensionUrls[oldId];
163
- const oldExtensionUrlPointer = `/extensionURLs/${escapeJsonPointer(oldId)}`;
164
- projectClassified.add(referenceKey('project.source.json', 'key', oldExtensionUrlPointer));
165
- counts.extensionUrlKeys += 1;
166
- const expectedOldUrl = `embedded-extension:extensions/${oldId}.js`;
167
- assert(
168
- oldExtensionUrl === expectedOldUrl,
169
- `Embedded extension URL mismatch for ${oldId}: ${oldExtensionUrl}`,
170
- );
171
- extensionUrls[oldId] = `embedded-extension:extensions/${newId}.js`;
172
- projectClassified.add(referenceKey('project.source.json', 'value', oldExtensionUrlPointer));
173
- counts.extensionUrlValues += 1;
174
- migratedProject.extensionURLs = replaceObjectKeyAtSamePosition(extensionUrls, oldId, newId);
175
-
176
- for (const [targetIndex, target] of (migratedProject.targets ?? []).entries()) {
177
- if (!target?.blocks || typeof target.blocks !== 'object') continue;
178
- for (const [blockId, block] of Object.entries(target.blocks)) {
179
- if (!block || typeof block !== 'object' || Array.isArray(block)) continue;
180
- if (typeof block.opcode === 'string' && block.opcode.startsWith(`${oldId}_`)) {
181
- block.opcode = `${newId}_${block.opcode.slice(oldId.length + 1)}`;
182
- counts.blockOpcodes += 1;
183
- projectClassified.add(
184
- referenceKey(
185
- 'project.source.json',
186
- 'value',
187
- `/targets/${targetIndex}/blocks/${escapeJsonPointer(blockId)}/opcode`,
188
- ),
189
- );
190
- }
191
- }
192
- }
193
-
194
- for (const [monitorIndex, monitor] of (migratedProject.monitors ?? []).entries()) {
195
- if (
196
- monitor &&
197
- typeof monitor === 'object' &&
198
- !Array.isArray(monitor) &&
199
- typeof monitor.opcode === 'string' &&
200
- monitor.opcode.startsWith(`${oldId}_`)
201
- ) {
202
- monitor.opcode = `${newId}_${monitor.opcode.slice(oldId.length + 1)}`;
203
- counts.monitorOpcodes += 1;
204
- projectClassified.add(
205
- referenceKey('project.source.json', 'value', `/monitors/${monitorIndex}/opcode`),
206
- );
207
- }
208
- }
209
-
210
- const extension = extensions[extensionIndex];
211
- extension.id = newId;
212
- counts.manifestIds += 1;
213
- manifestClassified.add(
214
- referenceKey('embedded-extensions.json', 'value', `/extensions/${extensionIndex}/id`),
215
- );
216
- const oldPath = `extensions/${oldId}.js`;
217
- assert(
218
- extension.path === oldPath,
219
- `Embedded extension path mismatch for ${oldId}: ${extension.path}`,
220
- );
221
- extension.path = `extensions/${newId}.js`;
222
- counts.manifestPaths += 1;
223
- manifestClassified.add(
224
- referenceKey('embedded-extensions.json', 'value', `/extensions/${extensionIndex}/path`),
225
- );
226
- let oldApiManifestPath = null;
227
- let newApiManifestPath = null;
228
- if (apiManifestArtifact !== undefined) {
229
- assert(
230
- extension.source?.apiManifest,
231
- `Extension ${oldId} has no managed API manifest metadata.`,
232
- );
233
- }
234
- if (extension.source?.apiManifest) {
235
- oldApiManifestPath = `extensions/${oldId}.manifest.json`;
236
- newApiManifestPath = `extensions/${newId}.manifest.json`;
237
- assert(
238
- extension.source.apiManifest.path === oldApiManifestPath,
239
- `Extension API manifest path mismatch for ${oldId}: ${extension.source.apiManifest.path}`,
240
- );
241
- extension.source.apiManifest.path = newApiManifestPath;
242
- counts.manifestPaths += 1;
243
- manifestClassified.add(
244
- referenceKey(
245
- 'embedded-extensions.json',
246
- 'value',
247
- `/extensions/${extensionIndex}/source/apiManifest/path`,
248
- ),
249
- );
250
- if (
251
- apiManifestArtifact !== undefined &&
252
- extension.source.apiManifest.artifact !== apiManifestArtifact
253
- ) {
254
- extension.source.apiManifest.artifact = apiManifestArtifact;
255
- counts.apiManifestArtifacts += 1;
256
- manifestClassified.add(
257
- referenceKey(
258
- 'embedded-extensions.json',
259
- 'value',
260
- `/extensions/${extensionIndex}/source/apiManifest/artifact`,
261
- ),
262
- );
263
- }
264
- }
265
- if (sourceArtifact !== undefined) {
266
- assert(extension.source, `Extension ${oldId} has no managed source metadata.`);
267
- if (extension.source.artifact !== sourceArtifact) {
268
- extension.source.artifact = sourceArtifact;
269
- counts.sourceArtifacts += 1;
270
- manifestClassified.add(
271
- referenceKey(
272
- 'embedded-extensions.json',
273
- 'value',
274
- `/extensions/${extensionIndex}/source/artifact`,
275
- ),
276
- );
277
- }
278
- }
279
-
280
- const unclassifiedReferences = [
281
- ...collectUnclassifiedReferences(
282
- originalProject,
283
- oldId,
284
- 'project.source.json',
285
- projectClassified,
286
- ),
287
- ...collectUnclassifiedReferences(
288
- originalManifest,
289
- oldId,
290
- 'embedded-extensions.json',
291
- manifestClassified,
292
- ),
293
- ];
294
- const totalChanges = Object.values(counts).reduce((total, count) => total + count, 0);
295
- return {
296
- counts,
297
- extensionIndex,
298
- extensionManifest: migratedManifest,
299
- newApiManifestPath,
300
- newPath: `extensions/${newId}.js`,
301
- oldApiManifestPath,
302
- oldPath,
303
- project: migratedProject,
304
- totalChanges,
305
- unclassifiedReferences,
306
- };
307
- }
308
-
309
- async function inspectMigrationSource(sourceDirectory, willReplace) {
310
- const resolvedSourceDirectory = path.resolve(sourceDirectory);
311
- if (willReplace) {
312
- assert(
313
- resolvedSourceDirectory !== path.parse(resolvedSourceDirectory).root,
314
- 'Refusing to replace a filesystem root during extension ID migration.',
315
- );
316
- assert(
317
- !(await pathExists(path.join(resolvedSourceDirectory, '.git'))),
318
- 'Refusing to replace a Git repository root during extension ID migration.',
319
- );
320
- }
321
- const stats = await lstat(resolvedSourceDirectory);
322
- assert(
323
- stats.isDirectory() && !stats.isSymbolicLink(),
324
- `SB3 source must be a directory, not a file or symbolic link: ${resolvedSourceDirectory}`,
325
- );
326
- if (willReplace) {
327
- await assertNoInterruptedRollback(resolvedSourceDirectory);
328
- }
329
- return inspectSb3SourceForExtensionSync(resolvedSourceDirectory);
330
- }
331
-
332
- async function migrationContext(sourceDirectory, oldId, newId, willReplace) {
333
- const source = await inspectMigrationSource(sourceDirectory, willReplace);
334
- const extensionManifestPath = path.join(
335
- source.resolvedSourceDirectory,
336
- source.sourceManifest.embeddedExtensions,
337
- );
338
- const extensionManifest = JSON.parse(await readFile(extensionManifestPath, 'utf8'));
339
- const rewrite = rewriteExtensionIdDocuments({
340
- extensionManifest,
341
- newId,
342
- oldId,
343
- project: source.project,
344
- });
345
- const extension = source.extensions[rewrite.extensionIndex];
346
- const contents = source.extensionContents.get(oldId);
347
- const apiManifestContents = source.extensionApiManifestContents.get(oldId) ?? null;
348
- let apiManifestReady = true;
349
- if (extension.source?.apiManifest) {
350
- apiManifestReady =
351
- apiManifestContents !== null &&
352
- extensionApiManifestIntegrity(apiManifestContents) === extension.source.apiManifest.integrity;
353
- if (apiManifestReady) {
354
- try {
355
- parseExtensionApiManifest(apiManifestContents, {expectedId: newId});
356
- } catch {
357
- apiManifestReady = false;
358
- }
359
- }
360
- }
361
- return {
362
- apiManifestContents,
363
- artifactReady: extensionHeaderId(contents) === newId && apiManifestReady,
364
- contents,
365
- extension,
366
- rewrite,
367
- source,
368
- };
369
- }
370
-
371
- export async function planExtensionIdMigration({fromId, sourceDirectory, toId}) {
372
- const context = await migrationContext(sourceDirectory, fromId, toId, false);
373
- return {
374
- artifactReady: context.artifactReady,
375
- counts: context.rewrite.counts,
376
- fromId,
377
- sourceDirectory: context.source.resolvedSourceDirectory,
378
- toId,
379
- totalChanges: context.rewrite.totalChanges,
380
- unclassifiedReferences: context.rewrite.unclassifiedReferences,
381
- };
382
- }
383
-
384
- export async function migrateExtensionId({fromId, sourceDirectory, toId, yes = false}) {
385
- const context = await migrationContext(sourceDirectory, fromId, toId, yes);
386
- const plan = {
387
- artifactReady: context.artifactReady,
388
- counts: context.rewrite.counts,
389
- fromId,
390
- sourceDirectory: context.source.resolvedSourceDirectory,
391
- toId,
392
- totalChanges: context.rewrite.totalChanges,
393
- unclassifiedReferences: context.rewrite.unclassifiedReferences,
394
- };
395
- if (!yes) {
396
- return {
397
- applied: false,
398
- changed: false,
399
- ...plan,
400
- rollbackCleanupWarning: null,
401
- };
402
- }
403
-
404
- assert(
405
- context.artifactReady,
406
- `Extension artifact must declare // ID: ${toId} before migration. ` +
407
- `For managed extensions, use extensions update ${fromId} --migrate-id ${toId}.`,
408
- );
409
- if (context.extension.source) {
410
- assert(
411
- extensionIntegrity(context.contents) === context.extension.source.integrity,
412
- `Managed extension ${fromId} does not match its source integrity. ` +
413
- 'Use extensions update with --migrate-id so provenance is updated atomically.',
414
- );
415
- }
416
- const initialComparison = await compareDirectories(
417
- context.source.resolvedSourceDirectory,
418
- context.source.resolvedSourceDirectory,
419
- );
420
- assert(
421
- initialComparison.identical &&
422
- initialComparison.existingFingerprint === initialComparison.candidateFingerprint,
423
- 'SB3 source changed while its initial migration state was being inspected.',
424
- );
425
-
426
- const parentDirectory = path.dirname(context.source.resolvedSourceDirectory);
427
- const candidateDirectory = await mkdtemp(
428
- path.join(parentDirectory, `.${path.basename(context.source.resolvedSourceDirectory)}.id-`),
429
- );
430
- let installed = false;
431
- try {
432
- await cp(context.source.resolvedSourceDirectory, candidateDirectory, {
433
- preserveTimestamps: true,
434
- recursive: true,
435
- verbatimSymlinks: true,
436
- });
437
- const replacements = [
438
- writeFile(
439
- path.join(candidateDirectory, context.source.sourceManifest.project),
440
- `${JSON.stringify(context.rewrite.project, null, 2)}\n`,
441
- ),
442
- writeFile(
443
- path.join(candidateDirectory, context.source.sourceManifest.embeddedExtensions),
444
- `${JSON.stringify(context.rewrite.extensionManifest, null, 2)}\n`,
445
- ),
446
- rename(
447
- path.join(candidateDirectory, context.rewrite.oldPath),
448
- path.join(candidateDirectory, context.rewrite.newPath),
449
- ),
450
- ];
451
- if (context.rewrite.oldApiManifestPath && context.rewrite.newApiManifestPath) {
452
- replacements.push(
453
- rename(
454
- path.join(candidateDirectory, context.rewrite.oldApiManifestPath),
455
- path.join(candidateDirectory, context.rewrite.newApiManifestPath),
456
- ),
457
- );
458
- }
459
- await Promise.all(replacements);
460
- await createDeterministicSb3(candidateDirectory);
461
- const comparison = await compareDirectories(
462
- context.source.resolvedSourceDirectory,
463
- candidateDirectory,
464
- );
465
- assert(
466
- comparison.existingFingerprint === initialComparison.existingFingerprint,
467
- 'SB3 source changed while the ID migration candidate was prepared; refusing to replace it.',
468
- );
469
- assert(!comparison.identical, 'Extension ID migration produced no source changes.');
470
- const latestComparison = await compareDirectories(
471
- context.source.resolvedSourceDirectory,
472
- candidateDirectory,
473
- );
474
- assert(
475
- latestComparison.existingFingerprint === comparison.existingFingerprint &&
476
- latestComparison.candidateFingerprint === comparison.candidateFingerprint,
477
- 'SB3 source or ID migration candidate changed during migration; refusing to replace it.',
478
- );
479
- const replacement = await replaceDirectoryTransactionally(
480
- candidateDirectory,
481
- context.source.resolvedSourceDirectory,
482
- );
483
- installed = true;
484
- return {
485
- applied: true,
486
- changed: true,
487
- comparison,
488
- ...plan,
489
- ...replacement,
490
- };
491
- } finally {
492
- if (!installed) {
493
- await rm(candidateDirectory, {recursive: true, force: true});
494
- }
495
- }
496
- }