@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,695 +0,0 @@
1
- // SPDX-License-Identifier: MPL-2.0
2
-
3
- import {extensionHeaderMetadata} from './extension-dependencies.js';
4
-
5
- export const extensionBundleRecoveryMarker = 'SB3-Toolchain-Reversible-Bundle-v1';
6
-
7
- function assert(condition, message) {
8
- if (!condition) {
9
- throw new Error(message);
10
- }
11
- }
12
-
13
- function isObject(value) {
14
- return value && typeof value === 'object' && !Array.isArray(value);
15
- }
16
-
17
- function validateBundleId(id, description = 'Extension bundle ID') {
18
- assert(
19
- typeof id === 'string' && /^[a-z0-9]+$/u.test(id),
20
- `${description} must use TurboWarp's [a-z0-9]+ format: ${JSON.stringify(id)}`,
21
- );
22
- return id;
23
- }
24
-
25
- function validateBundleName(name) {
26
- assert(
27
- typeof name === 'string' && name.trim() === name && name.length > 0 && !/[\r\n]/u.test(name),
28
- `Extension bundle name must be a non-empty single line: ${JSON.stringify(name)}`,
29
- );
30
- return name;
31
- }
32
-
33
- export function validateExtensionBundleConfigurations(extensionBundles, extensions) {
34
- if (extensionBundles === undefined) return [];
35
- assert(
36
- Array.isArray(extensionBundles),
37
- 'embedded-extensions.json extensionBundles must be an array.',
38
- );
39
-
40
- const extensionsById = new Map(extensions.map((extension) => [extension.id, extension]));
41
- const bundleIds = new Set();
42
- const bundledMemberIds = new Set();
43
-
44
- return extensionBundles.map((bundle, bundleIndex) => {
45
- assert(isObject(bundle), `Extension bundle ${bundleIndex} must be an object.`);
46
- validateBundleId(bundle.id, `Extension bundle ${bundleIndex} ID`);
47
- validateBundleName(bundle.name);
48
- assert(
49
- !extensionsById.has(bundle.id),
50
- `Extension bundle ID collides with an extension: ${bundle.id}`,
51
- );
52
- assert(!bundleIds.has(bundle.id), `Duplicate extension bundle ID: ${bundle.id}`);
53
- bundleIds.add(bundle.id);
54
- assert(
55
- Array.isArray(bundle.members) && bundle.members.length >= 2,
56
- `Extension bundle ${bundle.id} must contain at least two members.`,
57
- );
58
- assert(
59
- bundle.recoveryCapsule === undefined || typeof bundle.recoveryCapsule === 'boolean',
60
- `Extension bundle ${bundle.id} recoveryCapsule must be a boolean when present.`,
61
- );
62
-
63
- const localMemberIds = new Set();
64
- for (const memberId of bundle.members) {
65
- validateBundleId(memberId, `Extension bundle ${bundle.id} member ID`);
66
- assert(
67
- extensionsById.has(memberId),
68
- `Extension bundle ${bundle.id} has unknown member: ${memberId}`,
69
- );
70
- assert(
71
- !localMemberIds.has(memberId),
72
- `Extension bundle ${bundle.id} repeats member: ${memberId}`,
73
- );
74
- assert(
75
- !bundledMemberIds.has(memberId),
76
- `Embedded extension belongs to more than one bundle: ${memberId}`,
77
- );
78
- localMemberIds.add(memberId);
79
- bundledMemberIds.add(memberId);
80
- }
81
- return {
82
- id: bundle.id,
83
- members: [...bundle.members],
84
- name: bundle.name,
85
- ...(bundle.recoveryCapsule === undefined ? {} : {recoveryCapsule: bundle.recoveryCapsule}),
86
- };
87
- });
88
- }
89
-
90
- function readBundleComponents(bundle, extensionsById, extensionContents) {
91
- return bundle.members.map((memberId) => {
92
- const extension = extensionsById.get(memberId);
93
- const contents = extensionContents.get(memberId);
94
- assert(contents, `Extension bundle ${bundle.id} has no contents for member: ${memberId}`);
95
- assert(
96
- extension.mediaType === 'text/javascript' || extension.mediaType === 'application/javascript',
97
- `Extension bundle ${bundle.id} member ${memberId} must be JavaScript, got ${extension.mediaType}.`,
98
- );
99
- const metadata = extensionHeaderMetadata(contents);
100
- assert(
101
- metadata.id === memberId,
102
- `Extension bundle ${bundle.id} member header ID mismatch: expected ${memberId}, ` +
103
- `got ${metadata.id ?? '(missing)'}`,
104
- );
105
- for (const [property, label] of [
106
- ['name', 'Name'],
107
- ['author', 'By'],
108
- ['description', 'Description'],
109
- ['license', 'License'],
110
- ]) {
111
- assert(
112
- metadata[property],
113
- `Extension bundle ${bundle.id} member ${memberId} requires a // ${label}: header.`,
114
- );
115
- }
116
- const source = Buffer.from(contents).toString('utf8');
117
- assert(
118
- !source.startsWith('#!'),
119
- `Extension bundle ${bundle.id} member ${memberId} cannot use a shebang.`,
120
- );
121
- assert(
122
- !source.includes(extensionBundleRecoveryMarker),
123
- `Extension bundle ${bundle.id} member ${memberId} contains the reserved recovery marker.`,
124
- );
125
- const registrations = source.match(/\bScratch\s*\.\s*extensions\s*\.\s*register\s*\(/gu) ?? [];
126
- assert(
127
- registrations.length === 1,
128
- `Extension bundle ${bundle.id} member ${memberId} must contain exactly one synchronous ` +
129
- `Scratch.extensions.register call; found ${registrations.length}.`,
130
- );
131
- return {contents: source, extension, metadata, originalContents: Buffer.from(contents)};
132
- });
133
- }
134
-
135
- function commentLine(value) {
136
- return String(value).replaceAll('\r', ' ').replaceAll('\n', ' ');
137
- }
138
-
139
- function bundleHeader(bundle, components) {
140
- const authors = [...new Set(components.map((component) => component.metadata.author))];
141
- const lines = [
142
- `// Name: ${commentLine(bundle.name)}`,
143
- `// ID: ${bundle.id}`,
144
- `// Description: Static bundle of ${components.length} TurboWarp extensions.`,
145
- `// By: ${commentLine(authors.join(', '))}`,
146
- '// License: See the bundled extension notices below.',
147
- '//',
148
- '// Bundled extensions:',
149
- ];
150
- for (const component of components) {
151
- lines.push(
152
- `// - Name: ${commentLine(component.metadata.name)}`,
153
- `// ID: ${component.metadata.id}`,
154
- `// By: ${commentLine(component.metadata.author)}`,
155
- `// Description: ${commentLine(component.metadata.description)}`,
156
- `// License: ${commentLine(component.metadata.license)}`,
157
- );
158
- }
159
- return `${lines.join('\n')}\n`;
160
- }
161
-
162
- function componentLoadSource(component) {
163
- const memberId = JSON.stringify(component.metadata.id);
164
- const source = component.contents.endsWith('\n') ? component.contents : `${component.contents}\n`;
165
- return `loadComponent(${memberId}, function (Scratch) {\n${source}});\n`;
166
- }
167
-
168
- function percentEncode(contents) {
169
- return [...Buffer.from(contents)]
170
- .map((byte) => `%${byte.toString(16).padStart(2, '0').toUpperCase()}`)
171
- .join('');
172
- }
173
-
174
- function componentDataUrl(component) {
175
- const metadata = [component.extension.mediaType, ...component.extension.parameters].join(';');
176
- const originalContents = component.originalContents ?? Buffer.from(component.contents);
177
- if (component.extension.encoding === 'base64') {
178
- return `data:${metadata};base64,${originalContents.toString('base64')}`;
179
- }
180
- return `data:${metadata},${percentEncode(originalContents)}`;
181
- }
182
-
183
- function recoveryCapsule(bundle, components, originalProject) {
184
- return {
185
- formatVersion: 1,
186
- bundle: {id: bundle.id, name: bundle.name},
187
- components: components.map((component) => ({
188
- dataUrl: componentDataUrl(component),
189
- id: component.metadata.id,
190
- })),
191
- originalExtensionIds: Array.isArray(originalProject?.extensions)
192
- ? [...originalProject.extensions]
193
- : null,
194
- originalExtensionUrlIds: Object.keys(originalProject?.extensionURLs ?? {}),
195
- };
196
- }
197
-
198
- export function createStaticExtensionBundle(bundle, components, originalProject = undefined) {
199
- const componentIds = JSON.stringify(components.map((component) => component.metadata.id));
200
- const header = bundleHeader(bundle, components);
201
- const loaders = components.map(componentLoadSource).join('\n');
202
- const runtime = `(function (Scratch) {
203
- 'use strict';
204
-
205
- const BUNDLE_ID = ${JSON.stringify(bundle.id)};
206
- const BUNDLE_NAME = ${JSON.stringify(bundle.name)};
207
- const COMPONENT_IDS = ${componentIds};
208
- const components = new Map();
209
-
210
- const rewriteOpcode = (componentId, opcode) => {
211
- const prefix = componentId + '_';
212
- return typeof opcode === 'string' && opcode.startsWith(prefix)
213
- ? BUNDLE_ID + '_' + componentId + '__' + opcode.slice(prefix.length)
214
- : opcode;
215
- };
216
-
217
- const rewriteBundleOpcode = (opcode) => {
218
- for (const componentId of COMPONENT_IDS) {
219
- const rewritten = rewriteOpcode(componentId, opcode);
220
- if (rewritten !== opcode) return rewritten;
221
- }
222
- return opcode;
223
- };
224
-
225
- const xmlEscape = (value) => String(value).replace(/[<>&'"]/gu, (character) => ({
226
- '<': '&lt;',
227
- '>': '&gt;',
228
- '&': '&amp;',
229
- "'": '&apos;',
230
- '"': '&quot;',
231
- })[character]);
232
-
233
- const installStorageAliases = (storage) => {
234
- if (!storage || typeof storage !== 'object') return;
235
- const hasBundleStorage = Object.prototype.hasOwnProperty.call(storage, BUNDLE_ID);
236
- const hasMemberStorage = COMPONENT_IDS.some((id) => Object.prototype.hasOwnProperty.call(storage, id));
237
- if (!hasBundleStorage && !hasMemberStorage) return;
238
- let bundleStorage = storage[BUNDLE_ID];
239
- if (!bundleStorage || typeof bundleStorage !== 'object' || Array.isArray(bundleStorage)) {
240
- bundleStorage = {formatVersion: 1, components: {}};
241
- storage[BUNDLE_ID] = bundleStorage;
242
- }
243
- if (!bundleStorage.components || typeof bundleStorage.components !== 'object' || Array.isArray(bundleStorage.components)) {
244
- throw new Error('Invalid extension storage for static bundle ' + BUNDLE_ID + '.');
245
- }
246
- for (const id of COMPONENT_IDS) {
247
- const descriptor = Object.getOwnPropertyDescriptor(storage, id);
248
- if (descriptor && !descriptor.get && !Object.prototype.hasOwnProperty.call(bundleStorage.components, id)) {
249
- bundleStorage.components[id] = storage[id];
250
- }
251
- if (!descriptor || !descriptor.get) {
252
- delete storage[id];
253
- Object.defineProperty(storage, id, {
254
- configurable: true,
255
- enumerable: false,
256
- get: () => bundleStorage.components[id],
257
- set: (value) => {
258
- bundleStorage.components[id] = value;
259
- },
260
- });
261
- }
262
- }
263
- };
264
-
265
- const installAllStorageAliases = () => {
266
- const runtime = Scratch.vm && Scratch.vm.runtime;
267
- if (!runtime) return;
268
- installStorageAliases(runtime.extensionStorage);
269
- for (const target of runtime.targets || []) installStorageAliases(target.extensionStorage);
270
- };
271
-
272
- installAllStorageAliases();
273
-
274
- const createComponentScratch = (componentId, register) => {
275
- const baseRuntime = Scratch.vm && Scratch.vm.runtime;
276
- const runtime = baseRuntime && new Proxy(baseRuntime, {
277
- get(target, property) {
278
- if (property === 'startHats') {
279
- return (opcode, ...args) => target.startHats(rewriteOpcode(componentId, opcode), ...args);
280
- }
281
- if (property === 'getOpcodeFunction') {
282
- return (opcode, ...args) => target.getOpcodeFunction(rewriteBundleOpcode(opcode), ...args);
283
- }
284
- const value = Reflect.get(target, property, target);
285
- return typeof value === 'function' ? value.bind(target) : value;
286
- },
287
- });
288
- const baseVm = Scratch.vm;
289
- const vm = baseVm && new Proxy(baseVm, {
290
- get(target, property) {
291
- if (property === 'runtime') return runtime;
292
- const value = Reflect.get(target, property, target);
293
- return typeof value === 'function' ? value.bind(target) : value;
294
- },
295
- });
296
- const extensions = Object.create(Scratch.extensions);
297
- Object.defineProperty(extensions, 'register', {value: register});
298
- return new Proxy(Scratch, {
299
- get(target, property) {
300
- if (property === 'extensions') return extensions;
301
- if (property === 'vm') return vm;
302
- return Reflect.get(target, property, target);
303
- },
304
- });
305
- };
306
-
307
- const loadComponent = (componentId, execute) => {
308
- let registration = null;
309
- let registrationCount = 0;
310
- let acceptingRegistration = true;
311
- const componentScratch = createComponentScratch(componentId, (extension) => {
312
- if (!acceptingRegistration) {
313
- throw new Error('Asynchronous registration is unsupported in static bundle member ' + componentId + '.');
314
- }
315
- registration = extension;
316
- registrationCount += 1;
317
- });
318
- execute(componentScratch);
319
- acceptingRegistration = false;
320
- if (registrationCount !== 1) {
321
- throw new Error(
322
- 'Static bundle member ' + componentId + ' must register exactly once synchronously; got ' + registrationCount + '.',
323
- );
324
- }
325
- components.set(componentId, registration);
326
- };
327
-
328
- ${loaders}
329
- class StaticExtensionBundle {
330
- constructor() {
331
- this.delegates = new Map();
332
- }
333
-
334
- addDelegate(name, component, originalName) {
335
- if (this.delegates.has(name)) throw new Error('Duplicate static bundle delegate: ' + name);
336
- if (typeof originalName !== 'string' || typeof component[originalName] !== 'function') {
337
- throw new Error('Missing static bundle handler: ' + originalName);
338
- }
339
- this.delegates.set(name, {component, originalName});
340
- this[name] = (...args) => {
341
- installAllStorageAliases();
342
- return component[originalName](...args);
343
- };
344
- }
345
-
346
- getInfo() {
347
- const result = {
348
- id: BUNDLE_ID,
349
- name: BUNDLE_NAME,
350
- color1: '#5B67A5',
351
- blocks: [],
352
- menus: {},
353
- customFieldTypes: {},
354
- };
355
- this.delegates.clear();
356
- const transformedOpcodes = new Set();
357
-
358
- for (const [componentIndex, componentId] of COMPONENT_IDS.entries()) {
359
- const component = components.get(componentId);
360
- const info = component.getInfo();
361
- if (!info || info.id !== componentId) {
362
- throw new Error(
363
- 'Static bundle member runtime ID mismatch: expected ' + componentId + ', got ' +
364
- (info && info.id ? info.id : '(missing)') + '.',
365
- );
366
- }
367
- if (typeof info.name !== 'string' || info.name.length === 0) {
368
- throw new Error('Static bundle member ' + componentId + ' must have a non-empty name.');
369
- }
370
- const namespace = componentId + '__';
371
- const memberBlockIconURI =
372
- typeof info.blockIconURI === 'string' && info.blockIconURI.length > 0
373
- ? info.blockIconURI
374
- : null;
375
- const customFieldTypes = info.customFieldTypes || {};
376
- for (const [fieldName, fieldInfo] of Object.entries(customFieldTypes)) {
377
- result.customFieldTypes[namespace + fieldName] = fieldInfo;
378
- }
379
- if (componentIndex > 0) result.blocks.push('---', '---');
380
- result.blocks.push({
381
- blockType: Scratch.BlockType.LABEL,
382
- sb3Toolchain: {kind: 'bundle-member-heading', memberId: componentId},
383
- text: '◆ ' + info.name + ' [' + componentId + '] ◆',
384
- });
385
- if (info.docsURI) {
386
- const docsURI = String(info.docsURI);
387
- result.blocks.push({
388
- blockType: Scratch.BlockType.XML,
389
- sb3Toolchain: {
390
- docsURI,
391
- kind: 'bundle-member-docs',
392
- memberId: componentId,
393
- },
394
- xml: '<button text="Open Documentation" callbackKey="OPEN_EXTENSION_DOCS" callbackData="' + xmlEscape(docsURI) + '"></button>',
395
- });
396
- }
397
- for (const block of info.blocks || []) {
398
- if (block === '---') {
399
- result.blocks.push(block);
400
- continue;
401
- }
402
- if (!block || typeof block !== 'object') throw new Error('Invalid block in static bundle member ' + componentId + '.');
403
- if (block.blockType === Scratch.BlockType.XML) {
404
- throw new Error('XML blocks are unsupported in static bundle member ' + componentId + '.');
405
- }
406
- const transformed = {...block};
407
- if (
408
- memberBlockIconURI !== null &&
409
- !Object.prototype.hasOwnProperty.call(block, 'blockIconURI') &&
410
- block.blockType !== Scratch.BlockType.LABEL &&
411
- block.blockType !== Scratch.BlockType.BUTTON
412
- ) {
413
- transformed.blockIconURI = memberBlockIconURI;
414
- }
415
- if (block.arguments) {
416
- transformed.arguments = Object.fromEntries(
417
- Object.entries(block.arguments).map(([argumentName, argument]) => {
418
- const transformedArgument = {...argument};
419
- if (typeof transformedArgument.menu === 'string') {
420
- transformedArgument.menu = namespace + transformedArgument.menu;
421
- }
422
- if (typeof transformedArgument.type === 'string' && Object.prototype.hasOwnProperty.call(customFieldTypes, transformedArgument.type)) {
423
- transformedArgument.type = namespace + transformedArgument.type;
424
- }
425
- return [argumentName, transformedArgument];
426
- }),
427
- );
428
- }
429
- if (block.blockType === Scratch.BlockType.LABEL) {
430
- result.blocks.push(transformed);
431
- continue;
432
- }
433
- if (block.blockType === Scratch.BlockType.BUTTON) {
434
- const delegateName = namespace + 'button__' + block.func;
435
- transformed.func = delegateName;
436
- this.addDelegate(delegateName, component, block.func);
437
- result.blocks.push(transformed);
438
- continue;
439
- }
440
- if (typeof block.opcode !== 'string' || block.opcode.length === 0) {
441
- throw new Error('Missing opcode in static bundle member ' + componentId + '.');
442
- }
443
- transformed.opcode = namespace + block.opcode;
444
- if (transformedOpcodes.has(transformed.opcode)) {
445
- throw new Error('Duplicate static bundle opcode: ' + transformed.opcode);
446
- }
447
- transformedOpcodes.add(transformed.opcode);
448
- if (block.blockType !== Scratch.BlockType.EVENT) {
449
- const originalName = block.func || block.opcode;
450
- transformed.func = transformed.opcode;
451
- this.addDelegate(transformed.opcode, component, originalName);
452
- } else {
453
- delete transformed.func;
454
- }
455
- result.blocks.push(transformed);
456
- }
457
- for (const [menuName, menu] of Object.entries(info.menus || {})) {
458
- const transformedMenuName = namespace + menuName;
459
- if (typeof menu === 'string') {
460
- const delegateName = namespace + 'menu__' + menuName;
461
- this.addDelegate(delegateName, component, menu);
462
- result.menus[transformedMenuName] = {items: delegateName};
463
- } else if (Array.isArray(menu)) {
464
- result.menus[transformedMenuName] = [...menu];
465
- } else if (menu && typeof menu === 'object') {
466
- const transformedMenu = {...menu};
467
- if (typeof menu.items === 'string') {
468
- const delegateName = namespace + 'menu__' + menuName;
469
- this.addDelegate(delegateName, component, menu.items);
470
- transformedMenu.items = delegateName;
471
- }
472
- result.menus[transformedMenuName] = transformedMenu;
473
- } else {
474
- throw new Error('Invalid menu in static bundle member ' + componentId + ': ' + menuName + '.');
475
- }
476
- }
477
- }
478
- return result;
479
- }
480
- }
481
-
482
- Scratch.extensions.register(new StaticExtensionBundle());
483
- })(Scratch);
484
- `;
485
- if (bundle.recoveryCapsule !== true) {
486
- return Buffer.from(`${header}\n${runtime}`);
487
- }
488
- const capsule = Buffer.from(
489
- JSON.stringify(
490
- recoveryCapsule(
491
- bundle,
492
- components,
493
- originalProject ?? {
494
- extensions: bundle.members,
495
- extensionURLs: Object.fromEntries(bundle.members.map((memberId) => [memberId, true])),
496
- },
497
- ),
498
- ),
499
- ).toString('base64');
500
- return Buffer.from(`${header}\n${runtime}\n// ${extensionBundleRecoveryMarker}: ${capsule}\n`);
501
- }
502
-
503
- function replaceMemberKeys(object, memberIds, bundleId, bundleValue) {
504
- const replacement = {};
505
- let inserted = false;
506
- for (const [key, value] of Object.entries(object)) {
507
- if (memberIds.has(key)) {
508
- if (!inserted) {
509
- replacement[bundleId] = bundleValue(value);
510
- inserted = true;
511
- }
512
- } else {
513
- replacement[key] = value;
514
- }
515
- }
516
- return {inserted, replacement};
517
- }
518
-
519
- function bundleStorage(storage, bundle) {
520
- if (!isObject(storage)) return storage;
521
- const memberIds = new Set(bundle.members);
522
- const componentStorage = {};
523
- for (const memberId of bundle.members) {
524
- if (Object.hasOwn(storage, memberId)) componentStorage[memberId] = storage[memberId];
525
- }
526
- if (Object.keys(componentStorage).length === 0) return storage;
527
- assert(
528
- !Object.hasOwn(storage, bundle.id),
529
- `Extension storage already contains bundle ID: ${bundle.id}`,
530
- );
531
- return replaceMemberKeys(storage, memberIds, bundle.id, () => ({
532
- formatVersion: 1,
533
- components: componentStorage,
534
- })).replacement;
535
- }
536
-
537
- function rewriteOpcodeValues(value, bundle, counts) {
538
- if (!value || typeof value !== 'object') return;
539
- if (Array.isArray(value)) {
540
- for (const entry of value) rewriteOpcodeValues(entry, bundle, counts);
541
- return;
542
- }
543
- for (const [key, entry] of Object.entries(value)) {
544
- if (key === 'opcode' && typeof entry === 'string') {
545
- for (const memberId of bundle.members) {
546
- const prefix = `${memberId}_`;
547
- if (entry.startsWith(prefix)) {
548
- value[key] = `${bundle.id}_${memberId}__${entry.slice(prefix.length)}`;
549
- counts.opcodes += 1;
550
- break;
551
- }
552
- }
553
- } else {
554
- rewriteOpcodeValues(entry, bundle, counts);
555
- }
556
- }
557
- }
558
-
559
- function collectRemainingOpcodeReferences(value, bundle) {
560
- const references = [];
561
- const prefixes = bundle.members.map((memberId) => `${memberId}_`);
562
- function visit(current, pointer) {
563
- if (typeof current === 'string') {
564
- if (prefixes.some((prefix) => current.startsWith(prefix))) references.push(pointer || '/');
565
- return;
566
- }
567
- if (!current || typeof current !== 'object') return;
568
- if (Array.isArray(current)) {
569
- current.forEach((entry, index) => visit(entry, `${pointer}/${index}`));
570
- return;
571
- }
572
- for (const [key, entry] of Object.entries(current)) visit(entry, `${pointer}/${key}`);
573
- }
574
- visit(value, '');
575
- return references;
576
- }
577
-
578
- function rewriteProjectForBundle(project, bundle) {
579
- const rewritten = structuredClone(project);
580
- const memberIds = new Set(bundle.members);
581
- const counts = {extensionStorage: 0, extensionUrls: 0, opcodes: 0, projectExtensions: 0};
582
- assert(isObject(rewritten.extensionURLs), 'project.source.json extensionURLs must be an object.');
583
- assert(
584
- !Object.hasOwn(rewritten.extensionURLs, bundle.id),
585
- `project.source.json already uses bundle ID: ${bundle.id}`,
586
- );
587
- for (const memberId of bundle.members) {
588
- assert(
589
- rewritten.extensionURLs[memberId] === `embedded-extension:extensions/${memberId}.js`,
590
- `Extension bundle ${bundle.id} member URL mismatch: ${memberId}`,
591
- );
592
- }
593
- const extensionUrls = replaceMemberKeys(
594
- rewritten.extensionURLs,
595
- memberIds,
596
- bundle.id,
597
- () => `embedded-extension:extensions/${bundle.id}.js`,
598
- );
599
- assert(
600
- extensionUrls.inserted,
601
- `Extension bundle ${bundle.id} did not replace any extension URL.`,
602
- );
603
- rewritten.extensionURLs = extensionUrls.replacement;
604
- counts.extensionUrls = bundle.members.length + 1;
605
-
606
- if (rewritten.extensions !== undefined) {
607
- assert(
608
- Array.isArray(rewritten.extensions),
609
- 'project.source.json extensions must be an array when present.',
610
- );
611
- const output = [];
612
- let inserted = false;
613
- for (const id of rewritten.extensions) {
614
- if (memberIds.has(id)) {
615
- counts.projectExtensions += 1;
616
- if (!inserted) {
617
- output.push(bundle.id);
618
- inserted = true;
619
- }
620
- } else {
621
- output.push(id);
622
- }
623
- }
624
- rewritten.extensions = output;
625
- }
626
-
627
- const originalGlobalStorage = rewritten.extensionStorage;
628
- rewritten.extensionStorage = bundleStorage(rewritten.extensionStorage, bundle);
629
- if (rewritten.extensionStorage !== originalGlobalStorage) counts.extensionStorage += 1;
630
- for (const target of rewritten.targets ?? []) {
631
- const originalTargetStorage = target?.extensionStorage;
632
- if (target) target.extensionStorage = bundleStorage(target.extensionStorage, bundle);
633
- if (target?.extensionStorage !== originalTargetStorage) counts.extensionStorage += 1;
634
- }
635
-
636
- rewriteOpcodeValues(rewritten.targets, bundle, counts);
637
- rewriteOpcodeValues(rewritten.monitors, bundle, counts);
638
- const remainingReferences = collectRemainingOpcodeReferences(rewritten, bundle);
639
- assert(
640
- remainingReferences.length === 0,
641
- `Extension bundle ${bundle.id} has unsupported opcode references at: ` +
642
- remainingReferences.slice(0, 8).join(', '),
643
- );
644
- return {counts, project: rewritten};
645
- }
646
-
647
- export function buildExtensionBundles({extensionBundles, extensionContents, extensions, project}) {
648
- if (extensionBundles.length === 0) {
649
- return {bundlePlans: [], extensionContents, extensions, project};
650
- }
651
- const extensionsById = new Map(extensions.map((extension) => [extension.id, extension]));
652
- const bundlesByMemberId = new Map();
653
- const bundlePlans = [];
654
- let bundledProject = project;
655
- const bundledContents = new Map(extensionContents);
656
-
657
- for (const bundle of extensionBundles) {
658
- const components = readBundleComponents(bundle, extensionsById, extensionContents);
659
- const rewrite = rewriteProjectForBundle(bundledProject, bundle);
660
- const contents = createStaticExtensionBundle(bundle, components, project);
661
- bundledProject = rewrite.project;
662
- bundledContents.set(bundle.id, contents);
663
- for (const memberId of bundle.members) {
664
- bundlesByMemberId.set(memberId, bundle);
665
- bundledContents.delete(memberId);
666
- }
667
- bundlePlans.push({bundle, components, contents, counts: rewrite.counts});
668
- }
669
-
670
- const bundledExtensions = [];
671
- const emittedBundleIds = new Set();
672
- for (const extension of extensions) {
673
- const bundle = bundlesByMemberId.get(extension.id);
674
- if (!bundle) {
675
- bundledExtensions.push(extension);
676
- } else if (!emittedBundleIds.has(bundle.id)) {
677
- emittedBundleIds.add(bundle.id);
678
- bundledExtensions.push({
679
- encoding: 'base64',
680
- id: bundle.id,
681
- mediaType: 'text/javascript',
682
- parameters: [],
683
- path: `extensions/${bundle.id}.js`,
684
- });
685
- }
686
- }
687
- return {
688
- bundlePlans,
689
- extensionContents: bundledContents,
690
- extensions: bundledExtensions,
691
- project: bundledProject,
692
- };
693
- }
694
-
695
- export {validateBundleId, validateBundleName};