@kubohiroya/sb3-toolchain 0.23.0 → 0.25.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.
@@ -0,0 +1,134 @@
1
+ import { assert, errorMessage } from "./assert.js";
2
+ import { blockPaletteCommentMarker, blockPaletteCommentMaxLength, blockPaletteCommentReference, blockPaletteFile, blockPaletteFormatVersion, blockPaletteSpriteCommentHeader, blockPaletteStageCommentHeader, formatBlockPaletteComment, resolveBlockPaletteReferences, serializeBlockPaletteDocument, validateBlockPaletteDocument } from "./block-palette.js";
3
+ import { validateArchiveEntryName } from "./archive.js";
4
+ import { assertSameFileSet, blockPaletteSourceFormatVersion, collectSourceAssetReferences, isObject, sourceFormatVersion, supportedSourceFormatVersions, validateExtensionLayout, validateSourceManifest } from "./source-format.js";
5
+ import { packageVersion } from "./constants.js";
6
+ import { Sb3SourceError, expandArchive, formatSourceFiles } from "./expand-archive.js";
7
+ import { strFromU8 } from "fflate";
8
+ import { md5 } from "@noble/hashes/legacy.js";
9
+ import { bytesToHex } from "@noble/hashes/utils.js";
10
+ //#region src/browser.ts
11
+ var archiveLimits = {
12
+ maxArchiveBytes: 104857600,
13
+ maxEntryBytes: 104857600,
14
+ maxExpandedBytes: 536870912,
15
+ maxEntries: 2e4
16
+ };
17
+ function validateEditorProject(project) {
18
+ if (project.turboWarpPlus !== void 0) throw new Sb3SourceError("unsupported-project", "Plus extension manifests are not supported in project folders.");
19
+ assert(Array.isArray(project.targets), "Missing project targets.");
20
+ const targetNames = /* @__PURE__ */ new Set();
21
+ let stages = 0;
22
+ for (const target of project.targets) {
23
+ assert(isObject(target) && typeof target.isStage === "boolean" && typeof target.name === "string", "Invalid project target.");
24
+ if (target.isStage) stages++;
25
+ else {
26
+ assert(!targetNames.has(target.name), `Duplicate sprite name: ${target.name}`);
27
+ targetNames.add(target.name);
28
+ }
29
+ assert(target.blocks === void 0 || isObject(target.blocks), "Invalid target blocks.");
30
+ assert(target.comments === void 0 || isObject(target.comments), "Invalid target comments.");
31
+ }
32
+ assert(stages === 1, "Expected exactly one stage.");
33
+ assert(project.extensionURLs === void 0 || isObject(project.extensionURLs) && Object.values(project.extensionURLs).every((url) => typeof url === "string"), "Invalid project extensionURLs.");
34
+ }
35
+ function validatedAssetReferences(project) {
36
+ try {
37
+ validateEditorProject(project);
38
+ return collectSourceAssetReferences(project);
39
+ } catch (cause) {
40
+ if (cause instanceof Sb3SourceError) throw cause;
41
+ throw new Sb3SourceError("invalid-project", errorMessage(cause), { cause });
42
+ }
43
+ }
44
+ /** Validate the layout and asset bytes of a project folder in memory. */
45
+ function validateSourceFiles(files) {
46
+ const json = (filename) => {
47
+ const bytes = files.get(filename);
48
+ assert(bytes, `Missing source file: ${filename}`);
49
+ return JSON.parse(strFromU8(bytes));
50
+ };
51
+ try {
52
+ const manifest = json("sb3-source.json");
53
+ validateSourceManifest(manifest);
54
+ const project = json(manifest.project);
55
+ assert(isObject(project), "project.source.json must contain an object.");
56
+ const references = validatedAssetReferences(project);
57
+ const assetEntries = manifest.archiveEntries.filter((name) => name !== "project.json");
58
+ assertSameFileSet(assetEntries, references.map(({ filename }) => filename), "Asset manifest");
59
+ const seen = /* @__PURE__ */ new Set();
60
+ for (const { filename, description } of references) {
61
+ if (seen.has(filename)) continue;
62
+ seen.add(filename);
63
+ const asset = files.get(`assets/${filename}`);
64
+ if (!asset) throw new Sb3SourceError("missing-asset", `Referenced asset is missing for ${description}: ${filename}`);
65
+ if (bytesToHex(md5(asset)) !== filename.slice(0, 32)) throw new Sb3SourceError("invalid-asset", `Asset content hash mismatch for ${description}: ${filename}`);
66
+ }
67
+ try {
68
+ const blockPalette = manifest.blockPalette === void 0 ? null : validateBlockPaletteDocument(json(manifest.blockPalette));
69
+ resolveBlockPaletteReferences(project, blockPalette);
70
+ } catch (cause) {
71
+ throw new Sb3SourceError("invalid-block-palette", errorMessage(cause), { cause });
72
+ }
73
+ const extensionFiles = [];
74
+ const expected = /* @__PURE__ */ new Set([
75
+ "sb3-source.json",
76
+ manifest.project,
77
+ manifest.embeddedExtensions,
78
+ ...manifest.blockPalette === void 0 ? [] : [manifest.blockPalette],
79
+ ...assetEntries.map((name) => `assets/${name}`)
80
+ ]);
81
+ for (const name of files.keys()) {
82
+ try {
83
+ validateArchiveEntryName(name);
84
+ } catch (cause) {
85
+ throw new Sb3SourceError("unsafe-path", errorMessage(cause), { cause });
86
+ }
87
+ if (name.startsWith("extensions/")) extensionFiles.push(name.slice(11));
88
+ else assert(expected.has(name), `Unexpected source file: ${name}`);
89
+ }
90
+ try {
91
+ validateExtensionLayout(json(manifest.embeddedExtensions), project, extensionFiles);
92
+ } catch (cause) {
93
+ throw new Sb3SourceError("invalid-extension", errorMessage(cause), { cause });
94
+ }
95
+ } catch (cause) {
96
+ if (cause instanceof Sb3SourceError) throw cause;
97
+ throw new Sb3SourceError("invalid-source", errorMessage(cause), { cause });
98
+ }
99
+ }
100
+ /** Expand an SB3 into files suitable for opening as an Editor project folder. */
101
+ function unpackSb3(bytes) {
102
+ const expanded = expandArchive(bytes, archiveLimits);
103
+ const references = new Set(validatedAssetReferences(expanded.project).map(({ filename }) => filename));
104
+ for (const name of references) if (!expanded.assets.has(name)) throw new Sb3SourceError("missing-asset", `Referenced asset is missing: ${name}`);
105
+ const warnings = expanded.blockPaletteWarnings.map((warning) => ({
106
+ ...warning,
107
+ path: "project.json"
108
+ }));
109
+ expanded.archiveEntries = expanded.archiveEntries.filter((name) => {
110
+ if (name === "project.json" || references.has(name)) return true;
111
+ if (name.endsWith("/")) warnings.push({
112
+ code: "directory-entry",
113
+ path: name
114
+ });
115
+ else if (/^[a-f0-9]{32}\.[A-Za-z0-9]+$/u.test(name)) {
116
+ expanded.assets.delete(name);
117
+ warnings.push({
118
+ code: "unreferenced-asset",
119
+ path: name
120
+ });
121
+ } else throw new Sb3SourceError("unsupported-project", `Unsupported SB3 attachment: ${name}`);
122
+ return false;
123
+ });
124
+ const files = formatSourceFiles(expanded);
125
+ validateSourceFiles(files);
126
+ return {
127
+ files,
128
+ warnings
129
+ };
130
+ }
131
+ //#endregion
132
+ export { Sb3SourceError, blockPaletteCommentMarker, blockPaletteCommentMaxLength, blockPaletteCommentReference, blockPaletteFile, blockPaletteFormatVersion, blockPaletteSourceFormatVersion, blockPaletteSpriteCommentHeader, blockPaletteStageCommentHeader, formatBlockPaletteComment, packageVersion, serializeBlockPaletteDocument, sourceFormatVersion, supportedSourceFormatVersions, unpackSb3, validateBlockPaletteDocument, validateSourceFiles };
133
+
134
+ //# sourceMappingURL=browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser.js","names":[],"sources":["../src/browser.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {md5} from '@noble/hashes/legacy.js';\nimport {bytesToHex} from '@noble/hashes/utils.js';\nimport {strFromU8} from 'fflate';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert, errorMessage} from './assert';\nimport {resolveBlockPaletteReferences, validateBlockPaletteDocument} from './block-palette';\nimport type {BlockPaletteWarningCode} from './block-palette';\nimport {expandArchive, formatSourceFiles, Sb3SourceError} from './expand-archive';\nimport {\n assertSameFileSet,\n collectSourceAssetReferences,\n isObject,\n validateExtensionLayout,\n validateSourceManifest,\n} from './source-format';\nimport type {ProjectJson} from './types';\n\nexport {Sb3SourceError} from './expand-archive';\nexport type {Sb3SourceErrorCode} from './expand-archive';\nexport {packageVersion} from './constants';\nexport {\n blockPaletteCommentMarker,\n blockPaletteCommentMaxLength,\n blockPaletteCommentReference,\n blockPaletteFile,\n blockPaletteFormatVersion,\n blockPaletteSpriteCommentHeader,\n blockPaletteStageCommentHeader,\n formatBlockPaletteComment,\n serializeBlockPaletteDocument,\n validateBlockPaletteDocument,\n} from './block-palette';\nexport type {\n BlockPaletteDocument,\n BlockPaletteSet,\n BlockPaletteTargetSetting,\n} from './block-palette';\nexport {\n blockPaletteSourceFormatVersion,\n sourceFormatVersion,\n supportedSourceFormatVersions,\n} from './source-format';\n\nexport interface UnpackWarning {\n code: 'directory-entry' | 'unreferenced-asset' | BlockPaletteWarningCode;\n /** The archive entry, or `project.json` for block palette comments. */\n path: string;\n /** Present for block palette warnings. */\n commentId?: string;\n message?: string;\n target?: string;\n}\n\nexport interface UnpackedSb3 {\n files: Map<string, Uint8Array>;\n warnings: UnpackWarning[];\n}\n\nconst archiveLimits = {\n maxArchiveBytes: 100 * 1024 * 1024,\n maxEntryBytes: 100 * 1024 * 1024,\n maxExpandedBytes: 512 * 1024 * 1024,\n maxEntries: 20_000,\n};\n\nfunction validateEditorProject(project: ProjectJson) {\n if (project.turboWarpPlus !== undefined) {\n throw new Sb3SourceError(\n 'unsupported-project',\n 'Plus extension manifests are not supported in project folders.',\n );\n }\n assert(Array.isArray(project.targets), 'Missing project targets.');\n const targetNames = new Set<string>();\n let stages = 0;\n for (const target of project.targets) {\n assert(\n isObject(target) && typeof target.isStage === 'boolean' && typeof target.name === 'string',\n 'Invalid project target.',\n );\n if (target.isStage) {\n stages++;\n } else {\n assert(!targetNames.has(target.name), `Duplicate sprite name: ${target.name}`);\n targetNames.add(target.name);\n }\n assert(target.blocks === undefined || isObject(target.blocks), 'Invalid target blocks.');\n assert(target.comments === undefined || isObject(target.comments), 'Invalid target comments.');\n }\n assert(stages === 1, 'Expected exactly one stage.');\n assert(\n project.extensionURLs === undefined ||\n (isObject(project.extensionURLs) &&\n Object.values(project.extensionURLs).every((url) => typeof url === 'string')),\n 'Invalid project extensionURLs.',\n );\n}\n\nfunction validatedAssetReferences(project: ProjectJson) {\n try {\n validateEditorProject(project);\n return collectSourceAssetReferences(project);\n } catch (cause) {\n if (cause instanceof Sb3SourceError) throw cause;\n throw new Sb3SourceError('invalid-project', errorMessage(cause), {cause});\n }\n}\n\n/** Validate the layout and asset bytes of a project folder in memory. */\nexport function validateSourceFiles(files: ReadonlyMap<string, Uint8Array>): void {\n const json = (filename: string): unknown => {\n const bytes = files.get(filename);\n assert(bytes, `Missing source file: ${filename}`);\n return JSON.parse(strFromU8(bytes));\n };\n\n try {\n const manifest = json('sb3-source.json');\n validateSourceManifest(manifest);\n const project = json(manifest.project);\n assert(isObject(project), 'project.source.json must contain an object.');\n const references = validatedAssetReferences(project);\n\n const assetEntries = manifest.archiveEntries.filter((name) => name !== 'project.json');\n assertSameFileSet(\n assetEntries,\n references.map(({filename}) => filename),\n 'Asset manifest',\n );\n const seen = new Set<string>();\n for (const {filename, description} of references) {\n if (seen.has(filename)) continue;\n seen.add(filename);\n const asset = files.get(`assets/${filename}`);\n if (!asset) {\n throw new Sb3SourceError(\n 'missing-asset',\n `Referenced asset is missing for ${description}: ${filename}`,\n );\n }\n if (bytesToHex(md5(asset)) !== filename.slice(0, 32)) {\n throw new Sb3SourceError(\n 'invalid-asset',\n `Asset content hash mismatch for ${description}: ${filename}`,\n );\n }\n }\n\n try {\n const blockPalette =\n manifest.blockPalette === undefined\n ? null\n : validateBlockPaletteDocument(json(manifest.blockPalette));\n resolveBlockPaletteReferences(project, blockPalette);\n } catch (cause) {\n throw new Sb3SourceError('invalid-block-palette', errorMessage(cause), {cause});\n }\n\n const extensionFiles: string[] = [];\n const expected = new Set([\n 'sb3-source.json',\n manifest.project,\n manifest.embeddedExtensions,\n ...(manifest.blockPalette === undefined ? [] : [manifest.blockPalette]),\n ...assetEntries.map((name) => `assets/${name}`),\n ]);\n for (const name of files.keys()) {\n try {\n validateArchiveEntryName(name);\n } catch (cause) {\n throw new Sb3SourceError('unsafe-path', errorMessage(cause), {cause});\n }\n if (name.startsWith('extensions/')) {\n extensionFiles.push(name.slice('extensions/'.length));\n } else {\n assert(expected.has(name), `Unexpected source file: ${name}`);\n }\n }\n try {\n validateExtensionLayout(json(manifest.embeddedExtensions), project, extensionFiles);\n } catch (cause) {\n throw new Sb3SourceError('invalid-extension', errorMessage(cause), {cause});\n }\n } catch (cause) {\n if (cause instanceof Sb3SourceError) throw cause;\n throw new Sb3SourceError('invalid-source', errorMessage(cause), {cause});\n }\n}\n\n/** Expand an SB3 into files suitable for opening as an Editor project folder. */\nexport function unpackSb3(bytes: Uint8Array): UnpackedSb3 {\n const expanded = expandArchive(bytes, archiveLimits);\n const references = new Set(\n validatedAssetReferences(expanded.project).map(({filename}) => filename),\n );\n for (const name of references) {\n if (!expanded.assets.has(name)) {\n throw new Sb3SourceError('missing-asset', `Referenced asset is missing: ${name}`);\n }\n }\n const warnings: UnpackWarning[] = expanded.blockPaletteWarnings.map((warning) => ({\n ...warning,\n path: 'project.json',\n }));\n expanded.archiveEntries = expanded.archiveEntries.filter((name) => {\n if (name === 'project.json' || references.has(name)) return true;\n if (name.endsWith('/')) {\n warnings.push({code: 'directory-entry', path: name});\n } else if (/^[a-f0-9]{32}\\.[A-Za-z0-9]+$/u.test(name)) {\n expanded.assets.delete(name);\n warnings.push({code: 'unreferenced-asset', path: name});\n } else {\n throw new Sb3SourceError('unsupported-project', `Unsupported SB3 attachment: ${name}`);\n }\n return false;\n });\n const files = formatSourceFiles(expanded);\n validateSourceFiles(files);\n return {files, warnings};\n}\n"],"mappings":";;;;;;;;;;AA6DA,IAAM,gBAAgB;CACpB,iBAAiB;CACjB,eAAe;CACf,kBAAkB;CAClB,YAAY;AACd;AAEA,SAAS,sBAAsB,SAAsB;CACnD,IAAI,QAAQ,kBAAkB,KAAA,GAC5B,MAAM,IAAI,eACR,uBACA,gEACF;CAEF,OAAO,MAAM,QAAQ,QAAQ,OAAO,GAAG,0BAA0B;CACjE,MAAM,8BAAc,IAAI,IAAY;CACpC,IAAI,SAAS;CACb,KAAK,MAAM,UAAU,QAAQ,SAAS;EACpC,OACE,SAAS,MAAM,KAAK,OAAO,OAAO,YAAY,aAAa,OAAO,OAAO,SAAS,UAClF,yBACF;EACA,IAAI,OAAO,SACT;OACK;GACL,OAAO,CAAC,YAAY,IAAI,OAAO,IAAI,GAAG,0BAA0B,OAAO,MAAM;GAC7E,YAAY,IAAI,OAAO,IAAI;EAC7B;EACA,OAAO,OAAO,WAAW,KAAA,KAAa,SAAS,OAAO,MAAM,GA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AAC,CAAC,KAAK,EAAC,eAAc,QAAQ,CACzE;CACA,KAAK,MAAM,QAAQ,YACjB,IAAI,CAAC,SAAS,OAAO,IAAI,IAAI,GAC3B,MAAM,IAAI,eAAe,iBAAiB,gCAAgC,MAAM;CAGpF,MAAM,WAA4B,SAAS,qBAAqB,KAAK,aAAa;EAChF,GAAG;EACH,MAAM;CACR,EAAE;CACF,SAAS,iBAAiB,SAAS,eAAe,QAAQ,SAAS;EACjE,IAAI,SAAS,kBAAkB,WAAW,IAAI,IAAI,GAAG,OAAO;EAC5D,IAAI,KAAK,SAAS,GAAG,GACnB,SAAS,KAAK;GAAC,MAAM;GAAmB,MAAM;EAAI,CAAC;OAC9C,IAAI,gCAAgC,KAAK,IAAI,GAAG;GACrD,SAAS,OAAO,OAAO,IAAI;GAC3B,SAAS,KAAK;IAAC,MAAM;IAAsB,MAAM;GAAI,CAAC;EACxD,OACE,MAAM,IAAI,eAAe,uBAAuB,+BAA+B,MAAM;EAEvF,OAAO;CACT,CAAC;CACD,MAAM,QAAQ,kBAAkB,QAAQ;CACxC,oBAAoB,KAAK;CACzB,OAAO;EAAC;EAAO;CAAQ;AACzB"}
package/dist/cli.js CHANGED
@@ -708,6 +708,7 @@ async function runCli(arguments_, { fetch: fetchImplementation = globalThis.fetc
708
708
  const differenceMessage = result.differenceCounts ? ` Changes: +${result.differenceCounts.added} ~${result.differenceCounts.modified} -${result.differenceCounts.removed}.` : "";
709
709
  log(`Imported ${result.archiveEntryCount} SB3 entries into ${result.outputDirectory} (${result.assetCount} assets, ${result.embeddedExtensionCount} embedded extensions).` + differenceMessage);
710
710
  } else log(`Already up to date; no files changed: ${result.outputDirectory}`);
711
+ for (const warning of result.warnings) log(`Warning: ${warning.message}`);
711
712
  if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
712
713
  }
