@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
package/src/cli.js DELETED
@@ -1,748 +0,0 @@
1
- // SPDX-License-Identifier: MPL-2.0
2
-
3
- import path from 'node:path';
4
- import process from 'node:process';
5
- import {createInterface} from 'node:readline/promises';
6
-
7
- import {buildSb3} from './build.js';
8
- import {packageVersion} from './constants.js';
9
- import {bundleExtensions, unbundleExtensions} from './extension-bundle-configuration.js';
10
- import {unbundleSb3} from './extension-bundle-archive.js';
11
- import {migrateExtensionId} from './extension-id-migration.js';
12
- import {extensionStatus, syncExtensions, updateExtensions} from './extension-sync.js';
13
- import {importSb3} from './import.js';
14
- import {createDeterministicSb3, validateSb3Source} from './source.js';
15
-
16
- /**
17
- * @param {unknown} condition
18
- * @param {string} message
19
- * @returns {asserts condition}
20
- */
21
- function assert(condition, message) {
22
- if (!condition) {
23
- throw new Error(message);
24
- }
25
- }
26
-
27
- export function usage() {
28
- return `Usage:
29
- sb3-toolchain import INPUT.sb3 --output SOURCE_DIR [--yes] [--discard-local-changes]
30
- sb3-toolchain check SOURCE_DIR [--project-assets MANIFEST.json] [--allow-asset-root DIR ...]
31
- sb3-toolchain build SOURCE_DIR --output OUTPUT.sb3 [--project-assets MANIFEST.json] [--allow-asset-root DIR ...] [--clean-up-blocks] [--yes]
32
- sb3-toolchain extensions status SOURCE_DIR
33
- sb3-toolchain extensions sync SOURCE_DIR [--yes]
34
- sb3-toolchain extensions update SOURCE_DIR [EXTENSION_ID] [--migrate-id NEW_ID] [--artifact PATH] [--api-manifest-artifact PATH] [--allow-breaking-api --yes]
35
- sb3-toolchain extensions migrate-id SOURCE_DIR --from OLD_ID --to NEW_ID [--yes]
36
- sb3-toolchain extensions bundle SOURCE_DIR --id BUNDLE_ID --name NAME [EXTENSION_ID ...] [--include-recovery-capsule] [--yes]
37
- sb3-toolchain extensions unbundle SOURCE_DIR BUNDLE_ID [--yes]
38
- sb3-toolchain extensions unbundle INPUT.sb3 BUNDLE_ID --output OUTPUT.sb3 [--yes]
39
-
40
- Commands:
41
- import Expand an SB3 into Git-friendly source files.
42
- check Validate an expanded SB3 source directory.
43
- build Build a deterministic SB3 from expanded sources.
44
- extensions Inspect, restore, or update managed embedded extensions.
45
-
46
- Build layout cleanup:
47
- --clean-up-blocks applies a deterministic TurboWarp-style "Clean up Blocks"
48
- layout to every target in the generated SB3. It never deletes blocks,
49
- variables, lists, or comments. The expanded source is unchanged, but the
50
- generated SB3 might not be able to undo the coordinate changes.
51
-
52
- Project asset additions:
53
- --project-assets validates a JSON or YAML manifest and adds its sprites,
54
- backdrops, costumes, and sounds only to the generated SB3. Input files are confined to the
55
- manifest directory unless --allow-asset-root explicitly permits another root.
56
-
57
- Replacement safety:
58
- Differing outputs require interactive confirmation or --yes.
59
- Import refuses to discard uncommitted Git changes unless
60
- --discard-local-changes is also specified. --force is not supported.`;
61
- }
62
-
63
- function takeValue(arguments_, index, option) {
64
- const value = arguments_[index + 1];
65
- assert(value && !value.startsWith('-'), `${option} requires a value.`);
66
- return value;
67
- }
68
-
69
- function parseImportArguments(arguments_) {
70
- let inputPath;
71
- let outputDirectory;
72
- let discardLocalChanges = false;
73
- let yes = false;
74
-
75
- for (let index = 0; index < arguments_.length; index += 1) {
76
- const argument = arguments_[index];
77
- if (argument === '--output') {
78
- outputDirectory = path.resolve(takeValue(arguments_, index, '--output'));
79
- index += 1;
80
- } else if (argument === '--yes') {
81
- yes = true;
82
- } else if (argument === '--discard-local-changes') {
83
- discardLocalChanges = true;
84
- } else {
85
- assert(
86
- argument !== '--force',
87
- '--force is intentionally unsupported. Use --yes and, only when necessary, ' +
88
- '--discard-local-changes.',
89
- );
90
- assert(!argument.startsWith('-'), `Unknown option: ${argument}`);
91
- assert(!inputPath, 'Only one input SB3 may be specified.');
92
- inputPath = path.resolve(argument);
93
- }
94
- }
95
-
96
- assert(inputPath, 'The import command requires INPUT.sb3.');
97
- assert(outputDirectory, 'The import command requires --output SOURCE_DIR.');
98
- return {command: 'import', discardLocalChanges, inputPath, outputDirectory, yes};
99
- }
100
-
101
- /**
102
- * @param {string[]} arguments_
103
- * @returns {{allowedAssetRoots?: string[], command: 'check', projectAssetsPath?: string, sourceDirectory: string}}
104
- */
105
- function parseCheckArguments(arguments_) {
106
- const allowedAssetRoots = [];
107
- let projectAssetsPath;
108
- let sourceDirectory;
109
- for (let index = 0; index < arguments_.length; index += 1) {
110
- const argument = arguments_[index];
111
- if (argument === '--project-assets') {
112
- projectAssetsPath = path.resolve(takeValue(arguments_, index, '--project-assets'));
113
- index += 1;
114
- } else if (argument === '--allow-asset-root') {
115
- allowedAssetRoots.push(path.resolve(takeValue(arguments_, index, '--allow-asset-root')));
116
- index += 1;
117
- } else {
118
- assert(!argument.startsWith('-'), `Unknown option: ${argument}`);
119
- assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');
120
- sourceDirectory = path.resolve(argument);
121
- }
122
- }
123
- assert(sourceDirectory, 'The check command requires SOURCE_DIR.');
124
- assert(
125
- allowedAssetRoots.length === 0 || projectAssetsPath,
126
- '--allow-asset-root requires --project-assets.',
127
- );
128
- return {
129
- ...(allowedAssetRoots.length > 0 ? {allowedAssetRoots} : {}),
130
- command: 'check',
131
- ...(projectAssetsPath ? {projectAssetsPath} : {}),
132
- sourceDirectory,
133
- };
134
- }
135
-
136
- /**
137
- * @param {string[]} arguments_
138
- * @returns {{allowedAssetRoots?: string[], cleanUpBlocks?: boolean, command: 'build', outputPath: string, projectAssetsPath?: string, sourceDirectory: string, yes: boolean}}
139
- */
140
- function parseBuildArguments(arguments_) {
141
- const allowedAssetRoots = [];
142
- let cleanUpBlocks = false;
143
- let sourceDirectory;
144
- let outputPath;
145
- let projectAssetsPath;
146
- let yes = false;
147
-
148
- for (let index = 0; index < arguments_.length; index += 1) {
149
- const argument = arguments_[index];
150
- if (argument === '--clean-up-blocks') {
151
- cleanUpBlocks = true;
152
- } else if (argument === '--project-assets') {
153
- projectAssetsPath = path.resolve(takeValue(arguments_, index, '--project-assets'));
154
- index += 1;
155
- } else if (argument === '--allow-asset-root') {
156
- allowedAssetRoots.push(path.resolve(takeValue(arguments_, index, '--allow-asset-root')));
157
- index += 1;
158
- } else if (argument === '--output') {
159
- outputPath = path.resolve(takeValue(arguments_, index, '--output'));
160
- index += 1;
161
- } else if (argument === '--yes') {
162
- yes = true;
163
- } else {
164
- assert(!argument.startsWith('-'), `Unknown option: ${argument}`);
165
- assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');
166
- sourceDirectory = path.resolve(argument);
167
- }
168
- }
169
-
170
- assert(sourceDirectory, 'The build command requires SOURCE_DIR.');
171
- assert(outputPath, 'The build command requires --output OUTPUT.sb3.');
172
- assert(
173
- allowedAssetRoots.length === 0 || projectAssetsPath,
174
- '--allow-asset-root requires --project-assets.',
175
- );
176
- return {
177
- ...(allowedAssetRoots.length > 0 ? {allowedAssetRoots} : {}),
178
- ...(cleanUpBlocks ? {cleanUpBlocks} : {}),
179
- command: 'build',
180
- outputPath,
181
- ...(projectAssetsPath ? {projectAssetsPath} : {}),
182
- sourceDirectory,
183
- yes,
184
- };
185
- }
186
-
187
- function parseExtensionMutationArguments(action, arguments_) {
188
- let allowBreakingApi = false;
189
- let apiManifestArtifact;
190
- let sourceDirectory;
191
- let extensionId;
192
- let migrateToId;
193
- let sourceArtifact;
194
- let yes = false;
195
-
196
- for (let index = 0; index < arguments_.length; index += 1) {
197
- const argument = arguments_[index];
198
- if (argument === '--yes') {
199
- yes = true;
200
- } else if (argument === '--allow-breaking-api') {
201
- assert(action === 'update', '--allow-breaking-api is only valid for extensions update.');
202
- allowBreakingApi = true;
203
- } else if (argument === '--migrate-id') {
204
- assert(action === 'update', '--migrate-id is only valid for extensions update.');
205
- migrateToId = takeValue(arguments_, index, '--migrate-id');
206
- index += 1;
207
- } else if (argument === '--artifact') {
208
- assert(action === 'update', '--artifact is only valid for extensions update.');
209
- sourceArtifact = takeValue(arguments_, index, '--artifact');
210
- index += 1;
211
- } else if (argument === '--api-manifest-artifact') {
212
- assert(action === 'update', '--api-manifest-artifact is only valid for extensions update.');
213
- apiManifestArtifact = takeValue(arguments_, index, '--api-manifest-artifact');
214
- index += 1;
215
- } else {
216
- assert(!argument.startsWith('-'), `Unknown option: ${argument}`);
217
- if (!sourceDirectory) {
218
- sourceDirectory = path.resolve(argument);
219
- } else {
220
- assert(action === 'update', `The extensions ${action} command accepts only SOURCE_DIR.`);
221
- assert(!extensionId, 'Only one EXTENSION_ID may be specified.');
222
- assert(
223
- /^[A-Za-z0-9._-]+$/u.test(argument),
224
- `Invalid embedded extension ID: ${JSON.stringify(argument)}`,
225
- );
226
- extensionId = argument;
227
- }
228
- }
229
- }
230
-
231
- assert(sourceDirectory, `The extensions ${action} command requires SOURCE_DIR.`);
232
- assert(
233
- migrateToId === undefined || extensionId !== undefined,
234
- '--migrate-id requires an explicit existing EXTENSION_ID.',
235
- );
236
- assert(
237
- sourceArtifact === undefined || migrateToId !== undefined,
238
- '--artifact requires --migrate-id.',
239
- );
240
- assert(
241
- apiManifestArtifact === undefined || migrateToId !== undefined,
242
- '--api-manifest-artifact requires --migrate-id.',
243
- );
244
- assert(!allowBreakingApi || yes, '--allow-breaking-api requires --yes.');
245
- return {
246
- action,
247
- ...(allowBreakingApi ? {allowBreakingApi} : {}),
248
- ...(apiManifestArtifact ? {apiManifestArtifact} : {}),
249
- command: 'extensions',
250
- extensionId,
251
- migrateToId,
252
- sourceArtifact,
253
- sourceDirectory,
254
- yes,
255
- };
256
- }
257
-
258
- function parseExtensionIdMigrationArguments(arguments_) {
259
- let fromId;
260
- let sourceDirectory;
261
- let toId;
262
- let yes = false;
263
-
264
- for (let index = 0; index < arguments_.length; index += 1) {
265
- const argument = arguments_[index];
266
- if (argument === '--from') {
267
- fromId = takeValue(arguments_, index, '--from');
268
- index += 1;
269
- } else if (argument === '--to') {
270
- toId = takeValue(arguments_, index, '--to');
271
- index += 1;
272
- } else if (argument === '--yes') {
273
- yes = true;
274
- } else {
275
- assert(!argument.startsWith('-'), `Unknown option: ${argument}`);
276
- assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');
277
- sourceDirectory = path.resolve(argument);
278
- }
279
- }
280
- assert(sourceDirectory, 'The extensions migrate-id command requires SOURCE_DIR.');
281
- assert(fromId, 'The extensions migrate-id command requires --from OLD_ID.');
282
- assert(toId, 'The extensions migrate-id command requires --to NEW_ID.');
283
- return {
284
- action: 'migrate-id',
285
- command: 'extensions',
286
- fromId,
287
- sourceDirectory,
288
- toId,
289
- yes,
290
- };
291
- }
292
-
293
- function parseExtensionBundleArguments(arguments_) {
294
- let bundleId;
295
- let bundleName;
296
- let recoveryCapsule = false;
297
- let sourceDirectory;
298
- const extensionIds = [];
299
- let yes = false;
300
-
301
- for (let index = 0; index < arguments_.length; index += 1) {
302
- const argument = arguments_[index];
303
- if (argument === '--id') {
304
- bundleId = takeValue(arguments_, index, '--id');
305
- index += 1;
306
- } else if (argument === '--name') {
307
- bundleName = takeValue(arguments_, index, '--name');
308
- index += 1;
309
- } else if (argument === '--yes') {
310
- yes = true;
311
- } else if (argument === '--include-recovery-capsule') {
312
- recoveryCapsule = true;
313
- } else {
314
- assert(!argument.startsWith('-'), `Unknown option: ${argument}`);
315
- if (!sourceDirectory) {
316
- sourceDirectory = path.resolve(argument);
317
- } else {
318
- assert(
319
- /^[a-z0-9]+$/u.test(argument),
320
- `Bundle member ID must use TurboWarp's [a-z0-9]+ format: ${JSON.stringify(argument)}`,
321
- );
322
- extensionIds.push(argument);
323
- }
324
- }
325
- }
326
- assert(sourceDirectory, 'The extensions bundle command requires SOURCE_DIR.');
327
- assert(bundleId, 'The extensions bundle command requires --id BUNDLE_ID.');
328
- assert(bundleName, 'The extensions bundle command requires --name NAME.');
329
- return {
330
- action: 'bundle',
331
- bundleId,
332
- bundleName,
333
- command: 'extensions',
334
- extensionIds,
335
- recoveryCapsule,
336
- sourceDirectory,
337
- yes,
338
- };
339
- }
340
-
341
- function parseExtensionUnbundleArguments(arguments_) {
342
- let bundleId;
343
- let input;
344
- let outputPath;
345
- let yes = false;
346
- for (let index = 0; index < arguments_.length; index += 1) {
347
- const argument = arguments_[index];
348
- if (argument === '--yes') {
349
- yes = true;
350
- } else if (argument === '--output') {
351
- outputPath = path.resolve(takeValue(arguments_, index, '--output'));
352
- index += 1;
353
- } else {
354
- assert(!argument.startsWith('-'), `Unknown option: ${argument}`);
355
- if (!input) {
356
- input = path.resolve(argument);
357
- } else {
358
- assert(!bundleId, 'Only one BUNDLE_ID may be specified.');
359
- bundleId = argument;
360
- }
361
- }
362
- }
363
- assert(input, 'The extensions unbundle command requires SOURCE_DIR or INPUT.sb3.');
364
- assert(bundleId, 'The extensions unbundle command requires BUNDLE_ID.');
365
- if (path.extname(input).toLowerCase() === '.sb3') {
366
- assert(outputPath, 'SB3 unbundle requires --output OUTPUT.sb3.');
367
- return {
368
- action: 'unbundle',
369
- bundleId,
370
- command: 'extensions',
371
- inputPath: input,
372
- outputPath,
373
- yes,
374
- };
375
- }
376
- assert(!outputPath, '--output is only valid when unbundling an SB3 file.');
377
- return {
378
- action: 'unbundle',
379
- bundleId,
380
- command: 'extensions',
381
- sourceDirectory: input,
382
- yes,
383
- };
384
- }
385
-
386
- function parseExtensionsArguments(arguments_) {
387
- const [action, ...actionArguments] = arguments_;
388
- assert(
389
- action === 'bundle' ||
390
- action === 'migrate-id' ||
391
- action === 'status' ||
392
- action === 'sync' ||
393
- action === 'unbundle' ||
394
- action === 'update',
395
- 'The extensions command requires status, sync, update, migrate-id, bundle, or unbundle.',
396
- );
397
- if (action === 'status') {
398
- assert(
399
- actionArguments.length === 1 && !actionArguments[0].startsWith('-'),
400
- 'The extensions status command requires exactly one SOURCE_DIR.',
401
- );
402
- return {
403
- action,
404
- command: 'extensions',
405
- sourceDirectory: path.resolve(actionArguments[0]),
406
- };
407
- }
408
- if (action === 'migrate-id') {
409
- return parseExtensionIdMigrationArguments(actionArguments);
410
- }
411
- if (action === 'bundle') {
412
- return parseExtensionBundleArguments(actionArguments);
413
- }
414
- if (action === 'unbundle') {
415
- return parseExtensionUnbundleArguments(actionArguments);
416
- }
417
- return parseExtensionMutationArguments(action, actionArguments);
418
- }
419
-
420
- export function parseCliArguments(arguments_) {
421
- const normalized = arguments_.filter((argument) => argument !== '--');
422
- if (normalized.length === 0 || normalized[0] === '--help' || normalized[0] === '-h') {
423
- return {command: 'help'};
424
- }
425
- if (normalized[0] === '--version' || normalized[0] === '-v') {
426
- return {command: 'version'};
427
- }
428
-
429
- const [command, ...commandArguments] = normalized;
430
- if (commandArguments.includes('--help') || commandArguments.includes('-h')) {
431
- return {command: 'help'};
432
- }
433
- if (command === 'import') return parseImportArguments(commandArguments);
434
- if (command === 'check') return parseCheckArguments(commandArguments);
435
- if (command === 'build') return parseBuildArguments(commandArguments);
436
- if (command === 'extensions') return parseExtensionsArguments(commandArguments);
437
- throw new Error(`Unknown command: ${command}`);
438
- }
439
-
440
- function formatDifferenceLines(differences) {
441
- const labels = {added: '+', modified: '~', removed: '-'};
442
- const lines = Object.entries(differences).flatMap(([kind, paths]) =>
443
- paths.map((relativePath) => `${labels[kind]} ${relativePath}`),
444
- );
445
- const visibleLines = lines.slice(0, 12);
446
- if (lines.length > visibleLines.length) {
447
- visibleLines.push(`... and ${lines.length - visibleLines.length} more`);
448
- }
449
- return visibleLines.join('\n');
450
- }
451
-
452
- async function confirmImportReplacement(context) {
453
- const {comparison, discardLocalChanges, gitState, outputDirectory} = context;
454
- assert(
455
- process.stdin.isTTY && process.stdout.isTTY,
456
- `Output directory already exists: ${outputDirectory}. ` +
457
- 'Non-interactive replacement requires --yes.',
458
- );
459
- const readline = createInterface({input: process.stdin, output: process.stdout});
460
- try {
461
- const gitMessage = gitState.clean
462
- ? 'Git state: clean'
463
- : 'Git state: uncommitted changes will be discarded';
464
- const answer = await readline.question(
465
- `Existing SB3 source differs from the import candidate:\n` +
466
- ` ${outputDirectory}\n` +
467
- `${formatDifferenceLines(comparison.differences)}\n` +
468
- `${gitMessage}\n` +
469
- `${discardLocalChanges ? 'WARNING: --discard-local-changes is active.\n' : ''}` +
470
- 'Replace the existing source directory? [y/N] ',
471
- );
472
- return /^(?:y|yes)$/iu.test(answer.trim());
473
- } finally {
474
- readline.close();
475
- }
476
- }
477
-
478
- async function confirmBuildReplacement(outputPath) {
479
- assert(
480
- process.stdin.isTTY && process.stdout.isTTY,
481
- `Existing SB3 output differs: ${outputPath}. Non-interactive replacement requires --yes.`,
482
- );
483
- const readline = createInterface({input: process.stdin, output: process.stdout});
484
- try {
485
- const answer = await readline.question(
486
- `Existing generated SB3 will be replaced:\n ${outputPath}\nContinue? [y/N] `,
487
- );
488
- return /^(?:y|yes)$/iu.test(answer.trim());
489
- } finally {
490
- readline.close();
491
- }
492
- }
493
-
494
- async function confirmExtensionReplacement({comparison, sourceDirectory}) {
495
- assert(
496
- process.stdin.isTTY && process.stdout.isTTY,
497
- `Managed extension files differ in ${sourceDirectory}. ` +
498
- 'Non-interactive replacement requires --yes.',
499
- );
500
- const readline = createInterface({input: process.stdin, output: process.stdout});
501
- try {
502
- const answer = await readline.question(
503
- `Managed extension changes will be installed:\n` +
504
- ` ${sourceDirectory}\n` +
505
- `${formatDifferenceLines(comparison.differences)}\n` +
506
- 'Replace these files? [y/N] ',
507
- );
508
- return /^(?:y|yes)$/iu.test(answer.trim());
509
- } finally {
510
- readline.close();
511
- }
512
- }
513
-
514
- function logMigrationResult(result, log) {
515
- const counts = Object.entries(result.counts)
516
- .filter(([, count]) => count > 0)
517
- .map(([kind, count]) => `${kind}=${count}`)
518
- .join(', ');
519
- const action = result.applied ? 'Migrated' : 'Dry run';
520
- log(
521
- `${action}: ${result.fromId} -> ${result.toId}; ` +
522
- `${result.totalChanges} classified changes (${counts || 'none'}); ` +
523
- `artifact=${result.artifactReady ? 'ready' : 'requires-new-ID'}.`,
524
- );
525
- for (const reference of result.unclassifiedReferences) {
526
- log(
527
- `Unclassified ${reference.kind}: ${reference.file}${reference.path} = ` +
528
- JSON.stringify(reference.value),
529
- );
530
- }
531
- }
532
-
533
- export async function runCli(
534
- arguments_,
535
- {fetch: fetchImplementation = globalThis.fetch, log = console.log} = {},
536
- ) {
537
- const options = parseCliArguments(arguments_);
538
- if (options.command === 'help') {
539
- log(usage());
540
- return;
541
- }
542
- if (options.command === 'version') {
543
- log(packageVersion);
544
- return;
545
- }
546
- if (options.command === 'check') {
547
- assert(
548
- 'sourceDirectory' in options && !('action' in options),
549
- 'Internal CLI check command routing error.',
550
- );
551
- if (options.projectAssetsPath) {
552
- const result = await createDeterministicSb3(options.sourceDirectory, {
553
- allowedAssetRoots: options.allowedAssetRoots,
554
- projectAssetsPath: options.projectAssetsPath,
555
- });
556
- log(
557
- `Valid SB3 source with project assets: ${result.source.resolvedSourceDirectory} ` +
558
- `(${result.entryCount} entries, ${result.assetCount} assets, ` +
559
- `${result.assetReferenceCount} references, ${result.embeddedExtensionCount} embedded extensions).`,
560
- );
561
- return;
562
- }
563
- const result = await validateSb3Source(options.sourceDirectory);
564
- log(
565
- `Valid SB3 source: ${result.resolvedSourceDirectory} ` +
566
- `(${result.sourceManifest.archiveEntries.length} entries, ` +
567
- `${result.assetContents.size} assets, ${result.assetReferenceCount} references, ` +
568
- `${result.extensions.length} embedded extensions).`,
569
- );
570
- return;
571
- }
572
- if (
573
- options.command === 'build' &&
574
- 'outputPath' in options &&
575
- 'sourceDirectory' in options &&
576
- !('action' in options)
577
- ) {
578
- const result = await buildSb3({
579
- allowedAssetRoots: options.allowedAssetRoots,
580
- cleanUpBlocks: options.cleanUpBlocks,
581
- confirmReplace: confirmBuildReplacement,
582
- outputPath: options.outputPath,
583
- projectAssetsPath: options.projectAssetsPath,
584
- sourceDirectory: options.sourceDirectory,
585
- yes: options.yes,
586
- });
587
- const action = result.changed ? 'Built' : 'Already up to date';
588
- const cleanUpMessage = result.blockCleanUp
589
- ? `, ${result.blockCleanUp.movedScriptCount}/${result.blockCleanUp.scriptCount} scripts laid out`
590
- : '';
591
- log(
592
- `${action}: ${result.outputPath} (${result.entryCount} entries, ` +
593
- `${result.assetCount} assets, ${result.embeddedExtensionCount} embedded extensions` +
594
- `${cleanUpMessage}).`,
595
- );
596
- if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
597
- return;
598
- }
599
- if (options.command === 'extensions') {
600
- if (options.action === 'bundle') {
601
- const result = await bundleExtensions({
602
- bundleId: options.bundleId,
603
- bundleName: options.bundleName,
604
- extensionIds: options.extensionIds,
605
- recoveryCapsule: options.recoveryCapsule,
606
- sourceDirectory: options.sourceDirectory,
607
- yes: options.yes,
608
- });
609
- log(
610
- `${result.applied ? 'Configured' : 'Dry run'} extension bundle: ${result.bundleId} ` +
611
- `(${result.members.join(', ')}).`,
612
- );
613
- if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
614
- return;
615
- }
616
- if (options.action === 'unbundle') {
617
- if ('inputPath' in options) {
618
- const result = await unbundleSb3({
619
- bundleId: options.bundleId,
620
- inputPath: options.inputPath,
621
- outputPath: options.outputPath,
622
- yes: options.yes,
623
- });
624
- log(
625
- `${result.applied ? 'Wrote' : 'Dry run'} unbundled SB3: ${result.bundleId} ` +
626
- `(${result.members.join(', ')}) -> ${result.outputPath}.`,
627
- );
628
- if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
629
- return;
630
- }
631
- const result = await unbundleExtensions({
632
- bundleId: options.bundleId,
633
- sourceDirectory: options.sourceDirectory,
634
- yes: options.yes,
635
- });
636
- log(
637
- `${result.applied ? 'Removed' : 'Dry run'} extension bundle: ${result.bundleId} ` +
638
- `(${result.members.join(', ')}).`,
639
- );
640
- if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
641
- return;
642
- }
643
- if (options.action === 'migrate-id') {
644
- const result = await migrateExtensionId({
645
- fromId: options.fromId,
646
- sourceDirectory: options.sourceDirectory,
647
- toId: options.toId,
648
- yes: options.yes,
649
- });
650
- logMigrationResult(result, log);
651
- if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
652
- return;
653
- }
654
- if (options.action === 'status') {
655
- const statuses = await extensionStatus(options.sourceDirectory, {
656
- fetch: fetchImplementation,
657
- });
658
- if (statuses.length === 0) {
659
- log(`No managed embedded extensions: ${options.sourceDirectory}`);
660
- return;
661
- }
662
- for (const status of statuses) {
663
- if (status.package) {
664
- log(
665
- `${status.id}: ${status.state}; local=${status.local}; ` +
666
- `${status.package}@${status.version} (installed ${status.installedVersion})`,
667
- );
668
- continue;
669
- }
670
- log(
671
- `${status.id}: ${status.state}; local=${status.local}; ` +
672
- `${status.ref} -> ${status.remoteCommit} ` +
673
- `(installed ${status.resolvedCommit})`,
674
- );
675
- }
676
- return;
677
- }
678
-
679
- const operationOptions = {
680
- confirmReplace: confirmExtensionReplacement,
681
- fetch: fetchImplementation,
682
- sourceDirectory: options.sourceDirectory,
683
- yes: options.yes,
684
- };
685
- const result =
686
- options.action === 'sync'
687
- ? await syncExtensions(operationOptions)
688
- : await updateExtensions({
689
- ...operationOptions,
690
- allowBreakingApi: options.allowBreakingApi,
691
- apiManifestArtifact: options.apiManifestArtifact,
692
- extensionId: options.extensionId,
693
- migrateToId: options.migrateToId,
694
- sourceArtifact: options.sourceArtifact,
695
- });
696
- const action = result.changed ? 'Updated' : 'Already up to date';
697
- log(
698
- `${action}: ${result.sourceDirectory} ` +
699
- `(${result.extensions.map((extension) => extension.id).join(', ')}).`,
700
- );
701
- if (result.migration) {
702
- logMigrationResult(
703
- {
704
- applied: result.changed,
705
- artifactReady: true,
706
- ...result.migration,
707
- },
708
- log,
709
- );
710
- }
711
- for (const compatibility of result.apiCompatibility) {
712
- for (const change of compatibility.changes) {
713
- log(
714
- `API ${compatibility.id}: ${change.breaking ? 'breaking' : 'compatible'} ` +
715
- `${change.kind} ${change.path}`,
716
- );
717
- }
718
- }
719
- if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
720
- return;
721
- }
722
-
723
- assert(
724
- options.command === 'import' && 'inputPath' in options,
725
- 'Internal CLI command routing error.',
726
- );
727
- const result = await importSb3({
728
- confirmReplace: confirmImportReplacement,
729
- discardLocalChanges: options.discardLocalChanges,
730
- inputPath: options.inputPath,
731
- outputDirectory: options.outputDirectory,
732
- yes: options.yes,
733
- });
734
- if (result.changed) {
735
- const differenceMessage = result.differenceCounts
736
- ? ` Changes: +${result.differenceCounts.added} ` +
737
- `~${result.differenceCounts.modified} -${result.differenceCounts.removed}.`
738
- : '';
739
- log(
740
- `Imported ${result.archiveEntryCount} SB3 entries into ${result.outputDirectory} ` +
741
- `(${result.assetCount} assets, ${result.embeddedExtensionCount} embedded extensions).` +
742
- differenceMessage,
743
- );
744
- } else {
745
- log(`Already up to date; no files changed: ${result.outputDirectory}`);
746
- }
747
- if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
748
- }