@kubohiroya/sb3-toolchain 0.1.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/cli.js ADDED
@@ -0,0 +1,465 @@
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 {migrateExtensionId} from './extension-id-migration.js';
10
+ import {extensionStatus, syncExtensions, updateExtensions} from './extension-sync.js';
11
+ import {importSb3} from './import.js';
12
+ import {validateSb3Source} from './source.js';
13
+
14
+ function assert(condition, message) {
15
+ if (!condition) {
16
+ throw new Error(message);
17
+ }
18
+ }
19
+
20
+ export function usage() {
21
+ return `Usage:
22
+ sb3-toolchain import INPUT.sb3 --output SOURCE_DIR [--yes] [--discard-local-changes]
23
+ sb3-toolchain check SOURCE_DIR
24
+ sb3-toolchain build SOURCE_DIR --output OUTPUT.sb3 [--yes]
25
+ sb3-toolchain extensions status SOURCE_DIR
26
+ sb3-toolchain extensions sync SOURCE_DIR [--yes]
27
+ sb3-toolchain extensions update SOURCE_DIR [EXTENSION_ID] [--migrate-id NEW_ID] [--artifact PATH] [--yes]
28
+ sb3-toolchain extensions migrate-id SOURCE_DIR --from OLD_ID --to NEW_ID [--yes]
29
+
30
+ Commands:
31
+ import Expand an SB3 into Git-friendly source files.
32
+ check Validate an expanded SB3 source directory.
33
+ build Build a deterministic SB3 from expanded sources.
34
+ extensions Inspect, restore, or update managed embedded extensions.
35
+
36
+ Replacement safety:
37
+ Differing outputs require interactive confirmation or --yes.
38
+ Import refuses to discard uncommitted Git changes unless
39
+ --discard-local-changes is also specified. --force is not supported.`;
40
+ }
41
+
42
+ function takeValue(arguments_, index, option) {
43
+ const value = arguments_[index + 1];
44
+ assert(value && !value.startsWith('-'), `${option} requires a value.`);
45
+ return value;
46
+ }
47
+
48
+ function parseImportArguments(arguments_) {
49
+ let inputPath;
50
+ let outputDirectory;
51
+ let discardLocalChanges = false;
52
+ let yes = false;
53
+
54
+ for (let index = 0; index < arguments_.length; index += 1) {
55
+ const argument = arguments_[index];
56
+ if (argument === '--output') {
57
+ outputDirectory = path.resolve(takeValue(arguments_, index, '--output'));
58
+ index += 1;
59
+ } else if (argument === '--yes') {
60
+ yes = true;
61
+ } else if (argument === '--discard-local-changes') {
62
+ discardLocalChanges = true;
63
+ } else {
64
+ assert(
65
+ argument !== '--force',
66
+ '--force is intentionally unsupported. Use --yes and, only when necessary, ' +
67
+ '--discard-local-changes.',
68
+ );
69
+ assert(!argument.startsWith('-'), `Unknown option: ${argument}`);
70
+ assert(!inputPath, 'Only one input SB3 may be specified.');
71
+ inputPath = path.resolve(argument);
72
+ }
73
+ }
74
+
75
+ assert(inputPath, 'The import command requires INPUT.sb3.');
76
+ assert(outputDirectory, 'The import command requires --output SOURCE_DIR.');
77
+ return {command: 'import', discardLocalChanges, inputPath, outputDirectory, yes};
78
+ }
79
+
80
+ function parseCheckArguments(arguments_) {
81
+ assert(
82
+ arguments_.length === 1 && !arguments_[0].startsWith('-'),
83
+ 'The check command requires exactly one SOURCE_DIR.',
84
+ );
85
+ return {command: 'check', sourceDirectory: path.resolve(arguments_[0])};
86
+ }
87
+
88
+ function parseBuildArguments(arguments_) {
89
+ let sourceDirectory;
90
+ let outputPath;
91
+ let yes = false;
92
+
93
+ for (let index = 0; index < arguments_.length; index += 1) {
94
+ const argument = arguments_[index];
95
+ if (argument === '--output') {
96
+ outputPath = path.resolve(takeValue(arguments_, index, '--output'));
97
+ index += 1;
98
+ } else if (argument === '--yes') {
99
+ yes = true;
100
+ } else {
101
+ assert(!argument.startsWith('-'), `Unknown option: ${argument}`);
102
+ assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');
103
+ sourceDirectory = path.resolve(argument);
104
+ }
105
+ }
106
+
107
+ assert(sourceDirectory, 'The build command requires SOURCE_DIR.');
108
+ assert(outputPath, 'The build command requires --output OUTPUT.sb3.');
109
+ return {command: 'build', outputPath, sourceDirectory, yes};
110
+ }
111
+
112
+ function parseExtensionMutationArguments(action, arguments_) {
113
+ let sourceDirectory;
114
+ let extensionId;
115
+ let migrateToId;
116
+ let sourceArtifact;
117
+ let yes = false;
118
+
119
+ for (let index = 0; index < arguments_.length; index += 1) {
120
+ const argument = arguments_[index];
121
+ if (argument === '--yes') {
122
+ yes = true;
123
+ } else if (argument === '--migrate-id') {
124
+ assert(action === 'update', '--migrate-id is only valid for extensions update.');
125
+ migrateToId = takeValue(arguments_, index, '--migrate-id');
126
+ index += 1;
127
+ } else if (argument === '--artifact') {
128
+ assert(action === 'update', '--artifact is only valid for extensions update.');
129
+ sourceArtifact = takeValue(arguments_, index, '--artifact');
130
+ index += 1;
131
+ } else {
132
+ assert(!argument.startsWith('-'), `Unknown option: ${argument}`);
133
+ if (!sourceDirectory) {
134
+ sourceDirectory = path.resolve(argument);
135
+ } else {
136
+ assert(action === 'update', `The extensions ${action} command accepts only SOURCE_DIR.`);
137
+ assert(!extensionId, 'Only one EXTENSION_ID may be specified.');
138
+ assert(
139
+ /^[A-Za-z0-9._-]+$/u.test(argument),
140
+ `Invalid embedded extension ID: ${JSON.stringify(argument)}`,
141
+ );
142
+ extensionId = argument;
143
+ }
144
+ }
145
+ }
146
+
147
+ assert(sourceDirectory, `The extensions ${action} command requires SOURCE_DIR.`);
148
+ assert(
149
+ migrateToId === undefined || extensionId !== undefined,
150
+ '--migrate-id requires an explicit existing EXTENSION_ID.',
151
+ );
152
+ assert(
153
+ sourceArtifact === undefined || migrateToId !== undefined,
154
+ '--artifact requires --migrate-id.',
155
+ );
156
+ return {
157
+ action,
158
+ command: 'extensions',
159
+ extensionId,
160
+ migrateToId,
161
+ sourceArtifact,
162
+ sourceDirectory,
163
+ yes,
164
+ };
165
+ }
166
+
167
+ function parseExtensionIdMigrationArguments(arguments_) {
168
+ let fromId;
169
+ let sourceDirectory;
170
+ let toId;
171
+ let yes = false;
172
+
173
+ for (let index = 0; index < arguments_.length; index += 1) {
174
+ const argument = arguments_[index];
175
+ if (argument === '--from') {
176
+ fromId = takeValue(arguments_, index, '--from');
177
+ index += 1;
178
+ } else if (argument === '--to') {
179
+ toId = takeValue(arguments_, index, '--to');
180
+ index += 1;
181
+ } else if (argument === '--yes') {
182
+ yes = true;
183
+ } else {
184
+ assert(!argument.startsWith('-'), `Unknown option: ${argument}`);
185
+ assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');
186
+ sourceDirectory = path.resolve(argument);
187
+ }
188
+ }
189
+ assert(sourceDirectory, 'The extensions migrate-id command requires SOURCE_DIR.');
190
+ assert(fromId, 'The extensions migrate-id command requires --from OLD_ID.');
191
+ assert(toId, 'The extensions migrate-id command requires --to NEW_ID.');
192
+ return {
193
+ action: 'migrate-id',
194
+ command: 'extensions',
195
+ fromId,
196
+ sourceDirectory,
197
+ toId,
198
+ yes,
199
+ };
200
+ }
201
+
202
+ function parseExtensionsArguments(arguments_) {
203
+ const [action, ...actionArguments] = arguments_;
204
+ assert(
205
+ action === 'migrate-id' || action === 'status' || action === 'sync' || action === 'update',
206
+ 'The extensions command requires status, sync, update, or migrate-id.',
207
+ );
208
+ if (action === 'status') {
209
+ assert(
210
+ actionArguments.length === 1 && !actionArguments[0].startsWith('-'),
211
+ 'The extensions status command requires exactly one SOURCE_DIR.',
212
+ );
213
+ return {
214
+ action,
215
+ command: 'extensions',
216
+ sourceDirectory: path.resolve(actionArguments[0]),
217
+ };
218
+ }
219
+ if (action === 'migrate-id') {
220
+ return parseExtensionIdMigrationArguments(actionArguments);
221
+ }
222
+ return parseExtensionMutationArguments(action, actionArguments);
223
+ }
224
+
225
+ export function parseCliArguments(arguments_) {
226
+ const normalized = arguments_.filter((argument) => argument !== '--');
227
+ if (normalized.length === 0 || normalized[0] === '--help' || normalized[0] === '-h') {
228
+ return {command: 'help'};
229
+ }
230
+ if (normalized[0] === '--version' || normalized[0] === '-v') {
231
+ return {command: 'version'};
232
+ }
233
+
234
+ const [command, ...commandArguments] = normalized;
235
+ if (commandArguments.includes('--help') || commandArguments.includes('-h')) {
236
+ return {command: 'help'};
237
+ }
238
+ if (command === 'import') return parseImportArguments(commandArguments);
239
+ if (command === 'check') return parseCheckArguments(commandArguments);
240
+ if (command === 'build') return parseBuildArguments(commandArguments);
241
+ if (command === 'extensions') return parseExtensionsArguments(commandArguments);
242
+ throw new Error(`Unknown command: ${command}`);
243
+ }
244
+
245
+ function formatDifferenceLines(differences) {
246
+ const labels = {added: '+', modified: '~', removed: '-'};
247
+ const lines = Object.entries(differences).flatMap(([kind, paths]) =>
248
+ paths.map((relativePath) => `${labels[kind]} ${relativePath}`),
249
+ );
250
+ const visibleLines = lines.slice(0, 12);
251
+ if (lines.length > visibleLines.length) {
252
+ visibleLines.push(`... and ${lines.length - visibleLines.length} more`);
253
+ }
254
+ return visibleLines.join('\n');
255
+ }
256
+
257
+ async function confirmImportReplacement(context) {
258
+ const {comparison, discardLocalChanges, gitState, outputDirectory} = context;
259
+ assert(
260
+ process.stdin.isTTY && process.stdout.isTTY,
261
+ `Output directory already exists: ${outputDirectory}. ` +
262
+ 'Non-interactive replacement requires --yes.',
263
+ );
264
+ const readline = createInterface({input: process.stdin, output: process.stdout});
265
+ try {
266
+ const gitMessage = gitState.clean
267
+ ? 'Git state: clean'
268
+ : 'Git state: uncommitted changes will be discarded';
269
+ const answer = await readline.question(
270
+ `Existing SB3 source differs from the import candidate:\n` +
271
+ ` ${outputDirectory}\n` +
272
+ `${formatDifferenceLines(comparison.differences)}\n` +
273
+ `${gitMessage}\n` +
274
+ `${discardLocalChanges ? 'WARNING: --discard-local-changes is active.\n' : ''}` +
275
+ 'Replace the existing source directory? [y/N] ',
276
+ );
277
+ return /^(?:y|yes)$/iu.test(answer.trim());
278
+ } finally {
279
+ readline.close();
280
+ }
281
+ }
282
+
283
+ async function confirmBuildReplacement(outputPath) {
284
+ assert(
285
+ process.stdin.isTTY && process.stdout.isTTY,
286
+ `Existing SB3 output differs: ${outputPath}. Non-interactive replacement requires --yes.`,
287
+ );
288
+ const readline = createInterface({input: process.stdin, output: process.stdout});
289
+ try {
290
+ const answer = await readline.question(
291
+ `Existing generated SB3 will be replaced:\n ${outputPath}\nContinue? [y/N] `,
292
+ );
293
+ return /^(?:y|yes)$/iu.test(answer.trim());
294
+ } finally {
295
+ readline.close();
296
+ }
297
+ }
298
+
299
+ async function confirmExtensionReplacement({comparison, sourceDirectory}) {
300
+ assert(
301
+ process.stdin.isTTY && process.stdout.isTTY,
302
+ `Managed extension files differ in ${sourceDirectory}. ` +
303
+ 'Non-interactive replacement requires --yes.',
304
+ );
305
+ const readline = createInterface({input: process.stdin, output: process.stdout});
306
+ try {
307
+ const answer = await readline.question(
308
+ `Managed extension changes will be installed:\n` +
309
+ ` ${sourceDirectory}\n` +
310
+ `${formatDifferenceLines(comparison.differences)}\n` +
311
+ 'Replace these files? [y/N] ',
312
+ );
313
+ return /^(?:y|yes)$/iu.test(answer.trim());
314
+ } finally {
315
+ readline.close();
316
+ }
317
+ }
318
+
319
+ function logMigrationResult(result, log) {
320
+ const counts = Object.entries(result.counts)
321
+ .filter(([, count]) => count > 0)
322
+ .map(([kind, count]) => `${kind}=${count}`)
323
+ .join(', ');
324
+ const action = result.applied ? 'Migrated' : 'Dry run';
325
+ log(
326
+ `${action}: ${result.fromId} -> ${result.toId}; ` +
327
+ `${result.totalChanges} classified changes (${counts || 'none'}); ` +
328
+ `artifact=${result.artifactReady ? 'ready' : 'requires-new-ID'}.`,
329
+ );
330
+ for (const reference of result.unclassifiedReferences) {
331
+ log(
332
+ `Unclassified ${reference.kind}: ${reference.file}${reference.path} = ` +
333
+ JSON.stringify(reference.value),
334
+ );
335
+ }
336
+ }
337
+
338
+ export async function runCli(
339
+ arguments_,
340
+ {fetch: fetchImplementation = globalThis.fetch, log = console.log} = {},
341
+ ) {
342
+ const options = parseCliArguments(arguments_);
343
+ if (options.command === 'help') {
344
+ log(usage());
345
+ return;
346
+ }
347
+ if (options.command === 'version') {
348
+ log(packageVersion);
349
+ return;
350
+ }
351
+ if (options.command === 'check') {
352
+ const result = await validateSb3Source(options.sourceDirectory);
353
+ log(
354
+ `Valid SB3 source: ${result.resolvedSourceDirectory} ` +
355
+ `(${result.sourceManifest.archiveEntries.length} entries, ` +
356
+ `${result.assetContents.size} assets, ${result.assetReferenceCount} references, ` +
357
+ `${result.extensions.length} embedded extensions).`,
358
+ );
359
+ return;
360
+ }
361
+ if (options.command === 'build' && 'outputPath' in options) {
362
+ const result = await buildSb3({
363
+ confirmReplace: confirmBuildReplacement,
364
+ outputPath: options.outputPath,
365
+ sourceDirectory: options.sourceDirectory,
366
+ yes: options.yes,
367
+ });
368
+ const action = result.changed ? 'Built' : 'Already up to date';
369
+ log(
370
+ `${action}: ${result.outputPath} (${result.entryCount} entries, ` +
371
+ `${result.assetCount} assets, ${result.embeddedExtensionCount} embedded extensions).`,
372
+ );
373
+ if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
374
+ return;
375
+ }
376
+ if (options.command === 'extensions') {
377
+ if (options.action === 'migrate-id') {
378
+ const result = await migrateExtensionId({
379
+ fromId: options.fromId,
380
+ sourceDirectory: options.sourceDirectory,
381
+ toId: options.toId,
382
+ yes: options.yes,
383
+ });
384
+ logMigrationResult(result, log);
385
+ if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
386
+ return;
387
+ }
388
+ if (options.action === 'status') {
389
+ const statuses = await extensionStatus(options.sourceDirectory, {
390
+ fetch: fetchImplementation,
391
+ });
392
+ if (statuses.length === 0) {
393
+ log(`No managed embedded extensions: ${options.sourceDirectory}`);
394
+ return;
395
+ }
396
+ for (const status of statuses) {
397
+ log(
398
+ `${status.id}: ${status.state}; local=${status.local}; ` +
399
+ `${status.ref} -> ${status.remoteCommit} ` +
400
+ `(installed ${status.resolvedCommit})`,
401
+ );
402
+ }
403
+ return;
404
+ }
405
+
406
+ const operationOptions = {
407
+ confirmReplace: confirmExtensionReplacement,
408
+ fetch: fetchImplementation,
409
+ sourceDirectory: options.sourceDirectory,
410
+ yes: options.yes,
411
+ };
412
+ const result =
413
+ options.action === 'sync'
414
+ ? await syncExtensions(operationOptions)
415
+ : await updateExtensions({
416
+ ...operationOptions,
417
+ extensionId: options.extensionId,
418
+ migrateToId: options.migrateToId,
419
+ sourceArtifact: options.sourceArtifact,
420
+ });
421
+ const action = result.changed ? 'Updated' : 'Already up to date';
422
+ log(
423
+ `${action}: ${result.sourceDirectory} ` +
424
+ `(${result.extensions.map((extension) => extension.id).join(', ')}).`,
425
+ );
426
+ if (result.migration) {
427
+ logMigrationResult(
428
+ {
429
+ applied: result.changed,
430
+ artifactReady: true,
431
+ ...result.migration,
432
+ },
433
+ log,
434
+ );
435
+ }
436
+ if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
437
+ return;
438
+ }
439
+
440
+ assert(
441
+ options.command === 'import' && 'inputPath' in options,
442
+ 'Internal CLI command routing error.',
443
+ );
444
+ const result = await importSb3({
445
+ confirmReplace: confirmImportReplacement,
446
+ discardLocalChanges: options.discardLocalChanges,
447
+ inputPath: options.inputPath,
448
+ outputDirectory: options.outputDirectory,
449
+ yes: options.yes,
450
+ });
451
+ if (result.changed) {
452
+ const differenceMessage = result.differenceCounts
453
+ ? ` Changes: +${result.differenceCounts.added} ` +
454
+ `~${result.differenceCounts.modified} -${result.differenceCounts.removed}.`
455
+ : '';
456
+ log(
457
+ `Imported ${result.archiveEntryCount} SB3 entries into ${result.outputDirectory} ` +
458
+ `(${result.assetCount} assets, ${result.embeddedExtensionCount} embedded extensions).` +
459
+ differenceMessage,
460
+ );
461
+ } else {
462
+ log(`Already up to date; no files changed: ${result.outputDirectory}`);
463
+ }
464
+ if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
465
+ }
@@ -0,0 +1,4 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ export const packageName = '@kubohiroya/sb3-toolchain';
4
+ export const packageVersion = '0.1.0';
@@ -0,0 +1,86 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ import {createHash} from 'node:crypto';
4
+
5
+ import {validateArchiveEntryName} from './archive.js';
6
+
7
+ function assert(condition, message) {
8
+ if (!condition) {
9
+ throw new Error(message);
10
+ }
11
+ }
12
+
13
+ export function extensionIntegrity(contents) {
14
+ return `sha256-${createHash('sha256').update(contents).digest('base64')}`;
15
+ }
16
+
17
+ export function extensionHeaderId(contents) {
18
+ const source = Buffer.from(contents).toString('utf8');
19
+ return source.match(/^\/\/ ID: ([A-Za-z0-9._-]+)\r?$/mu)?.[1] ?? null;
20
+ }
21
+
22
+ export function validateExtensionSourceMetadata(extension) {
23
+ if (extension.source === undefined) {
24
+ return null;
25
+ }
26
+
27
+ const source = extension.source;
28
+ assert(
29
+ source && typeof source === 'object' && !Array.isArray(source),
30
+ `Managed extension source must be an object: ${extension.id}`,
31
+ );
32
+ assert(
33
+ source.provider === 'github',
34
+ `Unsupported extension source provider for ${extension.id}: ${source.provider}`,
35
+ );
36
+ assert(
37
+ typeof source.repository === 'string' &&
38
+ /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]+$/u.test(source.repository),
39
+ `Invalid GitHub repository for extension ${extension.id}: ${source.repository}`,
40
+ );
41
+ assert(
42
+ typeof source.ref === 'string' &&
43
+ source.ref.length > 0 &&
44
+ !/[\u0000-\u0020\u007f]/u.test(source.ref),
45
+ `Invalid Git ref for extension ${extension.id}: ${source.ref}`,
46
+ );
47
+ assert(
48
+ typeof source.resolvedCommit === 'string' && /^[a-f0-9]{40}$/u.test(source.resolvedCommit),
49
+ `Managed extension ${extension.id} requires a 40-character resolvedCommit.`,
50
+ );
51
+ assert(
52
+ typeof source.artifact === 'string' && source.artifact.length > 0,
53
+ `Managed extension ${extension.id} requires an artifact path.`,
54
+ );
55
+ validateArchiveEntryName(source.artifact);
56
+ assert(
57
+ !source.artifact.endsWith('/'),
58
+ `Managed extension artifact must be a file: ${source.artifact}`,
59
+ );
60
+ assert(
61
+ typeof source.integrity === 'string' && /^sha256-[A-Za-z0-9+/]{43}=$/u.test(source.integrity),
62
+ `Managed extension ${extension.id} requires SHA-256 integrity.`,
63
+ );
64
+ return source;
65
+ }
66
+
67
+ export function validateManagedExtensionContents(extension, contents) {
68
+ const source = validateExtensionSourceMetadata(extension);
69
+ if (!source) {
70
+ return null;
71
+ }
72
+
73
+ const actualIntegrity = extensionIntegrity(contents);
74
+ assert(
75
+ actualIntegrity === source.integrity,
76
+ `Managed extension integrity mismatch for ${extension.id}: ` +
77
+ `expected ${source.integrity}, got ${actualIntegrity}`,
78
+ );
79
+ const actualId = extensionHeaderId(contents);
80
+ assert(
81
+ actualId === extension.id,
82
+ `Managed extension header ID mismatch for ${extension.id}: ` +
83
+ `expected ${extension.id}, got ${actualId ?? '(missing)'}`,
84
+ );
85
+ return {actualId, integrity: actualIntegrity, source};
86
+ }