713
714
  //#endregion
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport path from 'node:path';\nimport process from 'node:process';\nimport {createInterface} from 'node:readline/promises';\n\nimport {assert} from './assert';\nimport {buildSb3} from './build';\nimport {cleanUpSb3} from './clean-up-sb3';\nimport {packageVersion} from './constants';\nimport {unbundleSb3} from './extension-bundle-archive';\nimport {bundleExtensions, unbundleExtensions} from './extension-bundle-configuration';\nimport {validateExtensionBundleMetadata} from './extension-bundle-metadata';\nimport {\n formatExtensionDigestInventory,\n inventoryExtensionDigests,\n} from './extension-digest-inventory';\nimport type {ExtensionBundleMetadata} from './types';\nimport {migrateExtensionId} from './extension-id-migration';\nimport {replaceSb3Extensions} from './extension-sb3-replacement';\nimport type {ExtensionIdMigrationCounts, ExtensionIdReference} from './extension-id-migration';\nimport {extensionStatus, syncExtensions, updateExtensions} from './extension-sync';\nimport type {ExtensionSyncConfirmContext, FetchImplementation} from './extension-sync';\nimport {importSb3} from './import';\nimport type {OutputReplacementContext} from './import';\nimport type {DirectoryDifferences} from './output-safety';\nimport {createDeterministicSb3, validateSb3Source} from './source';\n\nexport interface HelpCliOptions {\n command: 'help';\n}\n\nexport interface VersionCliOptions {\n command: 'version';\n}\n\nexport interface ImportCliOptions {\n command: 'import';\n discardLocalChanges: boolean;\n inputPath: string;\n outputDirectory: string;\n yes: boolean;\n}\n\nexport interface CheckCliOptions {\n allowedAssetRoots?: string[];\n command: 'check';\n projectAssetsPath?: string;\n sourceDirectory: string;\n}\n\nexport interface BuildCliOptions {\n allowedAssetRoots?: string[];\n cleanUpBlocks?: boolean;\n command: 'build';\n outputPath: string;\n projectAssetsPath?: string;\n sourceDirectory: string;\n yes: boolean;\n}\n\nexport interface CleanUpCliOptions {\n command: 'clean-up';\n inputPath: string;\n outputPath: string;\n yes: boolean;\n}\n\nexport interface ExtensionsStatusCliOptions {\n action: 'status';\n command: 'extensions';\n sourceDirectory: string;\n}\n\nexport interface ExtensionsMutationCliOptions {\n action: 'sync' | 'update';\n allowBreakingApi?: boolean;\n apiManifestArtifact?: string;\n command: 'extensions';\n extensionId?: string;\n migrateToId?: string;\n sourceArtifact?: string;\n sourceDirectory: string;\n yes: boolean;\n}\n\nexport interface ExtensionsMigrateIdCliOptions {\n action: 'migrate-id';\n command: 'extensions';\n fromId: string;\n sourceDirectory: string;\n toId: string;\n yes: boolean;\n}\n\nexport interface ExtensionsBundleCliOptions {\n action: 'bundle';\n bundleId: string;\n bundleName: string;\n metadata?: ExtensionBundleMetadata;\n command: 'extensions';\n extensionIds: string[];\n recoveryCapsule: boolean;\n sourceDirectory: string;\n yes: boolean;\n buildMode?: 'classic' | 'module';\n sharedDependencies?: Record<string, string>;\n}\n\nexport interface ExtensionsUnbundleSourceCliOptions {\n action: 'unbundle';\n bundleId: string;\n command: 'extensions';\n sourceDirectory: string;\n yes: boolean;\n}\n\nexport interface ExtensionsUnbundleArchiveCliOptions {\n action: 'unbundle';\n bundleId: string;\n command: 'extensions';\n inputPath: string;\n outputPath: string;\n yes: boolean;\n}\n\nexport interface ExtensionsDigestsCliOptions {\n action: 'digests';\n command: 'extensions';\n inputPaths: string[];\n json: boolean;\n}\n\nexport interface ExtensionsReplaceSb3CliOptions {\n action: 'replace-sb3';\n command: 'extensions';\n fromPath?: string;\n inputPath: string;\n outputPath: string;\n yes: boolean;\n}\n\nexport type ExtensionsCliOptions =\n | ExtensionsDigestsCliOptions\n | ExtensionsReplaceSb3CliOptions\n | ExtensionsStatusCliOptions\n | ExtensionsMutationCliOptions\n | ExtensionsMigrateIdCliOptions\n | ExtensionsBundleCliOptions\n | ExtensionsUnbundleSourceCliOptions\n | ExtensionsUnbundleArchiveCliOptions;\n\nexport type CliOptions =\n | HelpCliOptions\n | VersionCliOptions\n | ImportCliOptions\n | CheckCliOptions\n | BuildCliOptions\n | CleanUpCliOptions\n | ExtensionsCliOptions;\n\nexport interface RunCliOptions {\n fetch?: FetchImplementation;\n log?: (message: string) => void;\n}\n\ninterface MigrationLogResult {\n applied: boolean;\n artifactReady: boolean;\n counts: ExtensionIdMigrationCounts;\n fromId: string | undefined;\n toId: string | undefined;\n totalChanges: number;\n unclassifiedReferences: ExtensionIdReference[];\n}\n\nexport function usage() {\n return `Usage:\n sb3-toolchain import INPUT.sb3 --output SOURCE_DIR [--yes] [--discard-local-changes]\n sb3-toolchain check SOURCE_DIR [--project-assets MANIFEST.json] [--allow-asset-root DIR ...]\n sb3-toolchain build SOURCE_DIR --output OUTPUT.sb3 [--project-assets MANIFEST.json] [--allow-asset-root DIR ...] [--clean-up-blocks] [--yes]\n sb3-toolchain clean-up INPUT.sb3 --output OUTPUT.sb3 [--yes]\n sb3-toolchain extensions digests INPUT.sb3 [INPUT.sb3 ...] [--json]\n sb3-toolchain extensions replace-sb3 INPUT.sb3 [--from DONOR.sb3] --output OUTPUT.sb3 [--yes]\n sb3-toolchain extensions status SOURCE_DIR\n sb3-toolchain extensions sync SOURCE_DIR [--yes]\n sb3-toolchain extensions update SOURCE_DIR [EXTENSION_ID] [--migrate-id NEW_ID] [--artifact PATH] [--api-manifest-artifact PATH] [--allow-breaking-api --yes]\n sb3-toolchain extensions migrate-id SOURCE_DIR --from OLD_ID --to NEW_ID [--yes]\n sb3-toolchain extensions bundle SOURCE_DIR --id BUNDLE_ID --name NAME [EXTENSION_ID ...] [--metadata-json JSON] [--build-mode classic|module] [--share PACKAGE@EXACT_VERSION] [--include-recovery-capsule] [--yes]\n sb3-toolchain extensions unbundle SOURCE_DIR BUNDLE_ID [--yes]\n sb3-toolchain extensions unbundle INPUT.sb3 BUNDLE_ID --output OUTPUT.sb3 [--yes]\n\nCommands:\n import Expand an SB3 into Git-friendly source files.\n check Validate an expanded SB3 source directory.\n build Build a deterministic SB3 from expanded sources.\n clean-up Arrange scripts in a more compact layout and write a separate SB3.\n extensions Inspect, restore, or update managed embedded extensions.\n\nBuild layout cleanup:\n --clean-up-blocks applies a deterministic TurboWarp-style \"Clean up Blocks\"\n layout to every target in the generated SB3. It never deletes blocks,\n variables, lists, or comments. The expanded source is unchanged, but the\n generated SB3 might not be able to undo the coordinate changes.\n\nProject asset additions:\n --project-assets validates a JSON or YAML manifest and adds its sprites,\n backdrops, costumes, and sounds only to the generated SB3. Input files are confined to the\n manifest directory unless --allow-asset-root explicitly permits another root.\n\nExtension digests:\n extensions digests reads each SB3's own manifest and reports every extension's ID,\n pinned SHA-256, source form (remote-non-cacheable, remote-cacheable, embedded-file,\n embedded-data), held byte size, and the project URI that names the cache bucket. Given\n several SB3s it also reports which digests more than one project names. Nothing is\n fetched and no browser storage is read: an extension cache belongs to an origin and a\n browser profile, so only the browser can list it, and an unresolved project URI never\n means an absent project.\n\nKamishibai SB3 replacement:\n extensions replace-sb3 replaces the runtime bundle and Block Script in INPUT.sb3.\n Omitting --from downloads the published block SB3 from the official samples site\n and verifies its size and SHA-256. --from uses a local donor without network access.\n The input is preserved; output must use a different path. Story data is not migrated.\n\nReplacement safety:\n Differing outputs require interactive confirmation or --yes.\n Import refuses to discard uncommitted Git changes unless\n --discard-local-changes is also specified. --force is not supported.`;\n}\n\nfunction takeValue(arguments_: string[], index: number, option: string): string {\n const value = arguments_[index + 1];\n assert(value && !value.startsWith('-'), `${option} requires a value.`);\n return value;\n}\n\nfunction parseImportArguments(arguments_: string[]): ImportCliOptions {\n let inputPath: string | undefined;\n let outputDirectory: string | undefined;\n let discardLocalChanges = false;\n let yes = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--output') {\n outputDirectory = path.resolve(takeValue(arguments_, index, '--output'));\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else if (argument === '--discard-local-changes') {\n discardLocalChanges = true;\n } else {\n assert(\n argument !== '--force',\n '--force is intentionally unsupported. Use --yes and, only when necessary, ' +\n '--discard-local-changes.',\n );\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!inputPath, 'Only one input SB3 may be specified.');\n inputPath = path.resolve(argument);\n }\n }\n\n assert(inputPath, 'The import command requires INPUT.sb3.');\n assert(outputDirectory, 'The import command requires --output SOURCE_DIR.');\n return {command: 'import', discardLocalChanges, inputPath, outputDirectory, yes};\n}\n\nfunction parseCleanUpArguments(arguments_: string[]): CleanUpCliOptions {\n let inputPath: string | undefined;\n let outputPath: string | undefined;\n let yes = false;\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--output') {\n assert(!outputPath, '--output may only be specified once.');\n outputPath = path.resolve(takeValue(arguments_, index, '--output'));\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!inputPath, 'Only one input SB3 may be specified.');\n inputPath = path.resolve(argument);\n }\n }\n assert(inputPath, 'The clean-up command requires INPUT.sb3.');\n assert(outputPath, 'The clean-up command requires --output OUTPUT.sb3.');\n return {command: 'clean-up', inputPath, outputPath, yes};\n}\n\nfunction parseCheckArguments(arguments_: string[]): CheckCliOptions {\n const allowedAssetRoots: string[] = [];\n let projectAssetsPath: string | undefined;\n let sourceDirectory: string | undefined;\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--project-assets') {\n projectAssetsPath = path.resolve(takeValue(arguments_, index, '--project-assets'));\n index += 1;\n } else if (argument === '--allow-asset-root') {\n allowedAssetRoots.push(path.resolve(takeValue(arguments_, index, '--allow-asset-root')));\n index += 1;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');\n sourceDirectory = path.resolve(argument);\n }\n }\n assert(sourceDirectory, 'The check command requires SOURCE_DIR.');\n assert(\n allowedAssetRoots.length === 0 || projectAssetsPath,\n '--allow-asset-root requires --project-assets.',\n );\n return {\n ...(allowedAssetRoots.length > 0 ? {allowedAssetRoots} : {}),\n command: 'check',\n ...(projectAssetsPath ? {projectAssetsPath} : {}),\n sourceDirectory,\n };\n}\n\nfunction parseBuildArguments(arguments_: string[]): BuildCliOptions {\n const allowedAssetRoots: string[] = [];\n let cleanUpBlocks = false;\n let sourceDirectory: string | undefined;\n let outputPath: string | undefined;\n let projectAssetsPath: string | undefined;\n let yes = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--clean-up-blocks') {\n cleanUpBlocks = true;\n } else if (argument === '--project-assets') {\n projectAssetsPath = path.resolve(takeValue(arguments_, index, '--project-assets'));\n index += 1;\n } else if (argument === '--allow-asset-root') {\n allowedAssetRoots.push(path.resolve(takeValue(arguments_, index, '--allow-asset-root')));\n index += 1;\n } else if (argument === '--output') {\n outputPath = path.resolve(takeValue(arguments_, index, '--output'));\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');\n sourceDirectory = path.resolve(argument);\n }\n }\n\n assert(sourceDirectory, 'The build command requires SOURCE_DIR.');\n assert(outputPath, 'The build command requires --output OUTPUT.sb3.');\n assert(\n allowedAssetRoots.length === 0 || projectAssetsPath,\n '--allow-asset-root requires --project-assets.',\n );\n return {\n ...(allowedAssetRoots.length > 0 ? {allowedAssetRoots} : {}),\n ...(cleanUpBlocks ? {cleanUpBlocks} : {}),\n command: 'build',\n outputPath,\n ...(projectAssetsPath ? {projectAssetsPath} : {}),\n sourceDirectory,\n yes,\n };\n}\n\nfunction parseExtensionMutationArguments(\n action: 'sync' | 'update',\n arguments_: string[],\n): ExtensionsMutationCliOptions {\n let allowBreakingApi = false;\n let apiManifestArtifact: string | undefined;\n let sourceDirectory: string | undefined;\n let extensionId: string | undefined;\n let migrateToId: string | undefined;\n let sourceArtifact: string | undefined;\n let yes = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--yes') {\n yes = true;\n } else if (argument === '--allow-breaking-api') {\n assert(action === 'update', '--allow-breaking-api is only valid for extensions update.');\n allowBreakingApi = true;\n } else if (argument === '--migrate-id') {\n assert(action === 'update', '--migrate-id is only valid for extensions update.');\n migrateToId = takeValue(arguments_, index, '--migrate-id');\n index += 1;\n } else if (argument === '--artifact') {\n assert(action === 'update', '--artifact is only valid for extensions update.');\n sourceArtifact = takeValue(arguments_, index, '--artifact');\n index += 1;\n } else if (argument === '--api-manifest-artifact') {\n assert(action === 'update', '--api-manifest-artifact is only valid for extensions update.');\n apiManifestArtifact = takeValue(arguments_, index, '--api-manifest-artifact');\n index += 1;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n if (!sourceDirectory) {\n sourceDirectory = path.resolve(argument);\n } else {\n assert(action === 'update', `The extensions ${action} command accepts only SOURCE_DIR.`);\n assert(!extensionId, 'Only one EXTENSION_ID may be specified.');\n assert(\n /^[A-Za-z0-9._-]+$/u.test(argument),\n `Invalid embedded extension ID: ${JSON.stringify(argument)}`,\n );\n extensionId = argument;\n }\n }\n }\n\n assert(sourceDirectory, `The extensions ${action} command requires SOURCE_DIR.`);\n assert(\n migrateToId === undefined || extensionId !== undefined,\n '--migrate-id requires an explicit existing EXTENSION_ID.',\n );\n assert(\n sourceArtifact === undefined || migrateToId !== undefined,\n '--artifact requires --migrate-id.',\n );\n assert(\n apiManifestArtifact === undefined || migrateToId !== undefined,\n '--api-manifest-artifact requires --migrate-id.',\n );\n assert(!allowBreakingApi || yes, '--allow-breaking-api requires --yes.');\n return {\n action,\n ...(allowBreakingApi ? {allowBreakingApi} : {}),\n ...(apiManifestArtifact ? {apiManifestArtifact} : {}),\n command: 'extensions',\n extensionId,\n migrateToId,\n sourceArtifact,\n sourceDirectory,\n yes,\n };\n}\n\nfunction parseExtensionIdMigrationArguments(arguments_: string[]): ExtensionsMigrateIdCliOptions {\n let fromId: string | undefined;\n let sourceDirectory: string | undefined;\n let toId: string | undefined;\n let yes = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--from') {\n fromId = takeValue(arguments_, index, '--from');\n index += 1;\n } else if (argument === '--to') {\n toId = takeValue(arguments_, index, '--to');\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');\n sourceDirectory = path.resolve(argument);\n }\n }\n assert(sourceDirectory, 'The extensions migrate-id command requires SOURCE_DIR.');\n assert(fromId, 'The extensions migrate-id command requires --from OLD_ID.');\n assert(toId, 'The extensions migrate-id command requires --to NEW_ID.');\n return {\n action: 'migrate-id',\n command: 'extensions',\n fromId,\n sourceDirectory,\n toId,\n yes,\n };\n}\n\nfunction parseExtensionBundleArguments(arguments_: string[]): ExtensionsBundleCliOptions {\n let bundleId: string | undefined;\n let bundleName: string | undefined;\n let metadata: ExtensionBundleMetadata | undefined;\n let recoveryCapsule = false;\n let sourceDirectory: string | undefined;\n const extensionIds: string[] = [];\n let yes = false;\n let buildMode: 'classic' | 'module' | undefined;\n const sharedDependencies: Record<string, string> = {};\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--id') {\n bundleId = takeValue(arguments_, index, '--id');\n index += 1;\n } else if (argument === '--name') {\n bundleName = takeValue(arguments_, index, '--name');\n index += 1;\n } else if (argument === '--metadata-json') {\n assert(metadata === undefined, '--metadata-json may only be specified once.');\n const value = takeValue(arguments_, index, '--metadata-json');\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n throw new Error('--metadata-json must contain a JSON object.');\n }\n metadata = validateExtensionBundleMetadata(parsed);\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else if (argument === '--include-recovery-capsule') {\n recoveryCapsule = true;\n } else if (argument === '--build-mode') {\n const value = takeValue(arguments_, index, '--build-mode');\n assert(value === 'classic' || value === 'module', '--build-mode must be classic or module.');\n buildMode = value;\n index += 1;\n } else if (argument === '--share') {\n const value = takeValue(arguments_, index, '--share');\n const separator = value.lastIndexOf('@');\n assert(separator > 0, '--share requires PACKAGE@EXACT_VERSION.');\n const name = value.slice(0, separator);\n assert(\n /^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*$/u.test(name),\n `Invalid shared dependency name: ${name}`,\n );\n assert(\n /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/u.test(value.slice(separator + 1)),\n '--share requires an exact semantic version.',\n );\n assert(!Object.hasOwn(sharedDependencies, name), `Duplicate shared dependency: ${name}`);\n sharedDependencies[name] = value.slice(separator + 1);\n index += 1;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n if (!sourceDirectory) {\n sourceDirectory = path.resolve(argument);\n } else {\n assert(\n /^[a-z0-9]+$/u.test(argument),\n `Bundle member ID must use TurboWarp's [a-z0-9]+ format: ${JSON.stringify(argument)}`,\n );\n extensionIds.push(argument);\n }\n }\n }\n assert(sourceDirectory, 'The extensions bundle command requires SOURCE_DIR.');\n assert(bundleId, 'The extensions bundle command requires --id BUNDLE_ID.');\n assert(bundleName, 'The extensions bundle command requires --name NAME.');\n assert(\n !Object.keys(sharedDependencies).length || buildMode === 'module',\n '--share requires --build-mode module.',\n );\n return {\n action: 'bundle',\n bundleId,\n bundleName,\n ...(metadata === undefined ? {} : {metadata}),\n command: 'extensions',\n extensionIds,\n recoveryCapsule,\n sourceDirectory,\n yes,\n ...(buildMode === undefined ? {} : {buildMode}),\n ...(Object.keys(sharedDependencies).length ? {sharedDependencies} : {}),\n };\n}\n\nfunction parseExtensionUnbundleArguments(\n arguments_: string[],\n): ExtensionsUnbundleSourceCliOptions | ExtensionsUnbundleArchiveCliOptions {\n let bundleId: string | undefined;\n let input: string | undefined;\n let outputPath: string | undefined;\n let yes = false;\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--yes') {\n yes = true;\n } else if (argument === '--output') {\n outputPath = path.resolve(takeValue(arguments_, index, '--output'));\n index += 1;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n if (!input) {\n input = path.resolve(argument);\n } else {\n assert(!bundleId, 'Only one BUNDLE_ID may be specified.');\n bundleId = argument;\n }\n }\n }\n assert(input, 'The extensions unbundle command requires SOURCE_DIR or INPUT.sb3.');\n assert(bundleId, 'The extensions unbundle command requires BUNDLE_ID.');\n if (path.extname(input).toLowerCase() === '.sb3') {\n assert(outputPath, 'SB3 unbundle requires --output OUTPUT.sb3.');\n return {\n action: 'unbundle',\n bundleId,\n command: 'extensions',\n inputPath: input,\n outputPath,\n yes,\n };\n }\n assert(!outputPath, '--output is only valid when unbundling an SB3 file.');\n return {\n action: 'unbundle',\n bundleId,\n command: 'extensions',\n sourceDirectory: input,\n yes,\n };\n}\n\nfunction parseExtensionDigestsArguments(arguments_: string[]): ExtensionsDigestsCliOptions {\n const inputPaths: string[] = [];\n let json = false;\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--json') {\n json = true;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n inputPaths.push(path.resolve(argument));\n }\n }\n assert(inputPaths.length > 0, 'The extensions digests command requires at least one INPUT.sb3.');\n return {action: 'digests', command: 'extensions', inputPaths, json};\n}\n\nfunction parseExtensionReplaceSb3Arguments(arguments_: string[]): ExtensionsReplaceSb3CliOptions {\n let fromPath: string | undefined;\n let inputPath: string | undefined;\n let outputPath: string | undefined;\n let yes = false;\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--from') {\n assert(!fromPath, '--from may only be specified once.');\n fromPath = path.resolve(takeValue(arguments_, index, '--from'));\n index += 1;\n } else if (argument === '--output') {\n assert(!outputPath, '--output may only be specified once.');\n outputPath = path.resolve(takeValue(arguments_, index, '--output'));\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!inputPath, 'Only one input SB3 may be specified.');\n inputPath = path.resolve(argument);\n }\n }\n assert(inputPath, 'The extensions replace-sb3 command requires INPUT.sb3.');\n assert(outputPath, 'The extensions replace-sb3 command requires --output OUTPUT.sb3.');\n return {action: 'replace-sb3', command: 'extensions', fromPath, inputPath, outputPath, yes};\n}\n\nfunction parseExtensionsArguments(arguments_: string[]): ExtensionsCliOptions {\n const [action, ...actionArguments] = arguments_;\n assert(\n action === 'digests' ||\n action === 'replace-sb3' ||\n action === 'bundle' ||\n action === 'migrate-id' ||\n action === 'status' ||\n action === 'sync' ||\n action === 'unbundle' ||\n action === 'update',\n 'The extensions command requires status, digests, sync, update, migrate-id, bundle, unbundle, or replace-sb3.',\n );\n if (action === 'digests') return parseExtensionDigestsArguments(actionArguments);\n if (action === 'replace-sb3') return parseExtensionReplaceSb3Arguments(actionArguments);\n if (action === 'status') {\n assert(\n actionArguments.length === 1 && !actionArguments[0].startsWith('-'),\n 'The extensions status command requires exactly one SOURCE_DIR.',\n );\n return {\n action,\n command: 'extensions',\n sourceDirectory: path.resolve(actionArguments[0]),\n };\n }\n if (action === 'migrate-id') {\n return parseExtensionIdMigrationArguments(actionArguments);\n }\n if (action === 'bundle') {\n return parseExtensionBundleArguments(actionArguments);\n }\n if (action === 'unbundle') {\n return parseExtensionUnbundleArguments(actionArguments);\n }\n return parseExtensionMutationArguments(action, actionArguments);\n}\n\nexport function parseCliArguments(arguments_: string[]): CliOptions {\n const normalized = arguments_.filter((argument) => argument !== '--');\n if (normalized.length === 0 || normalized[0] === '--help' || normalized[0] === '-h') {\n return {command: 'help'};\n }\n if (normalized[0] === '--version' || normalized[0] === '-v') {\n return {command: 'version'};\n }\n\n const [command, ...commandArguments] = normalized;\n if (commandArguments.includes('--help') || commandArguments.includes('-h')) {\n return {command: 'help'};\n }\n if (command === 'import') return parseImportArguments(commandArguments);\n if (command === 'check') return parseCheckArguments(commandArguments);\n if (command === 'build') return parseBuildArguments(commandArguments);\n if (command === 'clean-up') return parseCleanUpArguments(commandArguments);\n if (command === 'extensions') return parseExtensionsArguments(commandArguments);\n throw new Error(`Unknown command: ${command}`);\n}\n\nfunction formatDifferenceLines(differences: DirectoryDifferences): string {\n const labels: Record<string, string> = {added: '+', modified: '~', removed: '-'};\n const lines = Object.entries(differences).flatMap(([kind, paths]) =>\n paths.map((relativePath: string) => `${labels[kind]} ${relativePath}`),\n );\n const visibleLines = lines.slice(0, 12);\n if (lines.length > visibleLines.length) {\n visibleLines.push(`... and ${lines.length - visibleLines.length} more`);\n }\n return visibleLines.join('\\n');\n}\n\nasync function confirmImportReplacement(context: OutputReplacementContext): Promise<boolean> {\n const {comparison, discardLocalChanges, gitState, outputDirectory} = context;\n assert(\n process.stdin.isTTY && process.stdout.isTTY,\n `Output directory already exists: ${outputDirectory}. ` +\n 'Non-interactive replacement requires --yes.',\n );\n const readline = createInterface({input: process.stdin, output: process.stdout});\n try {\n const gitMessage = gitState.clean\n ? 'Git state: clean'\n : 'Git state: uncommitted changes will be discarded';\n const answer = await readline.question(\n `Existing SB3 source differs from the import candidate:\\n` +\n ` ${outputDirectory}\\n` +\n `${formatDifferenceLines(comparison.differences)}\\n` +\n `${gitMessage}\\n` +\n `${discardLocalChanges ? 'WARNING: --discard-local-changes is active.\\n' : ''}` +\n 'Replace the existing source directory? [y/N] ',\n );\n return /^(?:y|yes)$/iu.test(answer.trim());\n } finally {\n readline.close();\n }\n}\n\nasync function confirmBuildReplacement(outputPath: string): Promise<boolean> {\n assert(\n process.stdin.isTTY && process.stdout.isTTY,\n `Existing SB3 output differs: ${outputPath}. Non-interactive replacement requires --yes.`,\n );\n const readline = createInterface({input: process.stdin, output: process.stdout});\n try {\n const answer = await readline.question(\n `Existing generated SB3 will be replaced:\\n ${outputPath}\\nContinue? [y/N] `,\n );\n return /^(?:y|yes)$/iu.test(answer.trim());\n } finally {\n readline.close();\n }\n}\n\nasync function confirmExtensionReplacement({\n comparison,\n sourceDirectory,\n}: ExtensionSyncConfirmContext): Promise<boolean> {\n assert(\n process.stdin.isTTY && process.stdout.isTTY,\n `Managed extension files differ in ${sourceDirectory}. ` +\n 'Non-interactive replacement requires --yes.',\n );\n const readline = createInterface({input: process.stdin, output: process.stdout});\n try {\n const answer = await readline.question(\n `Managed extension changes will be installed:\\n` +\n ` ${sourceDirectory}\\n` +\n `${formatDifferenceLines(comparison.differences)}\\n` +\n 'Replace these files? [y/N] ',\n );\n return /^(?:y|yes)$/iu.test(answer.trim());\n } finally {\n readline.close();\n }\n}\n\nfunction logMigrationResult(result: MigrationLogResult, log: (message: string) => void): void {\n const counts = Object.entries(result.counts)\n .filter(([, count]) => count > 0)\n .map(([kind, count]) => `${kind}=${count}`)\n .join(', ');\n const action = result.applied ? 'Migrated' : 'Dry run';\n log(\n `${action}: ${result.fromId} -> ${result.toId}; ` +\n `${result.totalChanges} classified changes (${counts || 'none'}); ` +\n `artifact=${result.artifactReady ? 'ready' : 'requires-new-ID'}.`,\n );\n for (const reference of result.unclassifiedReferences) {\n log(\n `Unclassified ${reference.kind}: ${reference.file}${reference.path} = ` +\n JSON.stringify(reference.value),\n );\n }\n}\n\nexport async function runCli(\n arguments_: string[],\n {fetch: fetchImplementation = globalThis.fetch, log = console.log}: RunCliOptions = {},\n): Promise<void> {\n const options = parseCliArguments(arguments_);\n if (options.command === 'help') {\n log(usage());\n return;\n }\n if (options.command === 'version') {\n log(packageVersion);\n return;\n }\n if (options.command === 'check') {\n assert(\n 'sourceDirectory' in options && !('action' in options),\n 'Internal CLI check command routing error.',\n );\n if (options.projectAssetsPath) {\n const result = await createDeterministicSb3(options.sourceDirectory, {\n allowedAssetRoots: options.allowedAssetRoots,\n projectAssetsPath: options.projectAssetsPath,\n });\n log(\n `Valid SB3 source with project assets: ${result.source.resolvedSourceDirectory} ` +\n `(${result.entryCount} entries, ${result.assetCount} assets, ` +\n `${result.assetReferenceCount} references, ${result.embeddedExtensionCount} embedded extensions).`,\n );\n return;\n }\n const result = await validateSb3Source(options.sourceDirectory);\n log(\n `Valid SB3 source: ${result.resolvedSourceDirectory} ` +\n `(${result.sourceManifest.archiveEntries.length} entries, ` +\n `${result.assetContents.size} assets, ${result.assetReferenceCount} references, ` +\n `${result.extensions.length} embedded extensions).`,\n );\n return;\n }\n if (\n options.command === 'build' &&\n 'outputPath' in options &&\n 'sourceDirectory' in options &&\n !('action' in options)\n ) {\n const result = await buildSb3({\n allowedAssetRoots: options.allowedAssetRoots,\n cleanUpBlocks: options.cleanUpBlocks,\n confirmReplace: confirmBuildReplacement,\n outputPath: options.outputPath,\n projectAssetsPath: options.projectAssetsPath,\n sourceDirectory: options.sourceDirectory,\n yes: options.yes,\n });\n const action = result.changed ? 'Built' : 'Already up to date';\n const cleanUpMessage = result.blockCleanUp\n ? `, ${result.blockCleanUp.movedScriptCount}/${result.blockCleanUp.scriptCount} scripts laid out`\n : '';\n log(\n `${action}: ${result.outputPath} (${result.entryCount} entries, ` +\n `${result.assetCount} assets, ${result.embeddedExtensionCount} embedded extensions` +\n `${cleanUpMessage}).`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.command === 'clean-up') {\n const result = await cleanUpSb3({\n ...options,\n confirmReplace: confirmBuildReplacement,\n });\n log(\n `${result.changed ? 'Wrote' : 'Already up to date'}: ${result.outputPath} ` +\n `(${result.movedScriptCount}/${result.scriptCount} scripts moved across ${result.targetCount} targets).`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.command === 'extensions') {\n if (options.action === 'digests') {\n const inventory = await inventoryExtensionDigests(options.inputPaths);\n if (options.json) {\n log(`${JSON.stringify(inventory, null, 2)}`);\n return;\n }\n for (const line of formatExtensionDigestInventory(inventory)) log(line);\n return;\n }\n if (options.action === 'replace-sb3') {\n const result = await replaceSb3Extensions({\n confirmReplace: confirmBuildReplacement,\n fetch: fetchImplementation,\n fromPath: options.fromPath,\n inputPath: options.inputPath,\n outputPath: options.outputPath,\n yes: options.yes,\n });\n log(\n `${result.changed ? 'Wrote' : 'Already up to date'}: ${result.outputPath} (${result.extensionIds.join(', ')}).`,\n );\n log(\n `Donor: ${result.donor.source}; version=${result.donor.version ?? 'unknown'}; sha256=${result.donor.sha256}`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.action === 'bundle') {\n const result = await bundleExtensions({\n bundleId: options.bundleId,\n bundleName: options.bundleName,\n metadata: options.metadata,\n extensionIds: options.extensionIds,\n recoveryCapsule: options.recoveryCapsule,\n buildMode: options.buildMode,\n sharedDependencies: options.sharedDependencies,\n sourceDirectory: options.sourceDirectory,\n yes: options.yes,\n });\n log(\n `${result.applied ? 'Configured' : 'Dry run'} extension bundle: ${result.bundleId} ` +\n `(${result.members.join(', ')}).`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.action === 'unbundle') {\n if ('inputPath' in options) {\n const result = await unbundleSb3({\n bundleId: options.bundleId,\n inputPath: options.inputPath,\n outputPath: options.outputPath,\n yes: options.yes,\n });\n log(\n `${result.applied ? 'Wrote' : 'Dry run'} unbundled SB3: ${result.bundleId} ` +\n `(${result.members.join(', ')}) -> ${result.outputPath}.`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n const result = await unbundleExtensions({\n bundleId: options.bundleId,\n sourceDirectory: options.sourceDirectory,\n yes: options.yes,\n });\n log(\n `${result.applied ? 'Removed' : 'Dry run'} extension bundle: ${result.bundleId} ` +\n `(${result.members.join(', ')}).`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.action === 'migrate-id') {\n const result = await migrateExtensionId({\n fromId: options.fromId,\n sourceDirectory: options.sourceDirectory,\n toId: options.toId,\n yes: options.yes,\n });\n logMigrationResult(result, log);\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.action === 'status') {\n const statuses = await extensionStatus(options.sourceDirectory, {\n fetch: fetchImplementation,\n });\n if (statuses.length === 0) {\n log(`No managed embedded extensions: ${options.sourceDirectory}`);\n return;\n }\n for (const status of statuses) {\n if ('package' in status) {\n log(\n `${status.id}: ${status.state}; local=${status.local}; ` +\n `${status.package}@${status.version} (installed ${status.installedVersion})`,\n );\n continue;\n }\n log(\n `${status.id}: ${status.state}; local=${status.local}; ` +\n `${status.ref} -> ${status.remoteCommit} ` +\n `(installed ${status.resolvedCommit})`,\n );\n }\n return;\n }\n\n const operationOptions = {\n confirmReplace: confirmExtensionReplacement,\n fetch: fetchImplementation,\n sourceDirectory: options.sourceDirectory,\n yes: options.yes,\n };\n const result =\n options.action === 'sync'\n ? await syncExtensions(operationOptions)\n : await updateExtensions({\n ...operationOptions,\n allowBreakingApi: options.allowBreakingApi,\n apiManifestArtifact: options.apiManifestArtifact,\n extensionId: options.extensionId,\n migrateToId: options.migrateToId,\n sourceArtifact: options.sourceArtifact,\n });\n const action = result.changed ? 'Updated' : 'Already up to date';\n log(\n `${action}: ${result.sourceDirectory} ` +\n `(${result.extensions.map((extension) => extension.id).join(', ')}).`,\n );\n if (result.migration) {\n logMigrationResult(\n {\n applied: result.changed,\n artifactReady: true,\n ...result.migration,\n },\n log,\n );\n }\n for (const compatibility of result.apiCompatibility) {\n for (const change of compatibility.changes) {\n log(\n `API ${compatibility.id}: ${change.breaking ? 'breaking' : 'compatible'} ` +\n `${change.kind} ${change.path}`,\n );\n }\n }\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n\n assert(\n options.command === 'import' && 'inputPath' in options,\n 'Internal CLI command routing error.',\n );\n const result = await importSb3({\n confirmReplace: confirmImportReplacement,\n discardLocalChanges: options.discardLocalChanges,\n inputPath: options.inputPath,\n outputDirectory: options.outputDirectory,\n yes: options.yes,\n });\n if (result.changed) {\n const differenceMessage = result.differenceCounts\n ? ` Changes: +${result.differenceCounts.added} ` +\n `~${result.differenceCounts.modified} -${result.differenceCounts.removed}.`\n : '';\n log(\n `Imported ${result.archiveEntryCount} SB3 entries into ${result.outputDirectory} ` +\n `(${result.assetCount} assets, ${result.embeddedExtensionCount} embedded extensions).` +\n differenceMessage,\n );\n } else {\n log(`Already up to date; no files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ACZ,GACA,GACF;EAEF,KAAK,MAAM,iBAAiB,OAAO,kBACjC,KAAK,MAAM,UAAU,cAAc,SACjC,IACE,OAAO,cAAc,GAAG,IAAI,OAAO,WAAW,aAAa,aAAa,GACnE,OAAO,KAAK,GAAG,OAAO,MAC7B;EAGJ,IAAI,OAAO,wBAAwB,IAAI,OAAO,sBAAsB;EACpE;CACF;CAEA,OACE,QAAQ,YAAY,YAAY,eAAe,SAC/C,qCACF;CACA,MAAM,SAAS,MAAM,UAAU;EAC7B,gBAAgB;EAChB,qBAAqB,QAAQ;EAC7B,WAAW,QAAQ;EACnB,iBAAiB,QAAQ;EACzB,KAAK,QAAQ;CACf,CAAC;CACD,IAAI,OAAO,SAAS;EAClB,MAAM,oBAAoB,OAAO,mBAC7B,cAAc,OAAO,iBAAiB,MAAM,IACxC,OAAO,iBAAiB,SAAS,IAAI,OAAO,iBAAiB,QAAQ,KACzE;EACJ,IACE,YAAY,OAAO,kBAAkB,oBAAoB,OAAO,gBAAgB,IAC1E,OAAO,WAAW,WAAW,OAAO,uBAAuB,0BAC/D,iBACJ;CACF,OACE,IAAI,yCAAyC,OAAO,iBAAiB;CAEvE,IAAI,OAAO,wBAAwB,IAAI,OAAO,sBAAsB;AACtE"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport path from 'node:path';\nimport process from 'node:process';\nimport {createInterface} from 'node:readline/promises';\n\nimport {assert} from './assert';\nimport {buildSb3} from './build';\nimport {cleanUpSb3} from './clean-up-sb3';\nimport {packageVersion} from './constants';\nimport {unbundleSb3} from './extension-bundle-archive';\nimport {bundleExtensions, unbundleExtensions} from './extension-bundle-configuration';\nimport {validateExtensionBundleMetadata} from './extension-bundle-metadata';\nimport {\n formatExtensionDigestInventory,\n inventoryExtensionDigests,\n} from './extension-digest-inventory';\nimport type {ExtensionBundleMetadata} from './types';\nimport {migrateExtensionId} from './extension-id-migration';\nimport {replaceSb3Extensions} from './extension-sb3-replacement';\nimport type {ExtensionIdMigrationCounts, ExtensionIdReference} from './extension-id-migration';\nimport {extensionStatus, syncExtensions, updateExtensions} from './extension-sync';\nimport type {ExtensionSyncConfirmContext, FetchImplementation} from './extension-sync';\nimport {importSb3} from './import';\nimport type {OutputReplacementContext} from './import';\nimport type {DirectoryDifferences} from './output-safety';\nimport {createDeterministicSb3, validateSb3Source} from './source';\n\nexport interface HelpCliOptions {\n command: 'help';\n}\n\nexport interface VersionCliOptions {\n command: 'version';\n}\n\nexport interface ImportCliOptions {\n command: 'import';\n discardLocalChanges: boolean;\n inputPath: string;\n outputDirectory: string;\n yes: boolean;\n}\n\nexport interface CheckCliOptions {\n allowedAssetRoots?: string[];\n command: 'check';\n projectAssetsPath?: string;\n sourceDirectory: string;\n}\n\nexport interface BuildCliOptions {\n allowedAssetRoots?: string[];\n cleanUpBlocks?: boolean;\n command: 'build';\n outputPath: string;\n projectAssetsPath?: string;\n sourceDirectory: string;\n yes: boolean;\n}\n\nexport interface CleanUpCliOptions {\n command: 'clean-up';\n inputPath: string;\n outputPath: string;\n yes: boolean;\n}\n\nexport interface ExtensionsStatusCliOptions {\n action: 'status';\n command: 'extensions';\n sourceDirectory: string;\n}\n\nexport interface ExtensionsMutationCliOptions {\n action: 'sync' | 'update';\n allowBreakingApi?: boolean;\n apiManifestArtifact?: string;\n command: 'extensions';\n extensionId?: string;\n migrateToId?: string;\n sourceArtifact?: string;\n sourceDirectory: string;\n yes: boolean;\n}\n\nexport interface ExtensionsMigrateIdCliOptions {\n action: 'migrate-id';\n command: 'extensions';\n fromId: string;\n sourceDirectory: string;\n toId: string;\n yes: boolean;\n}\n\nexport interface ExtensionsBundleCliOptions {\n action: 'bundle';\n bundleId: string;\n bundleName: string;\n metadata?: ExtensionBundleMetadata;\n command: 'extensions';\n extensionIds: string[];\n recoveryCapsule: boolean;\n sourceDirectory: string;\n yes: boolean;\n buildMode?: 'classic' | 'module';\n sharedDependencies?: Record<string, string>;\n}\n\nexport interface ExtensionsUnbundleSourceCliOptions {\n action: 'unbundle';\n bundleId: string;\n command: 'extensions';\n sourceDirectory: string;\n yes: boolean;\n}\n\nexport interface ExtensionsUnbundleArchiveCliOptions {\n action: 'unbundle';\n bundleId: string;\n command: 'extensions';\n inputPath: string;\n outputPath: string;\n yes: boolean;\n}\n\nexport interface ExtensionsDigestsCliOptions {\n action: 'digests';\n command: 'extensions';\n inputPaths: string[];\n json: boolean;\n}\n\nexport interface ExtensionsReplaceSb3CliOptions {\n action: 'replace-sb3';\n command: 'extensions';\n fromPath?: string;\n inputPath: string;\n outputPath: string;\n yes: boolean;\n}\n\nexport type ExtensionsCliOptions =\n | ExtensionsDigestsCliOptions\n | ExtensionsReplaceSb3CliOptions\n | ExtensionsStatusCliOptions\n | ExtensionsMutationCliOptions\n | ExtensionsMigrateIdCliOptions\n | ExtensionsBundleCliOptions\n | ExtensionsUnbundleSourceCliOptions\n | ExtensionsUnbundleArchiveCliOptions;\n\nexport type CliOptions =\n | HelpCliOptions\n | VersionCliOptions\n | ImportCliOptions\n | CheckCliOptions\n | BuildCliOptions\n | CleanUpCliOptions\n | ExtensionsCliOptions;\n\nexport interface RunCliOptions {\n fetch?: FetchImplementation;\n log?: (message: string) => void;\n}\n\ninterface MigrationLogResult {\n applied: boolean;\n artifactReady: boolean;\n counts: ExtensionIdMigrationCounts;\n fromId: string | undefined;\n toId: string | undefined;\n totalChanges: number;\n unclassifiedReferences: ExtensionIdReference[];\n}\n\nexport function usage() {\n return `Usage:\n sb3-toolchain import INPUT.sb3 --output SOURCE_DIR [--yes] [--discard-local-changes]\n sb3-toolchain check SOURCE_DIR [--project-assets MANIFEST.json] [--allow-asset-root DIR ...]\n sb3-toolchain build SOURCE_DIR --output OUTPUT.sb3 [--project-assets MANIFEST.json] [--allow-asset-root DIR ...] [--clean-up-blocks] [--yes]\n sb3-toolchain clean-up INPUT.sb3 --output OUTPUT.sb3 [--yes]\n sb3-toolchain extensions digests INPUT.sb3 [INPUT.sb3 ...] [--json]\n sb3-toolchain extensions replace-sb3 INPUT.sb3 [--from DONOR.sb3] --output OUTPUT.sb3 [--yes]\n sb3-toolchain extensions status SOURCE_DIR\n sb3-toolchain extensions sync SOURCE_DIR [--yes]\n sb3-toolchain extensions update SOURCE_DIR [EXTENSION_ID] [--migrate-id NEW_ID] [--artifact PATH] [--api-manifest-artifact PATH] [--allow-breaking-api --yes]\n sb3-toolchain extensions migrate-id SOURCE_DIR --from OLD_ID --to NEW_ID [--yes]\n sb3-toolchain extensions bundle SOURCE_DIR --id BUNDLE_ID --name NAME [EXTENSION_ID ...] [--metadata-json JSON] [--build-mode classic|module] [--share PACKAGE@EXACT_VERSION] [--include-recovery-capsule] [--yes]\n sb3-toolchain extensions unbundle SOURCE_DIR BUNDLE_ID [--yes]\n sb3-toolchain extensions unbundle INPUT.sb3 BUNDLE_ID --output OUTPUT.sb3 [--yes]\n\nCommands:\n import Expand an SB3 into Git-friendly source files.\n check Validate an expanded SB3 source directory.\n build Build a deterministic SB3 from expanded sources.\n clean-up Arrange scripts in a more compact layout and write a separate SB3.\n extensions Inspect, restore, or update managed embedded extensions.\n\nBuild layout cleanup:\n --clean-up-blocks applies a deterministic TurboWarp-style \"Clean up Blocks\"\n layout to every target in the generated SB3. It never deletes blocks,\n variables, lists, or comments. The expanded source is unchanged, but the\n generated SB3 might not be able to undo the coordinate changes.\n\nProject asset additions:\n --project-assets validates a JSON or YAML manifest and adds its sprites,\n backdrops, costumes, and sounds only to the generated SB3. Input files are confined to the\n manifest directory unless --allow-asset-root explicitly permits another root.\n\nExtension digests:\n extensions digests reads each SB3's own manifest and reports every extension's ID,\n pinned SHA-256, source form (remote-non-cacheable, remote-cacheable, embedded-file,\n embedded-data), held byte size, and the project URI that names the cache bucket. Given\n several SB3s it also reports which digests more than one project names. Nothing is\n fetched and no browser storage is read: an extension cache belongs to an origin and a\n browser profile, so only the browser can list it, and an unresolved project URI never\n means an absent project.\n\nKamishibai SB3 replacement:\n extensions replace-sb3 replaces the runtime bundle and Block Script in INPUT.sb3.\n Omitting --from downloads the published block SB3 from the official samples site\n and verifies its size and SHA-256. --from uses a local donor without network access.\n The input is preserved; output must use a different path. Story data is not migrated.\n\nReplacement safety:\n Differing outputs require interactive confirmation or --yes.\n Import refuses to discard uncommitted Git changes unless\n --discard-local-changes is also specified. --force is not supported.`;\n}\n\nfunction takeValue(arguments_: string[], index: number, option: string): string {\n const value = arguments_[index + 1];\n assert(value && !value.startsWith('-'), `${option} requires a value.`);\n return value;\n}\n\nfunction parseImportArguments(arguments_: string[]): ImportCliOptions {\n let inputPath: string | undefined;\n let outputDirectory: string | undefined;\n let discardLocalChanges = false;\n let yes = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--output') {\n outputDirectory = path.resolve(takeValue(arguments_, index, '--output'));\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else if (argument === '--discard-local-changes') {\n discardLocalChanges = true;\n } else {\n assert(\n argument !== '--force',\n '--force is intentionally unsupported. Use --yes and, only when necessary, ' +\n '--discard-local-changes.',\n );\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!inputPath, 'Only one input SB3 may be specified.');\n inputPath = path.resolve(argument);\n }\n }\n\n assert(inputPath, 'The import command requires INPUT.sb3.');\n assert(outputDirectory, 'The import command requires --output SOURCE_DIR.');\n return {command: 'import', discardLocalChanges, inputPath, outputDirectory, yes};\n}\n\nfunction parseCleanUpArguments(arguments_: string[]): CleanUpCliOptions {\n let inputPath: string | undefined;\n let outputPath: string | undefined;\n let yes = false;\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--output') {\n assert(!outputPath, '--output may only be specified once.');\n outputPath = path.resolve(takeValue(arguments_, index, '--output'));\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!inputPath, 'Only one input SB3 may be specified.');\n inputPath = path.resolve(argument);\n }\n }\n assert(inputPath, 'The clean-up command requires INPUT.sb3.');\n assert(outputPath, 'The clean-up command requires --output OUTPUT.sb3.');\n return {command: 'clean-up', inputPath, outputPath, yes};\n}\n\nfunction parseCheckArguments(arguments_: string[]): CheckCliOptions {\n const allowedAssetRoots: string[] = [];\n let projectAssetsPath: string | undefined;\n let sourceDirectory: string | undefined;\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--project-assets') {\n projectAssetsPath = path.resolve(takeValue(arguments_, index, '--project-assets'));\n index += 1;\n } else if (argument === '--allow-asset-root') {\n allowedAssetRoots.push(path.resolve(takeValue(arguments_, index, '--allow-asset-root')));\n index += 1;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');\n sourceDirectory = path.resolve(argument);\n }\n }\n assert(sourceDirectory, 'The check command requires SOURCE_DIR.');\n assert(\n allowedAssetRoots.length === 0 || projectAssetsPath,\n '--allow-asset-root requires --project-assets.',\n );\n return {\n ...(allowedAssetRoots.length > 0 ? {allowedAssetRoots} : {}),\n command: 'check',\n ...(projectAssetsPath ? {projectAssetsPath} : {}),\n sourceDirectory,\n };\n}\n\nfunction parseBuildArguments(arguments_: string[]): BuildCliOptions {\n const allowedAssetRoots: string[] = [];\n let cleanUpBlocks = false;\n let sourceDirectory: string | undefined;\n let outputPath: string | undefined;\n let projectAssetsPath: string | undefined;\n let yes = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--clean-up-blocks') {\n cleanUpBlocks = true;\n } else if (argument === '--project-assets') {\n projectAssetsPath = path.resolve(takeValue(arguments_, index, '--project-assets'));\n index += 1;\n } else if (argument === '--allow-asset-root') {\n allowedAssetRoots.push(path.resolve(takeValue(arguments_, index, '--allow-asset-root')));\n index += 1;\n } else if (argument === '--output') {\n outputPath = path.resolve(takeValue(arguments_, index, '--output'));\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');\n sourceDirectory = path.resolve(argument);\n }\n }\n\n assert(sourceDirectory, 'The build command requires SOURCE_DIR.');\n assert(outputPath, 'The build command requires --output OUTPUT.sb3.');\n assert(\n allowedAssetRoots.length === 0 || projectAssetsPath,\n '--allow-asset-root requires --project-assets.',\n );\n return {\n ...(allowedAssetRoots.length > 0 ? {allowedAssetRoots} : {}),\n ...(cleanUpBlocks ? {cleanUpBlocks} : {}),\n command: 'build',\n outputPath,\n ...(projectAssetsPath ? {projectAssetsPath} : {}),\n sourceDirectory,\n yes,\n };\n}\n\nfunction parseExtensionMutationArguments(\n action: 'sync' | 'update',\n arguments_: string[],\n): ExtensionsMutationCliOptions {\n let allowBreakingApi = false;\n let apiManifestArtifact: string | undefined;\n let sourceDirectory: string | undefined;\n let extensionId: string | undefined;\n let migrateToId: string | undefined;\n let sourceArtifact: string | undefined;\n let yes = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--yes') {\n yes = true;\n } else if (argument === '--allow-breaking-api') {\n assert(action === 'update', '--allow-breaking-api is only valid for extensions update.');\n allowBreakingApi = true;\n } else if (argument === '--migrate-id') {\n assert(action === 'update', '--migrate-id is only valid for extensions update.');\n migrateToId = takeValue(arguments_, index, '--migrate-id');\n index += 1;\n } else if (argument === '--artifact') {\n assert(action === 'update', '--artifact is only valid for extensions update.');\n sourceArtifact = takeValue(arguments_, index, '--artifact');\n index += 1;\n } else if (argument === '--api-manifest-artifact') {\n assert(action === 'update', '--api-manifest-artifact is only valid for extensions update.');\n apiManifestArtifact = takeValue(arguments_, index, '--api-manifest-artifact');\n index += 1;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n if (!sourceDirectory) {\n sourceDirectory = path.resolve(argument);\n } else {\n assert(action === 'update', `The extensions ${action} command accepts only SOURCE_DIR.`);\n assert(!extensionId, 'Only one EXTENSION_ID may be specified.');\n assert(\n /^[A-Za-z0-9._-]+$/u.test(argument),\n `Invalid embedded extension ID: ${JSON.stringify(argument)}`,\n );\n extensionId = argument;\n }\n }\n }\n\n assert(sourceDirectory, `The extensions ${action} command requires SOURCE_DIR.`);\n assert(\n migrateToId === undefined || extensionId !== undefined,\n '--migrate-id requires an explicit existing EXTENSION_ID.',\n );\n assert(\n sourceArtifact === undefined || migrateToId !== undefined,\n '--artifact requires --migrate-id.',\n );\n assert(\n apiManifestArtifact === undefined || migrateToId !== undefined,\n '--api-manifest-artifact requires --migrate-id.',\n );\n assert(!allowBreakingApi || yes, '--allow-breaking-api requires --yes.');\n return {\n action,\n ...(allowBreakingApi ? {allowBreakingApi} : {}),\n ...(apiManifestArtifact ? {apiManifestArtifact} : {}),\n command: 'extensions',\n extensionId,\n migrateToId,\n sourceArtifact,\n sourceDirectory,\n yes,\n };\n}\n\nfunction parseExtensionIdMigrationArguments(arguments_: string[]): ExtensionsMigrateIdCliOptions {\n let fromId: string | undefined;\n let sourceDirectory: string | undefined;\n let toId: string | undefined;\n let yes = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--from') {\n fromId = takeValue(arguments_, index, '--from');\n index += 1;\n } else if (argument === '--to') {\n toId = takeValue(arguments_, index, '--to');\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');\n sourceDirectory = path.resolve(argument);\n }\n }\n assert(sourceDirectory, 'The extensions migrate-id command requires SOURCE_DIR.');\n assert(fromId, 'The extensions migrate-id command requires --from OLD_ID.');\n assert(toId, 'The extensions migrate-id command requires --to NEW_ID.');\n return {\n action: 'migrate-id',\n command: 'extensions',\n fromId,\n sourceDirectory,\n toId,\n yes,\n };\n}\n\nfunction parseExtensionBundleArguments(arguments_: string[]): ExtensionsBundleCliOptions {\n let bundleId: string | undefined;\n let bundleName: string | undefined;\n let metadata: ExtensionBundleMetadata | undefined;\n let recoveryCapsule = false;\n let sourceDirectory: string | undefined;\n const extensionIds: string[] = [];\n let yes = false;\n let buildMode: 'classic' | 'module' | undefined;\n const sharedDependencies: Record<string, string> = {};\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--id') {\n bundleId = takeValue(arguments_, index, '--id');\n index += 1;\n } else if (argument === '--name') {\n bundleName = takeValue(arguments_, index, '--name');\n index += 1;\n } else if (argument === '--metadata-json') {\n assert(metadata === undefined, '--metadata-json may only be specified once.');\n const value = takeValue(arguments_, index, '--metadata-json');\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n throw new Error('--metadata-json must contain a JSON object.');\n }\n metadata = validateExtensionBundleMetadata(parsed);\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else if (argument === '--include-recovery-capsule') {\n recoveryCapsule = true;\n } else if (argument === '--build-mode') {\n const value = takeValue(arguments_, index, '--build-mode');\n assert(value === 'classic' || value === 'module', '--build-mode must be classic or module.');\n buildMode = value;\n index += 1;\n } else if (argument === '--share') {\n const value = takeValue(arguments_, index, '--share');\n const separator = value.lastIndexOf('@');\n assert(separator > 0, '--share requires PACKAGE@EXACT_VERSION.');\n const name = value.slice(0, separator);\n assert(\n /^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*$/u.test(name),\n `Invalid shared dependency name: ${name}`,\n );\n assert(\n /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/u.test(value.slice(separator + 1)),\n '--share requires an exact semantic version.',\n );\n assert(!Object.hasOwn(sharedDependencies, name), `Duplicate shared dependency: ${name}`);\n sharedDependencies[name] = value.slice(separator + 1);\n index += 1;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n if (!sourceDirectory) {\n sourceDirectory = path.resolve(argument);\n } else {\n assert(\n /^[a-z0-9]+$/u.test(argument),\n `Bundle member ID must use TurboWarp's [a-z0-9]+ format: ${JSON.stringify(argument)}`,\n );\n extensionIds.push(argument);\n }\n }\n }\n assert(sourceDirectory, 'The extensions bundle command requires SOURCE_DIR.');\n assert(bundleId, 'The extensions bundle command requires --id BUNDLE_ID.');\n assert(bundleName, 'The extensions bundle command requires --name NAME.');\n assert(\n !Object.keys(sharedDependencies).length || buildMode === 'module',\n '--share requires --build-mode module.',\n );\n return {\n action: 'bundle',\n bundleId,\n bundleName,\n ...(metadata === undefined ? {} : {metadata}),\n command: 'extensions',\n extensionIds,\n recoveryCapsule,\n sourceDirectory,\n yes,\n ...(buildMode === undefined ? {} : {buildMode}),\n ...(Object.keys(sharedDependencies).length ? {sharedDependencies} : {}),\n };\n}\n\nfunction parseExtensionUnbundleArguments(\n arguments_: string[],\n): ExtensionsUnbundleSourceCliOptions | ExtensionsUnbundleArchiveCliOptions {\n let bundleId: string | undefined;\n let input: string | undefined;\n let outputPath: string | undefined;\n let yes = false;\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--yes') {\n yes = true;\n } else if (argument === '--output') {\n outputPath = path.resolve(takeValue(arguments_, index, '--output'));\n index += 1;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n if (!input) {\n input = path.resolve(argument);\n } else {\n assert(!bundleId, 'Only one BUNDLE_ID may be specified.');\n bundleId = argument;\n }\n }\n }\n assert(input, 'The extensions unbundle command requires SOURCE_DIR or INPUT.sb3.');\n assert(bundleId, 'The extensions unbundle command requires BUNDLE_ID.');\n if (path.extname(input).toLowerCase() === '.sb3') {\n assert(outputPath, 'SB3 unbundle requires --output OUTPUT.sb3.');\n return {\n action: 'unbundle',\n bundleId,\n command: 'extensions',\n inputPath: input,\n outputPath,\n yes,\n };\n }\n assert(!outputPath, '--output is only valid when unbundling an SB3 file.');\n return {\n action: 'unbundle',\n bundleId,\n command: 'extensions',\n sourceDirectory: input,\n yes,\n };\n}\n\nfunction parseExtensionDigestsArguments(arguments_: string[]): ExtensionsDigestsCliOptions {\n const inputPaths: string[] = [];\n let json = false;\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--json') {\n json = true;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n inputPaths.push(path.resolve(argument));\n }\n }\n assert(inputPaths.length > 0, 'The extensions digests command requires at least one INPUT.sb3.');\n return {action: 'digests', command: 'extensions', inputPaths, json};\n}\n\nfunction parseExtensionReplaceSb3Arguments(arguments_: string[]): ExtensionsReplaceSb3CliOptions {\n let fromPath: string | undefined;\n let inputPath: string | undefined;\n let outputPath: string | undefined;\n let yes = false;\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--from') {\n assert(!fromPath, '--from may only be specified once.');\n fromPath = path.resolve(takeValue(arguments_, index, '--from'));\n index += 1;\n } else if (argument === '--output') {\n assert(!outputPath, '--output may only be specified once.');\n outputPath = path.resolve(takeValue(arguments_, index, '--output'));\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!inputPath, 'Only one input SB3 may be specified.');\n inputPath = path.resolve(argument);\n }\n }\n assert(inputPath, 'The extensions replace-sb3 command requires INPUT.sb3.');\n assert(outputPath, 'The extensions replace-sb3 command requires --output OUTPUT.sb3.');\n return {action: 'replace-sb3', command: 'extensions', fromPath, inputPath, outputPath, yes};\n}\n\nfunction parseExtensionsArguments(arguments_: string[]): ExtensionsCliOptions {\n const [action, ...actionArguments] = arguments_;\n assert(\n action === 'digests' ||\n action === 'replace-sb3' ||\n action === 'bundle' ||\n action === 'migrate-id' ||\n action === 'status' ||\n action === 'sync' ||\n action === 'unbundle' ||\n action === 'update',\n 'The extensions command requires status, digests, sync, update, migrate-id, bundle, unbundle, or replace-sb3.',\n );\n if (action === 'digests') return parseExtensionDigestsArguments(actionArguments);\n if (action === 'replace-sb3') return parseExtensionReplaceSb3Arguments(actionArguments);\n if (action === 'status') {\n assert(\n actionArguments.length === 1 && !actionArguments[0].startsWith('-'),\n 'The extensions status command requires exactly one SOURCE_DIR.',\n );\n return {\n action,\n command: 'extensions',\n sourceDirectory: path.resolve(actionArguments[0]),\n };\n }\n if (action === 'migrate-id') {\n return parseExtensionIdMigrationArguments(actionArguments);\n }\n if (action === 'bundle') {\n return parseExtensionBundleArguments(actionArguments);\n }\n if (action === 'unbundle') {\n return parseExtensionUnbundleArguments(actionArguments);\n }\n return parseExtensionMutationArguments(action, actionArguments);\n}\n\nexport function parseCliArguments(arguments_: string[]): CliOptions {\n const normalized = arguments_.filter((argument) => argument !== '--');\n if (normalized.length === 0 || normalized[0] === '--help' || normalized[0] === '-h') {\n return {command: 'help'};\n }\n if (normalized[0] === '--version' || normalized[0] === '-v') {\n return {command: 'version'};\n }\n\n const [command, ...commandArguments] = normalized;\n if (commandArguments.includes('--help') || commandArguments.includes('-h')) {\n return {command: 'help'};\n }\n if (command === 'import') return parseImportArguments(commandArguments);\n if (command === 'check') return parseCheckArguments(commandArguments);\n if (command === 'build') return parseBuildArguments(commandArguments);\n if (command === 'clean-up') return parseCleanUpArguments(commandArguments);\n if (command === 'extensions') return parseExtensionsArguments(commandArguments);\n throw new Error(`Unknown command: ${command}`);\n}\n\nfunction formatDifferenceLines(differences: DirectoryDifferences): string {\n const labels: Record<string, string> = {added: '+', modified: '~', removed: '-'};\n const lines = Object.entries(differences).flatMap(([kind, paths]) =>\n paths.map((relativePath: string) => `${labels[kind]} ${relativePath}`),\n );\n const visibleLines = lines.slice(0, 12);\n if (lines.length > visibleLines.length) {\n visibleLines.push(`... and ${lines.length - visibleLines.length} more`);\n }\n return visibleLines.join('\\n');\n}\n\nasync function confirmImportReplacement(context: OutputReplacementContext): Promise<boolean> {\n const {comparison, discardLocalChanges, gitState, outputDirectory} = context;\n assert(\n process.stdin.isTTY && process.stdout.isTTY,\n `Output directory already exists: ${outputDirectory}. ` +\n 'Non-interactive replacement requires --yes.',\n );\n const readline = createInterface({input: process.stdin, output: process.stdout});\n try {\n const gitMessage = gitState.clean\n ? 'Git state: clean'\n : 'Git state: uncommitted changes will be discarded';\n const answer = await readline.question(\n `Existing SB3 source differs from the import candidate:\\n` +\n ` ${outputDirectory}\\n` +\n `${formatDifferenceLines(comparison.differences)}\\n` +\n `${gitMessage}\\n` +\n `${discardLocalChanges ? 'WARNING: --discard-local-changes is active.\\n' : ''}` +\n 'Replace the existing source directory? [y/N] ',\n );\n return /^(?:y|yes)$/iu.test(answer.trim());\n } finally {\n readline.close();\n }\n}\n\nasync function confirmBuildReplacement(outputPath: string): Promise<boolean> {\n assert(\n process.stdin.isTTY && process.stdout.isTTY,\n `Existing SB3 output differs: ${outputPath}. Non-interactive replacement requires --yes.`,\n );\n const readline = createInterface({input: process.stdin, output: process.stdout});\n try {\n const answer = await readline.question(\n `Existing generated SB3 will be replaced:\\n ${outputPath}\\nContinue? [y/N] `,\n );\n return /^(?:y|yes)$/iu.test(answer.trim());\n } finally {\n readline.close();\n }\n}\n\nasync function confirmExtensionReplacement({\n comparison,\n sourceDirectory,\n}: ExtensionSyncConfirmContext): Promise<boolean> {\n assert(\n process.stdin.isTTY && process.stdout.isTTY,\n `Managed extension files differ in ${sourceDirectory}. ` +\n 'Non-interactive replacement requires --yes.',\n );\n const readline = createInterface({input: process.stdin, output: process.stdout});\n try {\n const answer = await readline.question(\n `Managed extension changes will be installed:\\n` +\n ` ${sourceDirectory}\\n` +\n `${formatDifferenceLines(comparison.differences)}\\n` +\n 'Replace these files? [y/N] ',\n );\n return /^(?:y|yes)$/iu.test(answer.trim());\n } finally {\n readline.close();\n }\n}\n\nfunction logMigrationResult(result: MigrationLogResult, log: (message: string) => void): void {\n const counts = Object.entries(result.counts)\n .filter(([, count]) => count > 0)\n .map(([kind, count]) => `${kind}=${count}`)\n .join(', ');\n const action = result.applied ? 'Migrated' : 'Dry run';\n log(\n `${action}: ${result.fromId} -> ${result.toId}; ` +\n `${result.totalChanges} classified changes (${counts || 'none'}); ` +\n `artifact=${result.artifactReady ? 'ready' : 'requires-new-ID'}.`,\n );\n for (const reference of result.unclassifiedReferences) {\n log(\n `Unclassified ${reference.kind}: ${reference.file}${reference.path} = ` +\n JSON.stringify(reference.value),\n );\n }\n}\n\nexport async function runCli(\n arguments_: string[],\n {fetch: fetchImplementation = globalThis.fetch, log = console.log}: RunCliOptions = {},\n): Promise<void> {\n const options = parseCliArguments(arguments_);\n if (options.command === 'help') {\n log(usage());\n return;\n }\n if (options.command === 'version') {\n log(packageVersion);\n return;\n }\n if (options.command === 'check') {\n assert(\n 'sourceDirectory' in options && !('action' in options),\n 'Internal CLI check command routing error.',\n );\n if (options.projectAssetsPath) {\n const result = await createDeterministicSb3(options.sourceDirectory, {\n allowedAssetRoots: options.allowedAssetRoots,\n projectAssetsPath: options.projectAssetsPath,\n });\n log(\n `Valid SB3 source with project assets: ${result.source.resolvedSourceDirectory} ` +\n `(${result.entryCount} entries, ${result.assetCount} assets, ` +\n `${result.assetReferenceCount} references, ${result.embeddedExtensionCount} embedded extensions).`,\n );\n return;\n }\n const result = await validateSb3Source(options.sourceDirectory);\n log(\n `Valid SB3 source: ${result.resolvedSourceDirectory} ` +\n `(${result.sourceManifest.archiveEntries.length} entries, ` +\n `${result.assetContents.size} assets, ${result.assetReferenceCount} references, ` +\n `${result.extensions.length} embedded extensions).`,\n );\n return;\n }\n if (\n options.command === 'build' &&\n 'outputPath' in options &&\n 'sourceDirectory' in options &&\n !('action' in options)\n ) {\n const result = await buildSb3({\n allowedAssetRoots: options.allowedAssetRoots,\n cleanUpBlocks: options.cleanUpBlocks,\n confirmReplace: confirmBuildReplacement,\n outputPath: options.outputPath,\n projectAssetsPath: options.projectAssetsPath,\n sourceDirectory: options.sourceDirectory,\n yes: options.yes,\n });\n const action = result.changed ? 'Built' : 'Already up to date';\n const cleanUpMessage = result.blockCleanUp\n ? `, ${result.blockCleanUp.movedScriptCount}/${result.blockCleanUp.scriptCount} scripts laid out`\n : '';\n log(\n `${action}: ${result.outputPath} (${result.entryCount} entries, ` +\n `${result.assetCount} assets, ${result.embeddedExtensionCount} embedded extensions` +\n `${cleanUpMessage}).`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.command === 'clean-up') {\n const result = await cleanUpSb3({\n ...options,\n confirmReplace: confirmBuildReplacement,\n });\n log(\n `${result.changed ? 'Wrote' : 'Already up to date'}: ${result.outputPath} ` +\n `(${result.movedScriptCount}/${result.scriptCount} scripts moved across ${result.targetCount} targets).`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.command === 'extensions') {\n if (options.action === 'digests') {\n const inventory = await inventoryExtensionDigests(options.inputPaths);\n if (options.json) {\n log(`${JSON.stringify(inventory, null, 2)}`);\n return;\n }\n for (const line of formatExtensionDigestInventory(inventory)) log(line);\n return;\n }\n if (options.action === 'replace-sb3') {\n const result = await replaceSb3Extensions({\n confirmReplace: confirmBuildReplacement,\n fetch: fetchImplementation,\n fromPath: options.fromPath,\n inputPath: options.inputPath,\n outputPath: options.outputPath,\n yes: options.yes,\n });\n log(\n `${result.changed ? 'Wrote' : 'Already up to date'}: ${result.outputPath} (${result.extensionIds.join(', ')}).`,\n );\n log(\n `Donor: ${result.donor.source}; version=${result.donor.version ?? 'unknown'}; sha256=${result.donor.sha256}`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.action === 'bundle') {\n const result = await bundleExtensions({\n bundleId: options.bundleId,\n bundleName: options.bundleName,\n metadata: options.metadata,\n extensionIds: options.extensionIds,\n recoveryCapsule: options.recoveryCapsule,\n buildMode: options.buildMode,\n sharedDependencies: options.sharedDependencies,\n sourceDirectory: options.sourceDirectory,\n yes: options.yes,\n });\n log(\n `${result.applied ? 'Configured' : 'Dry run'} extension bundle: ${result.bundleId} ` +\n `(${result.members.join(', ')}).`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.action === 'unbundle') {\n if ('inputPath' in options) {\n const result = await unbundleSb3({\n bundleId: options.bundleId,\n inputPath: options.inputPath,\n outputPath: options.outputPath,\n yes: options.yes,\n });\n log(\n `${result.applied ? 'Wrote' : 'Dry run'} unbundled SB3: ${result.bundleId} ` +\n `(${result.members.join(', ')}) -> ${result.outputPath}.`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n const result = await unbundleExtensions({\n bundleId: options.bundleId,\n sourceDirectory: options.sourceDirectory,\n yes: options.yes,\n });\n log(\n `${result.applied ? 'Removed' : 'Dry run'} extension bundle: ${result.bundleId} ` +\n `(${result.members.join(', ')}).`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.action === 'migrate-id') {\n const result = await migrateExtensionId({\n fromId: options.fromId,\n sourceDirectory: options.sourceDirectory,\n toId: options.toId,\n yes: options.yes,\n });\n logMigrationResult(result, log);\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.action === 'status') {\n const statuses = await extensionStatus(options.sourceDirectory, {\n fetch: fetchImplementation,\n });\n if (statuses.length === 0) {\n log(`No managed embedded extensions: ${options.sourceDirectory}`);\n return;\n }\n for (const status of statuses) {\n if ('package' in status) {\n log(\n `${status.id}: ${status.state}; local=${status.local}; ` +\n `${status.package}@${status.version} (installed ${status.installedVersion})`,\n );\n continue;\n }\n log(\n `${status.id}: ${status.state}; local=${status.local}; ` +\n `${status.ref} -> ${status.remoteCommit} ` +\n `(installed ${status.resolvedCommit})`,\n );\n }\n return;\n }\n\n const operationOptions = {\n confirmReplace: confirmExtensionReplacement,\n fetch: fetchImplementation,\n sourceDirectory: options.sourceDirectory,\n yes: options.yes,\n };\n const result =\n options.action === 'sync'\n ? await syncExtensions(operationOptions)\n : await updateExtensions({\n ...operationOptions,\n allowBreakingApi: options.allowBreakingApi,\n apiManifestArtifact: options.apiManifestArtifact,\n extensionId: options.extensionId,\n migrateToId: options.migrateToId,\n sourceArtifact: options.sourceArtifact,\n });\n const action = result.changed ? 'Updated' : 'Already up to date';\n log(\n `${action}: ${result.sourceDirectory} ` +\n `(${result.extensions.map((extension) => extension.id).join(', ')}).`,\n );\n if (result.migration) {\n logMigrationResult(\n {\n applied: result.changed,\n artifactReady: true,\n ...result.migration,\n },\n log,\n );\n }\n for (const compatibility of result.apiCompatibility) {\n for (const change of compatibility.changes) {\n log(\n `API ${compatibility.id}: ${change.breaking ? 'breaking' : 'compatible'} ` +\n `${change.kind} ${change.path}`,\n );\n }\n }\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n\n assert(\n options.command === 'import' && 'inputPath' in options,\n 'Internal CLI command routing error.',\n );\n const result = await importSb3({\n confirmReplace: confirmImportReplacement,\n discardLocalChanges: options.discardLocalChanges,\n inputPath: options.inputPath,\n outputDirectory: options.outputDirectory,\n yes: options.yes,\n });\n if (result.changed) {\n const differenceMessage = result.differenceCounts\n ? ` Changes: +${result.differenceCounts.added} ` +\n `~${result.differenceCounts.modified} -${result.differenceCounts.removed}.`\n : '';\n log(\n `Imported ${result.archiveEntryCount} SB3 entries into ${result.outputDirectory} ` +\n `(${result.assetCount} assets, ${result.embeddedExtensionCount} embedded extensions).` +\n differenceMessage,\n );\n } else {\n log(`Already up to date; no files changed: ${result.outputDirectory}`);\n }\n for (const warning of result.warnings) log(`Warning: ${warning.message}`);\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgLA,SAAgB,QAAQ;CACtB,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDT;AAEA,SAAS,UAAU,YAAsB,OAAe,QAAwB;CAC9E,MAAM,QAAQ,WAAW,QAAQ;CACjC,OAAO,SAAS,CAAC,MAAM,WAAW,GAAG,GAAG,GAAG,OAAO,mBAAmB;CACrE,OAAO;AACT;AAEA,SAAS,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ACnB,iBAAiB,QAAQ;EACzB,KAAK,QAAQ;CACf,CAAC;CACD,IAAI,OAAO,SAAS;EAClB,MAAM,oBAAoB,OAAO,mBAC7B,cAAc,OAAO,iBAAiB,MAAM,IACxC,OAAO,iBAAiB,SAAS,IAAI,OAAO,iBAAiB,QAAQ,KACzE;EACJ,IACE,YAAY,OAAO,kBAAkB,oBAAoB,OAAO,gBAAgB,IAC1E,OAAO,WAAW,WAAW,OAAO,uBAAuB,0BAC/D,iBACJ;CACF,OACE,IAAI,yCAAyC,OAAO,iBAAiB;CAEvE,KAAK,MAAM,WAAW,OAAO,UAAU,IAAI,YAAY,QAAQ,SAAS;CACxE,IAAI,OAAO,wBAAwB,IAAI,OAAO,sBAAsB;AACtE"}
@@ -1,2 +1,2 @@
1
1
  export declare const packageName = "@kubohiroya/sb3-toolchain";
2
- export declare const packageVersion = "0.23.0";
2
+ export declare const packageVersion = "0.25.0";
package/dist/constants.js CHANGED
@@ -1,6 +1,6 @@
1
1
  //#region src/constants.ts
2
2
  var packageName = "@kubohiroya/sb3-toolchain";
3
- var packageVersion = "0.23.0";
3
+ var packageVersion = "0.25.0";
4
4
  //#endregion
5
5
  export { packageName, packageVersion };
6
6
 
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nexport const packageName = '@kubohiroya/sb3-toolchain';\nexport const packageVersion = '0.23.0';\n"],"mappings":";AAEA,IAAa,cAAc;AAC3B,IAAa,iBAAiB"}
1
+ {"version":3,"file":"constants.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nexport const packageName = '@kubohiroya/sb3-toolchain';\nexport const packageVersion = '0.25.0';\n"],"mappings":";AAEA,IAAa,cAAc;AAC3B,IAAa,iBAAiB"}
@@ -0,0 +1,32 @@
1
+ import { BlockPaletteDocument, BlockPaletteWarning } from './block-palette';
2
+ import { EmbeddedExtension, ExtensionEncoding, ProjectJson } from './types';
3
+ export type Sb3SourceErrorCode = 'invalid-archive' | 'archive-limit' | 'unsafe-path' | 'invalid-project' | 'invalid-extension' | 'missing-asset' | 'invalid-asset' | 'invalid-source' | 'invalid-block-palette' | 'unsupported-project';
4
+ export declare class Sb3SourceError extends Error {
5
+ readonly code: Sb3SourceErrorCode;
6
+ constructor(code: Sb3SourceErrorCode, message: string, options?: ErrorOptions);
7
+ }
8
+ interface ArchiveLimits {
9
+ maxArchiveBytes: number;
10
+ maxEntryBytes: number;
11
+ maxEntries: number;
12
+ maxExpandedBytes: number;
13
+ }
14
+ interface ExpandedArchive {
15
+ archiveEntries: string[];
16
+ assets: Map<string, Uint8Array>;
17
+ blockPalette: BlockPaletteDocument | null;
18
+ blockPaletteWarnings: BlockPaletteWarning[];
19
+ embeddedExtensions: EmbeddedExtension[];
20
+ extensionFiles: Map<string, Uint8Array>;
21
+ project: ProjectJson;
22
+ }
23
+ export declare function decodeExtensionBytes(dataUrl: unknown): {
24
+ encoding: ExtensionEncoding;
25
+ mediaType: string;
26
+ parameters: string[];
27
+ source: Uint8Array;
28
+ };
29
+ /** Parse and extract the archive once. Callers choose the rules for extra ZIP entries. */
30
+ export declare function expandArchive(bytes: Uint8Array, limits?: ArchiveLimits): ExpandedArchive;
31
+ export declare function formatSourceFiles({ archiveEntries, assets, blockPalette, embeddedExtensions, extensionFiles, project, }: ExpandedArchive): Map<string, Uint8Array>;
32
+ export {};