@kubohiroya/sb3-toolchain 0.1.1 → 0.3.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.
package/src/build.js CHANGED
@@ -103,8 +103,13 @@ async function installArchiveTransactionally(archive, outputPath, expectedOutput
103
103
  }
104
104
  }
105
105
 
106
- export async function buildSb3({confirmReplace, outputPath, sourceDirectory, yes = false}) {
107
- assert(typeof sourceDirectory === 'string', 'SB3 source directory is required.');
106
+ export async function writeSb3Archive({
107
+ archive,
108
+ confirmReplace = undefined,
109
+ outputPath,
110
+ yes = false,
111
+ }) {
112
+ assert(archive instanceof Uint8Array, 'SB3 archive contents are required.');
108
113
  assert(typeof outputPath === 'string', 'SB3 output path is required.');
109
114
  const resolvedOutputPath = path.resolve(outputPath);
110
115
  assert(
@@ -112,12 +117,10 @@ export async function buildSb3({confirmReplace, outputPath, sourceDirectory, yes
112
117
  `SB3 output path must use the .sb3 extension: ${resolvedOutputPath}`,
113
118
  );
114
119
  await assertNoInterruptedRollback(resolvedOutputPath);
115
- const built = await createDeterministicSb3(sourceDirectory);
116
120
  const existingOutput = await inspectOutput(resolvedOutputPath);
117
121
  if (existingOutput.exists) {
118
- if (Buffer.compare(existingOutput.contents, Buffer.from(built.archive)) === 0) {
122
+ if (Buffer.compare(existingOutput.contents, Buffer.from(archive)) === 0) {
119
123
  return {
120
- ...built,
121
124
  changed: false,
122
125
  outputPath: resolvedOutputPath,
123
126
  rollbackCleanupWarning: null,
@@ -138,14 +141,25 @@ export async function buildSb3({confirmReplace, outputPath, sourceDirectory, yes
138
141
 
139
142
  await mkdir(path.dirname(resolvedOutputPath), {recursive: true});
140
143
  const rollbackCleanupWarning = await installArchiveTransactionally(
141
- built.archive,
144
+ archive,
142
145
  resolvedOutputPath,
143
146
  existingOutput,
144
147
  );
145
148
  return {
146
- ...built,
147
149
  changed: true,
148
150
  outputPath: resolvedOutputPath,
149
151
  rollbackCleanupWarning,
150
152
  };
151
153
  }
154
+
155
+ export async function buildSb3({confirmReplace, outputPath, sourceDirectory, yes = false}) {
156
+ assert(typeof sourceDirectory === 'string', 'SB3 source directory is required.');
157
+ const built = await createDeterministicSb3(sourceDirectory);
158
+ const written = await writeSb3Archive({
159
+ archive: built.archive,
160
+ confirmReplace,
161
+ outputPath,
162
+ yes,
163
+ });
164
+ return {...built, ...written};
165
+ }
package/src/cli.js CHANGED
@@ -6,6 +6,8 @@ import {createInterface} from 'node:readline/promises';
6
6
 
7
7
  import {buildSb3} from './build.js';
8
8
  import {packageVersion} from './constants.js';
9
+ import {bundleExtensions, unbundleExtensions} from './extension-bundle-configuration.js';
10
+ import {unbundleSb3} from './extension-bundle-archive.js';
9
11
  import {migrateExtensionId} from './extension-id-migration.js';
10
12
  import {extensionStatus, syncExtensions, updateExtensions} from './extension-sync.js';
11
13
  import {importSb3} from './import.js';
@@ -24,8 +26,11 @@ export function usage() {
24
26
  sb3-toolchain build SOURCE_DIR --output OUTPUT.sb3 [--yes]
25
27
  sb3-toolchain extensions status SOURCE_DIR
26
28
  sb3-toolchain extensions sync SOURCE_DIR [--yes]
27
- sb3-toolchain extensions update SOURCE_DIR [EXTENSION_ID] [--migrate-id NEW_ID] [--artifact PATH] [--yes]
29
+ sb3-toolchain extensions update SOURCE_DIR [EXTENSION_ID] [--migrate-id NEW_ID] [--artifact PATH] [--api-manifest-artifact PATH] [--allow-breaking-api --yes]
28
30
  sb3-toolchain extensions migrate-id SOURCE_DIR --from OLD_ID --to NEW_ID [--yes]
31
+ sb3-toolchain extensions bundle SOURCE_DIR --id BUNDLE_ID --name NAME [EXTENSION_ID ...] [--yes]
32
+ sb3-toolchain extensions unbundle SOURCE_DIR BUNDLE_ID [--yes]
33
+ sb3-toolchain extensions unbundle INPUT.sb3 BUNDLE_ID --output OUTPUT.sb3 [--yes]
29
34
 
30
35
  Commands:
31
36
  import Expand an SB3 into Git-friendly source files.
@@ -110,6 +115,8 @@ function parseBuildArguments(arguments_) {
110
115
  }
111
116
 
112
117
  function parseExtensionMutationArguments(action, arguments_) {
118
+ let allowBreakingApi = false;
119
+ let apiManifestArtifact;
113
120
  let sourceDirectory;
114
121
  let extensionId;
115
122
  let migrateToId;
@@ -120,6 +127,9 @@ function parseExtensionMutationArguments(action, arguments_) {
120
127
  const argument = arguments_[index];
121
128
  if (argument === '--yes') {
122
129
  yes = true;
130
+ } else if (argument === '--allow-breaking-api') {
131
+ assert(action === 'update', '--allow-breaking-api is only valid for extensions update.');
132
+ allowBreakingApi = true;
123
133
  } else if (argument === '--migrate-id') {
124
134
  assert(action === 'update', '--migrate-id is only valid for extensions update.');
125
135
  migrateToId = takeValue(arguments_, index, '--migrate-id');
@@ -128,6 +138,10 @@ function parseExtensionMutationArguments(action, arguments_) {
128
138
  assert(action === 'update', '--artifact is only valid for extensions update.');
129
139
  sourceArtifact = takeValue(arguments_, index, '--artifact');
130
140
  index += 1;
141
+ } else if (argument === '--api-manifest-artifact') {
142
+ assert(action === 'update', '--api-manifest-artifact is only valid for extensions update.');
143
+ apiManifestArtifact = takeValue(arguments_, index, '--api-manifest-artifact');
144
+ index += 1;
131
145
  } else {
132
146
  assert(!argument.startsWith('-'), `Unknown option: ${argument}`);
133
147
  if (!sourceDirectory) {
@@ -153,8 +167,15 @@ function parseExtensionMutationArguments(action, arguments_) {
153
167
  sourceArtifact === undefined || migrateToId !== undefined,
154
168
  '--artifact requires --migrate-id.',
155
169
  );
170
+ assert(
171
+ apiManifestArtifact === undefined || migrateToId !== undefined,
172
+ '--api-manifest-artifact requires --migrate-id.',
173
+ );
174
+ assert(!allowBreakingApi || yes, '--allow-breaking-api requires --yes.');
156
175
  return {
157
176
  action,
177
+ ...(allowBreakingApi ? {allowBreakingApi} : {}),
178
+ ...(apiManifestArtifact ? {apiManifestArtifact} : {}),
158
179
  command: 'extensions',
159
180
  extensionId,
160
181
  migrateToId,
@@ -199,11 +220,105 @@ function parseExtensionIdMigrationArguments(arguments_) {
199
220
  };
200
221
  }
201
222
 
223
+ function parseExtensionBundleArguments(arguments_) {
224
+ let bundleId;
225
+ let bundleName;
226
+ let sourceDirectory;
227
+ const extensionIds = [];
228
+ let yes = false;
229
+
230
+ for (let index = 0; index < arguments_.length; index += 1) {
231
+ const argument = arguments_[index];
232
+ if (argument === '--id') {
233
+ bundleId = takeValue(arguments_, index, '--id');
234
+ index += 1;
235
+ } else if (argument === '--name') {
236
+ bundleName = takeValue(arguments_, index, '--name');
237
+ index += 1;
238
+ } else if (argument === '--yes') {
239
+ yes = true;
240
+ } else {
241
+ assert(!argument.startsWith('-'), `Unknown option: ${argument}`);
242
+ if (!sourceDirectory) {
243
+ sourceDirectory = path.resolve(argument);
244
+ } else {
245
+ assert(
246
+ /^[a-z0-9]+$/u.test(argument),
247
+ `Bundle member ID must use TurboWarp's [a-z0-9]+ format: ${JSON.stringify(argument)}`,
248
+ );
249
+ extensionIds.push(argument);
250
+ }
251
+ }
252
+ }
253
+ assert(sourceDirectory, 'The extensions bundle command requires SOURCE_DIR.');
254
+ assert(bundleId, 'The extensions bundle command requires --id BUNDLE_ID.');
255
+ assert(bundleName, 'The extensions bundle command requires --name NAME.');
256
+ return {
257
+ action: 'bundle',
258
+ bundleId,
259
+ bundleName,
260
+ command: 'extensions',
261
+ extensionIds,
262
+ sourceDirectory,
263
+ yes,
264
+ };
265
+ }
266
+
267
+ function parseExtensionUnbundleArguments(arguments_) {
268
+ let bundleId;
269
+ let input;
270
+ let outputPath;
271
+ let yes = false;
272
+ for (let index = 0; index < arguments_.length; index += 1) {
273
+ const argument = arguments_[index];
274
+ if (argument === '--yes') {
275
+ yes = true;
276
+ } else if (argument === '--output') {
277
+ outputPath = path.resolve(takeValue(arguments_, index, '--output'));
278
+ index += 1;
279
+ } else {
280
+ assert(!argument.startsWith('-'), `Unknown option: ${argument}`);
281
+ if (!input) {
282
+ input = path.resolve(argument);
283
+ } else {
284
+ assert(!bundleId, 'Only one BUNDLE_ID may be specified.');
285
+ bundleId = argument;
286
+ }
287
+ }
288
+ }
289
+ assert(input, 'The extensions unbundle command requires SOURCE_DIR or INPUT.sb3.');
290
+ assert(bundleId, 'The extensions unbundle command requires BUNDLE_ID.');
291
+ if (path.extname(input).toLowerCase() === '.sb3') {
292
+ assert(outputPath, 'SB3 unbundle requires --output OUTPUT.sb3.');
293
+ return {
294
+ action: 'unbundle',
295
+ bundleId,
296
+ command: 'extensions',
297
+ inputPath: input,
298
+ outputPath,
299
+ yes,
300
+ };
301
+ }
302
+ assert(!outputPath, '--output is only valid when unbundling an SB3 file.');
303
+ return {
304
+ action: 'unbundle',
305
+ bundleId,
306
+ command: 'extensions',
307
+ sourceDirectory: input,
308
+ yes,
309
+ };
310
+ }
311
+
202
312
  function parseExtensionsArguments(arguments_) {
203
313
  const [action, ...actionArguments] = arguments_;
204
314
  assert(
205
- action === 'migrate-id' || action === 'status' || action === 'sync' || action === 'update',
206
- 'The extensions command requires status, sync, update, or migrate-id.',
315
+ action === 'bundle' ||
316
+ action === 'migrate-id' ||
317
+ action === 'status' ||
318
+ action === 'sync' ||
319
+ action === 'unbundle' ||
320
+ action === 'update',
321
+ 'The extensions command requires status, sync, update, migrate-id, bundle, or unbundle.',
207
322
  );
208
323
  if (action === 'status') {
209
324
  assert(
@@ -219,6 +334,12 @@ function parseExtensionsArguments(arguments_) {
219
334
  if (action === 'migrate-id') {
220
335
  return parseExtensionIdMigrationArguments(actionArguments);
221
336
  }
337
+ if (action === 'bundle') {
338
+ return parseExtensionBundleArguments(actionArguments);
339
+ }
340
+ if (action === 'unbundle') {
341
+ return parseExtensionUnbundleArguments(actionArguments);
342
+ }
222
343
  return parseExtensionMutationArguments(action, actionArguments);
223
344
  }
224
345
 
@@ -374,6 +495,48 @@ export async function runCli(
374
495
  return;
375
496
  }
376
497
  if (options.command === 'extensions') {
498
+ if (options.action === 'bundle') {
499
+ const result = await bundleExtensions({
500
+ bundleId: options.bundleId,
501
+ bundleName: options.bundleName,
502
+ extensionIds: options.extensionIds,
503
+ sourceDirectory: options.sourceDirectory,
504
+ yes: options.yes,
505
+ });
506
+ log(
507
+ `${result.applied ? 'Configured' : 'Dry run'} extension bundle: ${result.bundleId} ` +
508
+ `(${result.members.join(', ')}).`,
509
+ );
510
+ if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
511
+ return;
512
+ }
513
+ if (options.action === 'unbundle') {
514
+ if ('inputPath' in options) {
515
+ const result = await unbundleSb3({
516
+ bundleId: options.bundleId,
517
+ inputPath: options.inputPath,
518
+ outputPath: options.outputPath,
519
+ yes: options.yes,
520
+ });
521
+ log(
522
+ `${result.applied ? 'Wrote' : 'Dry run'} unbundled SB3: ${result.bundleId} ` +
523
+ `(${result.members.join(', ')}) -> ${result.outputPath}.`,
524
+ );
525
+ if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
526
+ return;
527
+ }
528
+ const result = await unbundleExtensions({
529
+ bundleId: options.bundleId,
530
+ sourceDirectory: options.sourceDirectory,
531
+ yes: options.yes,
532
+ });
533
+ log(
534
+ `${result.applied ? 'Removed' : 'Dry run'} extension bundle: ${result.bundleId} ` +
535
+ `(${result.members.join(', ')}).`,
536
+ );
537
+ if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
538
+ return;
539
+ }
377
540
  if (options.action === 'migrate-id') {
378
541
  const result = await migrateExtensionId({
379
542
  fromId: options.fromId,
@@ -414,6 +577,8 @@ export async function runCli(
414
577
  ? await syncExtensions(operationOptions)
415
578
  : await updateExtensions({
416
579
  ...operationOptions,
580
+ allowBreakingApi: options.allowBreakingApi,
581
+ apiManifestArtifact: options.apiManifestArtifact,
417
582
  extensionId: options.extensionId,
418
583
  migrateToId: options.migrateToId,
419
584
  sourceArtifact: options.sourceArtifact,
@@ -433,6 +598,14 @@ export async function runCli(
433
598
  log,
434
599
  );
435
600
  }
601
+ for (const compatibility of result.apiCompatibility) {
602
+ for (const change of compatibility.changes) {
603
+ log(
604
+ `API ${compatibility.id}: ${change.breaking ? 'breaking' : 'compatible'} ` +
605
+ `${change.kind} ${change.path}`,
606
+ );
607
+ }
608
+ }
436
609
  if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
437
610
  return;
438
611
  }
package/src/constants.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // SPDX-License-Identifier: MPL-2.0
2
2
 
3
3
  export const packageName = '@kubohiroya/sb3-toolchain';
4
- export const packageVersion = '0.1.1';
4
+ export const packageVersion = '0.3.0';
@@ -0,0 +1,336 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ import {createHash} from 'node:crypto';
4
+
5
+ import {validateArchiveEntryName} from './archive.js';
6
+
7
+ export const extensionApiManifestFormatVersion = 1;
8
+ export const defaultExtensionApiManifestSizeLimit = 1024 * 1024;
9
+
10
+ function assert(condition, message) {
11
+ if (!condition) {
12
+ throw new Error(message);
13
+ }
14
+ }
15
+
16
+ function isObject(value) {
17
+ return value && typeof value === 'object' && !Array.isArray(value);
18
+ }
19
+
20
+ function assertExactProperties(value, expected, description) {
21
+ const expectedProperties = new Set(expected);
22
+ const unexpected = Object.keys(value).filter((property) => !expectedProperties.has(property));
23
+ assert(
24
+ unexpected.length === 0,
25
+ `${description} has unsupported properties: ${unexpected.join(', ')}`,
26
+ );
27
+ }
28
+
29
+ function assertNonEmptyString(value, description) {
30
+ assert(
31
+ typeof value === 'string' && value.length > 0,
32
+ `${description} must be a non-empty string.`,
33
+ );
34
+ return value;
35
+ }
36
+
37
+ function compareIds(left, right) {
38
+ return left < right ? -1 : left > right ? 1 : 0;
39
+ }
40
+
41
+ function escapeJsonPointer(value) {
42
+ return value.replaceAll('~', '~0').replaceAll('/', '~1');
43
+ }
44
+
45
+ export function extensionApiManifestIntegrity(contents) {
46
+ return `sha256-${createHash('sha256').update(contents).digest('base64')}`;
47
+ }
48
+
49
+ export function extensionApiManifestLocalPath(extensionId) {
50
+ return `extensions/${extensionId}.manifest.json`;
51
+ }
52
+
53
+ export function validateExtensionApiManifestSourceMetadata(extension) {
54
+ const metadata = extension.source?.apiManifest;
55
+ if (metadata === undefined) return null;
56
+ assert(
57
+ isObject(metadata),
58
+ `Managed extension API manifest metadata must be an object: ${extension.id}`,
59
+ );
60
+ assertExactProperties(
61
+ metadata,
62
+ ['artifact', 'formatVersion', 'integrity', 'path'],
63
+ `Managed extension API manifest metadata for ${extension.id}`,
64
+ );
65
+ assert(
66
+ metadata.formatVersion === extensionApiManifestFormatVersion,
67
+ `Managed extension ${extension.id} requires API manifest formatVersion ${extensionApiManifestFormatVersion}.`,
68
+ );
69
+ assertNonEmptyString(
70
+ metadata.artifact,
71
+ `Managed extension ${extension.id} API manifest artifact`,
72
+ );
73
+ validateArchiveEntryName(metadata.artifact);
74
+ assert(
75
+ !metadata.artifact.endsWith('/'),
76
+ `Managed extension API manifest artifact must be a file: ${metadata.artifact}`,
77
+ );
78
+ const expectedPath = extensionApiManifestLocalPath(extension.id);
79
+ assert(
80
+ metadata.path === expectedPath,
81
+ `Managed extension API manifest path must match its ID: expected ${expectedPath}, got ${metadata.path}`,
82
+ );
83
+ assert(
84
+ typeof metadata.integrity === 'string' &&
85
+ /^sha256-[A-Za-z0-9+/]{43}=$/u.test(metadata.integrity),
86
+ `Managed extension ${extension.id} API manifest requires SHA-256 integrity.`,
87
+ );
88
+ return metadata;
89
+ }
90
+
91
+ function normalizeArgument(value, blockOpcode, index, menuIds) {
92
+ assert(isObject(value), `API manifest block ${blockOpcode} argument ${index} must be an object.`);
93
+ assertExactProperties(
94
+ value,
95
+ ['id', 'menu', 'type'],
96
+ `API manifest block ${blockOpcode} argument ${index}`,
97
+ );
98
+ const id = assertNonEmptyString(
99
+ value.id,
100
+ `API manifest block ${blockOpcode} argument ${index} ID`,
101
+ );
102
+ const type = assertNonEmptyString(
103
+ value.type,
104
+ `API manifest block ${blockOpcode} argument ${id} type`,
105
+ );
106
+ if (value.menu !== undefined) {
107
+ assertNonEmptyString(value.menu, `API manifest block ${blockOpcode} argument ${id} menu`);
108
+ assert(
109
+ menuIds.has(value.menu),
110
+ `API manifest block ${blockOpcode} argument ${id} references unknown menu: ${value.menu}`,
111
+ );
112
+ }
113
+ return value.menu === undefined ? {id, type} : {id, menu: value.menu, type};
114
+ }
115
+
116
+ function normalizeBlock(value, index, menuIds) {
117
+ assert(isObject(value), `API manifest block ${index} must be an object.`);
118
+ assertExactProperties(value, ['arguments', 'blockType', 'opcode'], `API manifest block ${index}`);
119
+ const opcode = assertNonEmptyString(value.opcode, `API manifest block ${index} opcode`);
120
+ const blockType = assertNonEmptyString(value.blockType, `API manifest block ${opcode} blockType`);
121
+ assert(
122
+ Array.isArray(value.arguments),
123
+ `API manifest block ${opcode} arguments must be an array.`,
124
+ );
125
+ const arguments_ = value.arguments.map((argument, argumentIndex) =>
126
+ normalizeArgument(argument, opcode, argumentIndex, menuIds),
127
+ );
128
+ const argumentIds = new Set();
129
+ for (const argument of arguments_) {
130
+ assert(
131
+ !argumentIds.has(argument.id),
132
+ `API manifest block ${opcode} has duplicate argument ID: ${argument.id}`,
133
+ );
134
+ argumentIds.add(argument.id);
135
+ }
136
+ arguments_.sort((left, right) => compareIds(left.id, right.id));
137
+ return {arguments: arguments_, blockType, opcode};
138
+ }
139
+
140
+ function normalizeMenu(value, index) {
141
+ assert(isObject(value), `API manifest menu ${index} must be an object.`);
142
+ assertExactProperties(value, ['acceptReporters', 'id'], `API manifest menu ${index}`);
143
+ const id = assertNonEmptyString(value.id, `API manifest menu ${index} ID`);
144
+ assert(
145
+ typeof value.acceptReporters === 'boolean',
146
+ `API manifest menu ${id} acceptReporters must be a boolean.`,
147
+ );
148
+ return {acceptReporters: value.acceptReporters, id};
149
+ }
150
+
151
+ /**
152
+ * @param {string | Uint8Array} contents
153
+ * @param {{expectedId?: string}} [options]
154
+ */
155
+ export function parseExtensionApiManifest(contents, {expectedId} = {}) {
156
+ let manifest;
157
+ try {
158
+ manifest = JSON.parse(Buffer.from(contents).toString('utf8'));
159
+ } catch (error) {
160
+ throw new Error(`Extension API manifest is not valid JSON: ${error.message}`, {cause: error});
161
+ }
162
+ assert(isObject(manifest), 'Extension API manifest must contain an object.');
163
+ assertExactProperties(
164
+ manifest,
165
+ ['blocks', 'formatVersion', 'id', 'menus'],
166
+ 'Extension API manifest',
167
+ );
168
+ assert(
169
+ manifest.formatVersion === extensionApiManifestFormatVersion,
170
+ `Unsupported extension API manifest formatVersion: ${manifest.formatVersion}`,
171
+ );
172
+ assert(
173
+ typeof manifest.id === 'string' && /^[a-z0-9]+$/u.test(manifest.id),
174
+ `Invalid extension API manifest ID: ${JSON.stringify(manifest.id)}`,
175
+ );
176
+ if (expectedId !== undefined) {
177
+ assert(
178
+ manifest.id === expectedId,
179
+ `Extension API manifest ID mismatch: expected ${expectedId}, got ${manifest.id}`,
180
+ );
181
+ }
182
+ assert(Array.isArray(manifest.menus), 'Extension API manifest menus must be an array.');
183
+ const menus = manifest.menus.map(normalizeMenu);
184
+ const menuIds = new Set();
185
+ for (const menu of menus) {
186
+ assert(!menuIds.has(menu.id), `Extension API manifest has duplicate menu ID: ${menu.id}`);
187
+ menuIds.add(menu.id);
188
+ }
189
+ assert(Array.isArray(manifest.blocks), 'Extension API manifest blocks must be an array.');
190
+ const blocks = manifest.blocks.map((block, index) => normalizeBlock(block, index, menuIds));
191
+ const blockOpcodes = new Set();
192
+ for (const block of blocks) {
193
+ assert(
194
+ !blockOpcodes.has(block.opcode),
195
+ `Extension API manifest has duplicate block opcode: ${block.opcode}`,
196
+ );
197
+ blockOpcodes.add(block.opcode);
198
+ }
199
+ blocks.sort((left, right) => compareIds(left.opcode, right.opcode));
200
+ menus.sort((left, right) => compareIds(left.id, right.id));
201
+ return {blocks, formatVersion: extensionApiManifestFormatVersion, id: manifest.id, menus};
202
+ }
203
+
204
+ export function validateManagedExtensionApiManifest(
205
+ extension,
206
+ contents,
207
+ {expectedId = extension.id} = {},
208
+ ) {
209
+ const metadata = validateExtensionApiManifestSourceMetadata(extension);
210
+ if (!metadata) return null;
211
+ const actualIntegrity = extensionApiManifestIntegrity(contents);
212
+ assert(
213
+ actualIntegrity === metadata.integrity,
214
+ `Managed extension API manifest integrity mismatch for ${extension.id}: ` +
215
+ `expected ${metadata.integrity}, got ${actualIntegrity}`,
216
+ );
217
+ const manifest = parseExtensionApiManifest(contents, {expectedId});
218
+ assert(
219
+ manifest.formatVersion === metadata.formatVersion,
220
+ `Managed extension API manifest version mismatch for ${extension.id}.`,
221
+ );
222
+ return {integrity: actualIntegrity, manifest, metadata};
223
+ }
224
+
225
+ function addChange(changes, kind, path, before, after, breaking) {
226
+ changes.push({after, before, breaking, kind, path});
227
+ }
228
+
229
+ export function compareExtensionApiManifests(installed, candidate) {
230
+ const changes = [];
231
+ const installedBlocks = new Map(installed.blocks.map((block) => [block.opcode, block]));
232
+ const candidateBlocks = new Map(candidate.blocks.map((block) => [block.opcode, block]));
233
+ for (const [opcode, block] of installedBlocks) {
234
+ const path = `/blocks/${escapeJsonPointer(opcode)}`;
235
+ const replacement = candidateBlocks.get(opcode);
236
+ if (!replacement) {
237
+ addChange(changes, 'block-removed', path, block, null, true);
238
+ continue;
239
+ }
240
+ if (block.blockType !== replacement.blockType) {
241
+ addChange(
242
+ changes,
243
+ 'block-type-changed',
244
+ `${path}/blockType`,
245
+ block.blockType,
246
+ replacement.blockType,
247
+ true,
248
+ );
249
+ }
250
+ const installedArguments = new Map(block.arguments.map((argument) => [argument.id, argument]));
251
+ const candidateArguments = new Map(
252
+ replacement.arguments.map((argument) => [argument.id, argument]),
253
+ );
254
+ for (const [argumentId, argument] of installedArguments) {
255
+ const argumentPath = `${path}/arguments/${escapeJsonPointer(argumentId)}`;
256
+ const replacementArgument = candidateArguments.get(argumentId);
257
+ if (!replacementArgument) {
258
+ addChange(changes, 'argument-removed', argumentPath, argument, null, true);
259
+ continue;
260
+ }
261
+ for (const property of ['type', 'menu']) {
262
+ if (argument[property] !== replacementArgument[property]) {
263
+ addChange(
264
+ changes,
265
+ `argument-${property}-changed`,
266
+ `${argumentPath}/${property}`,
267
+ argument[property] ?? null,
268
+ replacementArgument[property] ?? null,
269
+ true,
270
+ );
271
+ }
272
+ }
273
+ }
274
+ for (const [argumentId, argument] of candidateArguments) {
275
+ if (!installedArguments.has(argumentId)) {
276
+ addChange(
277
+ changes,
278
+ 'argument-added',
279
+ `${path}/arguments/${escapeJsonPointer(argumentId)}`,
280
+ null,
281
+ argument,
282
+ true,
283
+ );
284
+ }
285
+ }
286
+ }
287
+ for (const [opcode, block] of candidateBlocks) {
288
+ if (!installedBlocks.has(opcode)) {
289
+ addChange(changes, 'block-added', `/blocks/${escapeJsonPointer(opcode)}`, null, block, false);
290
+ }
291
+ }
292
+
293
+ const installedMenus = new Map(installed.menus.map((menu) => [menu.id, menu]));
294
+ const candidateMenus = new Map(candidate.menus.map((menu) => [menu.id, menu]));
295
+ const referencedInstalledMenus = new Set();
296
+ for (const block of installed.blocks) {
297
+ for (const argument of block.arguments) {
298
+ if (argument.menu !== undefined) referencedInstalledMenus.add(argument.menu);
299
+ }
300
+ }
301
+ for (const [menuId, menu] of installedMenus) {
302
+ const path = `/menus/${escapeJsonPointer(menuId)}`;
303
+ const replacement = candidateMenus.get(menuId);
304
+ if (!replacement) {
305
+ addChange(changes, 'menu-removed', path, menu, null, referencedInstalledMenus.has(menuId));
306
+ } else if (menu.acceptReporters !== replacement.acceptReporters) {
307
+ addChange(
308
+ changes,
309
+ 'menu-accept-reporters-changed',
310
+ `${path}/acceptReporters`,
311
+ menu.acceptReporters,
312
+ replacement.acceptReporters,
313
+ true,
314
+ );
315
+ }
316
+ }
317
+ for (const [menuId, menu] of candidateMenus) {
318
+ if (!installedMenus.has(menuId)) {
319
+ addChange(changes, 'menu-added', `/menus/${escapeJsonPointer(menuId)}`, null, menu, false);
320
+ }
321
+ }
322
+ return changes.sort((left, right) =>
323
+ left.path === right.path
324
+ ? compareIds(left.kind, right.kind)
325
+ : compareIds(left.path, right.path),
326
+ );
327
+ }
328
+
329
+ export function formatExtensionApiCompatibilityChanges(extensionId, changes) {
330
+ return changes
331
+ .map(
332
+ (change) =>
333
+ `${extensionId} ${change.breaking ? 'breaking' : 'compatible'} ${change.kind} ${change.path}`,
334
+ )
335
+ .join('\n');
336
+ }